repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/NonTxEmCloser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.container;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.HashMap;
import java.util.Map;
import jakarta.persistence.EntityManager;
import org.wildfly.common.function.ThreadLocalStack;
/**
* Close the non tx invocations on transaction scoped entity manager
*
* @author Scott Marlow
*/
public class NonTxEmCloser {
/**
* Each thread will have its own list of SB invocations in progress.
* Key = scoped persistence unit name
*/
public static final ThreadLocalStack<Map<String, EntityManager>> nonTxStack = new ThreadLocalStack<Map<String, EntityManager>>();
/**
* entered new session bean invocation, start new collection for tracking transactional entity managers created
* without a Jakarta Transactions transaction.
*/
public static void pushCall() {
nonTxStack.push(null); // to conserve memory/cpu cycles, push a null placeholder that will only get replaced
// with a Map if we actually need it (in add() below).
}
/**
* current session bean invocation is ending, close any transactional entity managers created without a Jakarta Transactions
* transaction.
*/
public static void popCall() {
Map<String, EntityManager> emStack = nonTxStack.pop();
if (emStack != null) {
for (EntityManager entityManager : emStack.values()) {
try {
if (entityManager.isOpen()) {
entityManager.close();
}
} catch (RuntimeException safeToIgnore) {
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.trace("Could not close (non-transactional) container managed entity manager." +
" This shouldn't impact application functionality (only read " +
"operations occur in non-transactional mode)", safeToIgnore);
}
}
}
}
}
/**
* Return the transactional entity manager for the specified scoped persistence unit name
*
* @param puScopedName
* @return
*/
public static EntityManager get(String puScopedName) {
Map<String, EntityManager> map = nonTxStack.peek();
if (map != null) {
return map.get(puScopedName);
}
return null;
}
public static void add(String puScopedName, EntityManager entityManager) {
Map<String, EntityManager> map = nonTxStack.peek();
if (map == null && !nonTxStack.isEmpty()) {
// replace null with a collection to hold the entity managers.
map = new HashMap<String, EntityManager>();
nonTxStack.pop();
nonTxStack.push(map); // replace top of stack (currently null) with new collection
}
if (map != null) {
map.put(puScopedName, entityManager);
}
}
}
| 4,013 | 36.867925 | 133 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/ExtendedPersistenceDeepInheritance.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.container;
import java.util.Map;
/**
* ExtendedPersistenceInheritance.DEEP inheritance strategy where we can inherit from any bean being created or from the
* parent bean call stack.
*
* @author Scott Marlow
*/
public final class ExtendedPersistenceDeepInheritance implements ExtendedPersistenceInheritanceStrategy {
public static final ExtendedPersistenceDeepInheritance INSTANCE = new ExtendedPersistenceDeepInheritance();
@Override
public void registerExtendedPersistenceContext(String scopedPuName, ExtendedEntityManager entityManager) {
if (SFSBCallStack.getSFSBCreationBeanNestingLevel() > 0) {
SFSBCallStack.getSFSBCreationTimeInjectedXPCs(scopedPuName).registerDeepInheritance(scopedPuName, entityManager);
}
}
@Override
public ExtendedEntityManager findExtendedPersistenceContext(String puScopedName) {
ExtendedEntityManager result;
SFSBInjectedXPCs currentInjectedXPCs = SFSBCallStack.getSFSBCreationTimeInjectedXPCs(puScopedName);
// will look directly at the top level bean being created (registerExtendedPersistenceContext() registers xpc there).
result = currentInjectedXPCs.findExtendedPersistenceContextDeepInheritance(puScopedName);
if (result == null) {
// walk up the BEAN call stack (this also covers the case of a bean method JNDI searching for another bean)
for (Map<String, ExtendedEntityManager> handle : SFSBCallStack.currentSFSBCallStack()) {
result = handle.get(puScopedName);
if(result != null) {
return result;
}
}
}
return result;
}
}
| 2,743 | 41.215385 | 125 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/container/AbstractEntityManager.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.container;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.List;
import java.util.Map;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Query;
import jakarta.persistence.StoredProcedureQuery;
import jakarta.persistence.SynchronizationType;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.metamodel.Metamodel;
import org.jboss.as.jpa.messages.JpaLogger;
/**
* Abstract entity manager used by all container managed entity managers.
*
* @author Scott Marlow (forked from jboss-jpa)
*/
public abstract class AbstractEntityManager implements EntityManager {
// constants for TRACE lock mode logging
public static final String NULL_LOCK_MODE = "(null)";
public static final String OPTIMISTIC_LOCK_MODE = "optimistic";
public static final String OPTIMISTIC_FORCE_INCREMENT_LOCK_MODE = "optimistic_force_increment";
public static final String READ_LOCK_MODE = "read";
public static final String WRITE_LOCK_MODE = "write";
public static final String PESSIMISTIC_READ_LOCK_MODE = "pessimistic_read";
public static final String PESSIMISTIC_FORCE_INCREMENT_LOCK_MODE = "pessimistic_force_increment";
public static final String PESSIMISTIC_WRITE_LOCK_MODE = "pessimistic_write";
public static final String NONE_LOCK_MODE = "none";
private final transient boolean isTraceEnabled = ROOT_LOGGER.isTraceEnabled();
protected abstract EntityManager getEntityManager();
/**
* @return true if an extended persistence context is in use
* <p/>
* Precondition: getEntityManager() must be called previous to calling isExtendedPersistenceContext
*/
protected abstract boolean isExtendedPersistenceContext();
/**
* @return true if a Jakarta Transactions transaction active
* <p/>
* Precondition: getEntityManager() must be called previous to calling isInTx
*/
protected abstract boolean isInTx();
public abstract SynchronizationType getSynchronizationType();
protected abstract boolean deferEntityDetachUntilClose();
protected abstract boolean skipQueryDetach();
public <T> T unwrap(Class<T> cls) {
return getEntityManager().unwrap(cls);
}
public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachTypedQueryNonTxInvocation(entityManager,entityManager.createNamedQuery(name, resultClass));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNamedQuery name '%s', resultClass '%s' took %dms", name, resultClass.getName(), elapsed);
}
}
}
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachTypedQueryNonTxInvocation(entityManager,entityManager.createQuery(criteriaQuery));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createQuery took %dms", elapsed);
}
}
}
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachTypedQueryNonTxInvocation(entityManager,entityManager.createQuery(qlString, resultClass));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createQuery resultClass '%s' took %dms", resultClass.getName(), elapsed);
}
}
}
public void detach(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().detach(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("detach entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
final EntityManager underlyingEntityManager = getEntityManager();
T result = underlyingEntityManager.find(entityClass, primaryKey, properties);
detachNonTxInvocation(underlyingEntityManager);
return result;
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("find entityClass '%s' took %dms", entityClass.getName(), elapsed);
}
}
}
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
final EntityManager underlyingEntityManager = getEntityManager();
T result = underlyingEntityManager.find(entityClass, primaryKey, lockMode);
detachNonTxInvocation(underlyingEntityManager);
return result;
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("find entityClass '%s', lockMode '%s' took %dms", entityClass.getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
final EntityManager underlyingEntityManager = getEntityManager();
T result = underlyingEntityManager.find(entityClass, primaryKey, lockMode, properties);
detachNonTxInvocation(underlyingEntityManager);
return result;
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("find entityClass '%s', lockMode '%s' took %dms", entityClass.getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public <T> T find(Class<T> entityClass, Object primaryKey) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
final EntityManager underlyingEntityManager = getEntityManager();
T result = getEntityManager().find(entityClass, primaryKey);
detachNonTxInvocation(underlyingEntityManager);
return result;
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("find entityClass '%s' took %dms", entityClass.getName(), elapsed);
}
}
}
public CriteriaBuilder getCriteriaBuilder() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getCriteriaBuilder();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getCriteriaBuilder took %dms", elapsed);
}
}
}
public EntityManagerFactory getEntityManagerFactory() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getEntityManagerFactory();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getEntityManagerFactory took %dms", elapsed);
}
}
}
public LockModeType getLockMode(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
LockModeType result = null;
try {
result = getEntityManager().getLockMode(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getLockMode entityClass '%s', lockMode '%s' took %dms", entity.getClass().getName(), getLockModeAsString(result), elapsed);
}
}
return result;
}
public Metamodel getMetamodel() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getMetamodel();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getMetamodel took %dms", elapsed);
}
}
}
public Map<String, Object> getProperties() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getProperties();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getProperties took %dms", elapsed);
}
}
}
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().lock(entity, lockMode, properties);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("lock entityClass '%s', lockMode '%s' took %dms", entity.getClass().getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public void setProperty(String propertyName, Object value) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().setProperty(propertyName, value);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("setProperty took %dms", elapsed);
}
}
}
public void clear() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().clear();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("clear took %dms", elapsed);
}
}
}
public void close() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().close();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("close took %dms", elapsed);
}
}
}
public boolean contains(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().contains(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("contains '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public Query createNamedQuery(String name) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachQueryNonTxInvocation(entityManager, entityManager.createNamedQuery(name));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNamedQuery name '%s' took %dms", name, elapsed);
}
}
}
@SuppressWarnings("unchecked")
public Query createNativeQuery(String sqlString, Class resultClass) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachQueryNonTxInvocation(entityManager, entityManager.createNativeQuery(sqlString, resultClass));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNativeQuery resultClass '%s' took %dms", resultClass.getName(), elapsed);
}
}
}
public Query createNativeQuery(String sqlString, String resultSetMapping) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachQueryNonTxInvocation(entityManager, entityManager.createNativeQuery(sqlString, resultSetMapping));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNativeQuery took %dms", elapsed);
}
}
}
public Query createNativeQuery(String sqlString) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachQueryNonTxInvocation(entityManager, entityManager.createNativeQuery(sqlString));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNativeQuery took %dms", elapsed);
}
}
}
public Query createQuery(String ejbqlString) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
// invoke underlying entity manager method and if not running in a tx
// return a Query wrapper around the result.
EntityManager entityManager = getEntityManager();
return detachQueryNonTxInvocation(entityManager, entityManager.createQuery(ejbqlString));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createQuery took %dms", elapsed);
}
}
}
public void flush() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().flush();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("flush took %dms", elapsed);
}
}
}
public Object getDelegate() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getDelegate();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getDelegate took %dms", elapsed);
}
}
}
public FlushModeType getFlushMode() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getFlushMode();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getFlushMode took %dms", elapsed);
}
}
}
public <T> T getReference(Class<T> entityClass, Object primaryKey) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
final EntityManager underlyingEntityManager = getEntityManager();
T result = getEntityManager().getReference(entityClass, primaryKey);
detachNonTxInvocation(underlyingEntityManager);
return result;
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getReference entityClass '%s' took %dms", entityClass.getName(), elapsed);
}
}
}
public EntityTransaction getTransaction() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getTransaction();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getTransaction took %dms", elapsed);
}
}
}
public boolean isOpen() {
return getEntityManager().isOpen();
}
public void joinTransaction() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().joinTransaction();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("joinTransaction took %dms", elapsed);
}
}
}
public void lock(Object entity, LockModeType lockMode) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().lock(entity, lockMode);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("lock entityClass '%s', lockMode '%s' took %dms", entity.getClass().getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public <T> T merge(T entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
return getEntityManager().merge(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("merge entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public void persist(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().persist(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("persist entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public void refresh(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().refresh(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("refresh entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public void refresh(Object entity, Map<String, Object> properties) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().refresh(entity, properties);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("refresh entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public void refresh(Object entity, LockModeType lockMode) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().refresh(entity, lockMode);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("refresh entityClass '%s', lockMode '%s' took %dms", entity.getClass().getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().refresh(entity, lockMode, properties);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("refresh entityClass '%s', lockMode '%s' took %dms", entity.getClass().getName(), getLockModeAsString(lockMode), elapsed);
}
}
}
public void remove(Object entity) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
transactionIsRequired();
getEntityManager().remove(entity);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("remove entityClass '%s' took %dms", entity.getClass().getName(), elapsed);
}
}
}
public void setFlushMode(FlushModeType flushMode) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
getEntityManager().setFlushMode(flushMode);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("setFlushMode took %dms", elapsed);
}
}
}
public Query createQuery(CriteriaUpdate criteriaUpdate) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().createQuery(criteriaUpdate);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createQuery(CriteriaUpdate) took %dms", elapsed);
}
}
}
public Query createQuery(CriteriaDelete criteriaDelete) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().createQuery(criteriaDelete);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createQuery(criteriaDelete) took %dms", elapsed);
}
}
}
public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
EntityManager entityManager = getEntityManager();
return detachStoredProcedureQueryNonTxInvocation(entityManager, entityManager.createNamedStoredProcedureQuery(name));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createNamedStoredProcedureQuery %s took %dms", name, elapsed);
}
}
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
EntityManager entityManager = getEntityManager();
return detachStoredProcedureQueryNonTxInvocation(entityManager, entityManager.createStoredProcedureQuery(procedureName));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createStoredProcedureQuery %s took %dms", procedureName, elapsed);
}
}
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
EntityManager entityManager = getEntityManager();
return detachStoredProcedureQueryNonTxInvocation(entityManager, entityManager.createStoredProcedureQuery(procedureName, resultClasses));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createStoredProcedureQuery %s, resultClasses... took %dms", procedureName, elapsed);
}
}
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
EntityManager entityManager = getEntityManager();
return detachStoredProcedureQueryNonTxInvocation(entityManager, entityManager.createStoredProcedureQuery(procedureName, resultSetMappings));
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createStoredProcedureQuery %s, resultSetMappings... took %dms", procedureName, elapsed);
}
}
}
public <T> EntityGraph<T> createEntityGraph(Class<T> tClass) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().createEntityGraph(tClass);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createEntityGraph %s took %dms", tClass.getName(), elapsed);
}
}
}
public EntityGraph<?> createEntityGraph(String s) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().createEntityGraph(s);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("createEntityGraph %s took %dms", s, elapsed);
}
}
}
public EntityGraph<?> getEntityGraph(String s) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getEntityGraph(s);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getEntityGraph %s took %dms", s, elapsed);
}
}
}
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> tClass) {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().getEntityGraphs(tClass);
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("getEntityGraphs %s took %dms", tClass.getName(), elapsed);
}
}
}
public boolean isJoinedToTransaction() {
long start = 0;
if (isTraceEnabled)
start = System.currentTimeMillis();
try {
return getEntityManager().isJoinedToTransaction();
} finally {
if (isTraceEnabled) {
long elapsed = System.currentTimeMillis() - start;
ROOT_LOGGER.tracef("isJoinedToTransaction() took %dms", elapsed);
}
}
}
// used by TransactionScopedEntityManager to auto detach loaded entities
// after each non-Jakarta Transactions invocation
protected void detachNonTxInvocation(EntityManager underlyingEntityManager) {
if (!this.isExtendedPersistenceContext() && !this.isInTx() && !deferEntityDetachUntilClose()) {
underlyingEntityManager.clear();
}
}
// for JPA 2.0 section 3.8.6
// used by TransactionScopedEntityManager to detach entities loaded by a query in a non-Jakarta Transactions invocation.
protected Query detachQueryNonTxInvocation(EntityManager underlyingEntityManager, Query underLyingQuery) {
if (!this.isExtendedPersistenceContext() && !this.isInTx() && !skipQueryDetach()) {
return new QueryNonTxInvocationDetacher(underlyingEntityManager, underLyingQuery);
}
return underLyingQuery;
}
// for JPA 2.0 section 3.8.6
// used by TransactionScopedEntityManager to detach entities loaded by a query in a non-Jakarta Transactions invocation.
protected <T> TypedQuery<T> detachTypedQueryNonTxInvocation(EntityManager underlyingEntityManager, TypedQuery<T> underLyingQuery) {
if (!this.isExtendedPersistenceContext() && !this.isInTx() && !skipQueryDetach()) {
return new TypedQueryNonTxInvocationDetacher<>(underlyingEntityManager, underLyingQuery);
}
return underLyingQuery;
}
private StoredProcedureQuery detachStoredProcedureQueryNonTxInvocation(EntityManager underlyingEntityManager, StoredProcedureQuery underlyingStoredProcedureQuery) {
if (!this.isExtendedPersistenceContext() && !this.isInTx() && !skipQueryDetach()) {
return new StoredProcedureQueryNonTxInvocationDetacher(underlyingEntityManager, underlyingStoredProcedureQuery);
}
return underlyingStoredProcedureQuery;
}
// JPA 7.9.1 if invoked without a Jakarta Transactions transaction and a transaction scoped persistence context is used,
// will throw TransactionRequiredException for any calls to entity manager remove/merge/persist/refresh.
private void transactionIsRequired() {
if (!this.isExtendedPersistenceContext() && !this.isInTx()) {
throw JpaLogger.ROOT_LOGGER.transactionRequired();
}
}
private static String getLockModeAsString(LockModeType lockMode) {
if (lockMode == null)
return NULL_LOCK_MODE;
switch (lockMode) {
case OPTIMISTIC:
return OPTIMISTIC_LOCK_MODE;
case OPTIMISTIC_FORCE_INCREMENT:
return OPTIMISTIC_FORCE_INCREMENT_LOCK_MODE;
case READ:
return READ_LOCK_MODE;
case WRITE:
return WRITE_LOCK_MODE;
case PESSIMISTIC_READ:
return PESSIMISTIC_READ_LOCK_MODE;
case PESSIMISTIC_FORCE_INCREMENT:
return PESSIMISTIC_FORCE_INCREMENT_LOCK_MODE;
case PESSIMISTIC_WRITE:
return PESSIMISTIC_WRITE_LOCK_MODE;
default:
case NONE:
return NONE_LOCK_MODE;
}
}
}
| 34,664 | 37.135314 | 168 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/ManagementResourceDefinition.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS;
import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinition;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jipijapa.management.spi.Statistics;
/**
* ManagementResourceDefinition
*
* @author Scott Marlow
*/
public class ManagementResourceDefinition extends SimpleResourceDefinition {
private final Statistics statistics;
private final EntityManagerFactoryLookup entityManagerFactoryLookup;
private final ResourceDescriptionResolver descriptionResolver;
/**
* specify the management api version used in JPAExtension that 'enabled' attribute is deprecated in
*/
private static final ModelVersion ENABLED_ATTRIBUTE_DEPRECATED_MODEL_VERSION = ModelVersion.create(1, 2, 0);
private static final String ENABLED_ATTRIBUTE = "enabled";
public ManagementResourceDefinition(
final PathElement pathElement,
final ResourceDescriptionResolver descriptionResolver,
final Statistics statistics,
final EntityManagerFactoryLookup entityManagerFactoryLookup) {
super(pathElement, descriptionResolver);
this.statistics = statistics;
this.entityManagerFactoryLookup = entityManagerFactoryLookup;
this.descriptionResolver = descriptionResolver;
}
private ModelType getModelType(Class<?> type) {
if(Integer.class.equals(type)) {
return ModelType.INT;
}
else if(Long.class.equals(type)) {
return ModelType.LONG;
}
else if(String.class.equals(type)) {
return ModelType.STRING;
}
else if(Boolean.class.equals(type)) {
return ModelType.BOOLEAN;
}
return ModelType.OBJECT;
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
super.registerChildren(resourceRegistration);
for( final String sublevelChildName : statistics.getChildrenNames()) {
Statistics sublevelStatistics = statistics.getChild(sublevelChildName);
ResourceDescriptionResolver sublevelResourceDescriptionResolver = new StandardResourceDescriptionResolver(
sublevelChildName, sublevelStatistics.getResourceBundleName(), sublevelStatistics.getClass().getClassLoader());
resourceRegistration.registerSubModel(
new ManagementResourceDefinition(PathElement.pathElement(sublevelChildName), sublevelResourceDescriptionResolver, sublevelStatistics, entityManagerFactoryLookup));
}
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
super.registerAttributes(resourceRegistration);
for(final String statisticName: statistics.getNames()) {
final ModelType modelType = getModelType(statistics.getType(statisticName));
final SimpleAttributeDefinitionBuilder simpleAttributeDefinitionBuilder =
new SimpleAttributeDefinitionBuilder(statisticName, modelType, true)
.setXmlName(statisticName)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME);
if (statistics.isAttribute(statisticName)) {
// WFLY-561 improves usability by using "statistics-enabled" instead of "enabled"
if (ENABLED_ATTRIBUTE.equals(statisticName)) {
simpleAttributeDefinitionBuilder.setDeprecated(ENABLED_ATTRIBUTE_DEPRECATED_MODEL_VERSION);
}
OperationStepHandler readHandler =
new AbstractMetricsHandler() {
@Override
void handle(final ModelNode response, OperationContext context, final ModelNode operation) {
Object result = statistics.getValue(
statisticName,
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
if (result != null) {
setResponse(response, result, modelType);
}
}
};
// handle writeable attributes
if (statistics.isWriteable(statisticName)) {
OperationStepHandler writeHandler =
new AbstractMetricsHandler() {
@Override
void handle(final ModelNode response, OperationContext context, final ModelNode operation) {
Object oldSetting = statistics.getValue(
statisticName,
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
{
final ModelNode value = operation.get(ModelDescriptionConstants.VALUE).resolve();
if (Boolean.class.equals(statistics.getType(statisticName))) {
statistics.setValue(
statisticName,
value.asBoolean(),
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
} else if(Integer.class.equals(statistics.getType(statisticName))) {
statistics.setValue(
statisticName,
value.asInt(),
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
} else if(Long.class.equals(statistics.getType(statisticName))) {
statistics.setValue(
statisticName,
value.asLong(),
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
} else {
statistics.setValue(
statisticName,
value.asString(),
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
}
}
final Object rollBackValue = oldSetting;
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
statistics.setValue(
statisticName,
rollBackValue,
entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
}
});
}
};
resourceRegistration.registerReadWriteAttribute(simpleAttributeDefinitionBuilder.build(), readHandler, writeHandler);
}
else {
resourceRegistration.registerMetric(simpleAttributeDefinitionBuilder.build(), readHandler);
}
}
}
}
private void setResponse(ModelNode response, Object result, ModelType modelType) {
if (ModelType.INT.equals(modelType)) {
response.set( ((Integer)result).intValue()); // TODO: JIPI-9 switch to value wrapper
}
else if (ModelType.LONG.equals(modelType)) {
response.set( ((Long)result).longValue()); // TODO: JIPI-9 switch to value wrapper
}
else if (ModelType.BOOLEAN.equals(modelType)) {
response.set( ((Boolean)result).booleanValue()); // TODO: JIPI-9 switch to value wrapper
}
else {
response.set(result.toString()); // ModelType.STRING
}
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
for(final String statisticName: statistics.getNames()) {
final ModelType modelType = getModelType(statistics.getType(statisticName));
if(statistics.isOperation(statisticName)) {
AttributeDefinition attributeDefinition =
new SimpleAttributeDefinitionBuilder(statisticName, modelType, true)
.setXmlName(statisticName)
.setAllowExpression(true)
.setFlags(AttributeAccess.Flag.STORAGE_RUNTIME)
.build();
OperationStepHandler operationHandler =
new AbstractMetricsHandler() {
@Override
void handle(final ModelNode response, OperationContext context, final ModelNode operation) {
Object result = statistics.getValue(
statisticName, entityManagerFactoryLookup,
StatisticNameLookup.statisticNameLookup(statisticName),
Path.path(PathAddress.pathAddress(operation.get(ADDRESS))));
if (result != null) {
setResponse(response, result, modelType);
}
}
};
SimpleOperationDefinition definition =
new SimpleOperationDefinitionBuilder(statisticName, descriptionResolver).setParameters(attributeDefinition).build();
resourceRegistration.registerOperationHandler(definition, operationHandler);
}
}
}
private abstract static class AbstractMetricsHandler extends AbstractRuntimeOnlyHandler {
abstract void handle(final ModelNode response, final OperationContext context, final ModelNode operation);
@Override
protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws
OperationFailedException {
handle(context.getResult(), context, operation);
}
}
}
| 13,993 | 50.072993 | 183 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/DynamicManagementStatisticsResource.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.dmr.ModelNode;
import org.jipijapa.management.spi.Statistics;
/**
* Resource representing a Jakarta Persistence PersistenceUnit (from a persistence.xml) deployment.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
* @author Scott Marlow
*/
public class DynamicManagementStatisticsResource extends PlaceholderResource.PlaceholderResourceEntry {
private final String puName;
private final ModelNode model = new ModelNode();
private final Statistics statistics;
private final String identificationLabel;
private final EntityManagerFactoryLookup entityManagerFactoryLookup;
public DynamicManagementStatisticsResource(
final Statistics statistics,
final String puName,
final String identificationLabel,
final EntityManagerFactoryLookup entityManagerFactoryLookup) {
super(identificationLabel, puName);
this.puName = puName;
this.statistics = statistics;
this.identificationLabel = identificationLabel;
this.entityManagerFactoryLookup = entityManagerFactoryLookup;
}
@Override
public ModelNode getModel() {
return model;
}
@Override
public boolean isModelDefined() {
return model.isDefined();
}
@Override
public boolean hasChild(PathElement element) {
try {
Statistics statistics = getStatistics();
// if element key matches, check if element value also matches
if (statistics.getChildrenNames().contains(element.getKey())) {
Statistics childStatistics = statistics.getChild(element.getKey());
return childStatistics != null && childStatistics.getDynamicChildrenNames(entityManagerFactoryLookup, PathWrapper.path(puName)).contains(element.getValue());
} else {
return super.hasChild(element);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return false;
}
}
@Override
public Resource getChild(PathElement element) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(element.getKey())) {
Statistics childStatistics = statistics.getChild(element.getKey());
return childStatistics != null && childStatistics.getDynamicChildrenNames(entityManagerFactoryLookup, PathWrapper.path(puName)).contains(element.getValue())
? PlaceholderResource.INSTANCE : null;
} else {
return super.getChild(element);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return super.getChild(element);
}
}
@Override
public Resource requireChild(PathElement element) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(element.getKey())) {
Statistics childStatistics = statistics.getChild(element.getKey());
if (childStatistics != null && childStatistics.getDynamicChildrenNames(entityManagerFactoryLookup, PathWrapper.path(puName)).contains(element.getValue())) {
return PlaceholderResource.INSTANCE;
}
throw new NoSuchResourceException(element);
} else {
return super.requireChild(element);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return super.requireChild(element);
}
}
@Override
public boolean hasChildren(String childType) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(childType)) {
Statistics childStatistics = statistics.getChild(childType);
return childStatistics != null && !childStatistics.getNames().isEmpty();
} else {
return super.hasChildren(childType);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return false;
}
}
@Override
public Resource navigate(PathAddress address) {
Statistics statistics = getStatistics();
if (address.size() > 0 && statistics.getChildrenNames().contains(address.getElement(0).getKey())) {
if (address.size() > 1) {
throw new NoSuchResourceException(address.getElement(1));
}
return PlaceholderResource.INSTANCE;
} else {
return super.navigate(address);
}
}
@Override
public Set<String> getChildTypes() {
try {
Set<String> result = new HashSet<String>(super.getChildTypes());
Statistics statistics = getStatistics();
result.addAll(statistics.getChildrenNames());
return result;
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return Collections.emptySet();
}
}
@Override
public Set<String> getChildrenNames(String childType) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(childType)) {
Statistics childStatistics = statistics.getChild(childType);
Set<String>result = new HashSet<String>();
for(String name:childStatistics.getDynamicChildrenNames(entityManagerFactoryLookup, PathWrapper.path(puName))) {
result.add(name);
}
return result;
} else {
return super.getChildrenNames(childType);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return Collections.emptySet();
}
}
@Override
public Set<ResourceEntry> getChildren(String childType) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(childType)) {
Set<ResourceEntry> result = new HashSet<ResourceEntry>();
Statistics childStatistics = statistics.getChild(childType);
for (String name : childStatistics.getDynamicChildrenNames(entityManagerFactoryLookup, PathWrapper.path(puName))) {
result.add(new PlaceholderResource.PlaceholderResourceEntry(childType, name));
}
return result;
} else {
return super.getChildren(childType);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
return Collections.emptySet();
}
}
@Override
public void registerChild(PathElement address, Resource resource) {
try {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(address.getKey())) {
throw JpaLogger.ROOT_LOGGER.resourcesOfTypeCannotBeRegistered(address.getKey());
} else {
super.registerChild(address, resource);
}
}
catch (RuntimeException e) {
// WFLY-2436 ignore unexpected exceptions (e.g. JIPI-27 may throw an IllegalStateException)
// WFLY-10413 : also make sure to catch HibernateExceptions
ROOT_LOGGER.unexpectedStatisticsProblem(e);
}
}
@Override
public Resource removeChild(PathElement address) {
Statistics statistics = getStatistics();
if (statistics.getChildrenNames().contains(address.getKey())) {
throw JpaLogger.ROOT_LOGGER.resourcesOfTypeCannotBeRemoved(address.getKey());
} else {
return super.removeChild(address);
}
}
@Override
public boolean isRuntime() {
return true;
}
@Override
public boolean isProxy() {
return false;
}
@Override
public DynamicManagementStatisticsResource clone() {
return new DynamicManagementStatisticsResource(statistics, puName, identificationLabel, entityManagerFactoryLookup);
}
private Statistics getStatistics() {
return statistics;
}
}
| 11,100 | 38.931655 | 173 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/Path.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import java.util.ArrayList;
import org.jboss.as.controller.PathElement;
import org.jipijapa.management.spi.PathAddress;
/**
* Path to a statistic value
*
* @author Scott Marlow
*/
public class Path implements PathAddress {
private final ArrayList<PathElement> pathElements = new ArrayList<>();
public Path(org.jboss.as.controller.PathAddress pathAddress) {
for (int looper = 0; looper < pathAddress.size(); looper++) {
pathElements.add(pathAddress.getElement(looper));
}
}
public static Path path(org.jboss.as.controller.PathAddress pathAddress) {
return new Path(pathAddress);
}
@Override
public int size() {
return pathElements.size();
}
@Override
public String getValue(String name) {
for ( PathElement pathElement : pathElements) {
if (pathElement.getKey().equals(name)) {
return pathElement.getValue();
}
}
return null;
}
@Override
public String getValue(int index) {
return pathElements.get(index).getValue();
}
}
| 2,165 | 30.852941 | 78 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/StatisticNameLookup.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import org.jipijapa.management.spi.StatisticName;
/**
* StatisticNameLookup
*
* @author Scott Marlow
*/
public class StatisticNameLookup implements StatisticName {
private final String name;
public StatisticNameLookup(String name) {
this.name = name;
}
public static StatisticNameLookup statisticNameLookup(String name) {
return new StatisticNameLookup(name);
}
@Override
public String getName() {
return name;
}
}
| 1,542 | 30.489796 | 72 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/EntityManagerFactoryLookup.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import jakarta.persistence.EntityManagerFactory;
import org.jboss.as.jpa.subsystem.PersistenceUnitRegistryImpl;
import org.jipijapa.management.spi.EntityManagerFactoryAccess;
import org.jipijapa.plugin.spi.PersistenceUnitService;
/**
* EntityManagerFactoryLookup
*
* @author Scott Marlow
*/
public class EntityManagerFactoryLookup implements EntityManagerFactoryAccess {
@Override
public EntityManagerFactory entityManagerFactory(final String scopedPersistenceUnitName) {
PersistenceUnitService persistenceUnitService = PersistenceUnitRegistryImpl.INSTANCE.getPersistenceUnitService(scopedPersistenceUnitName);
if (persistenceUnitService == null) {
return null;
}
return persistenceUnitService.getEntityManagerFactory();
}
}
| 1,852 | 36.816327 | 146 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/management/PathWrapper.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.management;
import org.jipijapa.management.spi.PathAddress;
/**
* Path wrapper for a static String value
*
* @author Scott Marlow
*/
public class PathWrapper implements PathAddress {
private final String value;
public PathWrapper(String value) {
this.value = value;
}
public static PathWrapper path(String value) {
return new PathWrapper(value);
}
@Override
public int size() {
return 1;
}
@Override
public String getValue(String name) {
return value;
}
@Override
public String getValue(int index) {
return value;
}
}
| 1,673 | 28.368421 | 70 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/HibernateSearchDeploymentMarker.java | package org.jboss.as.jpa.processor;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUtils;
import java.util.List;
public class HibernateSearchDeploymentMarker {
private static final AttachmentKey<AttachmentList<String>> BACKEND_TYPE_KEY = AttachmentKey.createList(String.class);
private static final AttachmentKey<AttachmentList<String>> COORDINATION_STRATEGY_KEY = AttachmentKey.createList(String.class);
public static void markBackendType(DeploymentUnit unit, String backendType) {
unit = DeploymentUtils.getTopDeploymentUnit(unit);
unit.addToAttachmentList(BACKEND_TYPE_KEY, backendType);
}
public static List<String> getBackendTypes(DeploymentUnit unit) {
unit = DeploymentUtils.getTopDeploymentUnit(unit);
return unit.getAttachmentList(BACKEND_TYPE_KEY);
}
public static void markCoordinationStrategy(DeploymentUnit unit, String coordinationStrategy) {
unit = DeploymentUtils.getTopDeploymentUnit(unit);
unit.addToAttachmentList(COORDINATION_STRATEGY_KEY, coordinationStrategy);
}
public static List<String> getCoordinationStrategies(DeploymentUnit unit) {
unit = DeploymentUtils.getTopDeploymentUnit(unit);
return unit.getAttachmentList(COORDINATION_STRATEGY_KEY);
}
private HibernateSearchDeploymentMarker() {
}
}
| 1,503 | 38.578947 | 130 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceUnitServiceHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import static org.jboss.as.server.Services.addServerExecutorDependency;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.SynchronizationType;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceProviderResolverHolder;
import javax.sql.DataSource;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.ee.beanvalidation.BeanValidationAttachments;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.jpa.beanmanager.BeanManagerAfterDeploymentValidation;
import org.jboss.as.jpa.beanmanager.ProxyBeanManager;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.config.PersistenceUnitsInApplication;
import org.jboss.as.jpa.container.TransactionScopedEntityManager;
import org.jboss.as.jpa.interceptor.WebNonTxEmCloserAction;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.persistenceprovider.PersistenceProviderLoader;
import org.jboss.as.jpa.processor.secondlevelcache.CacheDeploymentListener;
import org.jboss.as.jpa.service.JPAService;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.jpa.service.PhaseOnePersistenceUnitServiceImpl;
import org.jboss.as.jpa.spi.PersistenceUnitService;
import org.jboss.as.jpa.subsystem.PersistenceUnitRegistryImpl;
import org.jboss.as.jpa.transaction.JtaManagerImpl;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentModelUtils;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.WeldCapability;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.jandex.Index;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.modules.ModuleLoadException;
import org.jboss.msc.inject.InjectionException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistryException;
import org.jboss.msc.service.ServiceTarget;
import org.jipijapa.plugin.spi.ManagementAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderIntegratorAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.Platform;
import org.jipijapa.plugin.spi.TwoPhaseBootstrapCapable;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Handle the installation of the Persistence Unit service
*
* NOTE: References in this document to Java Persistence API (JPA) refer to the Jakarta Persistence unless otherwise noted.
*
* @author Scott Marlow
*/
public class PersistenceUnitServiceHandler {
private static final String ENTITYMANAGERFACTORY_JNDI_PROPERTY = "jboss.entity.manager.factory.jndi.name";
private static final String ENTITYMANAGER_JNDI_PROPERTY = "jboss.entity.manager.jndi.name";
public static final ServiceName BEANMANAGER_NAME = ServiceName.of("beanmanager");
private static final AttachmentKey<Map<String,PersistenceProviderAdaptor>> providerAdaptorMapKey = AttachmentKey.create(Map.class);
public static final AttributeDefinition SCOPED_UNIT_NAME = new SimpleAttributeDefinitionBuilder("scoped-unit-name", ModelType.STRING, true).setStorageRuntime().build();
private static final String FIRST_PHASE = "__FIRST_PHASE__";
private static final String EE_DEFAULT_DATASOURCE = "java:comp/DefaultDataSource";
public static void deploy(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException {
handleWarDeployment(phaseContext, startEarly, platform);
handleEarDeployment(phaseContext, startEarly, platform);
handleJarDeployment(phaseContext, startEarly, platform);
if( startEarly) {
nextPhaseDependsOnPersistenceUnit(phaseContext, platform);
}
}
public static void undeploy(DeploymentUnit context) {
List<PersistenceAdaptorRemoval> removals = context.getAttachmentList(REMOVAL_KEY);
if (removals != null) {
for (PersistenceAdaptorRemoval removal : removals) {
removal.cleanup();
}
context.removeAttachment(REMOVAL_KEY);
}
}
private static void handleJarDeployment(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!isEarDeployment(deploymentUnit) && !isWarDeployment(deploymentUnit) && JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
PersistenceUnitMetadataHolder holder;
if (deploymentRoot != null &&
(holder = deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null &&
!holder.getPersistenceUnits().isEmpty()) {
ArrayList<PersistenceUnitMetadataHolder> puList = new ArrayList<PersistenceUnitMetadataHolder>(1);
puList.add(holder);
ROOT_LOGGER.tracef("install persistence unit definition for jar %s", deploymentRoot.getRootName());
// assemble and install the PU service
addPuService(phaseContext, puList, startEarly, platform);
}
}
}
private static void handleWarDeployment(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (isWarDeployment(deploymentUnit) && JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
PersistenceUnitMetadataHolder holder;
ArrayList<PersistenceUnitMetadataHolder> puList = new ArrayList<PersistenceUnitMetadataHolder>(1);
String deploymentRootName = null;
// handle persistence.xml definition in the root of the war
if (deploymentRoot != null &&
(holder = deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null &&
!holder.getPersistenceUnits().isEmpty()) {
// assemble and install the PU service
puList.add(holder);
deploymentRootName = deploymentRoot.getRootName();
}
// look for persistence.xml in war files in the META-INF/persistence.xml directory
List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")
&& (((holder = resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null)
&& !holder.getPersistenceUnits().isEmpty())) {
// assemble and install the PU service
puList.add(holder);
}
}
if (startEarly) { // only add the WebNonTxEmCloserAction valve on the earlier invocation (AS7-6690).
deploymentUnit.addToAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS, new WebNonTxEmCloserAction());
}
ROOT_LOGGER.tracef("install persistence unit definitions for war %s", deploymentRootName);
addPuService(phaseContext, puList, startEarly, platform);
}
}
private static void handleEarDeployment(DeploymentPhaseContext phaseContext, boolean startEarly, Platform platform) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (isEarDeployment(deploymentUnit) && JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
// handle META-INF/persistence.xml
final List<ResourceRoot> deploymentRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
for (final ResourceRoot root : deploymentRoots) {
if (!SubDeploymentMarker.isSubDeployment(root)) {
PersistenceUnitMetadataHolder holder;
ArrayList<PersistenceUnitMetadataHolder> puList = new ArrayList<PersistenceUnitMetadataHolder>(1);
if (root != null &&
(holder = root.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS)) != null &&
!holder.getPersistenceUnits().isEmpty()) {
// assemble and install the PU service
puList.add(holder);
}
ROOT_LOGGER.tracef("install persistence unit definitions for ear %s",
root != null ? root.getRootName() : "null");
addPuService(phaseContext, puList, startEarly, platform);
}
}
}
}
/**
* Add one PU service per top level deployment that represents
*
*
* @param phaseContext
* @param puList
* @param startEarly
* @param platform
* @throws DeploymentUnitProcessingException
*
*/
private static void addPuService(final DeploymentPhaseContext phaseContext, final ArrayList<PersistenceUnitMetadataHolder> puList,
final boolean startEarly, final Platform platform)
throws DeploymentUnitProcessingException {
if (!puList.isEmpty()) {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
final ModuleClassLoader classLoader = module.getClassLoader();
for (PersistenceUnitMetadataHolder holder : puList) {
setAnnotationIndexes(holder, deploymentUnit);
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
// only start the persistence unit if JPA_CONTAINER_MANAGED is true
String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
boolean deployPU = (jpaContainerManaged == null? true : Boolean.parseBoolean(jpaContainerManaged));
if (deployPU) {
final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(deploymentUnit);
final PersistenceProvider provider = lookupProvider(pu, persistenceProviderDeploymentHolder, deploymentUnit);
final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor(pu, persistenceProviderDeploymentHolder, deploymentUnit, provider, platform);
final List<PersistenceProviderIntegratorAdaptor> integratorAdaptors = getPersistenceProviderIntegratorAdaptors(deploymentUnit);
final boolean twoPhaseBootStrapCapable = (adaptor instanceof TwoPhaseBootstrapCapable) && Configuration.allowTwoPhaseBootstrap(pu);
if (startEarly) {
if (twoPhaseBootStrapCapable) {
deployPersistenceUnitPhaseOne(deploymentUnit, eeModuleDescription, serviceTarget,
classLoader, pu, adaptor, integratorAdaptors);
}
else if (false == Configuration.needClassFileTransformer(pu)) {
// will start later when startEarly == false
ROOT_LOGGER.tracef("persistence unit %s in deployment %s is configured to not need class transformer to be set, no class rewriting will be allowed",
pu.getPersistenceUnitName(), deploymentUnit.getName());
}
else {
// we need class file transformer to work, don't allow Jakarta Contexts and Dependency Injection bean manager to be access since that
// could cause application classes to be loaded (workaround by setting jboss.as.jpa.classtransformer to false). WFLY-1463
final boolean allowCdiBeanManagerAccess = false;
deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget,
classLoader, pu, provider, adaptor, integratorAdaptors, allowCdiBeanManagerAccess);
}
}
else { // !startEarly
if (twoPhaseBootStrapCapable) {
deployPersistenceUnitPhaseTwo(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor, integratorAdaptors);
} else if (false == Configuration.needClassFileTransformer(pu)) {
final boolean allowCdiBeanManagerAccess = true;
// PUs that have Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false will start during INSTALL phase
deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget,
classLoader, pu, provider, adaptor, integratorAdaptors, allowCdiBeanManagerAccess);
}
}
}
else {
ROOT_LOGGER.tracef("persistence unit %s in deployment %s is not container managed (%s is set to false)",
pu.getPersistenceUnitName(), deploymentUnit.getName(), Configuration.JPA_CONTAINER_MANAGED);
}
}
}
}
}
/**
* start the persistence unit in one phase
*
* @param deploymentUnit
* @param eeModuleDescription
* @param serviceTarget
* @param classLoader
* @param pu
* @param provider
* @param adaptor
* @param integratorAdaptors Adapters for integrators, e.g. Hibernate Search.
* @param allowCdiBeanManagerAccess
* @throws DeploymentUnitProcessingException
*/
private static void deployPersistenceUnit(
final DeploymentUnit deploymentUnit,
final EEModuleDescription eeModuleDescription,
final ServiceTarget serviceTarget,
final ModuleClassLoader classLoader,
final PersistenceUnitMetadata pu,
final PersistenceProvider provider,
final PersistenceProviderAdaptor adaptor,
final List<PersistenceProviderIntegratorAdaptor> integratorAdaptors,
final boolean allowCdiBeanManagerAccess) throws DeploymentUnitProcessingException {
pu.setClassLoader(classLoader);
TransactionManager transactionManager = ContextTransactionManager.getInstance();
TransactionSynchronizationRegistry transactionSynchronizationRegistry = deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY);
CapabilityServiceSupport capabilitySupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
try {
ValidatorFactory validatorFactory = null;
final HashMap<String, Object> properties = new HashMap<>();
CapabilityServiceSupport css = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (!ValidationMode.NONE.equals(pu.getValidationMode())
&& css.hasCapability("org.wildfly.bean-validation")) {
// Get the Jakarta Contexts and Dependency Injection enabled ValidatorFactory
validatorFactory = deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);
}
BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation = registerJPAEntityListenerRegister(deploymentUnit, capabilitySupport);
final PersistenceAdaptorRemoval persistenceAdaptorRemoval = new PersistenceAdaptorRemoval(pu, adaptor);
deploymentUnit.addToAttachmentList(REMOVAL_KEY, persistenceAdaptorRemoval);
// add persistence provider specific properties
adaptor.addProviderProperties(properties, pu);
// add persistence provider integrator specific properties
for (PersistenceProviderIntegratorAdaptor integratorAdaptor : integratorAdaptors) {
integratorAdaptor.addIntegratorProperties(properties, pu);
}
final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
deploymentUnit.putAttachment(JpaAttachments.PERSISTENCE_UNIT_SERVICE_KEY, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, puServiceName);
final PersistenceUnitServiceImpl service =
new PersistenceUnitServiceImpl(properties, classLoader, pu, adaptor, integratorAdaptors, provider,
PersistenceUnitRegistryImpl.INSTANCE,
deploymentUnit.getServiceName(), validatorFactory,
deploymentUnit.getAttachment(org.jboss.as.ee.naming.Attachments.JAVA_NAMESPACE_SETUP_ACTION),
beanManagerAfterDeploymentValidation );
ServiceBuilder<PersistenceUnitService> builder = serviceTarget.addService(puServiceName, service);
boolean useDefaultDataSource = Configuration.allowDefaultDataSourceUse(pu);
final String jtaDataSource = adjustJndi(pu.getJtaDataSourceName());
final String nonJtaDataSource = adjustJndi(pu.getNonJtaDataSourceName());
if (jtaDataSource != null && jtaDataSource.length() > 0) {
if (jtaDataSource.equals(EE_DEFAULT_DATASOURCE)) { // explicit use of default datasource
useDefaultDataSource = true;
}
else {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, jtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
useDefaultDataSource = false;
}
}
if (nonJtaDataSource != null && nonJtaDataSource.length() > 0) {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, nonJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getNonJtaDataSourceInjector()));
useDefaultDataSource = false;
}
// JPA 2.0 8.2.1.5, container provides default Jakarta Transactions datasource
if (useDefaultDataSource) {
// try the default datasource defined in the ee subsystem
String defaultJtaDataSource = null;
if (eeModuleDescription != null) {
defaultJtaDataSource = eeModuleDescription.getDefaultResourceJndiNames().getDataSource();
}
if (defaultJtaDataSource == null ||
defaultJtaDataSource.isEmpty()) {
// try the datasource defined in the Jakarta Persistence subsystem
defaultJtaDataSource = adjustJndi(JPAService.getDefaultDataSourceName());
}
if (defaultJtaDataSource != null &&
!defaultJtaDataSource.isEmpty()) {
builder.addDependency(ContextNames.bindInfoFor(defaultJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
ROOT_LOGGER.tracef("%s is using the default data source '%s'", puServiceName, defaultJtaDataSource);
}
}
// JPA 2.1 sections 3.5.1 + 9.1 require the Jakarta Contexts and Dependency Injection bean manager to be passed to the peristence provider
// if the persistence unit is contained in a deployment that is a Jakarta Contexts and Dependency Injection bean archive (has beans.xml).
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME) && allowCdiBeanManagerAccess) {
support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.addBeanManagerService(deploymentUnit, builder, service.getBeanManagerInjector());
}
try {
// save a thread local reference to the builder for setting up the second level cache dependencies
CacheDeploymentListener.setInternalDeploymentSupport(builder, capabilitySupport);
adaptor.addProviderDependencies(pu);
}
finally {
CacheDeploymentListener.clearInternalDeploymentSupport();
}
/**
* handle extension that binds a transaction scoped entity manager to specified JNDI location
*/
entityManagerBind(eeModuleDescription, serviceTarget, pu, puServiceName, transactionManager, transactionSynchronizationRegistry);
/**
* handle extension that binds an entity manager factory to specified JNDI location
*/
entityManagerFactoryBind(eeModuleDescription, serviceTarget, pu, puServiceName);
// get async executor from Services.addServerExecutorDependency
addServerExecutorDependency(builder, service.getExecutorInjector());
builder.install();
ROOT_LOGGER.tracef("added PersistenceUnitService for '%s'. PU is ready for injector action.", puServiceName);
addManagementConsole(deploymentUnit, pu, adaptor, persistenceAdaptorRemoval);
} catch (ServiceRegistryException e) {
throw JpaLogger.ROOT_LOGGER.failedToAddPersistenceUnit(e, pu.getPersistenceUnitName());
}
}
/**
* first phase of starting the persistence unit
*
* @param deploymentUnit
* @param eeModuleDescription
* @param serviceTarget
* @param classLoader
* @param pu
* @param adaptor
* @param integratorAdaptors Adapters for integrators, e.g. Hibernate Search.
* @throws DeploymentUnitProcessingException
*/
private static void deployPersistenceUnitPhaseOne(
final DeploymentUnit deploymentUnit,
final EEModuleDescription eeModuleDescription,
final ServiceTarget serviceTarget,
final ModuleClassLoader classLoader,
final PersistenceUnitMetadata pu,
final PersistenceProviderAdaptor adaptor,
final List<PersistenceProviderIntegratorAdaptor> integratorAdaptors)
throws DeploymentUnitProcessingException {
CapabilityServiceSupport capabilitySupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
pu.setClassLoader(classLoader);
try {
final HashMap<String, Object> properties = new HashMap<>();
ProxyBeanManager proxyBeanManager = null;
// JPA 2.1 sections 3.5.1 + 9.1 require the Jakarta Contexts and Dependency Injection bean manager to be passed to the peristence provider
// if the persistence unit is contained in a deployment that is a Jakarta Contexts and Dependency Injection bean archive (has beans.xml).
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
boolean partOfWeldDeployment = false;
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
partOfWeldDeployment = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.isPartOfWeldDeployment(deploymentUnit);
}
if (partOfWeldDeployment) {
proxyBeanManager = new ProxyBeanManager();
registerJPAEntityListenerRegister(deploymentUnit, support); // register Jakarta Contexts and Dependency Injection extension before WeldDeploymentProcessor, which is important for
// EAR deployments that contain a WAR that has persistence units defined.
}
deploymentUnit.addToAttachmentList(REMOVAL_KEY, new PersistenceAdaptorRemoval(pu, adaptor));
// add persistence provider specific properties
adaptor.addProviderProperties(properties, pu);
// add persistence provider integrator specific properties
for (PersistenceProviderIntegratorAdaptor integratorAdaptor : integratorAdaptors) {
integratorAdaptor.addIntegratorProperties(properties, pu);
}
final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu).append(FIRST_PHASE);
deploymentUnit.putAttachment(JpaAttachments.PERSISTENCE_UNIT_SERVICE_KEY, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, puServiceName);
final PhaseOnePersistenceUnitServiceImpl service = new PhaseOnePersistenceUnitServiceImpl(classLoader, pu, adaptor, deploymentUnit.getServiceName(), proxyBeanManager);
service.getPropertiesInjector().inject(properties);
ServiceBuilder<PhaseOnePersistenceUnitServiceImpl> builder = serviceTarget.addService(puServiceName, service);
boolean useDefaultDataSource = Configuration.allowDefaultDataSourceUse(pu);
final String jtaDataSource = adjustJndi(pu.getJtaDataSourceName());
final String nonJtaDataSource = adjustJndi(pu.getNonJtaDataSourceName());
if (jtaDataSource != null && jtaDataSource.length() > 0) {
if (jtaDataSource.equals(EE_DEFAULT_DATASOURCE)) { // explicit use of default datasource
useDefaultDataSource = true;
}
else {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, jtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
useDefaultDataSource = false;
}
}
if (nonJtaDataSource != null && nonJtaDataSource.length() > 0) {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, nonJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getNonJtaDataSourceInjector()));
useDefaultDataSource = false;
}
// JPA 2.0 8.2.1.5, container provides default Jakarta Transactions datasource
if (useDefaultDataSource) {
// try the one defined in the Jakarta Persistence subsystem
String defaultJtaDataSource = null;
if (eeModuleDescription != null) {
defaultJtaDataSource = eeModuleDescription.getDefaultResourceJndiNames().getDataSource();
}
if (defaultJtaDataSource == null ||
defaultJtaDataSource.isEmpty()) {
// try the datasource defined in the JPA subsystem
defaultJtaDataSource = adjustJndi(JPAService.getDefaultDataSourceName());
}
if (defaultJtaDataSource != null &&
!defaultJtaDataSource.isEmpty()) {
builder.addDependency(ContextNames.bindInfoFor(defaultJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
ROOT_LOGGER.tracef("%s is using the default data source '%s'", puServiceName, defaultJtaDataSource);
}
}
try {
// save a thread local reference to the builder for setting up the second level cache dependencies
CacheDeploymentListener.setInternalDeploymentSupport(builder, capabilitySupport);
adaptor.addProviderDependencies(pu);
}
finally {
CacheDeploymentListener.clearInternalDeploymentSupport();
}
// get async executor from Services.addServerExecutorDependency
addServerExecutorDependency(builder, service.getExecutorInjector());
builder.install();
ROOT_LOGGER.tracef("added PersistenceUnitService (phase 1 of 2) for '%s'. PU is ready for injector action.", puServiceName);
} catch (ServiceRegistryException e) {
throw JpaLogger.ROOT_LOGGER.failedToAddPersistenceUnit(e, pu.getPersistenceUnitName());
}
}
/**
* Second phase of starting the persistence unit
*
* @param deploymentUnit
* @param eeModuleDescription
* @param serviceTarget
* @param classLoader
* @param pu
* @param provider
* @param adaptor
* @param integratorAdaptors Adapters for integrators, e.g. Hibernate Search.
* @throws DeploymentUnitProcessingException
*/
private static void deployPersistenceUnitPhaseTwo(
final DeploymentUnit deploymentUnit,
final EEModuleDescription eeModuleDescription,
final ServiceTarget serviceTarget,
final ModuleClassLoader classLoader,
final PersistenceUnitMetadata pu,
final PersistenceProvider provider,
final PersistenceProviderAdaptor adaptor,
final List<PersistenceProviderIntegratorAdaptor> integratorAdaptors) throws DeploymentUnitProcessingException {
TransactionManager transactionManager = ContextTransactionManager.getInstance();
TransactionSynchronizationRegistry transactionSynchronizationRegistry = deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY);
CapabilityServiceSupport capabilitySupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
pu.setClassLoader(classLoader);
try {
ValidatorFactory validatorFactory = null;
final HashMap<String, Object> properties = new HashMap<>();
if (!ValidationMode.NONE.equals(pu.getValidationMode())
&& capabilitySupport.hasCapability("org.wildfly.bean-validation")) {
// Get the Jakarta Contexts and Dependency Injection enabled ValidatorFactory
validatorFactory = deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);
}
BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation = registerJPAEntityListenerRegister(deploymentUnit, capabilitySupport);
final PersistenceAdaptorRemoval persistenceAdaptorRemoval = new PersistenceAdaptorRemoval(pu, adaptor);
deploymentUnit.addToAttachmentList(REMOVAL_KEY, persistenceAdaptorRemoval);
// add persistence provider specific properties
adaptor.addProviderProperties(properties, pu);
// add persistence provider integrator specific properties
for (PersistenceProviderIntegratorAdaptor integratorAdaptor : integratorAdaptors) {
integratorAdaptor.addIntegratorProperties(properties, pu);
}
final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
deploymentUnit.putAttachment(JpaAttachments.PERSISTENCE_UNIT_SERVICE_KEY, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, puServiceName);
deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, puServiceName);
final PersistenceUnitServiceImpl service = new PersistenceUnitServiceImpl(properties, classLoader, pu,
adaptor, integratorAdaptors, provider, PersistenceUnitRegistryImpl.INSTANCE,
deploymentUnit.getServiceName(), validatorFactory,
deploymentUnit.getAttachment(org.jboss.as.ee.naming.Attachments.JAVA_NAMESPACE_SETUP_ACTION),
beanManagerAfterDeploymentValidation);
ServiceBuilder<PersistenceUnitService> builder = serviceTarget.addService(puServiceName, service);
// the PU service has to depend on the JPAService which is responsible for setting up the necessary JPA infrastructure (like registering the cache EventListener(s))
// @see https://issues.jboss.org/browse/WFLY-1531 for details
builder.requires(JPAServiceNames.getJPAServiceName());
// add dependency on first phase
builder.addDependency(puServiceName.append(FIRST_PHASE), PhaseOnePersistenceUnitServiceImpl.class, service.getPhaseOnePersistenceUnitServiceImplInjector());
boolean useDefaultDataSource = Configuration.allowDefaultDataSourceUse(pu);
final String jtaDataSource = adjustJndi(pu.getJtaDataSourceName());
final String nonJtaDataSource = adjustJndi(pu.getNonJtaDataSourceName());
if (jtaDataSource != null && jtaDataSource.length() > 0) {
if (jtaDataSource.equals(EE_DEFAULT_DATASOURCE)) { // explicit use of default datasource
useDefaultDataSource = true;
}
else {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, jtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
useDefaultDataSource = false;
}
}
if (nonJtaDataSource != null && nonJtaDataSource.length() > 0) {
builder.addDependency(ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, nonJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getNonJtaDataSourceInjector()));
useDefaultDataSource = false;
}
// JPA 2.0 8.2.1.5, container provides default Jakarta Transactions datasource
if (useDefaultDataSource) {
// try the default datasource defined in the ee subsystem
String defaultJtaDataSource = null;
if (eeModuleDescription != null) {
defaultJtaDataSource = eeModuleDescription.getDefaultResourceJndiNames().getDataSource();
}
if (defaultJtaDataSource == null ||
defaultJtaDataSource.isEmpty()) {
// try the datasource defined in the Jakarta Persistence subsystem
defaultJtaDataSource = adjustJndi(JPAService.getDefaultDataSourceName());
}
if (defaultJtaDataSource != null &&
!defaultJtaDataSource.isEmpty()) {
builder.addDependency(ContextNames.bindInfoFor(defaultJtaDataSource).getBinderServiceName(), ManagedReferenceFactory.class, new ManagedReferenceFactoryInjector(service.getJtaDataSourceInjector()));
ROOT_LOGGER.tracef("%s is using the default data source '%s'", puServiceName, defaultJtaDataSource);
}
}
// JPA 2.1 sections 3.5.1 + 9.1 require the Jakarta Contexts and Dependency Injection bean manager to be passed to the persistence provider
// if the persistence unit is contained in a deployment that is a Jakarta Contexts and Dependency Injection bean archive (has beans.xml).
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
.addBeanManagerService(deploymentUnit, builder, service.getBeanManagerInjector());
}
try {
// save a thread local reference to the builder for setting up the second level cache dependencies
CacheDeploymentListener.setInternalDeploymentSupport(builder, capabilitySupport);
adaptor.addProviderDependencies(pu);
}
finally {
CacheDeploymentListener.clearInternalDeploymentSupport();
}
/**
* handle extension that binds a transaction scoped entity manager to specified JNDI location
*/
entityManagerBind(eeModuleDescription, serviceTarget, pu, puServiceName, transactionManager, transactionSynchronizationRegistry);
/**
* handle extension that binds an entity manager factory to specified JNDI location
*/
entityManagerFactoryBind(eeModuleDescription, serviceTarget, pu, puServiceName);
// get async executor from Services.addServerExecutorDependency
addServerExecutorDependency(builder, service.getExecutorInjector());
builder.install();
ROOT_LOGGER.tracef("added PersistenceUnitService (phase 2 of 2) for '%s'. PU is ready for injector action.", puServiceName);
addManagementConsole(deploymentUnit, pu, adaptor, persistenceAdaptorRemoval);
} catch (ServiceRegistryException e) {
throw JpaLogger.ROOT_LOGGER.failedToAddPersistenceUnit(e, pu.getPersistenceUnitName());
}
}
private static void entityManagerBind(EEModuleDescription eeModuleDescription, ServiceTarget serviceTarget, final PersistenceUnitMetadata pu, ServiceName puServiceName, TransactionManager transactionManager, TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
if (pu.getProperties().containsKey(ENTITYMANAGER_JNDI_PROPERTY)) {
String jndiName = pu.getProperties().get(ENTITYMANAGER_JNDI_PROPERTY).toString();
final ContextNames.BindInfo bindingInfo;
if (jndiName.startsWith("java:")) {
bindingInfo = ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, jndiName);
}
else {
bindingInfo = ContextNames.bindInfoFor(jndiName);
}
ROOT_LOGGER.tracef("binding the transaction scoped entity manager to jndi name '%s'", bindingInfo.getAbsoluteJndiName());
final BinderService binderService = new BinderService(bindingInfo.getBindName());
serviceTarget.addService(bindingInfo.getBinderServiceName(), binderService)
.addDependency(bindingInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.addDependency(puServiceName, PersistenceUnitServiceImpl.class, new Injector<PersistenceUnitServiceImpl>() {
@Override
public void inject(final PersistenceUnitServiceImpl value) throws
InjectionException {
binderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(
new TransactionScopedEntityManager(
pu.getScopedPersistenceUnitName(),
Collections.emptyMap(),
value.getEntityManagerFactory(),
SynchronizationType.SYNCHRONIZED, transactionSynchronizationRegistry, transactionManager)));
}
@Override
public void uninject() {
binderService.getNamingStoreInjector().uninject();
}
}).install();
}
}
private static void entityManagerFactoryBind(EEModuleDescription eeModuleDescription, ServiceTarget serviceTarget, PersistenceUnitMetadata pu, ServiceName puServiceName) {
if (pu.getProperties().containsKey(ENTITYMANAGERFACTORY_JNDI_PROPERTY)) {
String jndiName = pu.getProperties().get(ENTITYMANAGERFACTORY_JNDI_PROPERTY).toString();
final ContextNames.BindInfo bindingInfo;
if (jndiName.startsWith("java:")) {
bindingInfo = ContextNames.bindInfoForEnvEntry(eeModuleDescription.getApplicationName(), eeModuleDescription.getModuleName(), eeModuleDescription.getModuleName(), false, jndiName);
}
else {
bindingInfo = ContextNames.bindInfoFor(jndiName);
}
ROOT_LOGGER.tracef("binding the entity manager factory to jndi name '%s'", bindingInfo.getAbsoluteJndiName());
final BinderService binderService = new BinderService(bindingInfo.getBindName());
serviceTarget.addService(bindingInfo.getBinderServiceName(), binderService)
.addDependency(bindingInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector())
.addDependency(puServiceName, PersistenceUnitServiceImpl.class, new Injector<PersistenceUnitServiceImpl>() {
@Override
public void inject(final PersistenceUnitServiceImpl value) throws
InjectionException {
binderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(value.getEntityManagerFactory()));
}
@Override
public void uninject() {
binderService.getNamingStoreInjector().uninject();
}
}).install();
}
}
/**
* Setup the annotation index map
*
* @param puHolder
* @param deploymentUnit
*/
private static void setAnnotationIndexes(
final PersistenceUnitMetadataHolder puHolder,
DeploymentUnit deploymentUnit ) {
final Map<URL, Index> annotationIndexes = new HashMap<>();
do {
for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
final Index index = root.getAttachment(Attachments.ANNOTATION_INDEX);
if (index != null) {
try {
ROOT_LOGGER.tracef("adding '%s' to annotation index map", root.getRoot().toURL());
annotationIndexes.put(root.getRoot().toURL(), index);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
deploymentUnit = deploymentUnit.getParent(); // get annotation indexes for top level also
}
while (deploymentUnit != null);
for (PersistenceUnitMetadata pu : puHolder.getPersistenceUnits()) {
pu.setAnnotationIndex(annotationIndexes); // hold onto the annotation index for Persistence Provider use during deployment
}
}
private static String adjustJndi(String dataSourceName) {
if (dataSourceName != null && dataSourceName.length() > 0 && !dataSourceName.startsWith("java:")) {
if (dataSourceName.startsWith("jboss/")) {
return "java:" + dataSourceName;
}
return "java:/" + dataSourceName;
}
return dataSourceName;
}
/**
* Get the persistence provider adaptor. Will load the adapter module if needed.
*
*
* @param pu
* @param persistenceProviderDeploymentHolder
*
* @param provider
* @param platform
* @return
* @throws DeploymentUnitProcessingException
*
*/
private static PersistenceProviderAdaptor getPersistenceProviderAdaptor(
final PersistenceUnitMetadata pu,
final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder,
final DeploymentUnit deploymentUnit,
final PersistenceProvider provider,
final Platform platform) throws
DeploymentUnitProcessingException {
String adapterClass = pu.getProperties().getProperty(Configuration.ADAPTER_CLASS);
/**
* use adapter packaged in application deployment.
*/
if (persistenceProviderDeploymentHolder != null && adapterClass != null) {
List<PersistenceProviderAdaptor> persistenceProviderAdaptors = persistenceProviderDeploymentHolder.getAdapters();
for(PersistenceProviderAdaptor persistenceProviderAdaptor:persistenceProviderAdaptors) {
if(adapterClass.equals(persistenceProviderAdaptor.getClass().getName())) {
return persistenceProviderAdaptor;
}
}
}
String adaptorModule = pu.getProperties().getProperty(Configuration.ADAPTER_MODULE);
PersistenceProviderAdaptor adaptor;
adaptor = getPerDeploymentSharedPersistenceProviderAdaptor(deploymentUnit, adaptorModule, provider);
if (adaptor == null) {
try {
// will load the persistence provider adaptor (integration classes). if adaptorModule is null
// the noop adaptor is returned (can be used against any provider but the integration classes
// are handled externally via properties or code in the persistence provider).
if (adaptorModule != null) { // legacy way of loading adapter module
adaptor = PersistenceProviderAdaptorLoader.loadPersistenceAdapterModule(adaptorModule, platform, createManager(deploymentUnit));
}
else {
adaptor = PersistenceProviderAdaptorLoader.loadPersistenceAdapter(provider, platform, createManager(deploymentUnit));
}
} catch (ModuleLoadException e) {
throw JpaLogger.ROOT_LOGGER.persistenceProviderAdaptorModuleLoadError(e, adaptorModule);
}
adaptor = savePerDeploymentSharedPersistenceProviderAdaptor(deploymentUnit, adaptorModule, adaptor, provider);
}
if (adaptor == null) {
throw JpaLogger.ROOT_LOGGER.failedToGetAdapter(pu.getPersistenceProviderClassName());
}
return adaptor;
}
private static List<PersistenceProviderIntegratorAdaptor> getPersistenceProviderIntegratorAdaptors(DeploymentUnit deploymentUnit)
throws DeploymentUnitProcessingException {
List<String> integratorAdaptorModuleNames = deploymentUnit.getAttachmentList(JpaAttachments.INTEGRATOR_ADAPTOR_MODULE_NAMES);
List<PersistenceProviderIntegratorAdaptor> integratorAdaptorList = new ArrayList<>();
CompositeIndex compositeIndex = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
for (String moduleName : integratorAdaptorModuleNames) {
try {
integratorAdaptorList.addAll(PersistenceProviderAdaptorLoader.loadPersistenceProviderIntegratorModule(moduleName, compositeIndex.getIndexes()));
} catch (RuntimeException | ModuleLoadException e) {
throw JpaLogger.ROOT_LOGGER.cannotLoadPersistenceProviderIntegratorModule(e, moduleName);
}
}
return integratorAdaptorList;
}
private static JtaManagerImpl createManager(DeploymentUnit deploymentUnit) {
return new JtaManagerImpl(deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY));
}
/**
* Will save the PersistenceProviderAdaptor at the top level application deployment unit level for sharing with other persistence units
*
* @param deploymentUnit
* @param adaptorModule
* @param adaptor
* @param provider
* @return the application level shared PersistenceProviderAdaptor (which may of been set by a different thread)
*/
private static PersistenceProviderAdaptor savePerDeploymentSharedPersistenceProviderAdaptor(DeploymentUnit deploymentUnit, String adaptorModule, PersistenceProviderAdaptor adaptor, PersistenceProvider provider) {
if (deploymentUnit.getParent() != null) {
deploymentUnit = deploymentUnit.getParent();
}
synchronized (deploymentUnit) {
Map<String,PersistenceProviderAdaptor> map = deploymentUnit.getAttachment(providerAdaptorMapKey);
String key;
if (adaptorModule != null) {
key = adaptorModule; // handle legacy adapter module
}
else {
key = provider.getClass().getName();
}
PersistenceProviderAdaptor current = map.get(key);
// saved if not already set by another thread
if (current == null) {
map.put(key, adaptor);
current = adaptor;
}
return current;
}
}
private static PersistenceProviderAdaptor getPerDeploymentSharedPersistenceProviderAdaptor(DeploymentUnit deploymentUnit, String adaptorModule, PersistenceProvider provider) {
if (deploymentUnit.getParent() != null) {
deploymentUnit = deploymentUnit.getParent();
}
synchronized (deploymentUnit) {
Map<String,PersistenceProviderAdaptor> map = deploymentUnit.getAttachment(providerAdaptorMapKey);
if( map == null) {
map = new HashMap<>();
deploymentUnit.putAttachment(providerAdaptorMapKey, map);
}
String key;
if (adaptorModule != null) {
key = adaptorModule; // handle legacy adapter module
}
else {
key = provider.getClass().getName();
}
return map.get(key);
}
}
/**
* Look up the persistence provider
*
*
* @param pu
* @param deploymentUnit
* @return
*/
private static PersistenceProvider lookupProvider(
PersistenceUnitMetadata pu,
PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder,
DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
/**
* check if the deployment is already associated with the specified persistence provider
*/
Map<String, PersistenceProvider> providerMap = persistenceProviderDeploymentHolder != null ?
persistenceProviderDeploymentHolder.getProviders() : null;
if (providerMap != null) {
synchronized (providerMap) {
if(providerMap.containsKey(pu.getPersistenceProviderClassName())){
ROOT_LOGGER.tracef("deployment %s is using %s", deploymentUnit.getName(), pu.getPersistenceProviderClassName());
return providerMap.get(pu.getPersistenceProviderClassName());
}
}
}
String configuredPersistenceProviderModule = pu.getProperties().getProperty(Configuration.PROVIDER_MODULE);
String persistenceProviderClassName = pu.getPersistenceProviderClassName();
if (persistenceProviderClassName == null) {
persistenceProviderClassName = Configuration.PROVIDER_CLASS_DEFAULT;
}
/**
* locate persistence provider in specified static module
*/
if (configuredPersistenceProviderModule != null) {
List<PersistenceProvider> providers;
if (Configuration.PROVIDER_MODULE_APPLICATION_SUPPLIED.equals(configuredPersistenceProviderModule)) {
try {
// load the persistence provider from the application deployment
final ModuleClassLoader classLoader = deploymentUnit.getAttachment(Attachments.MODULE).getClassLoader();
PersistenceProvider provider = PersistenceProviderLoader.loadProviderFromDeployment(classLoader, persistenceProviderClassName);
providers = new ArrayList<>();
providers.add(provider);
PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
return provider;
} catch (ClassNotFoundException e) {
throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
} catch (InstantiationException e) {
throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
} catch (IllegalAccessException e) {
throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
}
} else {
try {
providers = PersistenceProviderLoader.loadProviderModuleByName(configuredPersistenceProviderModule);
PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
PersistenceProvider provider = getProviderByName(pu, providers);
if (provider != null) {
return provider;
}
} catch (ModuleLoadException e) {
throw JpaLogger.ROOT_LOGGER.cannotLoadPersistenceProviderModule(e, configuredPersistenceProviderModule, persistenceProviderClassName);
}
}
}
// try to determine the static module name based on the persistence provider class name
String providerNameDerivedFromClassName = Configuration.getProviderModuleNameFromProviderClassName(persistenceProviderClassName);
// see if the providerNameDerivedFromClassName has been loaded yet
PersistenceProvider provider = getProviderByName(pu);
// if we haven't loaded the provider yet, try loading now
if (provider == null && providerNameDerivedFromClassName != null) {
try {
List<PersistenceProvider> providers = PersistenceProviderLoader.loadProviderModuleByName(providerNameDerivedFromClassName);
PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
provider = getProviderByName(pu, providers);
} catch (ModuleLoadException e) {
throw JpaLogger.ROOT_LOGGER.cannotLoadPersistenceProviderModule(e, providerNameDerivedFromClassName, persistenceProviderClassName);
}
}
if (provider == null)
throw JpaLogger.ROOT_LOGGER.persistenceProviderNotFound(persistenceProviderClassName);
return provider;
}
private static PersistenceProvider getProviderByName(PersistenceUnitMetadata pu) {
return getProviderByName(pu, PersistenceProviderResolverHolder.getPersistenceProviderResolver().getPersistenceProviders());
}
private static PersistenceProvider getProviderByName(PersistenceUnitMetadata pu, List<PersistenceProvider> providers) {
String providerName = pu.getPersistenceProviderClassName();
for (PersistenceProvider provider : providers) {
if (providerName == null ||
provider.getClass().getName().equals(providerName) ||
// WFLY-4931 allow legacy Hibernate persistence provider name org.hibernate.ejb.HibernatePersistence to be used.
(provider.getClass().getName().equals(Configuration.PROVIDER_CLASS_DEFAULT) && providerName.equals(Configuration.PROVIDER_CLASS_HIBERNATE4_1))
) {
return provider; // return the provider that matched classname
}
}
return null;
}
/**
* The sub-deployment phases run in parallel, ensure that no deployment/sub-deployment moves past
* Phase.FIRST_MODULE_USE, until the applications persistence unit services are started.
*
* Note that some application persistence units will not be created until the Phase.INSTALL, in which case
* NEXT_PHASE_DEPS is not needed.
*/
private static void nextPhaseDependsOnPersistenceUnit(final DeploymentPhaseContext phaseContext, final Platform platform) throws DeploymentUnitProcessingException {
final DeploymentUnit topDeploymentUnit = DeploymentUtils.getTopDeploymentUnit(phaseContext.getDeploymentUnit());
final PersistenceUnitsInApplication persistenceUnitsInApplication = topDeploymentUnit.getAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION);
for(final PersistenceUnitMetadataHolder holder: persistenceUnitsInApplication.getPersistenceUnitHolders()) {
for (final PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
boolean deployPU = (jpaContainerManaged == null? true : Boolean.parseBoolean(jpaContainerManaged));
if (deployPU) {
final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(phaseContext.getDeploymentUnit());
final PersistenceProvider provider = lookupProvider(pu, persistenceProviderDeploymentHolder, phaseContext.getDeploymentUnit());
final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor(pu, persistenceProviderDeploymentHolder, phaseContext.getDeploymentUnit(), provider, platform);
final boolean twoPhaseBootStrapCapable = (adaptor instanceof TwoPhaseBootstrapCapable) && Configuration.allowTwoPhaseBootstrap(pu);
// only add the next phase dependency, if the persistence unit service is starting early.
if( Configuration.needClassFileTransformer(pu) && !Configuration.allowApplicationDefinedDatasource(pu)) {
// wait until the persistence unit service is started before starting the next deployment phase
phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, twoPhaseBootStrapCapable ? puServiceName.append(FIRST_PHASE) : puServiceName);
}
}
}
}
}
static boolean isEarDeployment(final DeploymentUnit context) {
return (DeploymentTypeMarker.isType(DeploymentType.EAR, context));
}
static boolean isWarDeployment(final DeploymentUnit context) {
return (DeploymentTypeMarker.isType(DeploymentType.WAR, context));
}
private static class ManagedReferenceFactoryInjector implements Injector<ManagedReferenceFactory> {
private volatile ManagedReference reference;
private final Injector<DataSource> dataSourceInjector;
public ManagedReferenceFactoryInjector(Injector<DataSource> dataSourceInjector) {
this.dataSourceInjector = dataSourceInjector;
}
@Override
public void inject(final ManagedReferenceFactory value) throws InjectionException {
this.reference = value.getReference();
dataSourceInjector.inject((DataSource) reference.getInstance());
}
@Override
public void uninject() {
reference.release();
reference = null;
dataSourceInjector.uninject();
}
}
/**
* add to management console (if ManagementAdapter is supported for provider).
* <p/>
* full path to management data will be:
* <p/>
* /deployment=Deployment/subsystem=jpa/hibernate-persistence-unit=FullyAppQualifiedPath#PersistenceUnitName/cache=EntityClassName
* <p/>
* example of full path:
* <p/>
* /deployment=jpa_SecondLevelCacheTestCase.jar/subsystem=jpa/hibernate-persistence-unit=jpa_SecondLevelCacheTestCase.jar#mypc/
* cache=org.jboss.as.test.integration.jpa.hibernate.Employee
* @param deploymentUnit
* @param pu
* @param adaptor
* @param persistenceAdaptorRemoval
*/
private static void addManagementConsole(final DeploymentUnit deploymentUnit, final PersistenceUnitMetadata pu,
final PersistenceProviderAdaptor adaptor, PersistenceAdaptorRemoval persistenceAdaptorRemoval) {
ManagementAdaptor managementAdaptor = adaptor.getManagementAdaptor();
// workaround for AS7-4441, if a custom hibernate.cache.region_prefix is specified, don't show the persistence
// unit in management console.
if (managementAdaptor != null &&
adaptor.doesScopedPersistenceUnitNameIdentifyCacheRegionName(pu)) {
final String providerLabel = managementAdaptor.getIdentificationLabel();
final String scopedPersistenceUnitName = pu.getScopedPersistenceUnitName();
Resource providerResource = JPAService.createManagementStatisticsResource(managementAdaptor, scopedPersistenceUnitName, deploymentUnit);
// Resource providerResource = managementAdaptor.createPersistenceUnitResource(scopedPersistenceUnitName, providerLabel);
ModelNode perPuNode = providerResource.getModel();
perPuNode.get(SCOPED_UNIT_NAME.getName()).set(pu.getScopedPersistenceUnitName());
// TODO this is a temporary hack into internals until DeploymentUnit exposes a proper Resource-based API
final Resource deploymentResource = deploymentUnit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE);
Resource subsystemResource;
synchronized (deploymentResource) {
subsystemResource = getOrCreateResource(deploymentResource, PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, "jpa"));
}
synchronized (subsystemResource) {
subsystemResource.registerChild(PathElement.pathElement(providerLabel, scopedPersistenceUnitName), providerResource);
// save the subsystemResource reference + path to scoped pu, so we can remove it during undeploy
persistenceAdaptorRemoval.registerManagementConsoleChild(subsystemResource, PathElement.pathElement(providerLabel, scopedPersistenceUnitName));
}
}
}
/**
* TODO this is a temporary hack into internals until DeploymentUnit exposes a proper Resource-based API
*/
private static Resource getOrCreateResource(final Resource parent, final PathElement element) {
synchronized (parent) {
if (parent.hasChild(element)) {
return parent.requireChild(element);
} else {
final Resource resource = Resource.Factory.create();
parent.registerChild(element, resource);
return resource;
}
}
}
private static PersistenceProviderDeploymentHolder getPersistenceProviderDeploymentHolder(DeploymentUnit deploymentUnit) {
deploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
return deploymentUnit.getAttachment(JpaAttachments.DEPLOYED_PERSISTENCE_PROVIDER);
}
private static BeanManagerAfterDeploymentValidation registerJPAEntityListenerRegister(DeploymentUnit deploymentUnit, CapabilityServiceSupport support) {
deploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
Optional<WeldCapability> weldCapability = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class);
if (weldCapability.get().isPartOfWeldDeployment(deploymentUnit)) {
synchronized (deploymentUnit) {
BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation = deploymentUnit.getAttachment(JpaAttachments.BEAN_MANAGER_AFTER_DEPLOYMENT_VALIDATION_ATTACHMENT_KEY);
if (null == beanManagerAfterDeploymentValidation) {
beanManagerAfterDeploymentValidation = new BeanManagerAfterDeploymentValidation();
deploymentUnit.putAttachment(JpaAttachments.BEAN_MANAGER_AFTER_DEPLOYMENT_VALIDATION_ATTACHMENT_KEY, beanManagerAfterDeploymentValidation);
weldCapability.get().registerExtensionInstance(beanManagerAfterDeploymentValidation, deploymentUnit);
}
return beanManagerAfterDeploymentValidation;
}
}
}
return new BeanManagerAfterDeploymentValidation(true);
}
private static class PersistenceAdaptorRemoval {
final PersistenceUnitMetadata pu;
final PersistenceProviderAdaptor adaptor;
volatile Resource subsystemResource;
volatile PathElement pathToScopedPu;
public PersistenceAdaptorRemoval(PersistenceUnitMetadata pu, PersistenceProviderAdaptor adaptor) {
this.pu = pu;
this.adaptor = adaptor;
}
private void cleanup() {
adaptor.cleanup(pu);
if(subsystemResource != null && pathToScopedPu != null) {
subsystemResource.removeChild(pathToScopedPu);
}
}
public void registerManagementConsoleChild(Resource subsystemResource, PathElement pathElement) {
this.subsystemResource = subsystemResource;
this.pathToScopedPu = pathElement;
}
}
private static AttachmentKey<AttachmentList<PersistenceAdaptorRemoval>> REMOVAL_KEY = AttachmentKey.createList(PersistenceAdaptorRemoval.class);
}
| 70,435 | 55.529695 | 343 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPAInterceptorProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.jpa.interceptor.SBInvocationInterceptor;
import org.jboss.as.jpa.interceptor.SFSBCreateInterceptor;
import org.jboss.as.jpa.interceptor.SFSBDestroyInterceptor;
import org.jboss.as.jpa.interceptor.SFSBInvocationInterceptor;
import org.jboss.as.jpa.interceptor.SFSBPreCreateInterceptor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* @author Stuart Douglas
*/
public class JPAInterceptorProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
for (ComponentDescription component : moduleDescription.getComponentDescriptions()) {
if (component instanceof SessionBeanComponentDescription) {
ROOT_LOGGER.tracef("registering session bean Jakarta Interceptors for component '%s' in '%s'", component.getComponentName(), deploymentUnit.getName());
registerSessionBeanInterceptors((SessionBeanComponentDescription) component, deploymentUnit);
}
}
}
// Register our listeners on SFSB that will be created
private void registerSessionBeanInterceptors(SessionBeanComponentDescription componentDescription, final DeploymentUnit deploymentUnit) {
// if it's a SFSB then setup appropriate Jakarta Interceptors
if (componentDescription.isStateful()) {
// first setup the post construct and pre destroy component Jakarta Interceptors
componentDescription.getConfigurators().addFirst(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws
DeploymentUnitProcessingException {
configuration.addPostConstructInterceptor(SFSBPreCreateInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.JPA_SFSB_PRE_CREATE);
configuration.addPostConstructInterceptor(SFSBCreateInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.JPA_SFSB_CREATE);
configuration.addPreDestroyInterceptor(SFSBDestroyInterceptor.FACTORY, InterceptorOrder.ComponentPreDestroy.JPA_SFSB_DESTROY);
configuration.addComponentInterceptor(SFSBInvocationInterceptor.FACTORY, InterceptorOrder.Component.JPA_SFSB_INTERCEPTOR, false);
//we need to serialized the entity manager state
configuration.getInterceptorContextKeys().add(SFSBInvocationInterceptor.CONTEXT_KEY);
}
});
}
// register interceptor on stateful/stateless SB with transactional entity manager.
if ((componentDescription.isStateful() || componentDescription.isStateless())) {
componentDescription.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws
DeploymentUnitProcessingException {
configuration.addComponentInterceptor(SBInvocationInterceptor.FACTORY, InterceptorOrder.Component.JPA_SESSION_BEAN_INTERCEPTOR, false);
}
});
}
}
}
| 5,257 | 56.152174 | 167 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/CacheDeploymentHelper.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.jpa.processor.secondlevelcache.CacheDeploymentListener;
import org.jipijapa.event.impl.EventListenerRegistration;
/**
* CacheDeploymentHelper
*
* @author Scott Marlow
*/
public class CacheDeploymentHelper {
private volatile CacheDeploymentListener listener;
public void register() {
listener = new CacheDeploymentListener();
EventListenerRegistration.add(listener);
}
public void unregister() {
if (listener != null) {
EventListenerRegistration.remove(listener);
listener = null;
}
}
}
| 1,651 | 32.714286 | 75 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPADelegatingClassFileTransformer.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.nio.ByteBuffer;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.modules.ClassTransformer;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.manager.action.GetAccessControlContextAction;
/**
* Helps implement PersistenceUnitInfo.addClassTransformer() by using DelegatingClassTransformer
*
* @author Scott Marlow
*/
class JPADelegatingClassFileTransformer implements ClassTransformer {
private final PersistenceUnitMetadata persistenceUnitMetadata;
public JPADelegatingClassFileTransformer(PersistenceUnitMetadata pu) {
persistenceUnitMetadata = pu;
}
@Override
public ByteBuffer transform(ClassLoader classLoader, String className, ProtectionDomain protectionDomain, ByteBuffer classBytes)
throws IllegalArgumentException {
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
PrivilegedAction<ByteBuffer> privilegedAction =
new PrivilegedAction<ByteBuffer>() {
// run as security privileged action
@Override
public ByteBuffer run() {
byte[] transformedBuffer = getBytes(classBytes);
boolean transformed = false;
for (jakarta.persistence.spi.ClassTransformer transformer : persistenceUnitMetadata.getTransformers()) {
if (ROOT_LOGGER.isTraceEnabled())
ROOT_LOGGER.tracef("rewrite entity class '%s' using transformer '%s' for '%s'", className,
transformer.getClass().getName(),
persistenceUnitMetadata.getScopedPersistenceUnitName());
byte[] result;
try {
// parameter classBeingRedefined is always passed as null
// because we won't ever be called to transform already loaded classes.
result = transformer.transform(classLoader, className, null, protectionDomain, transformedBuffer);
} catch (Exception e) {
throw JpaLogger.ROOT_LOGGER.invalidClassFormat(e, className);
}
if (result != null) {
transformedBuffer = result;
transformed = true;
if (ROOT_LOGGER.isTraceEnabled())
ROOT_LOGGER.tracef("entity class '%s' was rewritten", className);
}
}
return transformed ? ByteBuffer.wrap(transformedBuffer) : null;
}
};
return WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
}
private byte[] getBytes(ByteBuffer classBytes) {
if (classBytes == null) {
return null;
}
final int position = classBytes.position();
final int limit = classBytes.limit();
final byte[] bytes;
if (classBytes.hasArray() && classBytes.arrayOffset() == 0 && position == 0 && limit == classBytes.capacity()) {
bytes = classBytes.array();
} else {
bytes = new byte[limit - position];
classBytes.get(bytes);
classBytes.position(position);
}
return bytes;
}
}
| 4,962 | 44.118182 | 132 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPAClassFileTransformerProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.module.DelegatingClassTransformer;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Deployment processor which ensures the persistence provider ClassFileTransformer are used.
*
* @author Scott Marlow
*/
public class JPAClassFileTransformerProcessor implements DeploymentUnitProcessor {
public JPAClassFileTransformerProcessor() {
}
/**
* Add dependencies for modules required for Jakarta Persistence deployments
*/
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
setClassLoaderTransformer(deploymentUnit);
}
private void setClassLoaderTransformer(DeploymentUnit deploymentUnit) {
// (AS7-2233) each persistence unit can use a persistence provider, that might need
// to use ClassTransformers. Providers that need class transformers will add them
// during the call to CreateContainerEntityManagerFactory.
DelegatingClassTransformer transformer = deploymentUnit.getAttachment(DelegatingClassTransformer.ATTACHMENT_KEY);
boolean appContainsPersistenceProviderJars = false; // remove when we revert WFLY-10520
if ( transformer != null) {
for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {
PersistenceUnitMetadataHolder holder = resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
if (holder != null) {
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
if (Configuration.needClassFileTransformer(pu)) {
transformer.addTransformer(new JPADelegatingClassFileTransformer(pu));
}
}
}
}
}
}
}
| 3,478 | 44.776316 | 131 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceRefProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContextType;
import jakarta.persistence.SynchronizationType;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.DeploymentDescriptorEnvironment;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.LookupInjectionSource;
import org.jboss.as.ee.component.ResourceInjectionTarget;
import org.jboss.as.ee.component.deployers.AbstractDeploymentDescriptorBindingsProcessor;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.jpa.container.PersistenceUnitSearch;
import org.jboss.as.jpa.injectors.PersistenceContextInjectionSource;
import org.jboss.as.jpa.injectors.PersistenceUnitInjectionSource;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.metadata.javaee.spec.Environment;
import org.jboss.metadata.javaee.spec.PersistenceContextReferenceMetaData;
import org.jboss.metadata.javaee.spec.PersistenceContextReferencesMetaData;
import org.jboss.metadata.javaee.spec.PersistenceContextSynchronizationType;
import org.jboss.metadata.javaee.spec.PersistenceContextTypeDescription;
import org.jboss.metadata.javaee.spec.PersistenceUnitReferenceMetaData;
import org.jboss.metadata.javaee.spec.PersistenceUnitReferencesMetaData;
import org.jboss.metadata.javaee.spec.PropertiesMetaData;
import org.jboss.metadata.javaee.spec.PropertyMetaData;
import org.jboss.metadata.javaee.spec.RemoteEnvironment;
import org.jboss.msc.service.ServiceName;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Deployment processor responsible for processing persistence unit / context references from deployment descriptors.
*
* @author Stuart Douglas
*/
public class PersistenceRefProcessor extends AbstractDeploymentDescriptorBindingsProcessor {
@Override
protected List<BindingConfiguration> processDescriptorEntries(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ResourceInjectionTarget resourceInjectionTarget, final ComponentDescription componentDescription, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, final EEApplicationClasses applicationClasses) throws
DeploymentUnitProcessingException {
List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>();
bindings.addAll(getPersistenceUnitRefs(deploymentUnit, environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget));
bindings.addAll(getPersistenceContextRefs(deploymentUnit, environment, classLoader, deploymentReflectionIndex, resourceInjectionTarget));
return bindings;
}
/**
* Resolves persistence-unit-ref
*
* @param environment The environment to resolve the elements for
* @param classLoader The deployment class loader
* @param deploymentReflectionIndex The reflection index
* @return The bindings for the environment entries
*/
private List<BindingConfiguration> getPersistenceUnitRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionTarget resourceInjectionTarget) throws
DeploymentUnitProcessingException {
final List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
if (environment.getEnvironment() == null) {
return bindingConfigurations;
}
PersistenceUnitReferencesMetaData persistenceUnitRefs = environment.getEnvironment().getPersistenceUnitRefs();
if (persistenceUnitRefs != null) {
if (!persistenceUnitRefs.isEmpty()) {
JPADeploymentMarker.mark(deploymentUnit);
}
for (PersistenceUnitReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw JpaLogger.ROOT_LOGGER.cannotSpecifyBoth("<lookup-name>", lookup, "persistence-unit-name", persistenceUnitName, "<persistence-unit-ref/>", resourceInjectionTarget);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManagerFactory.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else {
InjectionSource puBindingSource = this.getPersistenceUnitBindingSource(deploymentUnit, persistenceUnitName);
bindingConfiguration = new BindingConfiguration(name, puBindingSource);
}
bindingConfigurations.add(bindingConfiguration);
}
}
return bindingConfigurations;
}
/**
* Resolves persistence-unit-ref
*
* @param environment The environment to resolve the elements for
* @param classLoader The deployment class loader
* @param deploymentReflectionIndex The reflection index
* @return The bindings for the environment entries
*/
private List<BindingConfiguration> getPersistenceContextRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, ResourceInjectionTarget resourceInjectionTarget) throws
DeploymentUnitProcessingException {
List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
final RemoteEnvironment remoteEnvironment = environment.getEnvironment();
if (remoteEnvironment == null) {
return bindingConfigurations;
}
if (remoteEnvironment instanceof Environment) {
PersistenceContextReferencesMetaData persistenceUnitRefs = ((Environment) remoteEnvironment).getPersistenceContextRefs();
if (persistenceUnitRefs != null) {
for (PersistenceContextReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw JpaLogger.ROOT_LOGGER.cannotSpecifyBoth("<lookup-name>", lookup, "persistence-unit-name", persistenceUnitName, "<persistence-context-ref/>", resourceInjectionTarget);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(resourceInjectionTarget, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManager.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else {
PropertiesMetaData properties = puRef.getProperties();
Map<String, String> map = new HashMap<>();
if (properties != null) {
for (PropertyMetaData prop : properties) {
map.put(prop.getKey(), prop.getValue());
}
}
PersistenceContextType type = (puRef.getPersistenceContextType() == null || puRef.getPersistenceContextType() == PersistenceContextTypeDescription.TRANSACTION) ? PersistenceContextType.TRANSACTION : PersistenceContextType.EXTENDED ;
SynchronizationType synchronizationType =
(puRef.getPersistenceContextSynchronization() == null || PersistenceContextSynchronizationType.Synchronized.equals(puRef.getPersistenceContextSynchronization()))?
SynchronizationType.SYNCHRONIZED: SynchronizationType.UNSYNCHRONIZED;
InjectionSource pcBindingSource = this.getPersistenceContextBindingSource(deploymentUnit, persistenceUnitName, type, synchronizationType, map);
bindingConfiguration = new BindingConfiguration(name, pcBindingSource);
}
bindingConfigurations.add(bindingConfiguration);
}
}
}
return bindingConfigurations;
}
private InjectionSource getPersistenceUnitBindingSource(final DeploymentUnit deploymentUnit, final String unitName) throws
DeploymentUnitProcessingException {
final String searchName;
if (isEmpty(unitName)) {
searchName = null;
} else {
searchName = unitName;
}
final PersistenceUnitMetadata pu = PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, searchName);
if (null == pu) {
throw new DeploymentUnitProcessingException(JpaLogger.ROOT_LOGGER.persistenceUnitNotFound(searchName, deploymentUnit));
}
String scopedPuName = pu.getScopedPersistenceUnitName();
ServiceName puServiceName = getPuServiceName(scopedPuName);
return new PersistenceUnitInjectionSource(puServiceName, deploymentUnit.getServiceRegistry(), EntityManagerFactory.class.getName(), pu);
}
private InjectionSource getPersistenceContextBindingSource(
final DeploymentUnit deploymentUnit,
final String unitName,
PersistenceContextType type,
SynchronizationType synchronizationType,
Map properties) throws
DeploymentUnitProcessingException {
PersistenceUnitMetadata pu = getPersistenceUnit(deploymentUnit, unitName);
String scopedPuName = pu.getScopedPersistenceUnitName();
ServiceName puServiceName = getPuServiceName(scopedPuName);
// get deployment settings from top level du (jboss-all.xml is only parsed at the top level).
final JPADeploymentSettings jpaDeploymentSettings = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(JpaAttachments.DEPLOYMENT_SETTINGS_KEY);
return new PersistenceContextInjectionSource(type, synchronizationType, properties, puServiceName, deploymentUnit.getServiceRegistry(), scopedPuName, EntityManager.class.getName(), pu, jpaDeploymentSettings);
}
private PersistenceUnitMetadata getPersistenceUnit(final DeploymentUnit deploymentUnit, final String puName)
throws DeploymentUnitProcessingException {
PersistenceUnitMetadata pu = PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, puName);
if (null == pu) {
throw new DeploymentUnitProcessingException(JpaLogger.ROOT_LOGGER.persistenceUnitNotFound(puName, deploymentUnit));
}
return pu;
}
private ServiceName getPuServiceName(String scopedPuName)
throws DeploymentUnitProcessingException {
return PersistenceUnitServiceImpl.getPUServiceName(scopedPuName);
}
private boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
}
| 13,882 | 53.65748 | 371 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JpaAttachments.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.jpa.beanmanager.BeanManagerAfterDeploymentValidation;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.msc.service.ServiceName;
import jakarta.transaction.TransactionSynchronizationRegistry;
/**
* @author Stuart Douglas
* @author [email protected]
*/
public final class JpaAttachments {
public static final AttachmentKey<String> ADAPTOR_CLASS_NAME = AttachmentKey.create(String.class);
public static final AttachmentKey<JPADeploymentSettings> DEPLOYMENT_SETTINGS_KEY = AttachmentKey.create(JPADeploymentSettings.class);
public static final AttachmentKey<ServiceName> PERSISTENCE_UNIT_SERVICE_KEY = AttachmentKey.create(ServiceName.class);
public static final AttachmentKey<Void> LOCAL_TRANSACTION_PROVIDER = AttachmentKey.create(Void.class);
public static final AttachmentKey<TransactionSynchronizationRegistry> TRANSACTION_SYNCHRONIZATION_REGISTRY= AttachmentKey.create(TransactionSynchronizationRegistry.class);
/**
* List<PersistenceUnitMetadataImpl> that represents the Jakarta Persistence persistent units
*/
public static final AttachmentKey<PersistenceProviderDeploymentHolder> DEPLOYED_PERSISTENCE_PROVIDER = AttachmentKey.create(PersistenceProviderDeploymentHolder.class);
public static final AttachmentKey<BeanManagerAfterDeploymentValidation> BEAN_MANAGER_AFTER_DEPLOYMENT_VALIDATION_ATTACHMENT_KEY = AttachmentKey.create(BeanManagerAfterDeploymentValidation.class);
public static final AttachmentKey<AttachmentList<String>> INTEGRATOR_ADAPTOR_MODULE_NAMES = AttachmentKey.createList(String.class);
private JpaAttachments() {
}
}
| 2,892 | 47.216667 | 199 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceProviderHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.spi.PersistenceProvider;
import org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.persistenceprovider.PersistenceProviderResolverImpl;
import org.jboss.as.jpa.transaction.JtaManagerImpl;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.ServicesAttachment;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.Platform;
/**
* Deploy Jakarta Persistence Persistence providers that are found in the application deployment.
*
* @author Scott Marlow
*/
public class PersistenceProviderHandler {
private static final String PERSISTENCE_PROVIDER_CLASSNAME = PersistenceProvider.class.getName();
public static void deploy(final DeploymentPhaseContext phaseContext, final Platform platform) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES);
if (module != null && servicesAttachment != null) {
final ModuleClassLoader deploymentModuleClassLoader = module.getClassLoader();
PersistenceProvider provider;
// collect list of persistence providers packaged with the application
final List<String> providerNames = servicesAttachment.getServiceImplementations(PERSISTENCE_PROVIDER_CLASSNAME);
List<PersistenceProvider> providerList = new ArrayList<PersistenceProvider>();
for (String providerName : providerNames) {
try {
final Class<? extends PersistenceProvider> providerClass = deploymentModuleClassLoader.loadClass(providerName).asSubclass(PersistenceProvider.class);
final Constructor<? extends PersistenceProvider> constructor = providerClass.getConstructor();
provider = constructor.newInstance();
providerList.add(provider);
JpaLogger.ROOT_LOGGER.tracef("deployment %s is using its own copy of %s", deploymentUnit.getName(), providerName);
} catch (Exception e) {
throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, providerName);
}
}
if (!providerList.isEmpty()) {
final String adapterClass = deploymentUnit.getAttachment(JpaAttachments.ADAPTOR_CLASS_NAME);
PersistenceProviderAdaptor adaptor;
if (adapterClass != null) {
try {
adaptor = (PersistenceProviderAdaptor) deploymentModuleClassLoader.loadClass(adapterClass).newInstance();
adaptor.injectJtaManager(new JtaManagerImpl(deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY)));
adaptor.injectPlatform(platform);
ArrayList<PersistenceProviderAdaptor> adaptorList = new ArrayList<>();
adaptorList.add(adaptor);
PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providerList, adaptorList);
} catch (InstantiationException e) {
throw JpaLogger.ROOT_LOGGER.cannotCreateAdapter(e, adapterClass);
} catch (IllegalAccessException e) {
throw JpaLogger.ROOT_LOGGER.cannotCreateAdapter(e, adapterClass);
} catch (ClassNotFoundException e) {
throw JpaLogger.ROOT_LOGGER.cannotCreateAdapter(e, adapterClass);
}
} else {
// register the provider (no adapter specified)
PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providerList, null);
}
}
}
}
public static void finishDeploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = PersistenceProviderDeploymentHolder.getPersistenceProviderDeploymentHolder(deploymentUnit);
Map<String, PersistenceProvider> providerMap = persistenceProviderDeploymentHolder != null ?
persistenceProviderDeploymentHolder.getProviders() : null;
if (providerMap != null) {
Set<ClassLoader> deploymentClassLoaders = allDeploymentModuleClassLoaders(deploymentUnit);
synchronized (providerMap){
for(Map.Entry<String, PersistenceProvider> kv: providerMap.entrySet()){
PersistenceProviderResolverImpl.getInstance().addDeploymentSpecificPersistenceProvider(kv.getValue(), deploymentClassLoaders);
}
}
}
}
public static void undeploy(final DeploymentUnit deploymentUnit) {
Set<ClassLoader> deploymentClassLoaders = allDeploymentModuleClassLoaders(deploymentUnit);
PersistenceProviderResolverImpl.getInstance().clearCachedDeploymentSpecificProviders(deploymentClassLoaders);
}
/**
* returns the toplevel deployment module classloader and all subdeployment classloaders
*
* @param deploymentUnit
* @return
*/
private static Set<ClassLoader> allDeploymentModuleClassLoaders(DeploymentUnit deploymentUnit) {
Set<ClassLoader> deploymentClassLoaders = new HashSet<ClassLoader>();
final DeploymentUnit topDeploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
final Module toplevelModule = topDeploymentUnit.getAttachment(Attachments.MODULE);
if (toplevelModule != null) {
deploymentClassLoaders.add(toplevelModule.getClassLoader());
final List<DeploymentUnit> subDeployments = topDeploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS);
for (DeploymentUnit subDeploymentUnit: subDeployments) {
final Module subDeploymentModule = subDeploymentUnit.getAttachment(Attachments.MODULE);
if (subDeploymentModule != null) {
deploymentClassLoaders.add(subDeploymentModule.getClassLoader());
}
}
}
return deploymentClassLoaders;
}
}
| 8,106 | 51.303226 | 174 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPAAnnotationProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContextType;
import jakarta.persistence.PersistenceContexts;
import jakarta.persistence.PersistenceUnit;
import jakarta.persistence.PersistenceUnits;
import jakarta.persistence.SynchronizationType;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleClassDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.FieldInjectionTarget;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.InjectionTarget;
import org.jboss.as.ee.component.LookupInjectionSource;
import org.jboss.as.ee.component.MethodInjectionTarget;
import org.jboss.as.ee.component.ResourceInjectionConfiguration;
import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.jpa.container.PersistenceUnitSearch;
import org.jboss.as.jpa.injectors.PersistenceContextInjectionSource;
import org.jboss.as.jpa.injectors.PersistenceUnitInjectionSource;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.MethodInfo;
import org.jboss.msc.service.ServiceName;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* Handle PersistenceContext and PersistenceUnit annotations.
*
* @author Scott Marlow (based on ResourceInjectionAnnotationParsingProcessor)
*/
public class JPAAnnotationProcessor implements DeploymentUnitProcessor {
private static final DotName PERSISTENCE_CONTEXT_ANNOTATION_NAME = DotName.createSimple(PersistenceContext.class.getName());
private static final DotName PERSISTENCE_CONTEXTS_ANNOTATION_NAME = DotName.createSimple(PersistenceContexts.class.getName());
private static final DotName PERSISTENCE_UNIT_ANNOTATION_NAME = DotName.createSimple(PersistenceUnit.class.getName());
private static final DotName PERSISTENCE_UNITS_ANNOTATION_NAME = DotName.createSimple(PersistenceUnits.class.getName());
private static final String ENTITY_MANAGER_CLASS = "jakarta.persistence.EntityManager";
private static final String ENTITY_MANAGERFACTORY_CLASS = "jakarta.persistence.EntityManagerFactory";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX);
final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
// @PersistenceContext
List<AnnotationInstance> persistenceContexts = index.getAnnotations(PERSISTENCE_CONTEXT_ANNOTATION_NAME);
// create binding and injection configurations out of the @PersistenceContext annotations
this.processPersistenceAnnotations(deploymentUnit, eeModuleDescription, persistenceContexts, applicationClasses);
// @PersistenceContexts
List<AnnotationInstance> collectionPersistenceContexts = index.getAnnotations(PERSISTENCE_CONTEXTS_ANNOTATION_NAME);
// create binding and injection configurations out of the @PersistenceContext annotations
processPersistenceAnnotations(deploymentUnit, eeModuleDescription, collectionPersistenceContexts, applicationClasses);
// @PersistenceUnits
List<AnnotationInstance> collectionPersistenceunits = index.getAnnotations(PERSISTENCE_UNITS_ANNOTATION_NAME);
processPersistenceAnnotations(deploymentUnit, eeModuleDescription, collectionPersistenceunits, applicationClasses);
// @PersistenceUnit
List<AnnotationInstance> persistenceUnits = index.getAnnotations(PERSISTENCE_UNIT_ANNOTATION_NAME);
// create binding and injection configurations out of the @PersistenceUnit annotations
this.processPersistenceAnnotations(deploymentUnit, eeModuleDescription, persistenceUnits, applicationClasses);
// if we found any @PersistenceContext or @PersistenceUnit annotations then mark this as a Jakarta Persistence deployment
if (!persistenceContexts.isEmpty() || !persistenceUnits.isEmpty() ||
!collectionPersistenceContexts.isEmpty() || !collectionPersistenceunits.isEmpty()) {
JPADeploymentMarker.mark(deploymentUnit);
}
}
private void processPersistenceAnnotations(final DeploymentUnit deploymentUnit, final EEModuleDescription eeModuleDescription, List<AnnotationInstance> persistenceContexts, final EEApplicationClasses applicationClasses) throws
DeploymentUnitProcessingException {
for (AnnotationInstance annotation : persistenceContexts) {
ClassInfo declaringClass;
final AnnotationTarget annotationTarget = annotation.target();
if (annotationTarget instanceof FieldInfo) {
FieldInfo fieldInfo = (FieldInfo) annotationTarget;
declaringClass = fieldInfo.declaringClass();
EEModuleClassDescription eeModuleClassDescription = eeModuleDescription.addOrGetLocalClassDescription(declaringClass.name().toString());
this.processField(deploymentUnit, annotation, fieldInfo, eeModuleClassDescription);
} else if (annotationTarget instanceof MethodInfo) {
MethodInfo methodInfo = (MethodInfo) annotationTarget;
declaringClass = methodInfo.declaringClass();
EEModuleClassDescription eeModuleClassDescription = eeModuleDescription.addOrGetLocalClassDescription(declaringClass.name().toString());
this.processMethod(deploymentUnit, annotation, methodInfo, eeModuleClassDescription);
} else if (annotationTarget instanceof ClassInfo) {
declaringClass = (ClassInfo) annotationTarget;
EEModuleClassDescription eeModuleClassDescription = eeModuleDescription.addOrGetLocalClassDescription(declaringClass.name().toString());
this.processClass(deploymentUnit, annotation, eeModuleClassDescription);
}
}
}
private void processField(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation, final FieldInfo fieldInfo,
final EEModuleClassDescription eeModuleClassDescription) throws
DeploymentUnitProcessingException {
final String fieldName = fieldInfo.name();
final AnnotationValue declaredNameValue = annotation.value("name");
final String declaredName = declaredNameValue != null ? declaredNameValue.asString() : null;
final String localContextName;
if (declaredName == null || declaredName.isEmpty()) {
localContextName = fieldInfo.declaringClass().name().toString() + "/" + fieldName;
} else {
localContextName = declaredName;
}
//final AnnotationValue declaredTypeValue = annotation.value("type");
final DotName declaredTypeDotName = fieldInfo.type().name();
final DotName injectionTypeDotName = declaredTypeDotName == null || declaredTypeDotName.toString().equals(Object.class.getName()) ? fieldInfo.type().name() : declaredTypeDotName;
final String injectionType = injectionTypeDotName.toString();
final InjectionSource bindingSource = this.getBindingSource(deploymentUnit, annotation, injectionType, eeModuleClassDescription);
if (bindingSource != null) {
final BindingConfiguration bindingConfiguration = new BindingConfiguration(localContextName, bindingSource);
eeModuleClassDescription.getBindingConfigurations().add(bindingConfiguration);
// setup the injection target
final InjectionTarget injectionTarget = new FieldInjectionTarget(fieldInfo.declaringClass().name().toString(), fieldName, fieldInfo.type().name().toString());
// source is always local ENC jndi
final InjectionSource injectionSource = new LookupInjectionSource(localContextName);
final ResourceInjectionConfiguration injectionConfiguration = new ResourceInjectionConfiguration(injectionTarget, injectionSource);
eeModuleClassDescription.addResourceInjection(injectionConfiguration);
}
}
private void processMethod(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation, final MethodInfo methodInfo,
final EEModuleClassDescription eeModuleClassDescription) throws
DeploymentUnitProcessingException {
final String methodName = methodInfo.name();
if (!methodName.startsWith("set") || methodInfo.args().length != 1) {
eeModuleClassDescription.setInvalid(JpaLogger.ROOT_LOGGER.setterMethodOnlyAnnotation(annotation.name().toString(), methodInfo));
return;
}
final String contextNameSuffix = methodName.substring(3, 4).toLowerCase(Locale.ENGLISH) + methodName.substring(4);
final AnnotationValue declaredNameValue = annotation.value("name");
final String declaredName = declaredNameValue != null ? declaredNameValue.asString() : null;
final String localContextName;
if (declaredName == null || declaredName.isEmpty()) {
localContextName = methodInfo.declaringClass().name().toString() + "/" + contextNameSuffix;
} else {
localContextName = declaredName;
}
final String injectionType = methodInfo.args()[0].name().toString();
final InjectionSource bindingSource = this.getBindingSource(deploymentUnit, annotation, injectionType, eeModuleClassDescription);
if (bindingSource != null) {
final BindingConfiguration bindingConfiguration = new BindingConfiguration(localContextName, bindingSource);
eeModuleClassDescription.getBindingConfigurations().add(bindingConfiguration);
// setup the injection configuration
final InjectionTarget injectionTarget = new MethodInjectionTarget(methodInfo.declaringClass().name().toString(), methodName, methodInfo.args()[0].name().toString());
// source is always local ENC jndi name
final InjectionSource injectionSource = new LookupInjectionSource(localContextName);
final ResourceInjectionConfiguration injectionConfiguration = new ResourceInjectionConfiguration(injectionTarget, injectionSource);
eeModuleClassDescription.addResourceInjection(injectionConfiguration);
}
}
private void processClass(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation,
final EEModuleClassDescription eeModuleClassDescription) throws
DeploymentUnitProcessingException {
bindClassSources(deploymentUnit, annotation, eeModuleClassDescription);
}
private void bindClassSources(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation, final EEModuleClassDescription classDescription)
throws DeploymentUnitProcessingException {
// handle PersistenceContext and PersistenceUnit annotations
if (isPersistenceContext(annotation) ||
isPersistenceUnit(annotation)) {
String injectionTypeName = getClassLevelInjectionType(annotation);
InjectionSource injectionSource = getBindingSource(deploymentUnit, annotation, injectionTypeName, classDescription);
if (injectionSource != null) {
final AnnotationValue nameValue = annotation.value("name");
if (nameValue == null || nameValue.asString().isEmpty()) {
classDescription.setInvalid(JpaLogger.ROOT_LOGGER.classLevelAnnotationParameterRequired(annotation.name().toString(), classDescription.getClassName(), "name"));
return;
}
final String name = nameValue.asString();
final BindingConfiguration bindingConfiguration = new BindingConfiguration(name, injectionSource);
classDescription.getBindingConfigurations().add(bindingConfiguration);
}
} else if (isPersistenceUnits(annotation)) {
// handle PersistenceUnits (array of PersistenceUnit)
AnnotationValue containedPersistenceUnits = annotation.value("value");
AnnotationInstance[] arrayPersistenceUnits;
if (containedPersistenceUnits != null &&
(arrayPersistenceUnits = containedPersistenceUnits.asNestedArray()) != null) {
for (int source = 0; source < arrayPersistenceUnits.length; source++) {
String injectionTypeName = getClassLevelInjectionType(arrayPersistenceUnits[source]);
InjectionSource injectionSource = getBindingSource(deploymentUnit, arrayPersistenceUnits[source], injectionTypeName, classDescription);
if (injectionSource != null) {
final AnnotationValue nameValue = arrayPersistenceUnits[source].value("name");
if (nameValue == null || nameValue.asString().isEmpty()) {
classDescription.setInvalid(JpaLogger.ROOT_LOGGER.classLevelAnnotationParameterRequired(arrayPersistenceUnits[source].name().toString(), classDescription.getClassName(), "name"));
return;
}
final String name = nameValue.asString();
final BindingConfiguration bindingConfiguration = new BindingConfiguration(name, injectionSource);
classDescription.getBindingConfigurations().add(bindingConfiguration);
}
}
}
} else if (isPersistenceContexts(annotation)) {
// handle PersistenceContexts (array of PersistenceContext)
AnnotationValue containedPersistenceContexts = annotation.value("value");
AnnotationInstance[] arrayPersistenceContexts;
if (containedPersistenceContexts != null &&
(arrayPersistenceContexts = containedPersistenceContexts.asNestedArray()) != null) {
for (int source = 0; source < arrayPersistenceContexts.length; source++) {
String injectionTypeName = getClassLevelInjectionType(arrayPersistenceContexts[source]);
InjectionSource injectionSource = getBindingSource(deploymentUnit, arrayPersistenceContexts[source], injectionTypeName, classDescription);
if (injectionSource != null) {
final AnnotationValue nameValue = arrayPersistenceContexts[source].value("name");
if (nameValue == null || nameValue.asString().isEmpty()) {
classDescription.setInvalid(JpaLogger.ROOT_LOGGER.classLevelAnnotationParameterRequired(arrayPersistenceContexts[source].name().toString(), classDescription.getClassName(), "name"));
return;
}
final String name = nameValue.asString();
final BindingConfiguration bindingConfiguration = new BindingConfiguration(name, injectionSource);
classDescription.getBindingConfigurations().add(bindingConfiguration);
}
}
}
}
}
private InjectionSource getBindingSource(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation, String injectionTypeName, final EEModuleClassDescription classDescription)
throws DeploymentUnitProcessingException {
PersistenceUnitMetadata pu = getPersistenceUnit(deploymentUnit, annotation, classDescription);
if (pu == null) {
return null;
}
String scopedPuName = pu.getScopedPersistenceUnitName();
ServiceName puServiceName = getPuServiceName(scopedPuName);
if (isPersistenceContext(annotation)) {
if (pu.getTransactionType() == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
classDescription.setInvalid(JpaLogger.ROOT_LOGGER.cannotInjectResourceLocalEntityManager());
return null;
}
AnnotationValue pcType = annotation.value("type");
PersistenceContextType type = (pcType == null || PersistenceContextType.TRANSACTION.name().equals(pcType.asString()))
? PersistenceContextType.TRANSACTION : PersistenceContextType.EXTENDED;
AnnotationValue stType = annotation.value("synchronization");
SynchronizationType synchronizationType =
(stType == null || SynchronizationType.SYNCHRONIZED.name().equals(stType.asString()))?
SynchronizationType.SYNCHRONIZED: SynchronizationType.UNSYNCHRONIZED;
Map<String, String> properties;
AnnotationValue value = annotation.value("properties");
AnnotationInstance[] props = value != null ? value.asNestedArray() : null;
if (props != null) {
properties = new HashMap<>();
for (int source = 0; source < props.length; source++) {
properties.put(props[source].value("name").asString(), props[source].value("value").asString());
}
} else {
properties = null;
}
// get deployment settings from top level du (jboss-all.xml is only parsed at the top level).
final JPADeploymentSettings jpaDeploymentSettings = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(JpaAttachments.DEPLOYMENT_SETTINGS_KEY);
return new PersistenceContextInjectionSource(type, synchronizationType , properties, puServiceName, deploymentUnit.getServiceRegistry(), scopedPuName, injectionTypeName, pu, jpaDeploymentSettings);
} else {
return new PersistenceUnitInjectionSource(puServiceName, deploymentUnit.getServiceRegistry(), injectionTypeName, pu);
}
}
private boolean isPersistenceContext(final AnnotationInstance annotation) {
return annotation.name().local().equals("PersistenceContext");
}
private boolean isPersistenceUnit(final AnnotationInstance annotation) {
return annotation.name().local().equals("PersistenceUnit");
}
private boolean isPersistenceContexts(final AnnotationInstance annotation) {
return annotation.name().local().equals("PersistenceContexts");
}
private boolean isPersistenceUnits(final AnnotationInstance annotation) {
return annotation.name().local().equals("PersistenceUnits");
}
/**
* Based on the the annotation type, its either entitymanager or entitymanagerfactory
*
* @param annotation
* @return
*/
private String getClassLevelInjectionType(final AnnotationInstance annotation) {
boolean isPC = annotation.name().local().equals("PersistenceContext");
return isPC ? ENTITY_MANAGER_CLASS : ENTITY_MANAGERFACTORY_CLASS;
}
private PersistenceUnitMetadata getPersistenceUnit(final DeploymentUnit deploymentUnit, final AnnotationInstance annotation, EEModuleClassDescription classDescription)
throws DeploymentUnitProcessingException {
final AnnotationValue puName = annotation.value("unitName");
String searchName = null; // note: a null searchName will match the first PU definition found
if (puName != null && (searchName = puName.asString()) != null) {
searchName = SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit).replaceProperties(searchName);
}
ROOT_LOGGER.debugf("persistence unit search for unitName=%s referenced from class=%s (annotation=%s)", searchName, classDescription.getClassName(), annotation.toString());
PersistenceUnitMetadata pu = PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, searchName);
if (null == pu) {
classDescription.setInvalid(JpaLogger.ROOT_LOGGER.persistenceUnitNotFound(searchName, deploymentUnit));
return null;
}
return pu;
}
private ServiceName getPuServiceName(String scopedPuName)
throws DeploymentUnitProcessingException {
return PersistenceUnitServiceImpl.getPUServiceName(scopedPuName);
}
}
| 22,668 | 58.033854 | 230 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPAJarJBossAllParser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.ee.structure.JBossDescriptorPropertyReplacement;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.jpa.jbossjpaparser.JBossJPAParser;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* JPAJarJBossAllParser
*
* @author Scott Marlow
*/
public class JPAJarJBossAllParser implements JBossAllXMLParser<JPADeploymentSettings> {
public static final AttachmentKey<JPADeploymentSettings> ATTACHMENT_KEY = AttachmentKey.create(JPADeploymentSettings.class);
public static final QName ROOT_ELEMENT = new QName("http://www.jboss.com/xml/ns/javaee", "jboss-jpa");
@Override
public JPADeploymentSettings parse(final XMLExtendedStreamReader reader, final DeploymentUnit deploymentUnit) throws XMLStreamException {
return JBossJPAParser.parser(reader, JBossDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));
}
}
| 2,213 | 41.576923 | 141 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/JPADependencyProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.config.PersistenceUnitsInApplication;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.metadata.ear.spec.EarMetaData;
import org.jboss.metadata.ear.spec.ModuleMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.ServiceName;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Deployment processor which adds a module dependencies for modules needed for Jakarta Persistence deployments.
*
* @author Scott Marlow (copied from WeldDepedencyProcessor)
*/
public class JPADependencyProcessor implements DeploymentUnitProcessor {
private static final ModuleIdentifier JAVAX_PERSISTENCE_API_ID = ModuleIdentifier.create("jakarta.persistence.api");
private static final ModuleIdentifier JBOSS_AS_JPA_ID = ModuleIdentifier.create("org.jboss.as.jpa");
private static final ModuleIdentifier JBOSS_AS_JPA_SPI_ID = ModuleIdentifier.create("org.jboss.as.jpa.spi");
private static final String JAR_FILE_EXTENSION = ".jar";
private static final String LIB_FOLDER = "lib";
/**
* Add dependencies for modules required for Jakarta Persistence deployments
*/
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
// all applications get the jakarta.persistence module added to their deplyoment by default
addDependency(moduleSpecification, moduleLoader, deploymentUnit, JAVAX_PERSISTENCE_API_ID);
if (!JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
return; // Skip if there are no persistence use in the deployment
}
addDependency(moduleSpecification, moduleLoader, deploymentUnit, JBOSS_AS_JPA_ID, JBOSS_AS_JPA_SPI_ID);
addPersistenceProviderModuleDependencies(phaseContext, moduleSpecification, moduleLoader);
}
private void addDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
DeploymentUnit deploymentUnit, ModuleIdentifier... moduleIdentifiers) {
for ( ModuleIdentifier moduleIdentifier : moduleIdentifiers) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, false, false, true, false));
ROOT_LOGGER.debugf("added %s dependency to %s", moduleIdentifier, deploymentUnit.getName());
}
}
private void addOptionalDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
DeploymentUnit deploymentUnit, ModuleIdentifier... moduleIdentifiers) {
for ( ModuleIdentifier moduleIdentifier : moduleIdentifiers) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, true, false, false, false));
ROOT_LOGGER.debugf("added %s dependency to %s", moduleIdentifier, deploymentUnit.getName());
}
}
private void addPersistenceProviderModuleDependencies(DeploymentPhaseContext phaseContext, ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) throws
DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
int defaultProviderCount = 0;
Set<String> moduleDependencies = new HashSet<String>();
// get the number of persistence units that use the default persistence provider module.
// Dependencies for other persistence provider will be added to the passed
// 'moduleDependencies' collection. Each persistence provider module that is found, will be injected into the
// passed moduleSpecification (for the current deployment unit).
PersistenceUnitsInApplication persistenceUnitsInApplication = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION);
for (PersistenceUnitMetadataHolder holder: persistenceUnitsInApplication.getPersistenceUnitHolders()) {
defaultProviderCount += loadPersistenceUnits(moduleSpecification, moduleLoader, deploymentUnit, moduleDependencies, holder);
}
// add dependencies for the default persistence provider module
if (defaultProviderCount > 0) {
moduleDependencies.add(Configuration.getDefaultProviderModuleName());
ROOT_LOGGER.debugf("added (default provider) %s dependency to %s (since %d PU(s) didn't specify %s",
Configuration.getDefaultProviderModuleName(), deploymentUnit.getName(),defaultProviderCount, Configuration.PROVIDER_MODULE + ")");
}
// add persistence provider dependency
for (String dependency : moduleDependencies) {
addDependency(moduleSpecification, moduleLoader, deploymentUnit, ModuleIdentifier.fromString(dependency));
}
// add the PU service as a dependency to all EE components in this scope
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final Collection<ComponentDescription> components = eeModuleDescription.getComponentDescriptions();
boolean earSubDeploymentsAreInitializedInCustomOrder = false;
EarMetaData earConfig = null;
earConfig = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA);
earSubDeploymentsAreInitializedInCustomOrder = earConfig != null && earConfig.getInitializeInOrder() && earConfig.getModules().size() > 1;
// WFLY-14923 as per https://jakarta.ee/specifications/platform/8/platform-spec-8.html#a3201,
// respect the `initialize-in-order` setting by only adding EE component dependencies on
// persistence units in the same sub-deployment (and top level deployment)
if (earSubDeploymentsAreInitializedInCustomOrder) {
if (deploymentUnit.getParent() != null) {
// add persistence units defined in current (sub) deployment unit to EE components
// also in current deployment unit.
List<PersistenceUnitMetadata> collectPersistenceUnitsForCurrentDeploymentUnit = new ArrayList<>();
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
final ModuleMetaData moduleMetaData = deploymentRoot.getAttachment(org.jboss.as.ee.structure.Attachments.MODULE_META_DATA);
for (PersistenceUnitMetadataHolder holder : persistenceUnitsInApplication.getPersistenceUnitHolders()) {
if (holder != null && holder.getPersistenceUnits() != null) {
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
String moduleName = pu.getContainingModuleName().get(pu.getContainingModuleName().size() - 1);
if (moduleName.equals(moduleMetaData.getFileName())) {
ROOT_LOGGER.tracef("Jakarta EE components in %s will depend on persistence unit %s", moduleName, pu.getScopedPersistenceUnitName());
collectPersistenceUnitsForCurrentDeploymentUnit.add(pu);
}
}
}
}
if (!collectPersistenceUnitsForCurrentDeploymentUnit.isEmpty()) {
addPUServiceDependencyToComponents(components,
new PersistenceUnitMetadataHolder(collectPersistenceUnitsForCurrentDeploymentUnit));
}
} else {
// WFLY-14923
// add Jakarta EE component dependencies on all persistence units in top level deployment unit.
List<ResourceRoot> resourceRoots = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
// look at resources that aren't subdeployments
if (!SubDeploymentMarker.isSubDeployment(resourceRoot)) {
addPUServiceDependencyToComponents(components, resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS));
}
}
}
// end of earSubDeploymentsAreInitializedInCustomOrder handling
} else {
// no `initialize-in-order` ordering configuration was specified (this is the default).
for (PersistenceUnitMetadataHolder holder : persistenceUnitsInApplication.getPersistenceUnitHolders()) {
addPUServiceDependencyToComponents(components, holder);
}
}
}
/**
* Add the <code>puServiceName</code> as a dependency on each of the passed <code>components</code>
*
* @param components The components to which the PU service is added as a dependency
* @param holder The persistence units
*/
private static void addPUServiceDependencyToComponents(final Collection<ComponentDescription> components, final PersistenceUnitMetadataHolder holder) {
if (components == null || components.isEmpty() || holder == null) {
return;
}
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
boolean deployPU = (jpaContainerManaged == null? true : Boolean.parseBoolean(jpaContainerManaged));
if (deployPU) {
final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
for (final ComponentDescription component : components) {
ROOT_LOGGER.debugf("Adding dependency on PU service %s for component %s", puServiceName, component.getComponentClassName());
component.addDependency(puServiceName);
}
}
}
}
private int loadPersistenceUnits(final ModuleSpecification moduleSpecification, final ModuleLoader moduleLoader, final DeploymentUnit deploymentUnit, final Set<String> moduleDependencies, final PersistenceUnitMetadataHolder holder) throws
DeploymentUnitProcessingException {
int defaultProviderCount = 0;
if (holder != null) {
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
String providerModule = pu.getProperties().getProperty(Configuration.PROVIDER_MODULE);
String adapterModule = pu.getProperties().getProperty(Configuration.ADAPTER_MODULE);
String adapterClass = pu.getProperties().getProperty(Configuration.ADAPTER_CLASS);
if (adapterModule != null) {
ROOT_LOGGER.debugf("%s is configured to use adapter module '%s'", pu.getPersistenceUnitName(), adapterModule);
moduleDependencies.add(adapterModule);
}
deploymentUnit.putAttachment(JpaAttachments.ADAPTOR_CLASS_NAME, adapterClass);
String provider = pu.getProperties().getProperty(Configuration.PROVIDER_MODULE);
if (provider != null) {
if (provider.equals(Configuration.PROVIDER_MODULE_APPLICATION_SUPPLIED)) {
ROOT_LOGGER.debugf("%s is configured to use application supplied persistence provider", pu.getPersistenceUnitName());
} else {
moduleDependencies.add(provider);
ROOT_LOGGER.debugf("%s is configured to use provider module '%s'", pu.getPersistenceUnitName(), provider);
}
} else if (Configuration.PROVIDER_CLASS_DEFAULT.equals(pu.getPersistenceProviderClassName())) {
defaultProviderCount++; // track number of references to default provider module
} else {
// inject other provider modules into application
// in case its not obvious, everything but hibernate3 can end up here. For Hibernate3, the Configuration.PROVIDER_MODULE
// should of been specified.
//
// since we don't know (until after PersistenceProviderProcessor runs in a later phase) if the provider
// is packaged with the app or will be accessed as a module, make the module dependency optional (in case it
// doesn't exist).
String providerModuleName = Configuration.getProviderModuleNameFromProviderClassName(pu.getPersistenceProviderClassName());
if (providerModuleName != null) {
addOptionalDependency(moduleSpecification, moduleLoader, deploymentUnit, ModuleIdentifier.fromString(providerModuleName));
ROOT_LOGGER.debugf("%s is configured to use persistence provider '%s', adding an optional dependency on module '%s'",
pu.getPersistenceUnitName(), pu.getPersistenceProviderClassName(), providerModuleName);
}
}
}
}
return defaultProviderCount;
}
}
| 15,790 | 59.969112 | 242 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceUnitParseProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011-2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.config.PersistenceUnitsInApplication;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.puparser.PersistenceUnitXmlParser;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.metadata.parser.util.NoopXMLResolver;
import org.jboss.vfs.VirtualFile;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* Handle parsing of Persistence unit persistence.xml files
* <p/>
* The jar file/directory whose META-INF directory contains the persistence.xml file is termed the root of the persistence
* unit.
* root of a persistence unit must be one of the following:
* EJB-JAR file
* the WEB-INF/classes directory of a WAR file
* jar file in the WEB-INF/lib directory of a WAR file
* jar file in the EAR library directory
* application client jar file
*
* @author Scott Marlow
*/
public class PersistenceUnitParseProcessor implements DeploymentUnitProcessor {
private static final String WEB_PERSISTENCE_XML = "WEB-INF/classes/META-INF/persistence.xml";
private static final String META_INF_PERSISTENCE_XML = "META-INF/persistence.xml";
private static final String JAR_FILE_EXTENSION = ".jar";
private static final String LIB_FOLDER = "lib";
private final boolean appClientContainerMode;
public PersistenceUnitParseProcessor(boolean appclient) {
appClientContainerMode = appclient;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
handleWarDeployment(phaseContext);
handleEarDeployment(phaseContext);
handleJarDeployment(phaseContext);
CapabilityServiceSupport capabilitySupport = phaseContext.getDeploymentUnit().getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
phaseContext.addDeploymentDependency(capabilitySupport.getCapabilityServiceName(JPAServiceNames.LOCAL_TRANSACTION_PROVIDER_CAPABILITY), JpaAttachments.LOCAL_TRANSACTION_PROVIDER);
phaseContext.addDeploymentDependency(capabilitySupport.getCapabilityServiceName(JPAServiceNames.TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY), JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY);
}
private void handleJarDeployment(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!isEarDeployment(deploymentUnit) && !isWarDeployment(deploymentUnit) &&
(!appClientContainerMode || DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit)) ) {
// handle META-INF/persistence.xml
// ordered list of PUs
List<PersistenceUnitMetadataHolder> listPUHolders = new ArrayList<PersistenceUnitMetadataHolder>(1);
// handle META-INF/persistence.xml
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
VirtualFile persistence_xml = deploymentRoot.getRoot().getChild(META_INF_PERSISTENCE_XML);
parse(persistence_xml, listPUHolders, deploymentUnit);
PersistenceUnitMetadataHolder holder = normalize(listPUHolders);
// save the persistent unit definitions
// deploymentUnit.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
deploymentRoot.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
markDU(holder, deploymentUnit);
ROOT_LOGGER.tracef("parsed persistence unit definitions for jar %s", deploymentRoot.getRootName());
incrementPersistenceUnitCount(deploymentUnit, holder.getPersistenceUnits().size());
addApplicationDependenciesOnProvider( deploymentUnit, holder);
}
}
private void handleWarDeployment(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!appClientContainerMode && isWarDeployment(deploymentUnit)) {
int puCount;
// ordered list of PUs
List<PersistenceUnitMetadataHolder> listPUHolders = new ArrayList<PersistenceUnitMetadataHolder>(1);
// handle WEB-INF/classes/META-INF/persistence.xml
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
VirtualFile persistence_xml = deploymentRoot.getRoot().getChild(WEB_PERSISTENCE_XML);
parse(persistence_xml, listPUHolders, deploymentUnit);
PersistenceUnitMetadataHolder holder = normalize(listPUHolders);
deploymentRoot.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
addApplicationDependenciesOnProvider( deploymentUnit, holder);
markDU(holder, deploymentUnit);
puCount = holder.getPersistenceUnits().size();
// look for persistence.xml in jar files in the META-INF/persistence.xml directory (these are not currently
// handled as subdeployments)
List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(JAR_FILE_EXTENSION)) {
listPUHolders = new ArrayList<PersistenceUnitMetadataHolder>(1);
persistence_xml = resourceRoot.getRoot().getChild(META_INF_PERSISTENCE_XML);
parse(persistence_xml, listPUHolders, deploymentUnit);
holder = normalize(listPUHolders);
resourceRoot.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
addApplicationDependenciesOnProvider( deploymentUnit, holder);
markDU(holder, deploymentUnit);
puCount += holder.getPersistenceUnits().size();
}
}
ROOT_LOGGER.tracef("parsed persistence unit definitions for war %s", deploymentRoot.getRootName());
incrementPersistenceUnitCount(deploymentUnit, puCount);
}
}
private void handleEarDeployment(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (isEarDeployment(deploymentUnit)) {
int puCount = 0;
// ordered list of PUs
List<PersistenceUnitMetadataHolder> listPUHolders = new ArrayList<PersistenceUnitMetadataHolder>(1);
// handle META-INF/persistence.xml
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
VirtualFile persistence_xml = deploymentRoot.getRoot().getChild(META_INF_PERSISTENCE_XML);
parse(persistence_xml, listPUHolders, deploymentUnit);
PersistenceUnitMetadataHolder holder = normalize(listPUHolders);
deploymentRoot.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
addApplicationDependenciesOnProvider( deploymentUnit, holder);
markDU(holder, deploymentUnit);
puCount = holder.getPersistenceUnits().size();
// Parsing persistence.xml in EJB jar/war files is handled as subdeployments.
// We need to handle jars in the EAR/lib folder here
List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
// look at lib/*.jar files that aren't subdeployments (subdeployments are passed
// to deploy(DeploymentPhaseContext)).
if (!SubDeploymentMarker.isSubDeployment(resourceRoot) &&
resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(JAR_FILE_EXTENSION) &&
resourceRoot.getRoot().getParent().getName().equals(LIB_FOLDER)) {
listPUHolders = new ArrayList<PersistenceUnitMetadataHolder>(1);
persistence_xml = resourceRoot.getRoot().getChild(META_INF_PERSISTENCE_XML);
parse(persistence_xml, listPUHolders, deploymentUnit);
holder = normalize(listPUHolders);
resourceRoot.putAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS, holder);
addApplicationDependenciesOnProvider( deploymentUnit, holder);
markDU(holder, deploymentUnit);
puCount += holder.getPersistenceUnits().size();
}
}
ROOT_LOGGER.tracef("parsed persistence unit definitions for ear %s", deploymentRoot.getRootName());
incrementPersistenceUnitCount(deploymentUnit, puCount);
}
}
private void parse(
final VirtualFile persistence_xml,
final List<PersistenceUnitMetadataHolder> listPUHolders,
final DeploymentUnit deploymentUnit)
throws DeploymentUnitProcessingException {
ROOT_LOGGER.tracef("parse checking if %s exists, result = %b",persistence_xml.toString(), persistence_xml.exists());
if (persistence_xml.exists() && persistence_xml.isFile()) {
InputStream is = null;
try {
is = persistence_xml.openStream();
final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setXMLResolver(NoopXMLResolver.create());
XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
PersistenceUnitMetadataHolder puHolder = PersistenceUnitXmlParser.parse(xmlReader, SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));
postParseSteps(persistence_xml, puHolder, deploymentUnit);
listPUHolders.add(puHolder);
} catch (Exception e) {
throw new DeploymentUnitProcessingException(JpaLogger.ROOT_LOGGER.failedToParse(persistence_xml), e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
}
}
}
/**
* Some of this might need to move to the install phase
*
* @param persistence_xml
* @param puHolder
*/
private void postParseSteps(
final VirtualFile persistence_xml,
final PersistenceUnitMetadataHolder puHolder,
final DeploymentUnit deploymentUnit ) {
for (PersistenceUnitMetadata pu : puHolder.getPersistenceUnits()) {
// set URLs
List<URL> jarfilesUrls = new ArrayList<URL>();
if (pu.getJarFiles() != null) {
for (String jar : pu.getJarFiles()) {
jarfilesUrls.add(getRelativeURL(persistence_xml, jar));
}
}
pu.setJarFileUrls(jarfilesUrls);
URL url = getPersistenceUnitURL(persistence_xml);
pu.setPersistenceUnitRootUrl(url);
String scopedPersistenceUnitName;
/**
* WFLY-5478 allow custom scoped persistence unit name hint in persistence unit definition.
* Specified scoped persistence unit name needs to be unique across application server deployments.
* Application is responsible for picking a unique name.
* Currently, a non-unique name will result in a DuplicateServiceException deployment failure:
* org.jboss.msc.service.DuplicateServiceException: Service jboss.persistenceunit.my2lccustom#test_pu.__FIRST_PHASE__ is already registered
*/
scopedPersistenceUnitName = Configuration.getScopedPersistenceUnitName(pu);
if (scopedPersistenceUnitName == null) {
scopedPersistenceUnitName = createBeanName(deploymentUnit, pu.getPersistenceUnitName());
} else {
ROOT_LOGGER.tracef("persistence unit '%s' specified a custom scoped persistence unit name hint " +
"(jboss.as.jpa.scopedname=%s). The specified name *must* be unique across all application server deployments.",
pu.getPersistenceUnitName(),
scopedPersistenceUnitName);
if (scopedPersistenceUnitName.indexOf('/') != -1) {
throw JpaLogger.ROOT_LOGGER.invalidScopedName(scopedPersistenceUnitName, '/');
}
}
pu.setScopedPersistenceUnitName(scopedPersistenceUnitName);
pu.setContainingModuleName(getContainingModuleName(deploymentUnit));
}
}
private static URL getRelativeURL(VirtualFile persistence_xml, String jar) {
try {
return new URL(jar);
} catch (MalformedURLException e) {
try {
VirtualFile deploymentUnitFile = persistence_xml;
//we need the parent 3 units up, 1 is META-INF, 2nd is the actual jar, 3rd is the jar files parent
VirtualFile parent = deploymentUnitFile.getParent().getParent().getParent();
VirtualFile baseDir = (parent != null ? parent : deploymentUnitFile);
VirtualFile jarFile = baseDir.getChild(jar);
if (jarFile == null)
throw JpaLogger.ROOT_LOGGER.childNotFound(jar, baseDir);
return jarFile.toURL();
} catch (Exception e1) {
throw JpaLogger.ROOT_LOGGER.relativePathNotFound(e1, jar);
}
}
}
private URL getPersistenceUnitURL(VirtualFile persistence_xml) {
try {
VirtualFile metaData = persistence_xml;// di.getMetaDataFile("persistence.xml");
return metaData.getParent().getParent().toURL();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Eliminate duplicate PU definitions from clustering the deployment (first definition will win)
* <p/>
* Jakarta Persistence 8.2 A persistence unit must have a name. Only one persistence unit of any given name must be defined
* within a single EJB-JAR file, within a single WAR file, within a single application client jar, or within
* an EAR. See Section 8.2.2, “Persistence Unit Scope”.
*
* @param listPUHolders
* @return
*/
private PersistenceUnitMetadataHolder normalize(List<PersistenceUnitMetadataHolder> listPUHolders) {
// eliminate duplicates (keeping the first instance of each PU by name)
Map<String, PersistenceUnitMetadata> flattened = new HashMap<String, PersistenceUnitMetadata>();
for (PersistenceUnitMetadataHolder puHolder : listPUHolders) {
for (PersistenceUnitMetadata pu : puHolder.getPersistenceUnits()) {
if (!flattened.containsKey(pu.getPersistenceUnitName())) {
flattened.put(pu.getPersistenceUnitName(), pu);
} else {
PersistenceUnitMetadata first = flattened.get(pu.getPersistenceUnitName());
PersistenceUnitMetadata duplicate = pu;
ROOT_LOGGER.duplicatePersistenceUnitDefinition(duplicate.getPersistenceUnitName(), first.getScopedPersistenceUnitName(), duplicate.getScopedPersistenceUnitName());
}
}
}
PersistenceUnitMetadataHolder holder = new PersistenceUnitMetadataHolder(new ArrayList<PersistenceUnitMetadata>(flattened.values()));
return holder;
}
static boolean isEarDeployment(final DeploymentUnit context) {
return (DeploymentTypeMarker.isType(DeploymentType.EAR, context));
}
static boolean isWarDeployment(final DeploymentUnit context) {
return (DeploymentTypeMarker.isType(DeploymentType.WAR, context));
}
private static String getScopedDeploymentUnitPath(DeploymentUnit deploymentUnit) {
ArrayList<String> parts = new ArrayList<String>(); // order of deployment elements will start with parent
do {
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
DeploymentUnit parentdeploymentUnit = deploymentUnit.getParent();
if (parentdeploymentUnit != null) {
ResourceRoot parentDeploymentRoot = parentdeploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
parts.add(0, deploymentRoot.getRoot().getPathNameRelativeTo(parentDeploymentRoot.getRoot()));
} else {
parts.add(0, deploymentRoot.getRoot().getName());
}
}
while ((deploymentUnit = deploymentUnit.getParent()) != null);
StringBuilder result = new StringBuilder();
boolean needSeparator = false;
for (String part : parts) {
if (needSeparator) {
result.append('/');
}
result.append(part);
needSeparator = true;
}
return result.toString();
}
// make scoped pu name (e.g. test2.ear/w2.war#warPUnit_PU or test3.jar#CTS-EXT-UNIT)
// old as6 names looked like: persistence.unit:unitName=ejb3_ext_propagation.ear/lib/ejb3_ext_propagation.jar#CTS-EXT-UNIT
public static String createBeanName(DeploymentUnit deploymentUnit, String persistenceUnitName) {
// persistenceUnitName must be a simple name
if (persistenceUnitName.indexOf('/') != -1) {
throw JpaLogger.ROOT_LOGGER.invalidPersistenceUnitName(persistenceUnitName, '/');
}
if (persistenceUnitName.indexOf('#') != -1) {
throw JpaLogger.ROOT_LOGGER.invalidPersistenceUnitName(persistenceUnitName, '#');
}
String unitName = getScopedDeploymentUnitPath(deploymentUnit) + "#" + persistenceUnitName;
return unitName;
}
// returns the EE deployment module name.
// For top level deployments, only one element will be returned representing the top level module.
// For sub-deployments, the first element identifies the top level module and the second element is the sub-module.
private ArrayList<String> getContainingModuleName(DeploymentUnit deploymentUnit) {
ArrayList<String> parts = new ArrayList<String>(); // order of deployment elements will start with parent
do {
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
DeploymentUnit parentdeploymentUnit = deploymentUnit.getParent();
if (parentdeploymentUnit != null) {
ResourceRoot parentDeploymentRoot = parentdeploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
parts.add(0, deploymentRoot.getRoot().getPathNameRelativeTo(parentDeploymentRoot.getRoot()));
} else {
parts.add(0, deploymentRoot.getRoot().getName());
}
}
while ((deploymentUnit = deploymentUnit.getParent()) != null);
return parts;
}
private void markDU(PersistenceUnitMetadataHolder holder, DeploymentUnit deploymentUnit) {
if (holder.getPersistenceUnits() != null && !holder.getPersistenceUnits().isEmpty()) {
JPADeploymentMarker.mark(deploymentUnit);
// Hibernate Search backend type detection
for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
Properties properties = persistenceUnit.getProperties();
String backendType = properties == null ? null
: trimToNull(properties.getProperty(Configuration.HIBERNATE_SEARCH_BACKEND_TYPE));
if (backendType != null) {
HibernateSearchDeploymentMarker.markBackendType(deploymentUnit, backendType);
}
String coordinationStrategy = properties == null ? null
: trimToNull(properties.getProperty(Configuration.HIBERNATE_SEARCH_COORDINATION_STRATEGY));
if (coordinationStrategy != null) {
HibernateSearchDeploymentMarker.markCoordinationStrategy(deploymentUnit, coordinationStrategy);
}
}
}
}
private String trimToNull(String string) {
if (string == null) {
return null;
}
string = string.trim();
if (string.isEmpty()) {
return null;
}
return string;
}
private void incrementPersistenceUnitCount(DeploymentUnit topDeploymentUnit, int persistenceUnitCount) {
topDeploymentUnit = DeploymentUtils.getTopDeploymentUnit(topDeploymentUnit);
// create persistence unit counter if not done already
synchronized (topDeploymentUnit) { // ensure that only one deployment thread sets this at a time
PersistenceUnitsInApplication persistenceUnitsInApplication = getPersistenceUnitsInApplication(topDeploymentUnit);
persistenceUnitsInApplication.increment(persistenceUnitCount);
}
ROOT_LOGGER.tracef("incrementing PU count for %s by %d", topDeploymentUnit.getName(), persistenceUnitCount);
}
private void addApplicationDependenciesOnProvider(DeploymentUnit topDeploymentUnit, PersistenceUnitMetadataHolder holder) {
topDeploymentUnit = DeploymentUtils.getTopDeploymentUnit(topDeploymentUnit);
synchronized (topDeploymentUnit) { // ensure that only one deployment thread sets this at a time
PersistenceUnitsInApplication persistenceUnitsInApplication = getPersistenceUnitsInApplication(topDeploymentUnit);
persistenceUnitsInApplication.addPersistenceUnitHolder(holder);
}
}
private PersistenceUnitsInApplication getPersistenceUnitsInApplication(DeploymentUnit topDeploymentUnit) {
PersistenceUnitsInApplication persistenceUnitsInApplication = topDeploymentUnit.getAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION);
if (persistenceUnitsInApplication == null) {
persistenceUnitsInApplication = new PersistenceUnitsInApplication();
topDeploymentUnit.putAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION, persistenceUnitsInApplication);
}
return persistenceUnitsInApplication;
}
}
| 24,859 | 50.791667 | 207 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceProviderAdaptorLoader.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.persistence.spi.PersistenceProvider;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.transaction.JtaManagerImpl;
import org.jboss.jandex.Index;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.jipijapa.plugin.spi.JtaManager;
import org.jipijapa.plugin.spi.ManagementAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderIntegratorAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.Platform;
/**
* Loads persistence provider adaptors
*
* @author Scott Marlow
*/
public class PersistenceProviderAdaptorLoader {
private static final PersistenceProviderAdaptor noopAdaptor = new PersistenceProviderAdaptor() {
@Override
public void injectJtaManager(JtaManager jtaManager) {
}
@Override
public void injectPlatform(Platform platform) {
}
@Override
public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
}
@Override
public void addProviderDependencies(PersistenceUnitMetadata pu) {
}
@Override
public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
}
@Override
public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
}
@Override
public ManagementAdaptor getManagementAdaptor() {
return null;
}
@Override
public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) {
return true;
}
@Override
public void cleanup(PersistenceUnitMetadata pu) {
}
@Override
public Object beanManagerLifeCycle(BeanManager beanManager) {
return null;
}
@Override
public void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle) {
}
};
/**
* Loads the persistence provider adapter
*
* @param adapterModule may specify the adapter module name (can be null to use noop provider)
* @return the persistence provider adaptor for the provider class
* @throws ModuleLoadException
*/
public static PersistenceProviderAdaptor loadPersistenceAdapterModule(final String adapterModule, final Platform platform, JtaManagerImpl manager) throws
ModuleLoadException {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
if (adapterModule == null) {
return noopAdaptor;
}
PersistenceProviderAdaptor persistenceProviderAdaptor=null;
Module module = moduleLoader.loadModule(ModuleIdentifier.fromString(adapterModule));
final ServiceLoader<PersistenceProviderAdaptor> serviceLoader =
module.loadService(PersistenceProviderAdaptor.class);
if (serviceLoader != null) {
for (PersistenceProviderAdaptor adaptor : serviceLoader) {
if (persistenceProviderAdaptor != null) {
throw JpaLogger.ROOT_LOGGER.multipleAdapters(adapterModule);
}
persistenceProviderAdaptor = adaptor;
ROOT_LOGGER.debugf("loaded persistence provider adapter %s", adapterModule);
}
if (persistenceProviderAdaptor != null) {
persistenceProviderAdaptor.injectJtaManager(manager);
persistenceProviderAdaptor.injectPlatform(platform);
}
}
return persistenceProviderAdaptor;
}
/**
* Loads the persistence provider adapter
*
* @param persistenceProvider classloader will be used to load the persistence provider adapter
* @return the persistence provider adaptor for the provider class
*/
public static PersistenceProviderAdaptor loadPersistenceAdapter(final PersistenceProvider persistenceProvider, final Platform platform, final JtaManagerImpl jtaManager) {
PersistenceProviderAdaptor persistenceProviderAdaptor=null;
final ServiceLoader<PersistenceProviderAdaptor> serviceLoader =
ServiceLoader.load(PersistenceProviderAdaptor.class, persistenceProvider.getClass().getClassLoader());
if (serviceLoader != null) {
for (PersistenceProviderAdaptor adaptor : serviceLoader) {
if (persistenceProviderAdaptor != null) {
throw JpaLogger.ROOT_LOGGER.classloaderHasMultipleAdapters(persistenceProvider.getClass().getClassLoader().toString());
}
persistenceProviderAdaptor = adaptor;
ROOT_LOGGER.debugf("loaded persistence provider adapter %s from classloader %s",
persistenceProviderAdaptor.getClass().getName(),
persistenceProvider.getClass().getClassLoader().toString());
}
if (persistenceProviderAdaptor != null) {
persistenceProviderAdaptor.injectJtaManager(jtaManager);
persistenceProviderAdaptor.injectPlatform(platform);
}
}
return persistenceProviderAdaptor == null ?
noopAdaptor:
persistenceProviderAdaptor;
}
/**
* Loads the persistence provider integrator adapter
*
* @param adapterModule the adapter module name
* @return the adaptors for the given module
* @throws ModuleLoadException
*/
public static List<PersistenceProviderIntegratorAdaptor> loadPersistenceProviderIntegratorModule(
String adapterModule, Collection<Index> indexes) throws ModuleLoadException {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
List<PersistenceProviderIntegratorAdaptor> persistenceProviderAdaptors = new ArrayList<>();
Module module = moduleLoader.loadModule(adapterModule);
final ServiceLoader<PersistenceProviderIntegratorAdaptor> serviceLoader =
module.loadService(PersistenceProviderIntegratorAdaptor.class);
for (PersistenceProviderIntegratorAdaptor adaptor : serviceLoader) {
persistenceProviderAdaptors.add(adaptor);
ROOT_LOGGER.debugf("loaded persistence provider integrator adapter %s from %s", adaptor, adapterModule);
if (adaptor != null) {
adaptor.injectIndexes(indexes);
}
}
return persistenceProviderAdaptors;
}
}
| 7,943 | 37.192308 | 174 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceCompleteInstallProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jipijapa.plugin.spi.Platform;
/**
* complete installation of persistence unit service and persistence providers in deployment
*
* @author Scott Marlow
*/
public class PersistenceCompleteInstallProcessor implements DeploymentUnitProcessor {
private final Platform platform;
public PersistenceCompleteInstallProcessor(Platform platform) {
this.platform = platform;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
if (deploymentHasPersistenceProvider(phaseContext.getDeploymentUnit())) {
// finish registration of persistence provider
PersistenceProviderHandler.finishDeploy(phaseContext);
}
// only install PUs with property Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false (since they weren't started before)
// this allows @DataSourceDefinition to work (which don't start until the Install phase)
PersistenceUnitServiceHandler.deploy(phaseContext, false, platform);
}
@Override
public void undeploy(DeploymentUnit context) {
PersistenceUnitServiceHandler.undeploy(context); // always uninstall persistent unit services from here
}
private static boolean deploymentHasPersistenceProvider(DeploymentUnit deploymentUnit) {
deploymentUnit = DeploymentUtils.getTopDeploymentUnit(deploymentUnit);
PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = deploymentUnit.getAttachment(JpaAttachments.DEPLOYED_PERSISTENCE_PROVIDER);
return (persistenceProviderDeploymentHolder != null && persistenceProviderDeploymentHolder.getProviders() != null ? persistenceProviderDeploymentHolder.getProviders().size() > 0: false);
}
}
| 3,209 | 44.211268 | 194 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/HibernateSearchProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.config.PersistenceUnitsInApplication;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.JPADeploymentMarker;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import java.util.List;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* Deployment processor which adds a Hibernate Search module dependency.
*
* @author Scott Marlow
*/
public class HibernateSearchProcessor implements DeploymentUnitProcessor {
private static final DotName ANNOTATION_INDEXED_NAME = DotName.createSimple("org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed");
private static final ModuleIdentifier MODULE_MAPPER_ORM_DEFAULT =
ModuleIdentifier.fromString(Configuration.HIBERNATE_SEARCH_MODULE_MAPPER_ORM);
private static final ModuleIdentifier MODULE_MAPPER_ORM_COORDINATION_OUTBOXPOLLING =
ModuleIdentifier.fromString(Configuration.HIBERNATE_SEARCH_MODULE_MAPPER_ORM_COORDINATION_OUTBOXPOLLING);
private static final ModuleIdentifier MODULE_BACKEND_LUCENE =
ModuleIdentifier.fromString(Configuration.HIBERNATE_SEARCH_MODULE_BACKEND_LUCENE);
private static final ModuleIdentifier MODULE_BACKEND_ELASTICSEARCH =
ModuleIdentifier.fromString(Configuration.HIBERNATE_SEARCH_MODULE_BACKEND_ELASTICSEARCH);
private static final String NONE = "none";
private static final String IGNORE = "auto"; // if set to `auto`, will behave like not having set the property
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
if (JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
addSearchDependency(moduleSpecification, moduleLoader, deploymentUnit);
}
}
private void addSearchDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
String searchMapperModuleName = null;
PersistenceUnitsInApplication persistenceUnitsInApplication = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION);
for (PersistenceUnitMetadataHolder holder : persistenceUnitsInApplication.getPersistenceUnitHolders()) {
for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
String providerModule = pu.getProperties().getProperty(Configuration.HIBERNATE_SEARCH_MODULE);
if (providerModule != null) {
// one persistence unit specifying the Hibernate search module is allowed
if (searchMapperModuleName == null) {
searchMapperModuleName = providerModule;
}
// more than one persistence unit specifying different Hibernate search module names is not allowed
else if (!providerModule.equals(searchMapperModuleName)) {
throw JpaLogger.ROOT_LOGGER.differentSearchModuleDependencies(deploymentUnit.getName(), searchMapperModuleName, providerModule);
}
}
}
}
if (NONE.equals(searchMapperModuleName)) {
// Hibernate Search module will not be added to deployment
ROOT_LOGGER.debugf("Not adding Hibernate Search dependency to deployment %s", deploymentUnit.getName());
return;
}
// use Search module name specified in persistence unit definition
if (searchMapperModuleName != null && !IGNORE.equals(searchMapperModuleName)) {
ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(searchMapperModuleName);
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, false, true, true, false));
ROOT_LOGGER.debugf("added %s dependency to %s", moduleIdentifier, deploymentUnit.getName());
} else {
// add Hibernate Search module dependency if application is using the Hibernate Search Indexed annotation
final CompositeIndex index = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX);
List<AnnotationInstance> annotations = index.getAnnotations(ANNOTATION_INDEXED_NAME);
if (annotations != null && !annotations.isEmpty()) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, MODULE_MAPPER_ORM_DEFAULT,
false, true, true, false));
ROOT_LOGGER.debugf("deployment %s contains %s annotation, added %s dependency", deploymentUnit.getName(),
ANNOTATION_INDEXED_NAME, MODULE_MAPPER_ORM_DEFAULT);
}
}
// Configure sourcing of Jandex indexes in Hibernate Search,
// so that it can look for @ProjectionConstructor annotations
deploymentUnit.addToAttachmentList(JpaAttachments.INTEGRATOR_ADAPTOR_MODULE_NAMES,
Configuration.HIBERNATE_SEARCH_INTEGRATOR_ADAPTOR_MODULE_NAME);
List<String> backendTypes = HibernateSearchDeploymentMarker.getBackendTypes(deploymentUnit);
if (backendTypes != null) {
if (backendTypes.contains(Configuration.HIBERNATE_SEARCH_BACKEND_TYPE_VALUE_LUCENE)) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, MODULE_BACKEND_LUCENE,
false, true, true, false));
}
if (backendTypes.contains(Configuration.HIBERNATE_SEARCH_BACKEND_TYPE_VALUE_ELASTICSEARCH)) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, MODULE_BACKEND_ELASTICSEARCH,
false, true, true, false));
}
}
List<String> coordinationStrategies = HibernateSearchDeploymentMarker.getCoordinationStrategies(deploymentUnit);
if (coordinationStrategies != null) {
if (coordinationStrategies.contains(Configuration.HIBERNATE_SEARCH_COORDINATION_STRATEGY_VALUE_OUTBOX_POLLING)) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, MODULE_MAPPER_ORM_COORDINATION_OUTBOXPOLLING,
false, true, true, false));
}
}
}
}
| 8,612 | 54.928571 | 201 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/PersistenceBeginInstallProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jipijapa.plugin.spi.Platform;
/**
* begin installation of persistence unit service and persistence providers in deployment
*
* @author Scott Marlow
*/
public class PersistenceBeginInstallProcessor implements DeploymentUnitProcessor {
private final Platform platform;
public PersistenceBeginInstallProcessor(Platform platform) {
this.platform = platform;
}
/**
* {@inheritDoc}
*/
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
// deploy any persistence providers found in deployment
PersistenceProviderHandler.deploy(phaseContext, platform);
// start each PU service (except the PUs with property Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false)
PersistenceUnitServiceHandler.deploy(phaseContext, true, platform);
}
/**
* {@inheritDoc}
*/
public void undeploy(final DeploymentUnit deploymentUnit) {
PersistenceProviderHandler.undeploy(deploymentUnit);
}
}
| 2,359 | 35.875 | 117 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/secondlevelcache/CacheDeploymentListener.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor.secondlevelcache;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.HashMap;
import java.util.Properties;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.msc.service.ServiceBuilder;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.cache.spi.Wrapper;
import org.jipijapa.event.spi.EventListener;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* CacheDeploymentListener
*
* @author Scott Marlow
*/
public class CacheDeploymentListener implements EventListener {
private interface DeploymentSupport {
ServiceBuilder<?> getServiceBuilder();
CapabilityServiceSupport getCapabilityServiceSupport();
}
private static final ThreadLocal<DeploymentSupport> DEPLOYMENT_SUPPORT = new ThreadLocal<>();
HashMap<String,EventListener> delegates = new HashMap<String,EventListener>();
public CacheDeploymentListener() {
delegates.put(Classification.INFINISPAN.getLocalName(), new InfinispanCacheDeploymentListener());
}
public static void setInternalDeploymentSupport(ServiceBuilder<?> serviceBuilder, CapabilityServiceSupport support) {
DEPLOYMENT_SUPPORT.set(new DeploymentSupport() {
@Override
public ServiceBuilder<?> getServiceBuilder() {
return serviceBuilder;
}
@Override
public CapabilityServiceSupport getCapabilityServiceSupport() {
return support;
}
});
}
public static void clearInternalDeploymentSupport() {
DEPLOYMENT_SUPPORT.remove();
}
public static ServiceBuilder<?> getInternalDeploymentServiceBuilder() {
return DEPLOYMENT_SUPPORT.get().getServiceBuilder();
}
public static CapabilityServiceSupport getInternalDeploymentCapablityServiceSupport() {
return DEPLOYMENT_SUPPORT.get().getCapabilityServiceSupport();
}
@Override
public void beforeEntityManagerFactoryCreate(Classification classification, PersistenceUnitMetadata persistenceUnitMetadata) {
delegates.get(classification.getLocalName()).beforeEntityManagerFactoryCreate(classification, persistenceUnitMetadata);
}
@Override
public void afterEntityManagerFactoryCreate(Classification classification, PersistenceUnitMetadata persistenceUnitMetadata) {
DEPLOYMENT_SUPPORT.remove();
delegates.get(classification.getLocalName()).afterEntityManagerFactoryCreate(classification, persistenceUnitMetadata);
}
@Override
public Wrapper startCache(Classification classification, Properties properties) throws Exception {
if(ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("start second level cache with properties '%s'", properties.toString());
}
return delegates.get(classification.getLocalName()).startCache(classification, properties);
}
@Override
public void addCacheDependencies(Classification classification, Properties properties) {
if(ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("add second level cache dependencies with properties '%s'", properties.toString());
}
delegates.get(classification.getLocalName()).addCacheDependencies(classification, properties);
}
@Override
public void stopCache(Classification classification, Wrapper wrapper) {
delegates.get(classification.getLocalName()).stopCache(classification, wrapper);
}
}
| 4,565 | 37.369748 | 130 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/processor/secondlevelcache/InfinispanCacheDeploymentListener.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor.secondlevelcache;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.security.AccessController;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;
import org.infinispan.manager.EmbeddedCacheManager;
import org.jboss.as.controller.ServiceNameFactory;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.cache.spi.Wrapper;
import org.jipijapa.event.spi.EventListener;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.wildfly.clustering.infinispan.service.InfinispanCacheRequirement;
import org.wildfly.clustering.infinispan.service.InfinispanRequirement;
/**
* InfinispanCacheDeploymentListener adds Infinispan second level cache dependencies during application deployment.
*
* @author Scott Marlow
* @author Paul Ferraro
*/
public class InfinispanCacheDeploymentListener implements EventListener {
public static final String CACHE_TYPE = "cachetype"; // shared (Jakarta Persistence) or private (for native applications)
public static final String CACHE_PRIVATE = "private";
public static final String CONTAINER = "container";
public static final String NAME = "name";
public static final String CACHES = "caches";
public static final String PENDING_PUTS = "pending-puts";
public static final String DEFAULT_CACHE_CONTAINER = "hibernate";
@Override
public void beforeEntityManagerFactoryCreate(Classification classification, PersistenceUnitMetadata persistenceUnitMetadata) {
}
@Override
public void afterEntityManagerFactoryCreate(Classification classification, PersistenceUnitMetadata persistenceUnitMetadata) {
}
@Override
public Wrapper startCache(Classification classification, Properties properties) throws Exception {
ServiceContainer target = currentServiceContainer();
String container = properties.getProperty(CONTAINER);
String cacheType = properties.getProperty(CACHE_TYPE);
// TODO Figure out how to access CapabilityServiceSupport from here
ServiceName containerServiceName = ServiceNameFactory.parseServiceName(InfinispanRequirement.CONTAINER.getName()).append(container);
// need a private cache for non-jpa application use
String name = properties.getProperty(NAME, UUID.randomUUID().toString());
ServiceBuilder<?> builder = target.addService(ServiceName.JBOSS.append(DEFAULT_CACHE_CONTAINER, name));
Supplier<EmbeddedCacheManager> manager = builder.requires(containerServiceName);
if (CACHE_PRIVATE.equals(cacheType)) {
// If using a private cache, addCacheDependencies(...) is never triggered
String[] caches = properties.getProperty(CACHES).split("\\s+");
for (String cache : caches) {
builder.requires(ServiceNameFactory.parseServiceName(InfinispanCacheRequirement.CONFIGURATION.getName()).append(container, cache));
}
}
final CountDownLatch latch = new CountDownLatch(1);
builder.addListener(new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.UP) {
latch.countDown();
controller.removeListener(this);
}
}
});
ServiceController<?> controller = builder.install();
// Ensure cache configuration services are started
latch.await();
return new CacheWrapper(manager.get(), controller);
}
@Override
public void addCacheDependencies(Classification classification, Properties properties) {
ServiceBuilder<?> builder = CacheDeploymentListener.getInternalDeploymentServiceBuilder();
CapabilityServiceSupport support = CacheDeploymentListener.getInternalDeploymentCapablityServiceSupport();
String container = properties.getProperty(CONTAINER);
for (String cache : properties.getProperty(CACHES).split("\\s+")) {
// Workaround for legacy default configuration, where the pending-puts cache configuration is missing
if (cache.equals(PENDING_PUTS) ? support.hasCapability(InfinispanCacheRequirement.CACHE.resolve(container, cache)) : true) {
builder.requires(InfinispanCacheRequirement.CONFIGURATION.getServiceName(support, container, cache));
}
}
}
@Override
public void stopCache(Classification classification, Wrapper wrapper) {
// Remove services created in startCache(...)
((CacheWrapper) wrapper).close();
}
private static class CacheWrapper implements Wrapper, AutoCloseable {
private final EmbeddedCacheManager embeddedCacheManager;
private final ServiceController<?> controller;
CacheWrapper(EmbeddedCacheManager embeddedCacheManager, ServiceController<?> controller) {
this.embeddedCacheManager = embeddedCacheManager;
this.controller = controller;
}
@Override
public Object getValue() {
return this.embeddedCacheManager;
}
@Override
public void close() {
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("stop second level cache by removing dependency on service '%s'", this.controller.getName().getCanonicalName());
}
final CountDownLatch latch = new CountDownLatch(1);
controller.addListener(new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.REMOVED) latch.countDown();
}
});
controller.setMode(ServiceController.Mode.REMOVE);
try {
latch.await();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
private static ServiceContainer currentServiceContainer() {
if (System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 7,827 | 43.225989 | 147 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/platform/PlatformImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.platform;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.plugin.spi.Platform;
/**
* represents the EE container platform that we are running in and its capabilities (e.g. default 2lc which
* currently can be INFINISPAN or NONE)
*
* @author Scott Marlow
*/
public class PlatformImpl implements Platform {
private final Classification defaultCacheClassification;
private final Set<Classification> cacheClassfications;
public PlatformImpl(Classification defaultCacheClassification, Classification... supportedClassifications) {
this.defaultCacheClassification = defaultCacheClassification;
ArrayList<Classification> includedClassifications = new ArrayList<>();
for(Classification eachClassification:supportedClassifications) {
includedClassifications.add(eachClassification);
}
this.cacheClassfications = !includedClassifications.isEmpty() ?
EnumSet.copyOf(includedClassifications):
Collections.<Classification>emptySet();
}
@Override
public Classification defaultCacheClassification() {
return defaultCacheClassification;
}
@Override
public Set<Classification> cacheClassifications() {
return cacheClassfications;
}
}
| 2,444 | 35.492537 | 112 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/Element.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* @author Scott Marlow
*/
public enum Element {
// must be first
UNKNOWN(null),
JPA(CommonAttributes.JPA),
DEFAULT_DATASOURCE(CommonAttributes.DEFAULT_DATASOURCE),
DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE(CommonAttributes.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE),;
private final String name;
Element(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null)
map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,170 | 30.463768 | 103 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/JPASubSystemAdd.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import static org.jboss.as.jpa.subsystem.JPADefinition.DEFAULT_DATASOURCE;
import static org.jboss.as.jpa.subsystem.JPADefinition.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.jpa.config.ExtendedPersistenceInheritance;
import org.jboss.as.jpa.persistenceprovider.PersistenceProviderResolverImpl;
import org.jboss.as.jpa.platform.PlatformImpl;
import org.jboss.as.jpa.processor.HibernateSearchProcessor;
import org.jboss.as.jpa.processor.JPAAnnotationProcessor;
import org.jboss.as.jpa.processor.JPAClassFileTransformerProcessor;
import org.jboss.as.jpa.processor.JPADependencyProcessor;
import org.jboss.as.jpa.processor.JPAInterceptorProcessor;
import org.jboss.as.jpa.processor.JPAJarJBossAllParser;
import org.jboss.as.jpa.processor.JpaAttachments;
import org.jboss.as.jpa.processor.PersistenceBeginInstallProcessor;
import org.jboss.as.jpa.processor.PersistenceCompleteInstallProcessor;
import org.jboss.as.jpa.processor.PersistenceRefProcessor;
import org.jboss.as.jpa.processor.PersistenceUnitParseProcessor;
import org.jboss.as.jpa.service.JPAService;
import org.jboss.as.jpa.service.JPAUserTransactionListenerService;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXmlParserRegisteringProcessor;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceTarget;
import org.jipijapa.cache.spi.Classification;
/**
* Add the Jakarta Persistence subsystem directive.
* <p/>
*
* @author Scott Marlow
*/
class JPASubSystemAdd extends AbstractBoottimeAddStepHandler {
public static final JPASubSystemAdd INSTANCE = new JPASubSystemAdd();
private JPASubSystemAdd() {
super(DEFAULT_DATASOURCE, DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE);
}
protected void performBoottime(final OperationContext context, final ModelNode operation, final ModelNode model) throws
OperationFailedException {
context.addStep(new AbstractDeploymentChainStep() {
protected void execute(DeploymentProcessorTarget processorTarget) {
// set Hibernate persistence provider as the default provider
jakarta.persistence.spi.PersistenceProviderResolverHolder.setPersistenceProviderResolver(
PersistenceProviderResolverImpl.getInstance());
final boolean appclient = context.getProcessType() == ProcessType.APPLICATION_CLIENT;
PlatformImpl platform;
if (appclient) {
// we do not yet support a second level cache in the client container
platform = new PlatformImpl(Classification.NONE);
} else {
// Infinispan can be used in server container
platform = new PlatformImpl(Classification.INFINISPAN, Classification.INFINISPAN);
}
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_JPA,
new JBossAllXmlParserRegisteringProcessor<>(JPAJarJBossAllParser.ROOT_ELEMENT, JpaAttachments.DEPLOYMENT_SETTINGS_KEY, new JPAJarJBossAllParser()));
// handles parsing of persistence.xml
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_PERSISTENCE_UNIT, new PersistenceUnitParseProcessor(appclient));
// handles persistence unit / context annotations in components
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_PERSISTENCE_ANNOTATION, new JPAAnnotationProcessor());
// injects Jakarta Persistence dependencies into an application
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JPA, new JPADependencyProcessor());
// Inject Hibernate Search dependencies into an application
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES,Phase.DEPENDENCIES_HIBERNATE_SEARCH , new HibernateSearchProcessor());
// handle ClassFileTransformer
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.FIRST_MODULE_USE, Phase.FIRST_MODULE_USE_PERSISTENCE_CLASS_FILE_TRANSFORMER, new JPAClassFileTransformerProcessor());
final CapabilityServiceSupport capabilities = context.getCapabilityServiceSupport();
if (capabilities.hasCapability("org.wildfly.ejb3")) {
// registers listeners/interceptors on session beans
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.FIRST_MODULE_USE, Phase.FIRST_MODULE_USE_INTERCEPTORS, new JPAInterceptorProcessor());
}
// begin pu service install and deploying a persistence provider
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.FIRST_MODULE_USE, Phase.FIRST_MODULE_USE_PERSISTENCE_PREPARE, new PersistenceBeginInstallProcessor(platform));
// handles persistence unit / context references from deployment descriptors
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_PERSISTENCE_REF, new PersistenceRefProcessor());
// handles pu deployment (completes pu service installation)
processorTarget.addDeploymentProcessor(JPAExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_PERSISTENTUNIT, new PersistenceCompleteInstallProcessor(platform));
}
}, OperationContext.Stage.RUNTIME);
final String dataSourceName = DEFAULT_DATASOURCE.resolveModelAttribute(context, model).asStringOrNull();
final ExtendedPersistenceInheritance defaultExtendedPersistenceInheritance = ExtendedPersistenceInheritance.valueOf(DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE.resolveModelAttribute(context, model).asString());
final ServiceTarget target = context.getServiceTarget();
JPAService.addService(target, dataSourceName, defaultExtendedPersistenceInheritance);
JPAUserTransactionListenerService.addService(target);
}
}
| 7,719 | 57.484848 | 214 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/JPADefinition.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.StringLengthValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
import org.jboss.as.jpa.config.ExtendedPersistenceInheritance;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Jakarta Persistence ResourceDefinition
*
*/
public class JPADefinition extends SimpleResourceDefinition {
// This a private capability. Its runtime API or capability service tyoe are subject to change.
// See WFLY-7521
// Currently it exists to indicate a model dependency from the Jakarta Persistence subsystem to the transactions subsystem
private static final RuntimeCapability<Void> JPA_CAPABILITY = RuntimeCapability.Builder.of("org.wildfly.jpa")
.addRequirements(JPAServiceNames.LOCAL_TRANSACTION_PROVIDER_CAPABILITY)
.build();
protected static final SimpleAttributeDefinition DEFAULT_DATASOURCE =
new SimpleAttributeDefinitionBuilder(CommonAttributes.DEFAULT_DATASOURCE, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.DEFAULT_DATASOURCE)
.setValidator(new StringLengthValidator(0, Integer.MAX_VALUE, true, true))
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.build();
protected static final SimpleAttributeDefinition DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE =
new SimpleAttributeDefinitionBuilder(CommonAttributes.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE, ModelType.STRING, true)
.setAllowExpression(true)
.setXmlName(CommonAttributes.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE)
.setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
.setValidator(EnumValidator.create(ExtendedPersistenceInheritance.class))
.setDefaultValue(new ModelNode(ExtendedPersistenceInheritance.DEEP.toString()))
.build();
JPADefinition() {
super(getParameters());
}
private static Parameters getParameters() {
Parameters result = new Parameters(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, JPAExtension.SUBSYSTEM_NAME),
JPAExtension.getResourceDescriptionResolver())
.setFeature(true)
.setCapabilities(JPA_CAPABILITY)
.setAddHandler(JPASubSystemAdd.INSTANCE)
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE);
return result;
}
@Override
public void registerAttributes(ManagementResourceRegistration registration) {
registration.registerReadWriteAttribute(DEFAULT_DATASOURCE, null, new ReloadRequiredWriteAttributeHandler(DEFAULT_DATASOURCE));
registration.registerReadWriteAttribute(DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE, null, new ReloadRequiredWriteAttributeHandler(DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE));
}
@Override
public void registerAdditionalRuntimePackages(final ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(
// Only if annotation is in use.
RuntimePackageDependency.optional("org.hibernate.search.orm"),
RuntimePackageDependency.required("org.hibernate"),
// An alias to org.hibernate module.
RuntimePackageDependency.optional("org.hibernate.envers"));
}
}
| 5,297 | 50.436893 | 177 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/JPADeploymentDefinition.java | package org.jboss.as.jpa.subsystem;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.global.ReadAttributeHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import java.util.List;
import static org.jboss.as.jpa.subsystem.JPADefinition.DEFAULT_DATASOURCE;
import static org.jboss.as.jpa.subsystem.JPADefinition.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE;
public class JPADeploymentDefinition extends SimpleResourceDefinition {
private static final PathElement ADDRESS = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, JPAExtension.SUBSYSTEM_NAME);
JPADeploymentDefinition() {
super(getParameters());
}
private static Parameters getParameters() {
Parameters result = new Parameters(ADDRESS,
JPAExtension.getResourceDescriptionResolver())
.setFeature(false)
.setRuntime();
return result;
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeDefinition attribute : List.of(DEFAULT_DATASOURCE, DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE)) {
resourceRegistration.registerReadOnlyAttribute(attribute, (context, operation) -> {
PathAddress subsystemAddress = context.getCurrentAddress().getParent().getParent().append(ADDRESS);
context.addStep(Util.getReadAttributeOperation(subsystemAddress, attribute.getName()), ReadAttributeHandler.RESOLVE_INSTANCE, context.getCurrentStage(), true);
});
}
}
}
| 1,885 | 42.860465 | 175 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/CommonAttributes.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
/**
* @author Scott Marlow
*/
interface CommonAttributes {
String DEFAULT_DATASOURCE = "default-datasource";
String JPA = "jpa";
String DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE = "default-extended-persistence-inheritance";
}
| 1,300 | 37.264706 | 96 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/PersistenceUnitRegistryImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.jpa.spi.PersistenceUnitService;
import org.jipijapa.plugin.spi.PersistenceUnitServiceRegistry;
/**
* Standard {@link PersistenceUnitServiceRegistry} implementation.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class PersistenceUnitRegistryImpl implements PersistenceUnitServiceRegistry {
public static final PersistenceUnitRegistryImpl INSTANCE = new PersistenceUnitRegistryImpl();
private final Map<String, PersistenceUnitService> registry = Collections.synchronizedMap(new HashMap<String, PersistenceUnitService>());
@Override
public PersistenceUnitService getPersistenceUnitService(String persistenceUnitResourceName) {
return registry.get(persistenceUnitResourceName);
}
public void add(String scopedPersistenceUnitName, PersistenceUnitService service) {
registry.put(scopedPersistenceUnitName, service);
}
public void remove(String scopedPersistenceUnitName) {
registry.remove(scopedPersistenceUnitName);
}
}
| 2,163 | 35.677966 | 140 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/Attribute.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import java.util.HashMap;
import java.util.Map;
/**
* @author Scott Marlow
*/
enum Attribute {
UNKNOWN(null),
DEFAULT_DATASOURCE_NAME(CommonAttributes.DEFAULT_DATASOURCE),
DEFAULT_EXTENDEDPERSISTENCEINHERITANCE_NAME(CommonAttributes.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE),;
private final String name;
Attribute(final String name) {
this.name = name;
}
/**
* Get the local name of this attribute.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> MAP;
static {
final Map<String, Attribute> map = new HashMap<String, Attribute>();
for (Attribute element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Attribute forName(String localName) {
final Attribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
public String toString() {
return getLocalName();
}
}
| 2,188 | 29.830986 | 107 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/Namespace.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author Scott Marlow
*/
enum Namespace {
// must be first
UNKNOWN(null),
JPA_1_0("urn:jboss:domain:jpa:1.0"),
JPA_1_1("urn:jboss:domain:jpa:1.1"),
;
private final String name;
Namespace(final String name) {
this.name = name;
}
/**
* Get the URI of this namespace.
*
* @return the URI
*/
public String getUriString() {
return name;
}
/**
* Set of all namespaces, excluding the special {@link #UNKNOWN} value.
*/
public static final EnumSet<Namespace> STANDARD_NAMESPACES = EnumSet.complementOf(EnumSet.of(Namespace.UNKNOWN));
private static final Map<String, Namespace> MAP;
static {
final Map<String, Namespace> map = new HashMap<String, Namespace>();
for (Namespace namespace : values()) {
final String name = namespace.getUriString();
if (name != null) map.put(name, namespace);
}
MAP = map;
}
public static Namespace forUri(String uri) {
final Namespace element = MAP.get(uri);
return element == null ? UNKNOWN : element;
}
}
| 2,273 | 29.72973 | 117 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/subsystem/JPAExtension.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.subsystem;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.controller.persistence.SubsystemMarshallingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.jpa.persistenceprovider.PersistenceProviderLoader;
import org.jboss.dmr.ModelNode;
import org.jboss.modules.ModuleLoadException;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* Domain extension used to initialize the Jakarta Persistence subsystem element handlers.
*
* @author Scott Marlow
*/
public class JPAExtension implements Extension {
public static final String SUBSYSTEM_NAME = "jpa";
private static final String RESOURCE_NAME = JPAExtension.class.getPackage().getName() + ".LocalDescriptions";
public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
for (String kp : keyPrefix) {
prefix.append('.').append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, JPAExtension.class.getClassLoader(), true, false);
}
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 2, 0);
@Override
public void initialize(ExtensionContext context) {
SubsystemRegistration registration = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration nodeRegistration = registration.registerSubsystemModel(new JPADefinition());
nodeRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
registration.registerXMLElementWriter(new JPASubsystemElementParser1_1());
try {
PersistenceProviderLoader.loadDefaultProvider();
} catch (ModuleLoadException e) {
ROOT_LOGGER.errorPreloadingDefaultProvider(e);
}
if (context.isRuntimeOnlyRegistrationValid()) {
registration.registerDeploymentModel(new JPADeploymentDefinition());
}
}
@Override
public void initializeParsers(ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.JPA_1_1.getUriString(), JPASubsystemElementParser1_1::new);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.JPA_1_0.getUriString(), JPASubsystemElementParser1_0::new);
}
static class JPASubsystemElementParser1_1 implements XMLStreamConstants, XMLElementReader<List<ModelNode>>,
XMLElementWriter<SubsystemMarshallingContext> {
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
ModelNode subsystemAdd = null;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
Namespace readerNS = Namespace.forUri(reader.getNamespaceURI());
if (element == Element.JPA) {
subsystemAdd = parseJPA(reader, readerNS);
} else {
throw ParseUtils.unexpectedElement(reader);
}
}
if (subsystemAdd == null) {
throw ParseUtils.missingRequiredElement(reader, Collections.singleton(Element.JPA.getLocalName()));
}
list.add(subsystemAdd);
}
private ModelNode parseJPA(XMLExtendedStreamReader reader, Namespace readerNS) throws XMLStreamException {
final ModelNode operation = Util.createAddOperation(PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME)));
int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case DEFAULT_DATASOURCE_NAME: {
JPADefinition.DEFAULT_DATASOURCE.parseAndSetParameter(value, operation, reader);
break;
}
case DEFAULT_EXTENDEDPERSISTENCEINHERITANCE_NAME:
JPADefinition.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE.parseAndSetParameter(value, operation, reader);
break;
default: {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
}
// Require no content
ParseUtils.requireNoContent(reader);
return operation;
}
/**
* {@inheritDoc}
*/
@Override
public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws
XMLStreamException {
ModelNode node = context.getModelNode();
context.startSubsystemElement(Namespace.JPA_1_1.getUriString(), false);
writer.writeStartElement(Element.JPA.getLocalName());
JPADefinition.DEFAULT_DATASOURCE.marshallAsAttribute(node, writer);
JPADefinition.DEFAULT_EXTENDEDPERSISTENCE_INHERITANCE.marshallAsAttribute(node, writer);
writer.writeEndElement();
writer.writeEndElement();
}
}
static class JPASubsystemElementParser1_0 implements XMLStreamConstants, XMLElementReader<List<ModelNode>> {
/**
* {@inheritDoc}
*/
@Override
public void readElement(XMLExtendedStreamReader reader, List<ModelNode> list) throws XMLStreamException {
ModelNode subsystemAdd = null;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
Namespace readerNS = Namespace.forUri(reader.getNamespaceURI());
if (element == Element.JPA) {
subsystemAdd = parseJPA(reader, readerNS);
} else {
throw ParseUtils.unexpectedElement(reader);
}
}
if (subsystemAdd == null) {
throw ParseUtils.missingRequiredElement(reader, Collections.singleton(Element.JPA.getLocalName()));
}
list.add(subsystemAdd);
}
private ModelNode parseJPA(XMLExtendedStreamReader reader, Namespace readerNS) throws XMLStreamException {
final ModelNode operation = Util.createAddOperation(PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME)));
int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
if (attribute == Attribute.DEFAULT_DATASOURCE_NAME) {
JPADefinition.DEFAULT_DATASOURCE.parseAndSetParameter(value, operation, reader);
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
// Require no content
ParseUtils.requireNoContent(reader);
return operation;
}
}
}
| 9,544 | 43.812207 | 141 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/util/JPAServiceNames.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.util;
import org.jboss.as.controller.ServiceNameFactory;
import org.jboss.msc.service.ServiceName;
/**
* For Jakarta Persistence service names
*
* @author Scott Marlow
*/
public class JPAServiceNames {
// identifies the (instance per) persistence unit service name
private static final ServiceName PERSISTENCE_UNIT_SERVICE_NAME = ServiceName.JBOSS.append("persistenceunit");
// identifies the (singleton) Jakarta Persistence service
public static final ServiceName JPA_SERVICE_NAME = ServiceName.JBOSS.append("jpa");
public static ServiceName getPUServiceName(String scopedPersistenceUnitName) {
return PERSISTENCE_UNIT_SERVICE_NAME.append(scopedPersistenceUnitName);
}
public static ServiceName getJPAServiceName() {
return JPA_SERVICE_NAME;
}
/**
* Name of the capability that ensures a local provider of transactions is present.
* Once its service is started, calls to the getInstance() methods of ContextTransactionManager,
* and LocalUserTransaction can be made knowing that the global default TM and UT will be from that provider.
*/
public static final String LOCAL_TRANSACTION_PROVIDER_CAPABILITY = "org.wildfly.transactions.global-default-local-provider";
/**
* Name of the capability that ensures a local provider of transactions is present.
* Once its service is started, calls to the getInstance() methods of ContextTransactionManager,
* and LocalUserTransaction can be made knowing that the global default TM and UT will be from that provider.
*/
public static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY = "org.wildfly.transactions.transaction-synchronization-registry";
// This parsing isn't 100% ideal as it's somewhat 'internal' knowledge of the relationship between
// capability names and service names. But at this point that relationship really needs to become
// a contract anyway
public static final ServiceName TRANSACTION_SYNCHRONIZATION_REGISTRY_SERVICE = ServiceNameFactory.parseServiceName(TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY);
}
| 3,169 | 45.617647 | 168 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/puparser/Element.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.puparser;
import java.util.HashMap;
import java.util.Map;
/**
* An enumeration of all the possible XML attributes in the Persistence Unit schema, by name.
*
* @author Scott Marlow
*/
public enum Element {
// always first
UNKNOWN(null),
// followed by all entries in sorted order
CLASS("class"),
DESCRIPTION("description"),
EXCLUDEUNLISTEDCLASSES("exclude-unlisted-classes"),
JARFILE("jar-file"),
JTADATASOURCE("jta-data-source"),
MAPPINGFILE("mapping-file"),
NAME("name"),
NONJTADATASOURCE("non-jta-data-source"),
PERSISTENCE("persistence"),
PERSISTENCEUNIT("persistence-unit"),
PROPERTIES("properties"),
PROPERTY("property"),
PROVIDER("provider"),
SHAREDCACHEMODE("shared-cache-mode"),
VALIDATIONMODE("validation-mode"),
VERSION("version");
private final String name;
Element(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Element> MAP;
static {
final Map<String, Element> map = new HashMap<String, Element>();
for (Element element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Element forName(String localName) {
final Element element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,624 | 29.882353 | 93 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/puparser/PersistenceUnitXmlParser.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.puparser;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.ValidationMode;
import jakarta.persistence.spi.PersistenceUnitTransactionType;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.config.PersistenceUnitMetadataImpl;
import org.jboss.metadata.parser.util.MetaDataElementParser;
import org.jboss.metadata.property.PropertyReplacer;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
/**
* Parse a persistence.xml into a list of persistence unit definitions.
*
* @author Scott Marlow
*/
public class PersistenceUnitXmlParser extends MetaDataElementParser {
// cache the trace enabled flag
private static final boolean traceEnabled = ROOT_LOGGER.isTraceEnabled();
private static final Version DEFAULT_VERSION;
static {
Version defaultVersion;
try {
// Try and load a jakarta namespace Jakarta Persistence API class to see if we're EE 8 or a later EE
PersistenceUnitXmlParser.class.getClassLoader().loadClass("jakarta.persistence.SharedCacheMode");
defaultVersion = Version.JPA_3_0;
} catch (Throwable t) {
defaultVersion = Version.JPA_2_2;
}
DEFAULT_VERSION = defaultVersion;
}
public static PersistenceUnitMetadataHolder parse(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
reader.require(START_DOCUMENT, null, null); // check for a bogus document and throw error
// Read until the first start element
Version version = null;
while (reader.hasNext() && reader.next() != START_ELEMENT) {
if (reader.getEventType() == DTD) {
final String dtdLocation = readDTDLocation(reader);
if (dtdLocation != null) {
version = Version.forLocation(dtdLocation);
}
}
}
final String schemaLocation = readSchemaLocation(reader);
if (schemaLocation != null) {
version = Version.forLocation(schemaLocation);
}
if (version == null || Version.UNKNOWN.equals(version)) {
// Look at the version attribute
String versionString = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String attributeNamespace = reader.getAttributeNamespace(i);
if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
continue;
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
if (attribute == Attribute.VERSION) {
versionString = reader.getAttributeValue(i);
}
}
version = Version.forVersion(versionString);
if (version == Version.UNKNOWN) {
// Try shorthand values, "1", "2" etc
version = Version.forVersion(versionString + ".0");
if (version == Version.UNKNOWN) {
version = DEFAULT_VERSION;
}
}
}
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String attributeNamespace = reader.getAttributeNamespace(i);
if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
continue;
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case VERSION:
// log.info("version = " + value);
// TODO: handle version
break;
default:
throw unexpectedAttribute(reader, i);
}
}
final List<PersistenceUnitMetadata> PUs = new ArrayList<PersistenceUnitMetadata>();
// until the ending PERSISTENCE tag
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PERSISTENCEUNIT:
PersistenceUnitMetadata pu = parsePU(reader, version, propertyReplacer);
PUs.add(pu);
ROOT_LOGGER.readingPersistenceXml(pu.getPersistenceUnitName());
break;
default:
throw unexpectedElement(reader);
}
}
PersistenceUnitMetadataHolder result = new PersistenceUnitMetadataHolder(PUs);
if (ROOT_LOGGER.isTraceEnabled())
ROOT_LOGGER.trace(result.toString());
return result;
}
/**
* Parse the persistence unit definitions based on persistence_2_0.xsd.
*
*
* @param reader
* @param propertyReplacer
* @return
* @throws XMLStreamException
*/
private static PersistenceUnitMetadata parsePU(XMLStreamReader reader, Version version, final PropertyReplacer propertyReplacer) throws XMLStreamException {
PersistenceUnitMetadata pu = new PersistenceUnitMetadataImpl();
List<String> classes = new ArrayList<String>(1);
List<String> jarFiles = new ArrayList<String>(1);
List<String> mappingFiles = new ArrayList<String>(1);
Properties properties = new Properties();
// set defaults
pu.setTransactionType(PersistenceUnitTransactionType.JTA);
pu.setValidationMode(ValidationMode.AUTO);
pu.setSharedCacheMode(SharedCacheMode.UNSPECIFIED);
pu.setPersistenceProviderClassName(Configuration.PROVIDER_CLASS_DEFAULT);
pu.setPersistenceXMLSchemaVersion(version.getVersion());
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (traceEnabled) {
ROOT_LOGGER.tracef("parse persistence.xml: attribute value(%d) = %s", i, value);
}
final String attributeNamespace = reader.getAttributeNamespace(i);
if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
continue;
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
pu.setPersistenceUnitName(value);
break;
case TRANSACTIONTYPE:
if (value.equalsIgnoreCase("RESOURCE_LOCAL"))
pu.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
// until the ending PERSISTENCEUNIT tag
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
if (traceEnabled) {
ROOT_LOGGER.tracef("parse persistence.xml: element=%s", element.getLocalName());
}
switch (element) {
case CLASS:
classes.add(getElement(reader, propertyReplacer));
break;
case DESCRIPTION:
final String description = getElement(reader, propertyReplacer);
break;
case EXCLUDEUNLISTEDCLASSES:
String text = getElement(reader, propertyReplacer);
if (text == null || text.isEmpty()) {
//the spec has examples where an empty
//exclude-unlisted-classes element has the same
//effect as setting it to true
pu.setExcludeUnlistedClasses(true);
} else {
pu.setExcludeUnlistedClasses(Boolean.valueOf(text));
}
break;
case JARFILE:
String file = getElement(reader, propertyReplacer);
jarFiles.add(file);
break;
case JTADATASOURCE:
pu.setJtaDataSourceName(getElement(reader, propertyReplacer));
break;
case NONJTADATASOURCE:
pu.setNonJtaDataSourceName(getElement(reader, propertyReplacer));
break;
case MAPPINGFILE:
mappingFiles.add(getElement(reader, propertyReplacer));
break;
case PROPERTIES:
parseProperties(reader, properties, propertyReplacer);
break;
case PROVIDER:
pu.setPersistenceProviderClassName(getElement(reader, propertyReplacer));
break;
case SHAREDCACHEMODE:
String cm = getElement(reader, propertyReplacer);
pu.setSharedCacheMode(SharedCacheMode.valueOf(cm));
break;
case VALIDATIONMODE:
String validationMode = getElement(reader, propertyReplacer);
pu.setValidationMode(ValidationMode.valueOf(validationMode));
break;
default:
throw unexpectedElement(reader);
}
}
if (traceEnabled) {
ROOT_LOGGER.trace("parse persistence.xml: reached ending persistence-unit tag");
}
pu.setManagedClassNames(classes);
pu.setJarFiles(jarFiles);
pu.setMappingFiles(mappingFiles);
pu.setProperties(properties);
return pu;
}
private static void parseProperties(XMLStreamReader reader, Properties properties, final PropertyReplacer propertyReplacer) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTY:
final int count = reader.getAttributeCount();
String name = null, value = null;
for (int i = 0; i < count; i++) {
final String attributeValue = getAttribute(reader, i, propertyReplacer);
final String attributeNamespace = reader.getAttributeNamespace(i);
if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
continue;
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
name = attributeValue;
break;
case VALUE:
value = attributeValue;
if (name != null && value != null) {
properties.put(name, value);
}
name = value = null;
break;
default:
throw unexpectedAttribute(reader, i);
}
}
if (reader.hasNext() && (reader.nextTag() != END_ELEMENT))
throw unexpectedElement(reader);
break;
default:
throw unexpectedElement(reader);
}
}
}
private static String getElement(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
return propertyReplacer.replaceProperties(reader.getElementText());
}
private static String getAttribute(final XMLStreamReader reader, int i, final PropertyReplacer propertyReplacer) throws XMLStreamException {
return propertyReplacer.replaceProperties(reader.getAttributeValue(i));
}
}
| 13,548 | 41.606918 | 160 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/puparser/Version.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.puparser;
import java.util.HashMap;
import java.util.Map;
/**
* @author Scott Marlow
*/
public enum Version {
UNKNOWN(null, null),
JPA_1_0("http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd", "1.0"),
JPA_2_0("http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd", "2.0"),
JPA_2_1("http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd", "2.1"),
JPA_2_2("http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd", "2.2"),
JPA_3_0("https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd", "3.0");
private static final Map<String, Version> locationBindings = new HashMap<String, Version>();
private static final Map<String, Version> versionBindings = new HashMap<String, Version>();
private final String location;
private final String version;
Version(String location, String version) {
this.location = location;
this.version = version;
}
public String getVersion() {
return version;
}
static {
for (Version version : values()) {
locationBindings.put(version.location, version);
versionBindings.put(version.version, version);
}
}
public static Version forLocation(final String location) {
final Version version = locationBindings.get(location);
return version != null ? version : UNKNOWN;
}
public static Version forVersion(final String version) {
final Version result = versionBindings.get(version);
return result != null ? result : UNKNOWN;
}
}
| 2,609 | 34.753425 | 96 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/puparser/Attribute.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.puparser;
import java.util.HashMap;
import java.util.Map;
/**
* @author Scott Marlow (cloned from Remy Maucherat)
*/
public enum Attribute {
// always first
UNKNOWN(null),
// attributes in alpha order
ID("id"),
LANG("lang"),
NAME("name"),
TRANSACTIONTYPE("transaction-type"),
VALUE("value"),
VERSION("version");
private final String name;
Attribute(final String name) {
this.name = name;
}
/**
* Get the local name of this element.
*
* @return the local name
*/
public String getLocalName() {
return name;
}
private static final Map<String, Attribute> MAP;
static {
final Map<String, Attribute> map = new HashMap<String, Attribute>();
for (Attribute element : values()) {
final String name = element.getLocalName();
if (name != null) map.put(name, element);
}
MAP = map;
}
public static Attribute forName(String localName) {
final Attribute element = MAP.get(localName);
return element == null ? UNKNOWN : element;
}
}
| 2,167 | 28.297297 | 76 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/beanmanager/BeanManagerAfterDeploymentValidation.java | /*
*
* * JBoss, Home of Professional Open Source.
* * Copyright 2016, Red Hat, Inc., and individual contributors
* * as indicated by the @author tags. See the copyright.txt file in the
* * distribution for a full listing of individual contributors.
* *
* * This is free software; you can redistribute it and/or modify it
* * under the terms of the GNU Lesser General Public License as
* * published by the Free Software Foundation; either version 2.1 of
* * the License, or (at your option) any later version.
* *
* * This software is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* * Lesser General Public License for more details.
* *
* * You should have received a copy of the GNU Lesser General Public
* * License along with this software; if not, write to the Free
* * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.jboss.as.jpa.beanmanager;
import java.util.ArrayList;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AfterDeploymentValidation;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.Extension;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
/**
* BeanManagerAfterDeploymentValidation
*
* @author Scott Marlow
*/
public class BeanManagerAfterDeploymentValidation implements Extension {
public BeanManagerAfterDeploymentValidation(boolean afterDeploymentValidation) {
this.afterDeploymentValidation = afterDeploymentValidation;
}
public BeanManagerAfterDeploymentValidation() {
}
void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) {
markPersistenceUnitAvailable();
}
private boolean afterDeploymentValidation = false;
private final ArrayList<DeferredCall> deferredCalls = new ArrayList();
public synchronized void register(final PersistenceProviderAdaptor persistenceProviderAdaptor, final Object wrapperBeanManagerLifeCycle) {
if (afterDeploymentValidation) {
persistenceProviderAdaptor.markPersistenceUnitAvailable(wrapperBeanManagerLifeCycle);
} else {
deferredCalls.add(new DeferredCall(persistenceProviderAdaptor, wrapperBeanManagerLifeCycle));
}
}
public synchronized void markPersistenceUnitAvailable() {
afterDeploymentValidation = true;
for(DeferredCall deferredCall: deferredCalls) {
deferredCall.markPersistenceUnitAvailable();
}
deferredCalls.clear();
}
private static class DeferredCall {
private final PersistenceProviderAdaptor persistenceProviderAdaptor;
private final Object wrapperBeanManagerLifeCycle;
DeferredCall(final PersistenceProviderAdaptor persistenceProviderAdaptor, final Object wrapperBeanManagerLifeCycle) {
this.persistenceProviderAdaptor = persistenceProviderAdaptor;
this.wrapperBeanManagerLifeCycle = wrapperBeanManagerLifeCycle;
}
void markPersistenceUnitAvailable() {
persistenceProviderAdaptor.markPersistenceUnitAvailable(wrapperBeanManagerLifeCycle);
}
}
}
| 3,380 | 37.420455 | 142 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/beanmanager/ProxyBeanManager.java | package org.jboss.as.jpa.beanmanager;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jboss.weld.util.ForwardingBeanManager;
/**
* Proxy for Jakarta Contexts and Dependency Injection BeanManager
*
* @author Scott Marlow
*/
public class ProxyBeanManager extends ForwardingBeanManager {
private volatile BeanManager delegate;
@Override
public BeanManager delegate() {
return delegate;
}
public void setDelegate(BeanManager delegate) {
this.delegate = delegate;
}
}
| 526 | 20.08 | 66 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/injectors/PersistenceContextInjectionSource.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.injectors;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.lang.reflect.Proxy;
import java.util.Map;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContextType;
import jakarta.persistence.SynchronizationType;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.jpa.config.ExtendedPersistenceInheritance;
import org.jboss.as.jpa.config.JPADeploymentSettings;
import org.jboss.as.jpa.container.CreatedEntityManagers;
import org.jboss.as.jpa.container.EntityManagerUnwrappedTargetInvocationHandler;
import org.jboss.as.jpa.container.ExtendedEntityManager;
import org.jboss.as.jpa.container.ExtendedPersistenceDeepInheritance;
import org.jboss.as.jpa.container.ExtendedPersistenceShallowInheritance;
import org.jboss.as.jpa.container.TransactionScopedEntityManager;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.service.JPAService;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.jpa.util.JPAServiceNames;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Represents the PersistenceContext injected into a component.
*
* @author Scott Marlow
*/
public class PersistenceContextInjectionSource extends InjectionSource {
private final PersistenceContextType type;
private final PersistenceContextJndiInjectable injectable;
private final ServiceName puServiceName;
/**
* Constructor for the PersistenceContextInjectorService
* @param type The persistence context type
* @param properties The persistence context properties
* @param puServiceName represents the deployed persistence.xml that we are going to use.
* @param serviceRegistry The MSC service registry which will be used to find the PersistenceContext service
* @param scopedPuName the fully scoped reference to the persistence.xml
* @param injectionTypeName is normally "jakarta.persistence.EntityManager" but could be a different target class
* for example "org.hibernate.Session" in which case, EntityManager.unwrap(org.hibernate.Session.class is called)
* @param pu
* @param jpaDeploymentSettings Optional {@link JPADeploymentSettings} applicable for the persistence context
*/
public PersistenceContextInjectionSource(final PersistenceContextType type, final SynchronizationType synchronizationType, final Map properties, final ServiceName puServiceName,
final ServiceRegistry serviceRegistry, final String scopedPuName, final String injectionTypeName, final PersistenceUnitMetadata pu, final JPADeploymentSettings jpaDeploymentSettings) {
this.type = type;
injectable = new PersistenceContextJndiInjectable(puServiceName, serviceRegistry, this.type, synchronizationType , properties, scopedPuName, injectionTypeName, pu, jpaDeploymentSettings);
this.puServiceName = puServiceName;
}
public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws
DeploymentUnitProcessingException {
serviceBuilder.requires(puServiceName);
injector.inject(injectable);
}
public boolean equals(Object other) {
if (other instanceof PersistenceContextInjectionSource) {
PersistenceContextInjectionSource source = (PersistenceContextInjectionSource) other;
return (source.puServiceName.equals(puServiceName));
}
return false;
}
public int hashCode() {
return puServiceName.hashCode();
}
private static final class PersistenceContextJndiInjectable implements ManagedReferenceFactory {
private final ServiceName puServiceName;
private final ServiceRegistry serviceRegistry;
private final PersistenceContextType type;
private final SynchronizationType synchronizationType;
private final Map properties;
private final String unitName;
private final String injectionTypeName;
private final PersistenceUnitMetadata pu;
private final JPADeploymentSettings jpaDeploymentSettings;
private static final String ENTITY_MANAGER_CLASS = "jakarta.persistence.EntityManager";
public PersistenceContextJndiInjectable(
final ServiceName puServiceName,
final ServiceRegistry serviceRegistry,
final PersistenceContextType type,
SynchronizationType synchronizationType,
final Map properties,
final String unitName,
final String injectionTypeName,
final PersistenceUnitMetadata pu,
final JPADeploymentSettings jpaDeploymentSettings) {
this.puServiceName = puServiceName;
this.serviceRegistry = serviceRegistry;
this.type = type;
this.properties = properties;
this.unitName = unitName;
this.injectionTypeName = injectionTypeName;
this.pu = pu;
this.synchronizationType = synchronizationType;
this.jpaDeploymentSettings = jpaDeploymentSettings;
}
@Override
public ManagedReference getReference() {
PersistenceUnitServiceImpl service = (PersistenceUnitServiceImpl) serviceRegistry.getRequiredService(puServiceName).getValue();
EntityManagerFactory emf = service.getEntityManagerFactory();
EntityManager entityManager;
boolean standardEntityManager = ENTITY_MANAGER_CLASS.equals(injectionTypeName);
//TODO: change all this to use injections
//this is currntly safe, as there is a DUP dependency on the TSR
TransactionSynchronizationRegistry tsr = (TransactionSynchronizationRegistry) serviceRegistry.getRequiredService(JPAServiceNames.TRANSACTION_SYNCHRONIZATION_REGISTRY_SERVICE).getValue();
TransactionManager transactionManager = ContextTransactionManager.getInstance();
if (type.equals(PersistenceContextType.TRANSACTION)) {
entityManager = new TransactionScopedEntityManager(unitName, properties, emf, synchronizationType, tsr, transactionManager);
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf("created new TransactionScopedEntityManager for unit name=%s", unitName);
} else {
boolean useDeepInheritance = !ExtendedPersistenceInheritance.SHALLOW.equals(JPAService.getDefaultExtendedPersistenceInheritance());
if (jpaDeploymentSettings != null) {
useDeepInheritance = ExtendedPersistenceInheritance.DEEP.equals(jpaDeploymentSettings.getExtendedPersistenceInheritanceType());
}
boolean createdNewExtendedPersistence = false;
ExtendedEntityManager entityManager1;
// handle PersistenceContextType.EXTENDED
if (useDeepInheritance) {
entityManager1 = ExtendedPersistenceDeepInheritance.INSTANCE.findExtendedPersistenceContext(unitName);
}
else {
entityManager1 = ExtendedPersistenceShallowInheritance.INSTANCE.findExtendedPersistenceContext(unitName);
}
if (entityManager1 == null) {
if (SynchronizationType.UNSYNCHRONIZED.equals(synchronizationType)) {
entityManager1 = new ExtendedEntityManager(unitName, emf.createEntityManager(synchronizationType, properties), synchronizationType, tsr, transactionManager);
}
else {
entityManager1 = new ExtendedEntityManager(unitName, emf.createEntityManager(properties), synchronizationType, tsr, transactionManager);
}
createdNewExtendedPersistence = true;
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf("created new ExtendedEntityManager for unit name=%s, useDeepInheritance = %b", unitName, useDeepInheritance);
} else {
entityManager1.increaseReferenceCount();
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf("inherited existing ExtendedEntityManager from SFSB invocation stack, unit name=%s, " +
"%d beans sharing ExtendedEntityManager, useDeepInheritance = %b", unitName, entityManager1.getReferenceCount(), useDeepInheritance);
}
entityManager = entityManager1;
// register the EntityManager on TL so that SFSBCreateInterceptor will see it.
// this is important for creating a new XPC or inheriting existing XPC from SFSBCallStack
CreatedEntityManagers.registerPersistenceContext(entityManager1);
if (createdNewExtendedPersistence) {
//register the pc so it is accessible to other SFSB's during the creation process
if (useDeepInheritance) {
ExtendedPersistenceDeepInheritance.INSTANCE.registerExtendedPersistenceContext(unitName, entityManager1);
}
else {
ExtendedPersistenceShallowInheritance.INSTANCE.registerExtendedPersistenceContext(unitName, entityManager1);
}
}
}
if (!standardEntityManager) {
/**
* inject non-standard wrapped class (e.g. org.hibernate.Session).
* To accomplish this, we will create an instance of the (underlying provider's) entity manager and
* invoke the EntityManager.unwrap(TargetInjectionClass).
*/
Class<?> extensionClass;
try {
// provider classes should be on application classpath
extensionClass = pu.getClassLoader().loadClass(injectionTypeName);
} catch (ClassNotFoundException e) {
throw JpaLogger.ROOT_LOGGER.cannotLoadFromJpa(e, injectionTypeName);
}
// get example of target object
Object targetValueToInject = entityManager.unwrap(extensionClass);
// build array of classes that proxy will represent.
Class<?>[] targetInterfaces = targetValueToInject.getClass().getInterfaces();
Class<?>[] proxyInterfaces = new Class[targetInterfaces.length + 1]; // include extra element for extensionClass
boolean alreadyHasInterfaceClass = false;
for (int interfaceIndex = 0; interfaceIndex < targetInterfaces.length; interfaceIndex++) {
Class<?> interfaceClass = targetInterfaces[interfaceIndex];
if (interfaceClass.equals(extensionClass)) {
proxyInterfaces = targetInterfaces; // targetInterfaces already has all interfaces
alreadyHasInterfaceClass = true;
break;
}
proxyInterfaces[1 + interfaceIndex] = interfaceClass;
}
if (!alreadyHasInterfaceClass) {
proxyInterfaces[0] = extensionClass;
}
EntityManagerUnwrappedTargetInvocationHandler entityManagerUnwrappedTargetInvocationHandler =
new EntityManagerUnwrappedTargetInvocationHandler(entityManager, extensionClass);
Object proxyForUnwrappedObject = Proxy.newProxyInstance(
extensionClass.getClassLoader(), //use the target classloader so the proxy has the same scope
proxyInterfaces,
entityManagerUnwrappedTargetInvocationHandler
);
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf("injecting entity manager into a '%s' (unit name=%s)", extensionClass.getName(), unitName);
return new ValueManagedReference(proxyForUnwrappedObject);
}
return new ValueManagedReference(entityManager);
}
}
}
| 14,192 | 51.958955 | 229 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/injectors/PersistenceUnitInjectionSource.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.injectors;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jakarta.persistence.EntityManagerFactory;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* Represents the PersistenceUnit injected into a component.
* TODO: support injecting into a HibernateSessionFactory. Initially, hack it by checking injectionTypeName parameter
* for HibernateSessionFactory. If/when Jakarta Persistence supports unwrap on the EMF, switch to that.
*
* @author Scott Marlow
*/
public class PersistenceUnitInjectionSource extends InjectionSource {
private final PersistenceUnitJndiInjectable injectable;
private final ServiceName puServiceName;
public PersistenceUnitInjectionSource(final ServiceName puServiceName, final ServiceRegistry serviceRegistry, final String injectionTypeName, final PersistenceUnitMetadata pu) {
injectable = new PersistenceUnitJndiInjectable(puServiceName, serviceRegistry, injectionTypeName, pu);
this.puServiceName = puServiceName;
}
public void getResourceValue(final ResolutionContext resolutionContext, final ServiceBuilder<?> serviceBuilder, final DeploymentPhaseContext phaseContext, final Injector<ManagedReferenceFactory> injector) throws
DeploymentUnitProcessingException {
serviceBuilder.requires(puServiceName);
injector.inject(injectable);
}
public boolean equals(final Object other) {
if (other instanceof PersistenceUnitInjectionSource) {
PersistenceUnitInjectionSource source = (PersistenceUnitInjectionSource) other;
return (source.puServiceName.equals(puServiceName));
}
return false;
}
public int hashCode() {
return puServiceName.hashCode();
}
private static final class PersistenceUnitJndiInjectable implements ManagedReferenceFactory {
final ServiceName puServiceName;
final ServiceRegistry serviceRegistry;
final String injectionTypeName;
final PersistenceUnitMetadata pu;
private static final String ENTITY_MANAGER_FACTORY_CLASS = "jakarta.persistence.EntityManagerFactory";
public PersistenceUnitJndiInjectable(
final ServiceName puServiceName,
final ServiceRegistry serviceRegistry,
final String injectionTypeName,
final PersistenceUnitMetadata pu) {
this.puServiceName = puServiceName;
this.serviceRegistry = serviceRegistry;
this.injectionTypeName = injectionTypeName;
this.pu = pu;
}
@Override
public ManagedReference getReference() {
PersistenceUnitServiceImpl service = (PersistenceUnitServiceImpl) serviceRegistry.getRequiredService(puServiceName).getValue();
EntityManagerFactory emf = service.getEntityManagerFactory();
if (!ENTITY_MANAGER_FACTORY_CLASS.equals(injectionTypeName)) { // inject non-standard wrapped class (e.g. org.hibernate.SessionFactory)
Class<?> extensionClass;
try {
// make sure we can access the target class type
extensionClass = pu.getClassLoader().loadClass(injectionTypeName);
} catch (ClassNotFoundException e) {
throw JpaLogger.ROOT_LOGGER.cannotLoadFromJpa(e, injectionTypeName);
}
// TODO: when/if Jakarta Persistence supports unwrap, change to
// Object targetValueToInject = emf.unwrap(extensionClass);
// Until Jakarta Persistence supports unwrap on sessionfactory, only support hibernate
Method getSessionFactory;
try {
getSessionFactory = emf.getClass().getMethod("getSessionFactory");
} catch (NoSuchMethodException e) {
throw JpaLogger.ROOT_LOGGER.hibernateOnlyEntityManagerFactory();
}
Object targetValueToInject = null;
try {
targetValueToInject = getSessionFactory.invoke(emf, new Object[0]);
} catch (IllegalAccessException e) {
throw JpaLogger.ROOT_LOGGER.cannotGetSessionFactory(e);
} catch (InvocationTargetException e) {
throw JpaLogger.ROOT_LOGGER.cannotGetSessionFactory(e);
}
return new ValueManagedReference(targetValueToInject);
}
return new ValueManagedReference(emf);
}
}
}
| 6,224 | 43.148936 | 215 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/persistenceprovider/PersistenceProviderLoader.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.persistenceprovider;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import jakarta.persistence.spi.PersistenceProvider;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
/**
* For loading persistence provider modules
*
* @author Scott Marlow
*/
public class PersistenceProviderLoader {
/**
* pre-loads the default persistence provider
*
* @throws ModuleLoadException
*/
public static void loadDefaultProvider() throws ModuleLoadException {
String defaultProviderModule = Configuration.getDefaultProviderModuleName();
loadProviderModuleByName(defaultProviderModule);
}
/**
* Loads the specified Jakarta Persistence persistence provider module
*
* @param moduleName is the static module to be loaded
* @throws ModuleLoadException
* @return list of persistence providers in specified module
*
* Note: side effect of saving loaded persistence providers to static api in jakarta.persistence.spi.PersistenceProvider.
*/
public static List<PersistenceProvider> loadProviderModuleByName(String moduleName) throws ModuleLoadException {
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
Module module = moduleLoader.loadModule(ModuleIdentifier.fromString(moduleName));
final ServiceLoader<PersistenceProvider> serviceLoader =
module.loadService(PersistenceProvider.class);
List<PersistenceProvider> result = new ArrayList<>();
if (serviceLoader != null) {
for (PersistenceProvider provider1 : serviceLoader) {
// persistence provider jar may contain multiple provider service implementations
// save each provider
PersistenceProviderResolverImpl.getInstance().addPersistenceProvider(provider1);
result.add(provider1);
}
}
return result;
}
public static PersistenceProvider loadProviderFromDeployment(ClassLoader classLoader, String persistenceProviderClassName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return (PersistenceProvider) classLoader.loadClass(persistenceProviderClassName).newInstance();
}
}
| 3,472 | 39.858824 | 206 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/persistenceprovider/PersistenceProviderResolverImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.persistenceprovider;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import jakarta.persistence.spi.PersistenceProvider;
import jakarta.persistence.spi.PersistenceProviderResolver;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.modules.ModuleClassLoader;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Implementation of PersistenceProviderResolver
*
* @author Scott Marlow
*/
public class PersistenceProviderResolverImpl implements PersistenceProviderResolver {
private Map<ClassLoader, List<Class<? extends PersistenceProvider>>> persistenceProviderPerClassLoader = new HashMap<>();
private List<Class<? extends PersistenceProvider>> providers = new CopyOnWriteArrayList<>();
private static final PersistenceProviderResolverImpl INSTANCE = new PersistenceProviderResolverImpl();
public static PersistenceProviderResolverImpl getInstance() {
return INSTANCE;
}
public PersistenceProviderResolverImpl() {
}
/**
* Return a new instance of each persistence provider class
*
* @return
*/
@Override
public List<PersistenceProvider> getPersistenceProviders() {
List<PersistenceProvider> providersCopy = new ArrayList<>(providers.size());
/**
* Add the application specified providers first so they are found before the global providers
*/
synchronized(persistenceProviderPerClassLoader) {
if (persistenceProviderPerClassLoader.size() > 0) {
// get the deployment or subdeployment classloader
ClassLoader deploymentClassLoader = findParentModuleCl(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
ROOT_LOGGER.tracef("get application level Persistence Provider for classloader %s" , deploymentClassLoader);
// collect persistence providers associated with deployment/each sub-deployment
List<Class<? extends PersistenceProvider>> deploymentSpecificPersistenceProviders = persistenceProviderPerClassLoader.get(deploymentClassLoader);
ROOT_LOGGER.tracef("got application level Persistence Provider list %s" , deploymentSpecificPersistenceProviders);
if (deploymentSpecificPersistenceProviders != null) {
for (Class<? extends PersistenceProvider> providerClass : deploymentSpecificPersistenceProviders) {
try {
ROOT_LOGGER.tracef("application has its own Persistence Provider %s", providerClass.getName());
providersCopy.add(providerClass.newInstance());
} catch (InstantiationException e) {
throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
} catch (IllegalAccessException e) {
throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
}
}
}
}
}
// add global persistence providers last (so application packaged providers have priority)
for (Class<?> providerClass : providers) {
try {
providersCopy.add((PersistenceProvider) providerClass.newInstance());
ROOT_LOGGER.tracef("returning global (module) Persistence Provider %s", providerClass.getName());
} catch (InstantiationException e) {
throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
} catch (IllegalAccessException e) {
throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
}
}
return providersCopy;
}
@Override
public void clearCachedProviders() {
providers.clear();
}
/**
* Cleared at application undeployment time to remove any persistence providers that were deployed with the application
*
* @param deploymentClassLoaders
*/
public void clearCachedDeploymentSpecificProviders(Set<ClassLoader> deploymentClassLoaders) {
synchronized(persistenceProviderPerClassLoader) {
for (ClassLoader deploymentClassLoader: deploymentClassLoaders) {
persistenceProviderPerClassLoader.remove(deploymentClassLoader);
}
}
}
/**
* Set at application deployment time to the persistence providers packaged in the application
*
* @param persistenceProvider
* @param deploymentClassLoaders
*/
public void addDeploymentSpecificPersistenceProvider(PersistenceProvider persistenceProvider, Set<ClassLoader> deploymentClassLoaders) {
synchronized(persistenceProviderPerClassLoader) {
for (ClassLoader deploymentClassLoader: deploymentClassLoaders) {
List<Class<? extends PersistenceProvider>> list = persistenceProviderPerClassLoader.get(deploymentClassLoader);
ROOT_LOGGER.tracef("getting persistence provider list (%s) for deployment (%s)", list, deploymentClassLoader );
if (list == null) {
list = new ArrayList<>();
persistenceProviderPerClassLoader.put(deploymentClassLoader, list);
ROOT_LOGGER.tracef("saving new persistence provider list (%s) for deployment (%s)", list, deploymentClassLoader );
}
list.add(persistenceProvider.getClass());
ROOT_LOGGER.tracef("added new persistence provider (%s) to provider list (%s)", persistenceProvider.getClass().getName(), list);
}
}
}
/**
* If a custom CL is in use we want to get the module CL it delegates to
* @param classLoader The current CL
* @returnThe corresponding module CL
*/
private ClassLoader findParentModuleCl(ClassLoader classLoader) {
ClassLoader c = classLoader;
while (c != null && !(c instanceof ModuleClassLoader)) {
c = c.getParent();
}
return c;
}
public void addPersistenceProvider(PersistenceProvider persistenceProvider) {
providers.add(persistenceProvider.getClass());
}
}
| 7,526 | 42.508671 | 161 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/classloader/TempClassLoader.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.classloader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.jboss.modules.ConcurrentClassLoader;
/**
* Return a new instance of a ClassLoader that the may be used to temporarily load any classes,
* resources, or open URLs. None of the classes loaded by this class loader will be visible to
* application components.
* <p/>
* TempClassLoader is suitable for implementing jakarta.persistence.spi.PersistenceUnitInfo.getNewTempClassLoader()
* <p/>
*
* @author Scott Marlow
* @author Antti Laisi
*/
public class TempClassLoader extends ConcurrentClassLoader {
public static final String STARTS_WITH_JAVAX = "javax.";
public static final String STARTS_WITH_JAVA = "java.";
public static final String STARTS_WITH_JAKARTA = "jakarta.";
private final ClassLoader delegate;
private static final String MANIFEST_MF = "META-INF" + File.separatorChar + "MANIFEST.MF";
static {
try {
ClassLoader.registerAsParallelCapable();
} catch (Throwable ignored) {}
}
TempClassLoader(final ClassLoader delegate) {
super((ConcurrentClassLoader) null);
this.delegate = delegate;
}
@Override
protected Class<?> findClass(String name, boolean exportsOnly, boolean resolve) throws ClassNotFoundException {
Class<?> loaded = findLoadedClass(name);
if (loaded != null) {
return loaded;
}
// jakarta.persistence classes must be loaded by module classloader, otherwise
// the persistence provider can't read Jakarta Persistence annotations with reflection
if (name.startsWith(STARTS_WITH_JAKARTA) ||
name.startsWith(STARTS_WITH_JAVAX) ||
name.startsWith(STARTS_WITH_JAVA)) {
return Class.forName(name, resolve, delegate);
}
InputStream resource = delegate.getResourceAsStream(name.replace('.', '/') + ".class");
if (resource == null) {
throw new ClassNotFoundException(name);
}
// Ensure that the package is loaded
final int lastIdx = name.lastIndexOf('.');
if (lastIdx != -1) {
// there's a package name; get the Package for it
final String packageName = name.substring(0, lastIdx);
synchronized (this) {
Package pkg = findLoadedPackage(packageName);
if (pkg == null) {
Manifest manifest = readManifestFile();
if (manifest != null) {
final Attributes mainAttribute = manifest.getMainAttributes();
final Attributes entryAttribute = manifest.getAttributes(packageName);
URL url =
"true".equals(getDefinedAttribute(Attributes.Name.SEALED, entryAttribute, mainAttribute))
? delegate.getResource(name.replace('.', '/') + ".class") : null;
definePackage(
packageName,
getDefinedAttribute(Attributes.Name.SPECIFICATION_TITLE, entryAttribute, mainAttribute),
getDefinedAttribute(Attributes.Name.SPECIFICATION_VERSION, entryAttribute, mainAttribute),
getDefinedAttribute(Attributes.Name.SPECIFICATION_VENDOR, entryAttribute, mainAttribute),
getDefinedAttribute(Attributes.Name.IMPLEMENTATION_TITLE, entryAttribute, mainAttribute),
getDefinedAttribute(Attributes.Name.IMPLEMENTATION_VERSION, entryAttribute, mainAttribute),
getDefinedAttribute(Attributes.Name.IMPLEMENTATION_VENDOR, entryAttribute, mainAttribute),
url
);
}
else {
definePackage(packageName, null, null, null, null, null, null, null);
}
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
for (int i = 0; (i = resource.read(buffer, 0, buffer.length)) != -1; ) {
baos.write(buffer, 0, i);
}
buffer = baos.toByteArray();
return defineClass(name, buffer, 0, buffer.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
} finally {
try {
resource.close();
} catch (IOException e) {
// ignore
}
}
}
@Override
protected URL findResource(String name, boolean exportsOnly) {
return delegate.getResource(name);
}
@Override
protected Enumeration<URL> findResources(String name, boolean exportsOnly) throws IOException {
return delegate.getResources(name);
}
@Override
protected InputStream findResourceAsStream(String name, boolean exportsOnly) {
return delegate.getResourceAsStream(name);
}
/** {@inheritDoc} */
@Override
protected final Package definePackage(final String name, final String specTitle, final String specVersion, final String specVendor, final String implTitle, final String implVersion, final String implVendor, final URL sealBase) throws IllegalArgumentException {
return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
}
private Manifest readManifestFile() {
InputStream resource = null;
try {
resource = delegate.getResourceAsStream(MANIFEST_MF);
return resource != null ? new Manifest(resource) : null;
} catch (IOException e) {
return null;
}
finally {
if ( resource != null) {
try {
resource.close();
} catch (IOException ignored) {
}
}
}
}
private static String getDefinedAttribute(Attributes.Name name, Attributes entryAttribute, Attributes mainAttribute) {
final String value = entryAttribute == null ? null : entryAttribute.getValue(name);
return value == null ? mainAttribute == null ? null : mainAttribute.getValue(name) : value;
}
}
| 7,625 | 40 | 264 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/classloader/TempClassLoaderFactoryImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.classloader;
import org.jipijapa.plugin.spi.TempClassLoaderFactory;
/**
* Factory implementation that creates {@link TempClassLoader} instances.
*
* @author Antti Laisi
*/
public class TempClassLoaderFactoryImpl implements TempClassLoaderFactory {
private final ClassLoader delegateClassLoader;
public TempClassLoaderFactoryImpl(final ClassLoader delegateClassLoader) {
this.delegateClassLoader = delegateClassLoader;
}
@Override
public ClassLoader createNewTempClassLoader() {
return new TempClassLoader(delegateClassLoader);
}
}
| 1,630 | 34.456522 | 78 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/transaction/TransactionUtil.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.transaction;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.jpa.messages.JpaLogger.ROOT_LOGGER;
import java.security.PrivilegedAction;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.jpa.container.ExtendedEntityManager;
import org.jboss.as.jpa.messages.JpaLogger;
import org.jboss.tm.TxUtils;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.AssociationListener;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* Transaction utilities for Jakarta Persistence
*
* @author Scott Marlow (forked from code by Gavin King)
*/
public class TransactionUtil {
public static boolean isInTx(TransactionManager transactionManager) {
Transaction tx = getTransaction(transactionManager);
if (tx == null || !TxUtils.isActive(tx))
return false;
return true;
}
/**
* Get current persistence context. Only call while a transaction is active in the current thread.
*
* @param puScopedName
* @return
*/
public static EntityManager getTransactionScopedEntityManager(String puScopedName, TransactionSynchronizationRegistry tsr) {
return getEntityManagerInTransactionRegistry(puScopedName, tsr);
}
public static void registerSynchronization(EntityManager entityManager, String puScopedName, TransactionSynchronizationRegistry tsr, TransactionManager transactionManager) {
SessionSynchronization sessionSynchronization = new SessionSynchronization(entityManager, puScopedName);
tsr.registerInterposedSynchronization(sessionSynchronization);
final AbstractTransaction transaction = ((ContextTransactionManager) transactionManager).getTransaction();
doPrivileged((PrivilegedAction<Void>) () -> {
transaction.registerAssociationListener(sessionSynchronization);
return null;
});
}
public static Transaction getTransaction(TransactionManager transactionManager) {
try {
return transactionManager.getTransaction();
} catch (SystemException e) {
throw JpaLogger.ROOT_LOGGER.errorGettingTransaction(e);
}
}
private static String currentThread() {
return Thread.currentThread().getName();
}
public static String getEntityManagerDetails(EntityManager manager, String scopedPuName) {
String result = currentThread() + ":"; // show the thread for correlation with other modules
if (manager instanceof ExtendedEntityManager) {
result += manager.toString();
}
else {
result += "transaction scoped EntityManager [" + scopedPuName + "]";
}
return result;
}
private static EntityManager getEntityManagerInTransactionRegistry(String scopedPuName, TransactionSynchronizationRegistry tsr) {
return (EntityManager)tsr.getResource(scopedPuName);
}
/**
* Save the specified EntityManager in the local threads active transaction. The TransactionSynchronizationRegistry
* will clear the reference to the EntityManager when the transaction completes.
*
* @param scopedPuName
* @param entityManager
*/
public static void putEntityManagerInTransactionRegistry(String scopedPuName, EntityManager entityManager, TransactionSynchronizationRegistry tsr) {
tsr.putResource(scopedPuName, entityManager);
}
/**
* The AssociationListener helps protect against a non-application thread closing the entity manager at the same
* time that the application thread may be using the entity manager. We only close the entity manager after the
* Synchronization.afterCompletion has been triggered and zero threads are associated with the transaction.
*
* We know when the application thread is associated with the transaction and can defer closing the EntityManager
* until both conditions are met:
*
* 1. application thread is disassociated from transaction
* 2. Synchronization.afterCompletion has been called
*
* Note that entity managers do not get propagated on remote Jakarta Enterprise Beans invocations.
*
* See discussions for more details about how we arrived at using the AssociationListener (TransactionListener):
* https://developer.jboss.org/message/919807
* https://developer.jboss.org/thread/252572
*/
private static class SessionSynchronization implements Synchronization, AssociationListener {
private EntityManager manager; // the underlying entity manager
private String scopedPuName;
private boolean afterCompletionCalled = false;
private int associationCounter = 1; // set to one since transaction is associated with current thread already.
// incremented when a thread is associated with transaction,
// decremented when a thread is disassociated from transaction.
// synchronization on this object protects associationCounter.
public SessionSynchronization(EntityManager session, String scopedPuName) {
this.manager = session;
this.scopedPuName = scopedPuName;
}
public void beforeCompletion() {
afterCompletionCalled = false;
}
public void afterCompletion(int status) {
/**
* Note: synchronization is to protect against two concurrent threads from closing the EntityManager (manager)
* at the same time.
*/
synchronized (this) {
afterCompletionCalled = true;
safeCloseEntityManager();
}
}
/**
* After the Jakarta Transactions transaction is ended (Synchronization.afterCompletion has been called) and
* the Jakarta Transactions transaction is no longer associated with application thread (application thread called
* transaction.rollback/commit/suspend), the entity manager can safely be closed.
*
* NOTE: caller must call with synchronized(this), where this == instance of SessionSynchronization associated with
* the Jakarta Transactions transaction.
*/
private void safeCloseEntityManager() {
if (afterCompletionCalled
&& associationCounter == 0
&& manager != null) {
try {
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf("%s: closing entity managersession", getEntityManagerDetails(manager, scopedPuName));
manager.close();
} catch (Exception ignored) {
if (ROOT_LOGGER.isDebugEnabled())
ROOT_LOGGER.debugf(ignored, "ignoring error that occurred while closing EntityManager for %s (",
scopedPuName);
}
manager = null;
}
}
public void associationChanged(final AbstractTransaction transaction, final boolean associated) {
synchronized (this) {
// associationCounter is set to zero when application thread is no longer associated with Jakarta Transactions transaction.
// We are tracking when the application thread
// is no longer associated with the transaction, as that indicates that it is safe to
// close the entity manager (since the application is no longer using the entity manager).
//
// Expected values for associationCounter:
// 1 - application thread is associated with transaction
// 0 - application thread is not associated with transaction (e.g. tm.suspend called)
//
// Expected values for TM Reaper thread timing out transaction
// 1 - application thread is associated with transaction
// 2 - TM reaper thread is associated with transaction (tx timeout handling)
// 1 - either TM reaper or application thread disassociated from transaction
// 0 - both TM reaper and application thread are disassociated from transaction
//
// the safeCloseEntityManager() may close the entity manager in the (background) reaper thread or
// application thread (whichever thread reaches associationCounter == 0).
associationCounter += associated ? 1 : -1;
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.tracef("transaction association counter = %d for %s: ", associationCounter, getEntityManagerDetails(manager, scopedPuName));
}
safeCloseEntityManager();
}
}
}
}
| 10,258 | 46.49537 | 177 | java |
null | wildfly-main/jpa/subsystem/src/main/java/org/jboss/as/jpa/transaction/JtaManagerImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.jpa.spi.JtaManager;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* passes the TM and TSR into the persistence provider integration classes
*
* @author Scott Marlow
*/
public final class JtaManagerImpl implements JtaManager {
private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
public JtaManagerImpl(TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
}
@Override
public TransactionSynchronizationRegistry getSynchronizationRegistry() {
return transactionSynchronizationRegistry;
}
@Override
public TransactionManager locateTransactionManager() {
return ContextTransactionManager.getInstance();
}
}
| 2,017 | 36.37037 | 98 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/LastUpdateListener.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack;
import java.util.Date;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
public class LastUpdateListener {
@PreUpdate
@PrePersist
public void setLastUpdate(Cat o) {
o.setLastUpdate(new Date());
o.setManualVersion(o.getManualVersion() + 1);
}
}
| 1,163 | 33.235294 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/Kitten.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Hardy Ferentschik
*/
@SuppressWarnings("serial")
@Entity
public class Kitten {
private Integer id;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
public String toString() {
final String TAB = " ";
String retValue = "";
retValue = "Kitten ( "
+ super.toString() + TAB
+ "id = " + this.id + TAB
+ "name = " + this.name + TAB
+ " )";
return retValue;
}
}
| 1,862 | 24.875 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/Distributor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack;
import java.io.Serializable;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Distributor implements Serializable {
private Integer id;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (this == o) { return true; }
if (!(o instanceof Distributor)) { return false; }
final Distributor distributor = (Distributor) o;
if (!name.equals(distributor.name)) { return false; }
return true;
}
public int hashCode() {
return name.hashCode();
}
}
| 1,741 | 25.393939 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/Item.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityResult;
import jakarta.persistence.FieldResult;
import jakarta.persistence.Id;
import jakarta.persistence.LockModeType;
import jakarta.persistence.NamedNativeQueries;
import jakarta.persistence.NamedNativeQuery;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.QueryHint;
import jakarta.persistence.SqlResultSetMapping;
import org.hibernate.annotations.QueryHints;
/**
* @author Gavin King
*/
@Entity(name = "Item")
@SqlResultSetMapping(name = "getItem", entities =
@EntityResult(entityClass = Item.class, fields = {
@FieldResult(name = "name", column = "itemname"),
@FieldResult(name = "descr", column = "itemdescription")
})
)
@NamedNativeQueries({
@NamedNativeQuery(
name = "nativeItem1",
query = "select name as itemname, descr as itemdescription from Item",
resultSetMapping = "getItem"
),
@NamedNativeQuery(
name = "nativeItem2",
query = "select * from Item",
resultClass = Item.class
)
})
@NamedQueries({
@NamedQuery(
name = "itemJpaQueryWithLockModeAndHints",
query = "select i from Item i",
lockMode = LockModeType.PESSIMISTIC_WRITE,
hints = {
@QueryHint(name = QueryHints.TIMEOUT_JPA, value = "3000"),
@QueryHint(name = QueryHints.CACHE_MODE, value = "ignore"),
@QueryHint(name = QueryHints.CACHEABLE, value = "true"),
@QueryHint(name = QueryHints.READ_ONLY, value = "true"),
@QueryHint(name = QueryHints.COMMENT, value = "custom static comment"),
@QueryHint(name = QueryHints.FETCH_SIZE, value = "512"),
@QueryHint(name = QueryHints.FLUSH_MODE, value = "manual")
}
),
@NamedQuery(name = "query-construct", query = "select new Item(i.name,i.descr) from Item i")
})
public class Item implements Serializable {
private String name;
private String descr;
private Set<Distributor> distributors = new HashSet<Distributor>();
public Item() {
}
public Item(String name, String desc) {
this.name = name;
this.descr = desc;
}
@Column(length = 200)
public String getDescr() {
return descr;
}
public void setDescr(String desc) {
this.descr = desc;
}
@Id
@Column(length = 30)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany
public Set<Distributor> getDistributors() {
return distributors;
}
public void setDistributors(Set<Distributor> distributors) {
this.distributors = distributors;
}
public void addDistributor(Distributor d) {
if (distributors == null) { distributors = new HashSet(); }
distributors.add(d);
}
}
| 4,083 | 31.935484 | 100 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/Cat.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.PostLoad;
import jakarta.persistence.PostPersist;
import jakarta.persistence.PostUpdate;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.persistence.Transient;
import org.jboss.logging.Logger;
/**
* @author Emmanuel Bernard
*/
@SuppressWarnings({"unchecked", "serial"})
@Entity
@EntityListeners(LastUpdateListener.class)
public class Cat implements Serializable {
private static final Logger log = Logger.getLogger(Cat.class);
private static final List ids = new ArrayList(); // used for assertions
public static int postVersion = 0; // used for assertions
private Integer id;
private String name;
private Date dateOfBirth;
private int age;
private long length;
private Date lastUpdate;
private int manualVersion = 0;
private List<Kitten> kittens;
public static synchronized List getIdList() {
return Collections.unmodifiableList(ids);
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getManualVersion() {
return manualVersion;
}
public void setManualVersion(int manualVersion) {
this.manualVersion = manualVersion;
}
@Transient
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Basic
@Temporal(TemporalType.TIMESTAMP)
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
@PostUpdate
private void someLateUpdateWorking() {
log.debug("PostUpdate for: " + this.toString());
postVersion++;
}
@PostLoad
public void calculateAge() {
Calendar birth = new GregorianCalendar();
birth.setTime(dateOfBirth);
Calendar now = new GregorianCalendar();
now.setTime(new Date());
int adjust = 0;
if (now.get(Calendar.DAY_OF_YEAR) - birth.get(Calendar.DAY_OF_YEAR) < 0) {
adjust = -1;
}
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + adjust;
}
@PostPersist
public synchronized void addIdsToList() {
ids.add(getId());
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
@OneToMany(cascade = CascadeType.ALL)
public List<Kitten> getKittens() {
return kittens;
}
public void setKittens(List<Kitten> kittens) {
this.kittens = kittens;
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
@Override
public String toString() {
final String TAB = " ";
String retValue = "";
retValue = "Cat ( "
+ super.toString() + TAB
+ "id = " + this.id + TAB
+ "name = " + this.name + TAB
+ "dateOfBirth = " + this.dateOfBirth + TAB
+ "age = " + this.age + TAB
+ "length = " + this.length + TAB
+ "lastUpdate = " + this.lastUpdate + TAB
+ "manualVersion = " + this.manualVersion + TAB
+ "postVersion = " + Cat.postVersion + TAB
+ "kittens = " + this.kittens + TAB
+ " )";
return retValue;
}
}
| 5,159 | 26.015707 | 82 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/excludehbmpar/Caipirinha.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.excludehbmpar;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Caipirinha {
private Integer id;
private String name;
public Caipirinha() {
}
public Caipirinha(String name) {
this.name = name;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,449 | 24.892857 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/package-info.java | @NamedQuery(name = "allMouse",
query = "select m from ApplicationServer m")
package org.hibernate.jpa.test.pack.defaultpar;
import org.hibernate.annotations.NamedQuery;
| 179 | 24.714286 | 52 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/Lighter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
/**
* @author Emmanuel Bernard
*/
public class Lighter {
public String name;
public String power;
}
| 944 | 35.346154 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/Version.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
import jakarta.persistence.Embeddable;
/**
* @author Emmanuel Bernard
*/
@Embeddable
public class Version {
private static final String DOT = ".";
private int major;
private int minor;
private int micro;
public int getMajor() {
return major;
}
public void setMajor(int major) {
this.major = major;
}
public int getMinor() {
return minor;
}
public void setMinor(int minor) {
this.minor = minor;
}
public int getMicro() {
return micro;
}
public void setMicro(int micro) {
this.micro = micro;
}
public String toString() {
return new StringBuffer(major).append(DOT).append(minor).append(DOT).append(micro).toString();
}
}
| 1,590 | 25.966102 | 102 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/Money.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Money {
private Integer id;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
| 1,184 | 27.902439 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/OtherIncrementListener.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
/**
* @author Emmanuel Bernard
*/
public class OtherIncrementListener {
private static int increment;
public static int getIncrement() {
return OtherIncrementListener.increment;
}
public static void reset() {
increment = 0;
}
public void increment(Object entity) {
OtherIncrementListener.increment++;
}
}
| 1,196 | 31.351351 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/ApplicationServer.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class ApplicationServer {
private Integer id;
private String name;
private Version version;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
}
| 1,529 | 25.37931 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/Mouse.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
import jakarta.persistence.ExcludeDefaultListeners;
/**
* @author Emmanuel Bernard
*/
@ExcludeDefaultListeners
public class Mouse {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,270 | 27.244444 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/defaultpar/IncrementListener.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.defaultpar;
import jakarta.persistence.PrePersist;
/**
* @author Emmanuel Bernard
*/
public class IncrementListener {
private static int increment;
public static int getIncrement() {
return increment;
}
public static void reset() {
increment = 0;
}
@PrePersist
public void increment(Object entity) {
increment++;
}
}
| 1,201 | 29.05 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/cfgxmlpar/Morito.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.cfgxmlpar;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Morito {
private Integer id;
private String power;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPower() {
return power;
}
public void setPower(String power) {
this.power = power;
}
}
| 1,345 | 26.469388 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/explodedpar/package-info.java | @NamedQuery(name = "allCarpet", query = "select c from Carpet c")
package org.hibernate.jpa.test.pack.explodedpar;
import org.hibernate.annotations.NamedQuery; | 160 | 39.25 | 65 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/explodedpar/Elephant.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.explodedpar;
/**
* @author Emmanuel Bernard
*/
public class Elephant {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,196 | 27.5 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/explodedpar/Carpet.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.explodedpar;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Carpet {
private Integer id;
private String country;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
| 1,361 | 26.795918 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/spacepar/Bug.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.spacepar;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Bug {
@Id
@GeneratedValue
private Long id;
private String subject;
@Column(name = "`comment`")
private String comment;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
| 1,589 | 25.5 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/various/Airplane.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.various;
/**
* @author Emmanuel Bernard
*/
public class Airplane {
private String serialNumber;
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
| 1,104 | 32.484848 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/various/Seat.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.various;
/**
* @author Emmanuel Bernard
*/
public class Seat {
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
| 1,058 | 31.090909 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/externaljar/Scooter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.externaljar;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Scooter {
private String model;
private Long speed;
@Id
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Long getSpeed() {
return speed;
}
public void setSpeed(Long speed) {
this.speed = speed;
}
}
| 1,297 | 26.617021 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/overridenpar/Bug.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.overridenpar;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Bug {
@Id
@GeneratedValue
private Long id;
private String subject;
@Column(name = "`comment`")
private String comment;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
| 1,593 | 25.566667 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/explicitpar/Washer.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.explicitpar;
import jakarta.persistence.Entity;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Washer {
//No @id so picking it up should fail
}
| 981 | 34.071429 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/package-info.java | @NamedQuery(name = "allMouse",
query = "select m from ApplicationServer m")
package org.hibernate.jpa.test.pack.war;
import org.hibernate.annotations.NamedQuery; | 170 | 33.2 | 52 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/Lighter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
/**
* @author Emmanuel Bernard
*/
public class Lighter {
public String name;
public String power;
}
| 937 | 35.076923 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/Version.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
import jakarta.persistence.Embeddable;
/**
* @author Emmanuel Bernard
*/
@Embeddable
public class Version {
private static final String DOT = ".";
private int major;
private int minor;
private int micro;
public int getMajor() {
return major;
}
public void setMajor(int major) {
this.major = major;
}
public int getMinor() {
return minor;
}
public void setMinor(int minor) {
this.minor = minor;
}
public int getMicro() {
return micro;
}
public void setMicro(int micro) {
this.micro = micro;
}
public String toString() {
return new StringBuffer(major).append(DOT).append(minor).append(DOT).append(micro).toString();
}
}
| 1,583 | 25.847458 | 102 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/Money.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Money {
private Integer id;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
| 1,177 | 27.731707 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/OtherIncrementListener.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
/**
* @author Emmanuel Bernard
*/
public class OtherIncrementListener {
private static int increment;
public static int getIncrement() {
return OtherIncrementListener.increment;
}
public static void reset() {
increment = 0;
}
public void increment(Object entity) {
OtherIncrementListener.increment++;
}
}
| 1,189 | 31.162162 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/ApplicationServer.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class ApplicationServer {
private Integer id;
private String name;
private Version version;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
}
| 1,522 | 25.258621 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/Mouse.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
import jakarta.persistence.ExcludeDefaultListeners;
/**
* @author Emmanuel Bernard
*/
@ExcludeDefaultListeners
public class Mouse {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,263 | 27.088889 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/hibernate/jpa/test/pack/war/IncrementListener.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpa.test.pack.war;
import jakarta.persistence.PrePersist;
/**
* @author Emmanuel Bernard
*/
public class IncrementListener {
private static int increment;
public static int getIncrement() {
return increment;
}
public static void reset() {
increment = 0;
}
@PrePersist
public void increment(Object entity) {
increment++;
}
}
| 1,194 | 28.875 | 75 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/jboss/as/jpa/hibernate6/scan/ScannerTests.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2022, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate6.scan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.hibernate.boot.archive.internal.ArchiveHelper;
import org.jboss.shrinkwrap.api.ArchivePath;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.vfs.TempFileProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Steve Ebersole
*/
public class ScannerTests {
protected static ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
protected static ClassLoader bundleClassLoader;
protected static TempFileProvider tempFileProvider;
protected static File testSrcDirectory;
/**
* Directory where shrink-wrap built archives are written
*/
protected static File shrinkwrapArchiveDirectory;
static {
try {
tempFileProvider = TempFileProvider.create("test", new ScheduledThreadPoolExecutor(2));
} catch (IOException e) {
throw new RuntimeException(e);
}
// we make an assumption here that the directory which holds compiled classes (nested) also holds
// sources. We therefore look for our module directory name, and use that to locate bundles
final URL scannerTestsClassFileUrl = originalClassLoader.getResource(
ScannerTests.class.getName().replace('.', '/') + ".class"
);
if (scannerTestsClassFileUrl == null) {
// blow up
fail("Could not find ScannerTests class file url");
}
// look for the module name in that url
final int position = scannerTestsClassFileUrl.getFile().lastIndexOf("/hibernate6/");
if (position == -1) {
fail("Unable to setup packaging test");
}
final String moduleDirectoryPath = scannerTestsClassFileUrl.getFile().substring(0, position + "/hibernate5".length());
final File moduleDirectory = new File(moduleDirectoryPath);
testSrcDirectory = new File(new File(moduleDirectory, "src"), "test");
final File bundlesDirectory = new File(testSrcDirectory, "bundles");
try {
bundleClassLoader = new URLClassLoader(new URL[]{bundlesDirectory.toURL()}, originalClassLoader);
} catch (MalformedURLException e) {
fail("Unable to build custom class loader");
}
shrinkwrapArchiveDirectory = new File(moduleDirectory, "target/packages");
shrinkwrapArchiveDirectory.mkdirs();
}
@Before
public void prepareTCCL() {
// add the bundle class loader in order for ShrinkWrap to build the test package
Thread.currentThread().setContextClassLoader(bundleClassLoader);
}
@After
public void resetTCCL() throws Exception {
// reset the classloader
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
protected File buildLargeJar()throws Exception {
final String fileName = "large.jar";
final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, fileName);
// Build a large jar by adding a lorem ipsum file repeatedly.
final Path loremipsumTxtFile = Paths.get(ScannerTests.class.getResource("/org/hibernate/jpa/test/packaging/loremipsum.txt").toURI());
for (int i = 0; i < 100; i++) {
ArchivePath path = ArchivePaths.create("META-INF/file" + i);
archive.addAsResource(loremipsumTxtFile.toFile(), path);
}
File testPackage = new File(shrinkwrapArchiveDirectory, fileName);
archive.as(ZipExporter.class).exportTo(testPackage, true);
return testPackage;
}
@Test
public void testGetBytesFromInputStream() throws Exception {
File file = buildLargeJar();
InputStream stream = new BufferedInputStream(
new FileInputStream(file));
int oldLength = getBytesFromInputStream(stream).length;
stream.close();
stream = new BufferedInputStream(new FileInputStream(file));
int newLength = ArchiveHelper.getBytesFromInputStream(stream).length;
stream.close();
assertEquals(oldLength, newLength);
}
// This is the old getBytesFromInputStream from JarVisitorFactory before
// it was changed by HHH-7835. Use it as a regression test.
private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
int size;
byte[] entryBytes = new byte[0];
for (; ; ) {
byte[] tmpByte = new byte[4096];
size = inputStream.read(tmpByte);
if (size == -1) { break; }
byte[] current = new byte[entryBytes.length + size];
System.arraycopy(entryBytes, 0, current, 0, entryBytes.length);
System.arraycopy(tmpByte, 0, current, entryBytes.length, size);
entryBytes = current;
}
return entryBytes;
}
@Test
public void testGetBytesFromZeroInputStream() throws Exception {
// Ensure that JarVisitorFactory#getBytesFromInputStream
// can handle 0 length streams gracefully.
URL emptyTxtUrl = getClass().getResource("/org/hibernate/jpa/test/packaging/empty.txt");
if (emptyTxtUrl == null) {
throw new RuntimeException("Bah!");
}
InputStream emptyStream = new BufferedInputStream(emptyTxtUrl.openStream());
int length = ArchiveHelper.getBytesFromInputStream(emptyStream).length;
assertEquals(length, 0);
emptyStream.close();
}
}
| 6,844 | 37.892045 | 141 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/jboss/as/jpa/hibernate/cache/BasicCacheKeyImplementationMarshallerTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.hibernate.cache;
import java.io.IOException;
import java.util.UUID;
import org.hibernate.cache.internal.BasicCacheKeyImplementation;
import org.junit.Test;
import org.wildfly.clustering.marshalling.Tester;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory;
/**
* Unit test for {@link BasicCacheKeyImplementationMarshaller}.
* @author Paul Ferraro
*/
public class BasicCacheKeyImplementationMarshallerTestCase {
@Test
public void test() throws IOException {
Tester<BasicCacheKeyImplementation> tester = ProtoStreamTesterFactory.INSTANCE.createTester();
UUID id = UUID.randomUUID();
String entity = "foo";
tester.testKey(new BasicCacheKeyImplementation(id, entity, id.hashCode()));
tester.testKey(new BasicCacheKeyImplementation(id, entity, 1));
}
}
| 1,885 | 38.291667 | 102 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/jboss/as/jpa/hibernate/cache/CacheKeyImplementationMarshallerTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.hibernate.cache;
import java.io.IOException;
import java.util.UUID;
import org.hibernate.cache.internal.CacheKeyImplementation;
import org.junit.Test;
import org.wildfly.clustering.marshalling.Tester;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory;
/**
* Unit test for {@link CacheKeyImplementationMarshaller}.
* @author Paul Ferraro
*/
public class CacheKeyImplementationMarshallerTestCase {
@Test
public void test() throws IOException {
Tester<CacheKeyImplementation> tester = ProtoStreamTesterFactory.INSTANCE.createTester();
UUID id = UUID.randomUUID();
String entity = "foo";
String tenant = "bar";
tester.testKey(new CacheKeyImplementation(id, entity, tenant, id.hashCode()));
tester.testKey(new CacheKeyImplementation(id, entity, tenant, 1));
}
}
| 1,902 | 37.836735 | 97 | java |
null | wildfly-main/jpa/hibernate6/src/test/java/org/jboss/as/jpa/hibernate/cache/NaturalIdCacheKeyMarshallerTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.hibernate.cache;
import java.io.IOException;
import java.util.UUID;
import org.hibernate.cache.internal.NaturalIdCacheKey;
import org.junit.Test;
import org.wildfly.clustering.marshalling.Tester;
import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory;
/**
* Unit test for {@link NaturalIdCacheKeyMarshaller}.
* @author Paul Ferraro
*/
public class NaturalIdCacheKeyMarshallerTestCase {
@Test
public void test() throws IOException {
Tester<NaturalIdCacheKey> tester = ProtoStreamTesterFactory.INSTANCE.createTester();
UUID id = UUID.randomUUID();
String entity = "foo";
String tenant = "bar";
tester.testKey(new NaturalIdCacheKey(id, entity, tenant, id.hashCode()));
tester.testKey(new NaturalIdCacheKey(id, entity, tenant, 1));
}
}
| 1,872 | 37.22449 | 92 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/HibernateSecondLevelCache.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.COLLECTION_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_ENTITY_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_PENDING_PUTS_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_QUERY_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.DEF_TIMESTAMPS_RESOURCE;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.ENTITY_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.IMMUTABLE_ENTITY_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.INFINISPAN_CONFIG_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.NATURAL_ID_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.PENDING_PUTS_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.QUERY_CACHE_RESOURCE_PROP;
import static org.infinispan.hibernate.cache.spi.InfinispanProperties.TIMESTAMPS_CACHE_RESOURCE_PROP;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.hibernate.cfg.AvailableSettings;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.event.impl.internal.Notification;
/**
* Second level cache setup.
*
* @author Scott Marlow
*/
public class HibernateSecondLevelCache {
private static final String DEFAULT_REGION_FACTORY = "org.infinispan.hibernate.cache.v62.InfinispanRegionFactory";
public static final String CACHE_TYPE = "cachetype"; // shared (Jakarta Persistence) or private (for native applications)
public static final String CACHE_PRIVATE = "private";
public static final String CONTAINER = "container";
public static final String NAME = "name";
public static final String CACHES = "caches";
public static void addSecondLevelCacheDependencies(Properties mutableProperties, String scopedPersistenceUnitName) {
if (mutableProperties.getProperty(AvailableSettings.CACHE_REGION_PREFIX) == null
&& scopedPersistenceUnitName != null) {
// cache entries for this PU will be identified by scoped pu name + Entity class name
mutableProperties.setProperty(AvailableSettings.CACHE_REGION_PREFIX, scopedPersistenceUnitName);
}
String regionFactory = mutableProperties.getProperty(AvailableSettings.CACHE_REGION_FACTORY);
if (regionFactory == null) {
regionFactory = DEFAULT_REGION_FACTORY;
mutableProperties.setProperty(AvailableSettings.CACHE_REGION_FACTORY, regionFactory);
}
if (Boolean.parseBoolean(mutableProperties.getProperty(ManagedEmbeddedCacheManagerProvider.SHARED, ManagedEmbeddedCacheManagerProvider.DEFAULT_SHARED))) {
// Set infinispan defaults
String container = mutableProperties.getProperty(ManagedEmbeddedCacheManagerProvider.CACHE_CONTAINER);
if (container == null) {
container = ManagedEmbeddedCacheManagerProvider.DEFAULT_CACHE_CONTAINER;
mutableProperties.setProperty(ManagedEmbeddedCacheManagerProvider.CACHE_CONTAINER, container);
}
/**
* AS will need the ServiceBuilder<?> builder that used to be passed to PersistenceProviderAdaptor.addProviderDependencies
*/
Properties cacheSettings = new Properties();
cacheSettings.setProperty(CONTAINER, container);
cacheSettings.setProperty(CACHES, String.join(" ", findCaches(mutableProperties)));
Notification.addCacheDependencies(Classification.INFINISPAN, cacheSettings);
}
}
public static Set<String> findCaches(Properties properties) {
Set<String> caches = new HashSet<>();
caches.add(properties.getProperty(ENTITY_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE));
caches.add(properties.getProperty(IMMUTABLE_ENTITY_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE));
caches.add(properties.getProperty(COLLECTION_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE));
caches.add(properties.getProperty(NATURAL_ID_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE));
caches.add(properties.getProperty(PENDING_PUTS_CACHE_RESOURCE_PROP, DEF_PENDING_PUTS_RESOURCE));
if (Boolean.parseBoolean(properties.getProperty(AvailableSettings.USE_QUERY_CACHE))) {
caches.add(properties.getProperty(QUERY_CACHE_RESOURCE_PROP, DEF_QUERY_RESOURCE));
caches.add(properties.getProperty(TIMESTAMPS_CACHE_RESOURCE_PROP, DEF_TIMESTAMPS_RESOURCE));
}
int length = INFINISPAN_CONFIG_RESOURCE_PROP.length();
String customRegionPrefix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(0, length - 3) + properties.getProperty(AvailableSettings.CACHE_REGION_PREFIX, "");
String customRegionSuffix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(length - 4, length);
for (String propertyName : properties.stringPropertyNames()) {
if (propertyName.startsWith(customRegionPrefix) && propertyName.endsWith(customRegionSuffix)) {
caches.add(properties.getProperty(propertyName));
}
}
return caches;
}
}
| 6,105 | 52.095652 | 162 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/JpaLogger.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import static org.jboss.logging.Logger.Level.INFO;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* JipiJapa message range is 20200-20299
* note: keep duplicate messages in sync between different sub-projects that use the same messages
* @author <a href="mailto:[email protected]">James R. Perkins</a>
* @author Scott Marlow
*/
@MessageLogger(projectCode = "JIPIORMV6")
public interface JpaLogger extends BasicLogger {
/**
* A logger with the category {@code org.jipijapa}.
*/
JpaLogger JPA_LOGGER = Logger.getMessageLogger(JpaLogger.class, "org.jipijapa");
/**
* Inform that the Hibernate second level cache is enabled.
*
* @param puUnitName the persistence unit name
*/
@LogMessage(level = INFO)
@Message(id = 20260, value = "Second level cache enabled for %s")
void secondLevelCacheIsEnabled(Object puUnitName);
/**
* Creates an exception indicating that Hibernate ORM did not register the expected LifeCycleListener
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 20261, value = "Hibernate ORM did not register LifeCycleListener")
IllegalStateException HibernateORMDidNotRegisterLifeCycleListener();
/**
* Creates an exception indicating application is setting persistence unit property "hibernate.id.new_generator_mappings" to
* false which indicates that the old ID generator should be used, however Hibernate ORM 6 does not include the old ID generator.
*
* @return an {@link IllegalStateException} for the error.
*/
@Message(id = 20263, value = "hibernate.id.new_generator_mappings set to false is not supported" +
", remove the setting or set to true. "+
"Refer to Hibernate ORM migration documentation for how to update the next id state in the application database.")
IllegalStateException failOnIncompatibleSetting();
}
| 2,843 | 38.5 | 133 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/VirtualFileSystemArchiveDescriptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import org.hibernate.boot.archive.spi.ArchiveContext;
import org.hibernate.boot.archive.spi.ArchiveDescriptor;
import org.hibernate.boot.archive.spi.ArchiveEntry;
import org.hibernate.boot.archive.spi.InputStreamAccess;
import org.jboss.vfs.VirtualFile;
/**
* Representation of an archive in the JBoss VirtualFileSystem API in terms of how to walk entries.
*
* @author Steve Ebersole
*/
public class VirtualFileSystemArchiveDescriptor implements ArchiveDescriptor {
private final VirtualFile root;
public VirtualFileSystemArchiveDescriptor(VirtualFile archiveRoot, String entryBase) {
if ( entryBase != null && entryBase.length() > 0 && ! "/".equals( entryBase ) ) {
this.root = archiveRoot.getChild( entryBase );
}
else {
this.root = archiveRoot;
}
}
public VirtualFile getRoot() {
return root;
}
@Override
public void visitArchive(ArchiveContext archiveContext) {
processVirtualFile( root, null, archiveContext );
}
private void processVirtualFile(VirtualFile virtualFile, String path, ArchiveContext archiveContext) {
if ( path == null ) {
path = "";
}
else {
if ( !path.endsWith( "/'" ) ) {
path = path + "/";
}
}
for ( VirtualFile child : virtualFile.getChildren() ) {
if ( !child.exists() ) {
// should never happen conceptually, but...
continue;
}
if ( child.isDirectory() ) {
processVirtualFile( child, path + child.getName(), archiveContext );
continue;
}
final String name = child.getPathName();
final String relativeName = path + child.getName();
final InputStreamAccess inputStreamAccess = new VirtualFileInputStreamAccess( name, child );
final ArchiveEntry entry = new ArchiveEntry() {
@Override
public String getName() {
return name;
}
@Override
public String getNameWithinArchive() {
return relativeName;
}
@Override
public InputStreamAccess getStreamAccess() {
return inputStreamAccess;
}
};
archiveContext.obtainArchiveEntryHandler( entry ).handleEntry( entry, archiveContext );
}
}
}
| 3,263 | 31.969697 | 106 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/ManagedEmbeddedCacheManagerProvider.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import java.util.Properties;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.AvailableSettings;
import org.infinispan.hibernate.cache.spi.EmbeddedCacheManagerProvider;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.impl.AbstractDelegatingEmbeddedCacheManager;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.cache.spi.Wrapper;
import org.jipijapa.event.impl.internal.Notification;
import org.kohsuke.MetaInfServices;
/**
* Provides a managed {@link EmbeddedCacheManager} instance to Infinispan's region factory implementation.
* @author Paul Ferraro
*/
@MetaInfServices(EmbeddedCacheManagerProvider.class)
public class ManagedEmbeddedCacheManagerProvider implements EmbeddedCacheManagerProvider {
public static final String CACHE_CONTAINER = "hibernate.cache.infinispan.container";
public static final String DEFAULT_CACHE_CONTAINER = "hibernate";
public static final String SHARED = "hibernate.cache.infinispan.shared";
public static final String DEFAULT_SHARED = "true";
public static final String STATISTICS = "hibernate.cache.infinispan.statistics";
@Override
public EmbeddedCacheManager getEmbeddedCacheManager(Properties properties) {
Properties settings = new Properties();
String container = properties.getProperty(CACHE_CONTAINER, DEFAULT_CACHE_CONTAINER);
settings.setProperty(HibernateSecondLevelCache.CONTAINER, container);
if (!Boolean.parseBoolean(properties.getProperty(SHARED, DEFAULT_SHARED))) {
HibernateSecondLevelCache.addSecondLevelCacheDependencies(properties, null);
settings.setProperty(HibernateSecondLevelCache.CACHE_TYPE, HibernateSecondLevelCache.CACHE_PRIVATE);
// Find a suitable service name to represent this session factory instance
String name = properties.getProperty(AvailableSettings.SESSION_FACTORY_NAME);
if (name != null) {
settings.setProperty(HibernateSecondLevelCache.NAME, name);
}
settings.setProperty(HibernateSecondLevelCache.CACHES, String.join(" ", HibernateSecondLevelCache.findCaches(properties)));
}
try {
EmbeddedCacheManager manager = new JipiJapaCacheManager(Notification.startCache(Classification.INFINISPAN, settings));
if (manager.getCacheManagerConfiguration().statistics()) {
settings.setProperty(STATISTICS, Boolean.TRUE.toString());
}
return manager;
} catch (CacheException e) {
throw e;
} catch (Exception e) {
throw new CacheException(e);
}
}
private static class JipiJapaCacheManager extends AbstractDelegatingEmbeddedCacheManager {
private final Wrapper wrapper;
JipiJapaCacheManager(Wrapper wrapper) {
super((EmbeddedCacheManager) wrapper.getValue());
this.wrapper = wrapper;
}
@Override
public void stop() {
Notification.stopCache(Classification.INFINISPAN, this.wrapper);
}
@Override
public void close() {
this.stop();
}
}
}
| 3,949 | 39.306122 | 135 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/TwoPhaseBootstrapImpl.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import java.util.Map;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.spi.PersistenceUnitInfo;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.jipijapa.plugin.spi.EntityManagerFactoryBuilder;
/**
* TwoPhaseBootstrapImpl
*
* @author Scott Marlow
*/
public class TwoPhaseBootstrapImpl implements EntityManagerFactoryBuilder {
final org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder entityManagerFactoryBuilder;
public TwoPhaseBootstrapImpl(final PersistenceUnitInfo info, final Map map) {
entityManagerFactoryBuilder =
Bootstrap.getEntityManagerFactoryBuilder(info, map);
}
@Override
public EntityManagerFactory build() {
return entityManagerFactoryBuilder.build();
}
@Override
public void cancel() {
entityManagerFactoryBuilder.cancel();
}
@Override
public EntityManagerFactoryBuilder withValidatorFactory(Object validatorFactory) {
entityManagerFactoryBuilder.withValidatorFactory(validatorFactory);
return this;
}
}
| 1,824 | 29.416667 | 93 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/VirtualFileInputStreamAccess.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import java.io.IOException;
import java.io.InputStream;
import org.hibernate.boot.archive.spi.ArchiveException;
import org.hibernate.boot.archive.spi.InputStreamAccess;
import org.jboss.vfs.VirtualFile;
/**
* InputStreamAccess provides Hibernate with lazy, on-demand access to InputStreams for the various
* types of resources found during archive scanning.
*
* @author Steve Ebersole
*/
public class VirtualFileInputStreamAccess implements InputStreamAccess {
private final String name;
private final VirtualFile virtualFile;
public VirtualFileInputStreamAccess(String name, VirtualFile virtualFile) {
this.name = name;
this.virtualFile = virtualFile;
}
@Override
public String getStreamName() {
return name;
}
@Override
public InputStream accessInputStream() {
try {
return virtualFile.openStream();
}
catch (IOException e) {
throw new ArchiveException( "Unable to open VirtualFile-based InputStream", e );
}
}
}
| 1,791 | 29.372881 | 99 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/VirtualFileSystemArchiveDescriptorFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import java.net.URISyntaxException;
import java.net.URL;
import org.hibernate.boot.archive.internal.StandardArchiveDescriptorFactory;
import org.hibernate.boot.archive.spi.ArchiveDescriptor;
import org.jboss.vfs.VFS;
/**
* In Hibernate terms, the ArchiveDescriptorFactory contract is used to plug in handling for how to deal
* with archives in various systems. For JBoss, that means its VirtualFileSystem API.
*
* @author Steve Ebersole
*/
public class VirtualFileSystemArchiveDescriptorFactory extends StandardArchiveDescriptorFactory {
static final VirtualFileSystemArchiveDescriptorFactory INSTANCE = new VirtualFileSystemArchiveDescriptorFactory();
private VirtualFileSystemArchiveDescriptorFactory() {
}
@Override
public ArchiveDescriptor buildArchiveDescriptor(URL url, String entryBase) {
try {
return new VirtualFileSystemArchiveDescriptor( VFS.getChild( url.toURI() ), entryBase );
}
catch (URISyntaxException e) {
throw new IllegalArgumentException( e );
}
}
}
| 1,806 | 35.14 | 118 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/HibernateArchiveScanner.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import org.hibernate.boot.archive.scan.spi.AbstractScannerImpl;
import org.hibernate.boot.archive.scan.spi.Scanner;
/**
* Annotation scanner for Hibernate. Essentially just passes along the VFS-based ArchiveDescriptorFactory
*
* @author Steve Ebersole
*/
public class HibernateArchiveScanner extends AbstractScannerImpl implements Scanner {
public HibernateArchiveScanner() {
super( VirtualFileSystemArchiveDescriptorFactory.INSTANCE );
}
}
| 1,208 | 34.558824 | 106 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/HibernatePersistenceProviderAdaptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import java.util.Map;
import java.util.Properties;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.persistence.SharedCacheMode;
import jakarta.persistence.spi.PersistenceUnitInfo;
import org.hibernate.cfg.AvailableSettings;
import org.jboss.as.jpa.hibernate.management.HibernateManagementAdaptor;
import org.jboss.as.jpa.hibernate.service.WildFlyCustomJtaPlatform;
import org.jipijapa.cache.spi.Classification;
import org.jipijapa.event.impl.internal.Notification;
import org.jipijapa.plugin.spi.EntityManagerFactoryBuilder;
import org.jipijapa.plugin.spi.JtaManager;
import org.jipijapa.plugin.spi.ManagementAdaptor;
import org.jipijapa.plugin.spi.PersistenceProviderAdaptor;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.jipijapa.plugin.spi.Platform;
import org.jipijapa.plugin.spi.TwoPhaseBootstrapCapable;
/**
* Implements the PersistenceProviderAdaptor for Hibernate
*
* @author Scott Marlow
*/
public class HibernatePersistenceProviderAdaptor implements PersistenceProviderAdaptor, TwoPhaseBootstrapCapable {
public static final String NAMING_STRATEGY_JPA_COMPLIANT_IMPL = "org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl";
private volatile Platform platform;
private static final String SHARED_CACHE_MODE = "jakarta.persistence.sharedCache.mode";
private static final String NONE = SharedCacheMode.NONE.name();
private static final String UNSPECIFIED = SharedCacheMode.UNSPECIFIED.name();
// Hibernate ORM 5.3 setting which if false, the old IdentifierGenerator were used for AUTO, TABLE and SEQUENCE id generation.
// Hibernate ORM 6.0 does not support AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS
private static final String USE_NEW_ID_GENERATOR_MAPPINGS = "hibernate.id.new_generator_mappings";
@Override
public void injectJtaManager(JtaManager jtaManager) {
WildFlyCustomJtaPlatform.setTransactionSynchronizationRegistry(jtaManager.getSynchronizationRegistry());
}
@Override
public void injectPlatform(Platform platform) {
if (this.platform != platform) {
this.platform = platform;
}
}
@SuppressWarnings("deprecation")
@Override
public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
putPropertyIfAbsent(pu, properties, AvailableSettings.JPAQL_STRICT_COMPLIANCE, "true"); // JIPI-24 ignore jpql aliases case
failOnIncompatibleSetting(pu, properties); // fail application deployment if application sets hibernate.id.new_generator_mappings to false
// applications that set new_generator_mappings to false need to be migrated to Hibernate ORM 6+,
// the database may need changes as well to deal with ensuring the "next id" counter is represented
// correctly in the database to match what the application is changed to instead use when inserting
// new database table rows.
putPropertyIfAbsent(pu, properties, AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED,"false");
putPropertyIfAbsent(pu, properties, AvailableSettings.IMPLICIT_NAMING_STRATEGY, NAMING_STRATEGY_JPA_COMPLIANT_IMPL);
putPropertyIfAbsent(pu, properties, AvailableSettings.SCANNER, HibernateArchiveScanner.class);
properties.put(AvailableSettings.CLASSLOADERS, pu.getClassLoader());
// Only set SESSION_FACTORY_NAME_IS_JNDI to false if application didn't override Hibernate ORM session factory name.
if (!pu.getProperties().containsKey(AvailableSettings.SESSION_FACTORY_NAME)) {
putPropertyIfAbsent(pu, properties, AvailableSettings.SESSION_FACTORY_NAME_IS_JNDI, Boolean.FALSE);
}
putPropertyIfAbsent(pu, properties, AvailableSettings.SESSION_FACTORY_NAME, pu.getScopedPersistenceUnitName());
putPropertyIfAbsent( pu, properties, AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS, false );
// Enable JPA Compliance mode
putPropertyIfAbsent( pu, properties, AvailableSettings.JPA_COMPLIANCE, true);
}
private void failOnIncompatibleSetting(PersistenceUnitMetadata pu, Map properties) {
if ("false".equals(pu.getProperties().getProperty(USE_NEW_ID_GENERATOR_MAPPINGS))) {
throw JpaLogger.JPA_LOGGER.failOnIncompatibleSetting();
}
}
@Override
public void addProviderDependencies(PersistenceUnitMetadata pu) {
final Properties properties = pu.getProperties();
final String sharedCacheMode = properties.getProperty(SHARED_CACHE_MODE);
if (Classification.NONE.equals(platform.defaultCacheClassification())) {
JpaLogger.JPA_LOGGER.tracef("second level cache is not supported in platform, ignoring shared cache mode");
pu.setSharedCacheMode(SharedCacheMode.NONE);
}
// precedence order of cache settings (1 overrides other settings and 3 is lowest precedence level):
// 1 - SharedCacheMode.NONE
// 2 - AvailableSettings.USE_SECOND_LEVEL_CACHE
// 2 - AvailableSettings.USE_QUERY_CACHE
// 3 - SharedCacheMode.UNSPECIFIED
// 3 - SharedCacheMode.ENABLE_SELECTIVE
// 3 - SharedCacheMode.DISABLE_SELECTIVE
// if SharedCacheMode.NONE, set cacheDisabled to true.
boolean cacheDisabled = noneCacheMode(pu)
// Or if Hibernate cache settings are specified and Hibernate settings indicate cache is disabled, set cacheDisabled to true.
|| (haveHibernateCachePropertyDefined(pu) && !hibernateCacheEnabled(pu));
if (!cacheDisabled) {
HibernateSecondLevelCache.addSecondLevelCacheDependencies(pu.getProperties(), pu.getScopedPersistenceUnitName());
JpaLogger.JPA_LOGGER.secondLevelCacheIsEnabled(pu.getScopedPersistenceUnitName());
// for SharedCacheMode.UNSPECIFIED, enable the cache and enable caching for entities marked with Cacheable
if (unspecifiedCacheMode(pu)) {
pu.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
}
} else {
JpaLogger.JPA_LOGGER.tracef("second level cache disabled for %s, pu %s property = %s, pu.getSharedCacheMode = %s",
pu.getScopedPersistenceUnitName(),
SHARED_CACHE_MODE,
sharedCacheMode,
pu.getSharedCacheMode().toString());
pu.setSharedCacheMode(SharedCacheMode.NONE); // ensure that Hibernate doesn't try to use the 2lc
}
}
/**
* Determine if Hibernate cache properties are specified.
*
* @param pu
* @return true if Hibernate cache setting are specified.
*/
private boolean haveHibernateCachePropertyDefined(PersistenceUnitMetadata pu) {
return (pu.getProperties().getProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE) != null ||
pu.getProperties().getProperty(AvailableSettings.USE_QUERY_CACHE) != null);
}
/**
* Determine if Hibernate cache properties are enabling or disabling cache.
*
* @param pu
* @return true if cache enabled, false if cache disabled.
*/
private boolean hibernateCacheEnabled(PersistenceUnitMetadata pu) {
return (Boolean.parseBoolean(pu.getProperties().getProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE))
|| Boolean.parseBoolean(pu.getProperties().getProperty(AvailableSettings.USE_QUERY_CACHE))
);
}
private boolean unspecifiedCacheMode(PersistenceUnitMetadata pu) {
return SharedCacheMode.UNSPECIFIED.equals(pu.getSharedCacheMode()) ||
UNSPECIFIED.equals(pu.getProperties().getProperty(SHARED_CACHE_MODE));
}
private boolean noneCacheMode(PersistenceUnitMetadata pu) {
return SharedCacheMode.NONE.equals(pu.getSharedCacheMode()) ||
NONE.equals(pu.getProperties().getProperty(SHARED_CACHE_MODE));
}
private void putPropertyIfAbsent(PersistenceUnitMetadata pu, Map properties, String property, Object value) {
if (!pu.getProperties().containsKey(property)) {
properties.put(property, value);
}
}
@Override
public void beforeCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
Notification.beforeEntityManagerFactoryCreate(Classification.INFINISPAN, pu);
}
@Override
public void afterCreateContainerEntityManagerFactory(PersistenceUnitMetadata pu) {
Notification.afterEntityManagerFactoryCreate(Classification.INFINISPAN, pu);
}
@Override
public ManagementAdaptor getManagementAdaptor() {
return HibernateManagementAdaptor.getInstance();
}
/**
* determine if management console can display the second level cache entries
*
* @param pu
* @return false if a custom AvailableSettings.CACHE_REGION_PREFIX property is specified.
* true if the scoped persistence unit name is used to prefix cache entries.
*/
@Override
public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) {
String cacheRegionPrefix = pu.getProperties().getProperty(AvailableSettings.CACHE_REGION_PREFIX);
return cacheRegionPrefix == null || cacheRegionPrefix.equals(pu.getScopedPersistenceUnitName());
}
@Override
public void cleanup(PersistenceUnitMetadata pu) {
}
@Override
public Object beanManagerLifeCycle(BeanManager beanManager) {
return new HibernateExtendedBeanManager(beanManager);
}
@Override
public void markPersistenceUnitAvailable(Object wrapperBeanManagerLifeCycle) {
HibernateExtendedBeanManager hibernateExtendedBeanManager = (HibernateExtendedBeanManager) wrapperBeanManagerLifeCycle;
// notify Hibernate ORM ExtendedBeanManager extension that the entity listener(s) can now be registered.
hibernateExtendedBeanManager.beanManagerIsAvailableForUse();
}
/* start of TwoPhaseBootstrapCapable methods */
public EntityManagerFactoryBuilder getBootstrap(final PersistenceUnitInfo info, final Map map) {
return new TwoPhaseBootstrapImpl(info, map);
}
/* end of TwoPhaseBootstrapCapable methods */
}
| 11,107 | 45.476987 | 151 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/HibernateExtendedBeanManager.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate;
import jakarta.enterprise.inject.spi.BeanManager;
import org.hibernate.resource.beans.container.spi.ExtendedBeanManager;
import java.util.ArrayList;
/**
* HibernateExtendedBeanManager helps defer the registering of entity listeners, with the Jakarta Contexts and Dependency Injection BeanManager until
* after the persistence unit is available for lookup by Jakarta Contexts and Dependency Injection bean(s).
* This solves the WFLY-2387 issue of Jakarta Persistence entity listeners referencing the Jakarta Contexts and Dependency Injection bean, when the bean cycles back
* to the persistence unit, or a different persistence unit.
*
* @author Scott Marlow
*/
public class HibernateExtendedBeanManager implements ExtendedBeanManager {
private final BeanManager beanManager;
private final ArrayList<LifecycleListener> lifecycleListeners = new ArrayList<>();
public HibernateExtendedBeanManager(BeanManager beanManager) {
this.beanManager = beanManager;
}
/**
* Hibernate calls registerLifecycleListener to register callback to be notified
* when the Jakarta Contexts and Dependency Injection BeanManager can safely be used.
* The Jakarta Contexts and Dependency Injection BeanManager can safely be used
* when the Jakarta Contexts and Dependency Injection AfterDeploymentValidation event is reached.
* <p>
* Note: Caller (BeanManagerAfterDeploymentValidation) is expected to synchronize calls to
* registerLifecycleListener() + beanManagerIsAvailableForUse(), which protects
* HibernateExtendedBeanManager.lifecycleListeners from being read/written from multiple concurrent threads.
* There are many writer threads (one per deployed persistence unit) and one reader/writer thread expected
* to be triggered by one AfterDeploymentValidation event per deployment.
*/
public void beanManagerIsAvailableForUse() {
if (lifecycleListeners.isEmpty()) {
throw JpaLogger.JPA_LOGGER.HibernateORMDidNotRegisterLifeCycleListener();
}
for (LifecycleListener hibernateCallback : lifecycleListeners) {
hibernateCallback.beanManagerInitialized(beanManager);
}
}
@Override
public void registerLifecycleListener(LifecycleListener lifecycleListener) {
lifecycleListeners.add(lifecycleListener);
}
}
| 3,105 | 44.014493 | 164 | java |
null | wildfly-main/jpa/hibernate6/src/main/java/org/jboss/as/jpa/hibernate/service/WildFlyCustomJtaPlatform.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.jpa.hibernate.service;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.internal.JtaSynchronizationStrategy;
import org.wildfly.common.Assert;
/**
* WildFlyCustomJtaPlatform can obtain the Jakarta Transactions TransactionSynchronizationRegistry to be used by
* Hibernate ORM Jakarta Persistence + native applications.
* For Jakarta Persistence applications, we could of passed the TransactionSynchronizationRegistry into the
* constructor but Hibernate native apps wouldn't be able to do that, so this covers all app types.
*
* @author Scott Marlow
*/
public class WildFlyCustomJtaPlatform extends JBossAppServerJtaPlatform implements JtaSynchronizationStrategy {
// The 'transactionSynchronizationRegistry' used by Jakarta Persistence container managed applications,
// is reset every time the Transaction Manager service is restarted,
// as (application deployment) Jakarta Persistence persistence unit service depends on the TM service.
// For this reason, the static 'transactionSynchronizationRegistry' can be updated.
// Note that Hibernate native applications currently have to be (manually) restarted when the TM
// service restarts, as native applications do not have WildFly service dependencies set for them.
private static volatile TransactionSynchronizationRegistry transactionSynchronizationRegistry;
private static final String TSR_NAME = "java:jboss/TransactionSynchronizationRegistry";
// JtaSynchronizationStrategy
@Override
public void registerSynchronization(Synchronization synchronization) {
locateTransactionSynchronizationRegistry().
registerInterposedSynchronization(synchronization);
}
// JtaSynchronizationStrategy
@Override
public boolean canRegisterSynchronization() {
return locateTransactionSynchronizationRegistry().
getTransactionStatus() == Status.STATUS_ACTIVE;
}
@Override
protected JtaSynchronizationStrategy getSynchronizationStrategy() {
return this;
}
private TransactionSynchronizationRegistry locateTransactionSynchronizationRegistry() {
TransactionSynchronizationRegistry curTsr = transactionSynchronizationRegistry;
if (curTsr != null) {
return curTsr;
}
synchronized (WildFlyCustomJtaPlatform.class) {
curTsr = transactionSynchronizationRegistry;
if (curTsr != null) {
return curTsr;
}
return transactionSynchronizationRegistry = (TransactionSynchronizationRegistry) jndiService().locate(TSR_NAME);
}
}
/**
* Hibernate native applications cannot know when the TransactionManaTransactionManagerSerger + TransactionSynchronizationRegistry
* services are stopped but Jakarta Persistence container managed applications can and will call setTransactionSynchronizationRegistry
* with the new (global) TransactionSynchronizationRegistry to use.
*
* @param tsr
*/
public static void setTransactionSynchronizationRegistry(TransactionSynchronizationRegistry tsr) {
if ((Assert.checkNotNullParam("tsr", tsr)) != transactionSynchronizationRegistry) {
synchronized (WildFlyCustomJtaPlatform.class) {
if (tsr != transactionSynchronizationRegistry) {
transactionSynchronizationRegistry = tsr;
}
}
}
}
}
| 4,404 | 43.494949 | 138 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.