use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.
the class AdvancedMultiTenantSchemaJunitTest method testSetup.
/**
* test setup
* -uses existing connection to obtain DB info - username, pwd and connection string/schema name
* -creates new DB schema named '$existingSchema+"_MT"'
* -creates 2 data sources (first points to original schema, second to the newly created one)
* and 1 proxy datasource (wraps original DSs and all DB requests are going through this DS)
* -prepares tables in both DSs through the usage of proxy DS
* -stores properties necessary for proper EMF creation in emfProperties field
*/
public void testSetup() {
if (!getPlatform().isMySQL()) {
warning("this test is supported on MySQL only");
return;
}
DatabaseSessionImpl databaseSession = getDatabaseSession();
DatabaseLogin login = getDatabaseSession().getLogin();
String connectionString = login.getConnectionString();
int schemaIdx = connectionString.lastIndexOf('/');
int queryIdx = connectionString.indexOf('?', schemaIdx);
schema1 = connectionString.substring(schemaIdx + 1, queryIdx < 0 ? connectionString.length() : queryIdx);
schema2 = schema1 + "_MT";
String connectionStringMT = queryIdx < 0 ? connectionString + "_MT" : connectionString.substring(0, queryIdx) + "_MT" + connectionString.substring(queryIdx);
assertNotNull(schema1);
assertNotNull(schema2);
databaseSession.executeNonSelectingSQL("use " + schema1 + ";");
try {
databaseSession.executeNonSelectingSQL("drop schema " + schema2 + ";");
} catch (Throwable t) {
// ignore
}
try {
databaseSession.executeNonSelectingSQL("create schema " + schema2 + ";");
} catch (Throwable t) {
// we may not have enough permissions to create additional schema,
// in such case, skip all tests and log a warning
skipTest = true;
warning("Cannot create additional schema to run related tests.");
databaseSession.logThrowable(SessionLog.WARNING, SessionLog.CONNECTION, t);
return;
} finally {
databaseSession.logout();
}
Map<String, String> currentProps = JUnitTestCaseHelper.getDatabaseProperties(getPersistenceUnitName());
TestDataSource ds1 = new TestDataSource(login.getDriverClassName(), connectionString, (Properties) login.getProperties().clone());
TestDataSource ds2 = new TestDataSource(login.getDriverClassName(), connectionStringMT, (Properties) login.getProperties().clone());
proxyDataSource = new ProxyDS(databaseSession, currentProps.get(PersistenceUnitProperties.JDBC_USER), currentProps.get(PersistenceUnitProperties.JDBC_PASSWORD));
proxyDataSource.add(schema1, ds1);
proxyDataSource.add(schema2, ds2);
emfProperties = new Properties();
emfProperties.putAll(currentProps);
// need DS, not real JDBC Connections
emfProperties.remove(PersistenceUnitProperties.JDBC_DRIVER);
emfProperties.remove(PersistenceUnitProperties.JDBC_USER);
emfProperties.remove(PersistenceUnitProperties.JDBC_URL);
emfProperties.remove(PersistenceUnitProperties.JDBC_PASSWORD);
emfProperties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, proxyDataSource);
emfProperties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.NONE);
emfProperties.put(PersistenceUnitProperties.MULTITENANT_STRATEGY, "external");
// prepare 1st tenant
proxyDataSource.setCurrentDS(schema1);
EntityManagerFactory emf = Persistence.createEntityManagerFactory(getPersistenceUnitName(), emfProperties);
assertNotNull(emf);
new AdvancedTableCreator().replaceTables(((EntityManagerFactoryImpl) emf).getServerSession());
emf.close();
// prepare 2nd tenant
proxyDataSource.setCurrentDS(schema2);
emf = Persistence.createEntityManagerFactory(getPersistenceUnitName(), emfProperties);
assertNotNull(emf);
new AdvancedTableCreator().replaceTables(((EntityManagerFactoryImpl) emf).getServerSession());
emf.close();
}
use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.
the class DDLGenerationExtendTablesJUnitTestSuite method testSetup.
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
@Override
public void testSetup() {
// Create the EM. This might unnecessarily drop and create the tables
EntityManager em = createEntityManager(DDL_PU);
DatabaseSessionImpl session = getDatabaseSession(DDL_PU);
TableCreator defaultTableCreator = new DefaultTableGenerator(session.getProject(), true).generateDefaultTableCreator();
defaultTableCreator.setIgnoreDatabaseException(true);
// drop the tables using the current project
defaultTableCreator.dropTables(session);
// check that the tables do not exist:
Exception exception = null;
try {
em.createQuery("Select c from Course c").getResultList();
} catch (DatabaseException caught) {
// we expect an exception since the table should not exist, but do not know what exception the database might throw.
exception = caught;
} catch (PersistenceException e) {
exception = e;
}
assertNotNull("setup failed because a query on a drop table did not throw an exception.", exception);
// create some empty tables so that we can test they are altered correctly later.
TableCreator tbCreator = new EmptyTableCreator();
tbCreator.createTables(session);
// refresh the metadata with the create-or-alter table to create the remaining tables and alter the ones created above.
// testing later on just verifies that this worked correctly.
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_OR_EXTEND);
// create-or-extend only works on the database
properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION);
// this causes DDL generation to occur on refreshMetadata rather than wait until an em is obtained
properties.put(PersistenceUnitProperties.DEPLOY_ON_STARTUP, "true");
// JEE requires a transaction to keep the em open.
beginTransaction(em);
JpaHelper.getEntityManagerFactory(em).refreshMetadata(properties);
commitTransaction(em);
closeEntityManager(em);
clearCache(DDL_PU);
}
use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.
the class EntityManagerSetupImpl method deploy.
/**
* Deploy a persistence session and return an EntityManagerFactory.
*
* Deployment takes a session that was partially created in the predeploy call and makes it whole.
*
* This means doing any configuration that requires the real class definitions for the entities. In
* the predeploy phase we were in a stage where we were not let allowed to load the real classes.
*
* Deploy could be called several times - but only the first call does the actual deploying -
* additional calls allow to update session properties (in case the session is not connected).
*
* Note that there is no need to synchronize deploy method - it doesn't alter factoryCount
* and while deploy is executed no other method can alter the current state
* (predeploy call would just increment factoryCount; undeploy call would not drop factoryCount to 0).
* However precautions should be taken to handle concurrent calls to deploy, because those may
* alter the current state or connect the session.
*
* @param realClassLoader The class loader that was used to load the entity classes. This loader
* will be maintained for the lifespan of the loaded classes.
* @param additionalProperties added to persistence unit properties for updateServerSession overriding existing properties.
* In JSE case it allows to alter properties in main (as opposed to preMain where preDeploy is called).
* @return An EntityManagerFactory to be used by the Container to obtain EntityManagers
*/
public AbstractSession deploy(ClassLoader realClassLoader, Map additionalProperties) {
if (this.state != STATE_PREDEPLOYED && this.state != STATE_DEPLOYED && this.state != STATE_HALF_DEPLOYED) {
if (mustBeCompositeMember()) {
throw new PersistenceException(EntityManagerSetupException.compositeMemberCannotBeUsedStandalone(this.persistenceUnitInfo.getPersistenceUnitName()));
}
throw new PersistenceException(EntityManagerSetupException.cannotDeployWithoutPredeploy(this.persistenceUnitInfo.getPersistenceUnitName(), this.state, this.persistenceException));
}
// state is PREDEPLOYED or DEPLOYED
this.session.log(SessionLog.FINEST, SessionLog.JPA, "deploy_begin", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), this.session.getName(), this.state, this.factoryCount });
ClassLoader classLoaderToUse = realClassLoader;
if (additionalProperties.containsKey(PersistenceUnitProperties.CLASSLOADER)) {
classLoaderToUse = (ClassLoader) additionalProperties.get(PersistenceUnitProperties.CLASSLOADER);
} else if ((this.processor != null) && (this.processor.getProject() != null) && (this.processor.getProject().hasVirtualClasses()) && (this.state == STATE_PREDEPLOYED) && (!(classLoaderToUse instanceof DynamicClassLoader))) {
classLoaderToUse = new DynamicClassLoader(classLoaderToUse);
}
// indicates whether session has failed to connect, determines whether HALF_DEPLOYED state should be kept in case of exception.
boolean isLockAcquired = false;
try {
Map deployProperties = mergeMaps(additionalProperties, this.persistenceUnitInfo.getProperties());
updateTunerPreDeploy(deployProperties, classLoaderToUse);
translateOldProperties(deployProperties, this.session);
if (isComposite()) {
updateCompositeMembersProperties(deployProperties);
}
if (this.state == STATE_PREDEPLOYED) {
this.deployLock.acquire();
isLockAcquired = true;
if (this.state == STATE_PREDEPLOYED) {
if (this.shouldBuildProject && !this.isSessionLoadedFromSessionsXML) {
if (isComposite()) {
deployCompositeMembers(deployProperties, classLoaderToUse);
} else {
if (this.processor.getMetadataSource() != null) {
Map metadataProperties = this.processor.getMetadataSource().getPropertyOverrides(deployProperties, classLoaderToUse, this.session.getSessionLog());
if (metadataProperties != null && !metadataProperties.isEmpty()) {
translateOldProperties(metadataProperties, this.session);
deployProperties = mergeMaps(metadataProperties, deployProperties);
}
}
// listeners and queries require the real classes and are therefore built during deploy using the realClassLoader
this.processor.setClassLoader(classLoaderToUse);
this.processor.createDynamicClasses();
this.processor.addEntityListeners();
if (this.projectCacheAccessor != null) {
// cache the project:
this.projectCacheAccessor.storeProject(this.session.getProject(), deployProperties, this.session.getSessionLog());
}
// The project is initially created using class names rather than classes. This call will make the conversion.
// If the session was loaded from sessions.xml this will also convert the descriptor classes to the correct class loader.
this.session.getProject().convertClassNamesToClasses(classLoaderToUse);
if (!isCompositeMember()) {
addBeanValidationListeners(deployProperties, classLoaderToUse);
}
// Process the customizers last.
this.processor.processCustomizers();
}
this.processor = null;
} else {
// The project is initially created using class names rather than classes. This call will make the conversion.
// If the session was loaded from sessions.xml this will also convert the descriptor classes to the correct class loader.
this.session.getProject().convertClassNamesToClasses(classLoaderToUse);
if (!this.shouldBuildProject) {
// process anything that might not have been serialized/cached in the project correctly:
if (!isCompositeMember()) {
addBeanValidationListeners(deployProperties, classLoaderToUse);
}
// process Descriptor customizers:
processDescriptorsFromCachedProject(classLoaderToUse);
}
}
finishProcessingDescriptorEvents(classLoaderToUse);
this.structConverters = getStructConverters(classLoaderToUse);
updateRemote(deployProperties, classLoaderToUse);
initSession();
if (this.session.getIntegrityChecker().hasErrors()) {
this.session.handleException(new IntegrityException(session.getIntegrityChecker()));
}
this.session.getDatasourcePlatform().getConversionManager().setLoader(classLoaderToUse);
this.state = STATE_HALF_DEPLOYED;
// keep deployLock
} else {
// state is HALF_DEPLOYED or DEPLOY_FAILED
this.deployLock.release();
isLockAcquired = false;
if (this.state == STATE_DEPLOY_FAILED) {
// Rethrow the cache PersistenceException, which caused STATE_DEPLOYED_FAILED.
throw persistenceException;
}
}
}
// state is HALF_DEPLOYED or DEPLOYED
if (!isCompositeMember()) {
if (this.session.isDatabaseSession() && !((DatabaseSessionImpl) session).isLoggedIn()) {
// If it's HALF_DEPLOYED then deployLock has been already acquired.
if (!isLockAcquired) {
this.deployLock.acquire();
isLockAcquired = true;
}
if (!((DatabaseSessionImpl) this.session).isLoggedIn()) {
if (this.state == STATE_DEPLOY_FAILED) {
// Rethrow the cache PersistenceException, which caused STATE_DEPLOYED_FAILED.
throw persistenceException;
}
this.session.setProperties(deployProperties);
updateSession(deployProperties, classLoaderToUse);
if (isValidationOnly(deployProperties, false)) {
/**
* for 324213 we could add a session.loginAndDetectDatasource() call
* before calling initializeDescriptors when validation-only is True
* to avoid a native sequence exception on a generic DatabasePlatform
* by auto-detecting the correct DB platform.
* However, this would introduce a DB login when validation is on
* - in opposition to the functionality of the property (to only validate)
*/
if (this.state == STATE_HALF_DEPLOYED) {
getDatabaseSession().initializeDescriptors();
this.state = STATE_DEPLOYED;
}
} else {
try {
updateTunerDeploy(deployProperties, classLoaderToUse);
updateFreeMemory(deployProperties);
if (this.isSessionLoadedFromSessionsXML) {
getDatabaseSession().login();
} else {
login(getDatabaseSession(), deployProperties, requiresConnection);
}
final Platform platform = getDatabaseSession().getDatasourcePlatform();
String dbProperties = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, deployProperties, this.session);
PropertiesUtils.set(platform, PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, dbProperties);
// Make JTA integration throw JPA exceptions.
if (this.session.hasExternalTransactionController()) {
if (this.session.getExternalTransactionController().getExceptionHandler() == null) {
this.session.getExternalTransactionController().setExceptionHandler(new ExceptionHandler() {
@Override
public Object handleException(RuntimeException exception) {
if (exception instanceof org.eclipse.persistence.exceptions.OptimisticLockException) {
throw new OptimisticLockException(exception);
} else if (exception instanceof EclipseLinkException) {
throw new PersistenceException(exception);
} else {
throw exception;
}
}
});
}
}
this.state = STATE_DEPLOYED;
} catch (Throwable loginException) {
if (this.state == STATE_HALF_DEPLOYED) {
if (this.session.isConnected()) {
// Cannot recover from that - the user has to fix the persistence unit and redeploy it.
try {
getDatabaseSession().logout();
} catch (Throwable logoutException) {
// Ignore
}
this.state = STATE_DEPLOY_FAILED;
}
}
throw loginException;
}
if (!this.isSessionLoadedFromSessionsXML) {
addStructConverters();
}
// Generate the DDL using the correct connection.
writeDDL(deployProperties, getDatabaseSession(deployProperties), classLoaderToUse);
}
}
// Initialize platform specific identity sequences.
session.getDatasourcePlatform().initIdentitySequences(getDatabaseSession(), MetadataProject.DEFAULT_IDENTITY_GENERATOR);
updateTunerPostDeploy(deployProperties, classLoaderToUse);
this.deployLock.release();
isLockAcquired = false;
}
// 266912: Initialize the Metamodel, a login should have already occurred.
try {
this.getMetamodel(classLoaderToUse);
} catch (Exception e) {
this.session.log(SessionLog.FINEST, SessionLog.METAMODEL, "metamodel_init_failed", new Object[] { e.getMessage() });
}
}
// Clear the weaver's reference to meta-data information, as it is held by the class loader and will never gc.
if (this.weaver != null) {
this.weaver.clear();
this.weaver = null;
}
return this.session;
} catch (Throwable exception) {
// before releasing deployLock switch to the correct state
if (this.state == STATE_PREDEPLOYED) {
this.state = STATE_DEPLOY_FAILED;
}
PersistenceException persistenceEx;
if (this.state == STATE_DEPLOY_FAILED) {
if (exception == persistenceException) {
persistenceEx = new PersistenceException(EntityManagerSetupException.cannotDeployWithoutPredeploy(this.persistenceUnitInfo.getPersistenceUnitName(), this.state, this.persistenceException));
} else {
// before releasing deployLock cache the exception
persistenceEx = createDeployFailedPersistenceException(exception);
}
} else {
if (exception instanceof PersistenceException) {
persistenceEx = (PersistenceException) exception;
} else {
persistenceEx = new PersistenceException(exception);
}
}
if (isLockAcquired) {
this.deployLock.release();
}
this.session.logThrowable(SessionLog.SEVERE, SessionLog.EJB, exception);
throw persistenceEx;
} finally {
this.session.log(SessionLog.FINEST, SessionLog.JPA, "deploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), this.session.getName(), this.state, this.factoryCount });
}
}
use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.
the class EntityManagerSetupImpl method getDatabaseSession.
/**
* We may be provided a connection via the properties to use. Check for
* one and build a database session around it. Otherwise return the pu
* database session.
*/
public DatabaseSessionImpl getDatabaseSession(Map props) {
DatabaseSessionImpl databaseSession = getDatabaseSession();
Object connection = getConfigProperty(PersistenceUnitProperties.SCHEMA_GENERATION_CONNECTION, props);
if (connection == null) {
return databaseSession;
} else {
// A connection was provided. Build a database session using that
// connection and use the same log level set on the original
// database session.
DatabaseSessionImpl newDatabaseSession = new DatabaseSessionImpl();
newDatabaseSession.setAccessor(new DatabaseAccessor(connection));
newDatabaseSession.setLogLevel(databaseSession.getLogLevel());
newDatabaseSession.setProject(databaseSession.getProject().clone());
return newDatabaseSession;
}
}
use of org.eclipse.persistence.internal.sessions.DatabaseSessionImpl in project eclipselink by eclipse-ee4j.
the class SOAP12TestSuite method buildSessions.
@Override
public void buildSessions() {
XRDynamicClassLoader xrdecl = new XRDynamicClassLoader(parentClassLoader);
DatasourceLogin login = new DatabaseLogin();
login.setUserName(username);
login.setPassword(password);
((DatabaseLogin) login).setConnectionString(url);
((DatabaseLogin) login).setDriverClassName(DATABASE_PLATFORM);
Platform platform = builder.getDatabasePlatform();
ConversionManager conversionManager = platform.getConversionManager();
if (conversionManager != null) {
conversionManager.setLoader(xrdecl);
}
login.setDatasourcePlatform(platform);
((DatabaseLogin) login).bindAllParameters();
((DatabaseLogin) login).setUsesStreamsForBinding(true);
Project orProject = null;
if (DBWS_OR_STREAM.size() != 0) {
MetadataProcessor processor = new MetadataProcessor(new XRPersistenceUnitInfo(xrdecl), new DatabaseSessionImpl(login), xrdecl, false, true, false, false, false, null, null);
processor.setMetadataSource(new JPAMetadataSource(xrdecl, new StringReader(DBWS_OR_STREAM.toString())));
PersistenceUnitProcessor.processORMetadata(processor, true, PersistenceUnitProcessor.Mode.ALL);
processor.addNamedQueries();
orProject = processor.getProject().getProject();
} else {
orProject = new Project();
}
orProject.setName(builder.getProjectName().concat(OR_PRJ_SUFFIX));
orProject.setDatasourceLogin(login);
DatabaseSession databaseSession = orProject.createDatabaseSession();
if ("off".equalsIgnoreCase(builder.getLogLevel())) {
databaseSession.dontLogMessages();
} else {
databaseSession.setLogLevel(AbstractSessionLog.translateStringToLoggingLevel(builder.getLogLevel()));
}
xrService.setORSession(databaseSession);
orProject.convertClassNamesToClasses(xrdecl);
Project oxProject = null;
Map<String, OXMMetadataSource> metadataMap = new HashMap<String, OXMMetadataSource>();
StreamSource xml = new StreamSource(new StringReader(DBWS_OX_STREAM.toString()));
try {
JAXBContext jc = JAXBContext.newInstance(XmlBindingsModel.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<XmlBindingsModel> jaxbElt = unmarshaller.unmarshal(xml, XmlBindingsModel.class);
XmlBindingsModel model = jaxbElt.getValue();
for (XmlBindings xmlBindings : model.getBindingsList()) {
metadataMap.put(xmlBindings.getPackageName(), new OXMMetadataSource(xmlBindings));
}
} catch (JAXBException jaxbex) {
jaxbex.printStackTrace();
}
Map<String, Map<String, OXMMetadataSource>> properties = new HashMap<String, Map<String, OXMMetadataSource>>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, metadataMap);
try {
org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext jCtx = org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory.createContextFromOXM(parentClassLoader, properties);
oxProject = jCtx.getXMLContext().getSession(0).getProject();
} catch (JAXBException e) {
e.printStackTrace();
}
((XMLLogin) oxProject.getDatasourceLogin()).setPlatformClassName(DOM_PLATFORM_CLASSNAME);
((XMLLogin) oxProject.getDatasourceLogin()).setEqualNamespaceResolvers(false);
prepareDescriptors(oxProject, orProject, xrdecl);
ProjectHelper.fixOROXAccessors(orProject, oxProject);
xrService.setORSession(databaseSession);
xrService.setXMLContext(new XMLContext(oxProject));
xrService.setOXSession(xrService.getXMLContext().getSession(0));
}
Aggregations