Search in sources :

Example 1 with SessionManager

use of org.eclipse.persistence.sessions.factories.SessionManager in project blaze-persistence by Blazebit.

the class AbstractPersistenceTest method clearSchemaUsingJpa.

@Override
protected void clearSchemaUsingJpa() {
    Map<String, EntityManagerSetupImpl> emSetupImpls = EntityManagerFactoryProvider.getEmSetupImpls();
    Map<String, EntityManagerSetupImpl> copy = new HashMap<>(emSetupImpls);
    emSetupImpls.clear();
    SessionManager manager = SessionManager.getManager();
    for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
        manager.getSessions().remove(emSetupImpl.getSessionName());
    }
    try {
        super.clearSchemaUsingJpa();
    } finally {
        emSetupImpls.putAll(copy);
        for (EntityManagerSetupImpl emSetupImpl : copy.values()) {
            manager.addSession(emSetupImpl.getSession());
        }
    }
}
Also used : HashMap(java.util.HashMap) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) EntityManagerSetupImpl(org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl)

Example 2 with SessionManager

use of org.eclipse.persistence.sessions.factories.SessionManager in project eclipselink by eclipse-ee4j.

the class RuntimeFactory method createEntityManagerFactory.

public EntityManagerFactory createEntityManagerFactory(PersistenceUnit pu) {
    EntityManagerSetupImpl emSetupImpl = null;
    boolean isNew = false;
    // the name that uniquely defines persistence unit
    String name = pu.getName();
    pu.setProperty(PersistenceUnitProperties.METADATA_SOURCE, new MetadataSource(pu));
    SEPersistenceUnitInfo puInfo = (SEPersistenceUnitInfo) pu.getPersistenceUnitInfo();
    JPAInitializer initializer = new PersistenceProvider().getInitializer(name, null);
    Map<String, Object> props = new HashMap<String, Object>();
    String uniqueName = initializer.createUniquePersistenceUnitName(puInfo);
    String sessionName = EntityManagerSetupImpl.getOrBuildSessionName(props, puInfo, uniqueName);
    try {
        synchronized (EntityManagerFactoryProvider.emSetupImpls) {
            emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(sessionName);
            if (emSetupImpl != null) {
                if (puInfo.getClassLoader() != emSetupImpl.getPersistenceUnitInfo().getClassLoader()) {
                    emSetupImpl.undeploy();
                    EntityManagerFactoryProvider.emSetupImpls.remove(sessionName);
                    SessionManager manager = SessionManager.getManager();
                    if (manager.getSessions().containsKey(sessionName)) {
                        manager.destroySession(sessionName);
                    }
                    manager.destroy();
                    emSetupImpl = null;
                }
            }
            if (emSetupImpl == null) {
                // there may be initial emSetupImpl cached in Initializer - remove it and use.
                emSetupImpl = initializer.extractInitialEmSetupImpl(name);
                if (emSetupImpl == null) {
                    // create and predeploy a new emSetupImpl
                    emSetupImpl = initializer.callPredeploy(puInfo, props, uniqueName, sessionName);
                } else {
                    // change the name
                    emSetupImpl.changeSessionName(sessionName);
                }
                // emSetupImpl has been already predeployed, predeploy will just increment factoryCount.
                emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), props);
                EntityManagerFactoryProvider.addEntityManagerSetupImpl(sessionName, emSetupImpl);
                isNew = true;
            }
        }
    } catch (Exception e) {
        throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(initializer.getInitializationClassLoader(), e);
    }
    if (!isNew) {
        if (!uniqueName.equals(emSetupImpl.getPersistenceUnitUniqueName())) {
            throw PersistenceUnitLoadingException.sessionNameAlreadyInUse(sessionName, uniqueName, emSetupImpl.getPersistenceUnitUniqueName());
        }
        // synchronized to prevent undeploying by other threads.
        boolean undeployed = false;
        synchronized (emSetupImpl) {
            if (emSetupImpl.isUndeployed()) {
                undeployed = true;
            }
            // emSetupImpl has been already predeployed, predeploy will just increment factoryCount.
            emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), props);
        }
        if (undeployed) {
            // start all over again.
            return createEntityManagerFactory(pu);
        }
    }
    EntityManagerFactoryImpl factory = null;
    try {
        factory = new EntityManagerFactoryImpl(emSetupImpl, props);
        // actually calling createEntityManager
        if (emSetupImpl.shouldGetSessionOnCreateFactory(props)) {
            factory.getDatabaseSession();
        }
    } catch (RuntimeException ex) {
        if (factory != null) {
            factory.close();
        } else {
            emSetupImpl.undeploy();
        }
        throw ex;
    }
    return factory;
}
Also used : HashMap(java.util.HashMap) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) JPAInitializer(org.eclipse.persistence.internal.jpa.deployment.JPAInitializer) PersistenceProvider(org.eclipse.persistence.jpa.PersistenceProvider) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) MetadataSource(org.eclipse.persistence.internal.jpa.config.persistenceunit.MetadataSource) SEPersistenceUnitInfo(org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo) PersistenceUnitLoadingException(org.eclipse.persistence.exceptions.PersistenceUnitLoadingException) EntityManagerSetupImpl(org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl)

Example 3 with SessionManager

use of org.eclipse.persistence.sessions.factories.SessionManager in project eclipselink by eclipse-ee4j.

the class EntityManagerSetupImpl method predeploy.

/**
 * Perform any steps necessary prior to actual deployment.  This includes any steps in the session
 * creation that do not require the real loaded domain classes.
 *
 * The first call to this method caches persistenceUnitInfo which is reused in the following calls.
 *
 * Note that in JSE case factoryCount is NOT incremented on the very first call
 * (by JavaSECMPInitializer.callPredeploy, typically in preMain).
 * That provides 1 to 1 correspondence between factoryCount and the number of open factories.
 *
 * In case factoryCount &gt; 0 the method just increments factoryCount.
 * factory == 0 triggers creation of a new session.
 *
 * This method and undeploy - the only methods altering factoryCount - should be synchronized.
 *
 * @return A transformer (which may be null) that should be plugged into the proper
 *         classloader to allow classes to be transformed as they get loaded.
 * @see #deploy(ClassLoader, Map)
 */
public synchronized ClassTransformer predeploy(PersistenceUnitInfo info, Map extendedProperties) {
    ClassLoader classLoaderToUse = null;
    // session == null
    if (state == STATE_DEPLOY_FAILED || state == STATE_UNDEPLOYED) {
        throw new PersistenceException(EntityManagerSetupException.cannotPredeploy(persistenceUnitInfo.getPersistenceUnitName(), state, persistenceException));
    }
    // session != null
    if (state == STATE_PREDEPLOYED || state == STATE_DEPLOYED || state == STATE_HALF_DEPLOYED) {
        session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_begin", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state, factoryCount });
        factoryCount++;
        session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state, factoryCount });
        return null;
    // session == null
    } else if (state == STATE_INITIAL) {
        persistenceUnitInfo = info;
        if (!isCompositeMember()) {
            if (mustBeCompositeMember(persistenceUnitInfo)) {
                if (this.staticWeaveInfo == null) {
                    return null;
                } else {
                    // predeploy is used for static weaving
                    throw new PersistenceException(EntityManagerSetupException.compositeMemberCannotBeUsedStandalone(persistenceUnitInfo.getPersistenceUnitName()));
                }
            }
        }
    }
    // state is INITIAL or PREDEPLOY_FAILED or STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER, session == null
    try {
        // properties not used in STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER
        Map predeployProperties = null;
        // composite can't be in STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER
        boolean isComposite = false;
        if (state != STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER) {
            // set the claasloader early on and change it if needed
            classLoaderToUse = persistenceUnitInfo.getClassLoader();
            predeployProperties = mergeMaps(extendedProperties, persistenceUnitInfo.getProperties());
            // Translate old properties.
            // This should be done before using properties (i.e. ServerPlatform).
            translateOldProperties(predeployProperties, null);
            String sessionsXMLStr = (String) predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML);
            if (sessionsXMLStr != null) {
                isSessionLoadedFromSessionsXML = true;
            }
            // Create session (it needs to be done before initializing ServerPlatform and logging).
            // If a sessions-xml is used this will get replaced later, but is required for logging.
            isComposite = isComposite(persistenceUnitInfo);
            if (isComposite) {
                if (isSessionLoadedFromSessionsXML) {
                    throw EntityManagerSetupException.compositeIncompatibleWithSessionsXml(persistenceUnitInfo.getPersistenceUnitName());
                }
                session = new SessionBroker();
                ((SessionBroker) session).setShouldUseDescriptorAliases(true);
            } else {
                session = new ServerSession(new Project(new DatabaseLogin()));
                // set the listener to process RCM metadata refresh commands
                session.setRefreshMetadataListener(this);
            }
            session.setName(this.sessionName);
            updateTunerPreDeploy(predeployProperties, classLoaderToUse);
            updateTolerateInvalidJPQL(predeployProperties);
            if (this.compositeEmSetupImpl == null) {
                // session name and ServerPlatform must be set prior to setting the loggers.
                if (this.staticWeaveInfo == null) {
                    updateServerPlatform(predeployProperties, classLoaderToUse);
                    // Update loggers and settings for the singleton logger and the session logger.
                    updateLoggers(predeployProperties, true, classLoaderToUse);
                    // log the server platform being used by the session
                    if (session.getSessionLog().shouldLog(SessionLog.FINE)) {
                        session.getSessionLog().log(SessionLog.FINE, SessionLog.SERVER, "configured_server_platform", // NOI18N
                        session.getServerPlatform().getClass().getName());
                    }
                    // Get the temporary classLoader based on the platform
                    // Update performance profiler
                    updateProfiler(predeployProperties, classLoaderToUse);
                } else {
                    // predeploy is used for static weaving
                    Writer writer = this.staticWeaveInfo.getLogWriter();
                    if (writer != null) {
                        session.getSessionLog().setWriter(writer);
                    }
                    session.setLogLevel(this.staticWeaveInfo.getLogLevel());
                }
            } else {
                // composite member
                session.setSessionLog(this.compositeEmSetupImpl.session.getSessionLog());
                session.setProfiler(this.compositeEmSetupImpl.session.getProfiler());
            }
            // Cannot start logging until session and log and initialized, so log start of predeploy here.
            session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_begin", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state, factoryCount });
            // Project Cache accessor processing
            updateProjectCache(predeployProperties, classLoaderToUse);
            if (projectCacheAccessor != null) {
                // get the project from the cache
                Project project = projectCacheAccessor.retrieveProject(predeployProperties, classLoaderToUse, session.getSessionLog());
                if (project != null) {
                    try {
                        DatabaseSessionImpl tempSession = (DatabaseSessionImpl) project.createServerSession();
                        tempSession.setName(this.sessionName);
                        tempSession.setSessionLog(session.getSessionLog());
                        tempSession.getSessionLog().setSession(tempSession);
                        if (this.staticWeaveInfo != null) {
                            tempSession.setLogLevel(this.staticWeaveInfo.getLogLevel());
                        }
                        tempSession.setProfiler(session.getProfiler());
                        tempSession.setRefreshMetadataListener(this);
                        session = tempSession;
                        // reusing the serverPlatform from the existing session would have been preferred,
                        // but its session is only set through the ServerPlatform constructor.
                        updateServerPlatform(predeployProperties, classLoaderToUse);
                        shouldBuildProject = false;
                    } catch (Exception e) {
                        // need a better exception here
                        throw new PersistenceException(e);
                    }
                }
            }
            if (isSessionLoadedFromSessionsXML) {
                if (this.compositeEmSetupImpl == null && this.staticWeaveInfo == null) {
                    JPAClassLoaderHolder privateClassLoaderHolder = session.getServerPlatform().getNewTempClassLoader(persistenceUnitInfo);
                    classLoaderToUse = privateClassLoaderHolder.getClassLoader();
                } else {
                    classLoaderToUse = persistenceUnitInfo.getNewTempClassLoader();
                }
                // Loading session from sessions-xml.
                String tempSessionName = sessionName;
                if (isCompositeMember()) {
                    // composite member session name is always the same as puName
                    // need the session name specified in properties to read correct session from sessions.xml
                    tempSessionName = (String) predeployProperties.get(PersistenceUnitProperties.SESSION_NAME);
                }
                session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "loading_session_xml", sessionsXMLStr, tempSessionName);
                if (tempSessionName == null) {
                    throw EntityManagerSetupException.sessionNameNeedBeSpecified(persistenceUnitInfo.getPersistenceUnitName(), sessionsXMLStr);
                }
                XMLSessionConfigLoader xmlLoader = new XMLSessionConfigLoader(sessionsXMLStr);
                // Do not register the session with the SessionManager at this point, create temporary session using a local SessionManager and private class loader.
                // This allows for the project to be accessed without loading any of the classes to allow weaving.
                // Note that this method assigns sessionName to session.
                Session tempSession = new SessionManager().getSession(xmlLoader, tempSessionName, classLoaderToUse, false, false);
                // Load path of sessions-xml resource before throwing error so user knows which sessions-xml file was found (may be multiple).
                session.log(SessionLog.FINEST, SessionLog.PROPERTIES, "sessions_xml_path_where_session_load_from", xmlLoader.getSessionName(), xmlLoader.getResourcePath());
                if (tempSession == null) {
                    throw ValidationException.noSessionFound(sessionName, sessionsXMLStr);
                }
                // Currently the session must be either a ServerSession or a SessionBroker, cannot be just a DatabaseSessionImpl.
                if (tempSession.isServerSession() || tempSession.isSessionBroker()) {
                    session = (DatabaseSessionImpl) tempSession;
                    if (tempSessionName != sessionName) {
                        // set back the original session name
                        session.setName(sessionName);
                    }
                } else {
                    throw EntityManagerSetupException.sessionLoadedFromSessionsXMLMustBeServerSession(persistenceUnitInfo.getPersistenceUnitName(), (String) predeployProperties.get(PersistenceUnitProperties.SESSIONS_XML), tempSession);
                }
                if (this.staticWeaveInfo == null) {
                    // Must now reset logging and server-platform on the loaded session.
                    // ServerPlatform must be set prior to setting the loggers.
                    updateServerPlatform(predeployProperties, classLoaderToUse);
                    // Update loggers and settings for the singleton logger and the session logger.
                    updateLoggers(predeployProperties, true, classLoaderToUse);
                }
            } else {
                classLoaderToUse = persistenceUnitInfo.getClassLoader();
            }
            warnOldProperties(predeployProperties, session);
            session.getPlatform().setConversionManager(new JPAConversionManager());
            if (this.staticWeaveInfo == null) {
                if (!isComposite) {
                    PersistenceUnitTransactionType transactionType = null;
                    // bug 5867753: find and override the transaction type
                    String transTypeString = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.TRANSACTION_TYPE, predeployProperties, session);
                    if (transTypeString != null && transTypeString.length() > 0) {
                        transactionType = PersistenceUnitTransactionType.valueOf(transTypeString);
                    } else if (persistenceUnitInfo != null) {
                        transactionType = persistenceUnitInfo.getTransactionType();
                    }
                    if (!isValidationOnly(predeployProperties, false) && persistenceUnitInfo != null && transactionType == PersistenceUnitTransactionType.JTA) {
                        if (predeployProperties.get(PersistenceUnitProperties.JTA_DATASOURCE) == null && persistenceUnitInfo.getJtaDataSource() == null) {
                            if (predeployProperties.get(PersistenceUnitProperties.SCHEMA_DATABASE_PRODUCT_NAME) == null || predeployProperties.get(PersistenceUnitProperties.SCHEMA_DATABASE_MAJOR_VERSION) == null || predeployProperties.get(PersistenceUnitProperties.SCHEMA_DATABASE_MINOR_VERSION) == null) {
                                throw EntityManagerSetupException.jtaPersistenceUnitInfoMissingJtaDataSource(persistenceUnitInfo.getPersistenceUnitName());
                            }
                        }
                    }
                }
                // this flag is used to disable work done as a result of the LAZY hint on OneToOne and ManyToOne mappings
                if (state == STATE_INITIAL) {
                    if (compositeEmSetupImpl == null) {
                        if (null == enableWeaving) {
                            enableWeaving = Boolean.TRUE;
                        }
                        isWeavingStatic = false;
                        String weaving = getConfigPropertyAsString(PersistenceUnitProperties.WEAVING, predeployProperties);
                        if (weaving != null && weaving.equalsIgnoreCase("false")) {
                            enableWeaving = Boolean.FALSE;
                        } else if (weaving != null && weaving.equalsIgnoreCase("static")) {
                            isWeavingStatic = true;
                        }
                    } else {
                        // no weaving for composite forces no weaving for members
                        if (!compositeEmSetupImpl.enableWeaving) {
                            enableWeaving = Boolean.FALSE;
                        } else {
                            if (null == enableWeaving) {
                                enableWeaving = Boolean.TRUE;
                            }
                            String weaving = getConfigPropertyAsString(PersistenceUnitProperties.WEAVING, predeployProperties);
                            if (weaving != null && weaving.equalsIgnoreCase("false")) {
                                enableWeaving = Boolean.FALSE;
                            }
                        }
                        // static weaving is dictated by composite
                        isWeavingStatic = compositeEmSetupImpl.isWeavingStatic;
                    }
                }
                if (compositeEmSetupImpl == null) {
                    throwExceptionOnFail = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.THROW_EXCEPTIONS, predeployProperties, "true", session));
                } else {
                    // composite member
                    throwExceptionOnFail = compositeEmSetupImpl.throwExceptionOnFail;
                }
            } else {
                // predeploy is used for static weaving
                enableWeaving = Boolean.TRUE;
            }
            weaveChangeTracking = false;
            weaveLazy = false;
            weaveEager = false;
            weaveFetchGroups = false;
            weaveInternal = false;
            weaveRest = false;
            weaveMappedSuperClass = false;
            if (enableWeaving) {
                weaveChangeTracking = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_CHANGE_TRACKING, predeployProperties, "true", session));
                weaveLazy = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_LAZY, predeployProperties, "true", session));
                weaveEager = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_EAGER, predeployProperties, "false", session));
                weaveFetchGroups = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_FETCHGROUPS, predeployProperties, "true", session));
                weaveInternal = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_INTERNAL, predeployProperties, "true", session));
                weaveRest = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_REST, predeployProperties, shouldWeaveRestByDefault(classLoaderToUse), session));
                weaveMappedSuperClass = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.WEAVING_MAPPEDSUPERCLASS, predeployProperties, "true", session));
            }
        }
        if (shouldBuildProject && !isSessionLoadedFromSessionsXML) {
            if (isComposite) {
                predeployCompositeMembers(predeployProperties, classLoaderToUse);
            } else {
                MetadataProcessor compositeProcessor = null;
                if (compositeEmSetupImpl == null) {
                    mode = PersistenceUnitProcessor.Mode.ALL;
                } else {
                    // composite member
                    if (state != STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER) {
                        state = STATE_HALF_PREDEPLOYED_COMPOSITE_MEMBER;
                        mode = PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_INITIAL;
                    }
                    compositeProcessor = compositeEmSetupImpl.processor;
                }
                if (mode == PersistenceUnitProcessor.Mode.ALL || mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_INITIAL) {
                    boolean usesMultitenantSharedEmf = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.MULTITENANT_SHARED_EMF, predeployProperties, "true", session));
                    boolean usesMultitenantSharedCache = "true".equalsIgnoreCase(EntityManagerFactoryProvider.getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.MULTITENANT_SHARED_CACHE, predeployProperties, "false", session));
                    // Create an instance of MetadataProcessor for specified persistence unit info
                    processor = new MetadataProcessor(persistenceUnitInfo, session, classLoaderToUse, weaveLazy, weaveEager, weaveFetchGroups, usesMultitenantSharedEmf, usesMultitenantSharedCache, predeployProperties, compositeProcessor);
                    // need to use the real classloader to create the repository class
                    updateMetadataRepository(predeployProperties, classLoaderToUse);
                    // bug:299926 - Case insensitive table / column matching with native SQL queries
                    EntityManagerSetupImpl.updateCaseSensitivitySettings(predeployProperties, processor.getProject(), session);
                }
                // Set the shared cache mode to the jakarta.persistence.sharedCache.mode property value.
                updateSharedCacheMode(predeployProperties);
                // If Java Security is enabled, surround this call with a doPrivileged block.
                if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                    AccessController.doPrivileged(new PrivilegedAction<Void>() {

                        @Override
                        public Void run() {
                            PersistenceUnitProcessor.processORMetadata(processor, throwExceptionOnFail, mode);
                            return null;
                        }
                    });
                } else {
                    PersistenceUnitProcessor.processORMetadata(processor, throwExceptionOnFail, mode);
                }
                if (mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_INITIAL) {
                    mode = PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_MIDDLE;
                    session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state + " " + mode, factoryCount });
                    return null;
                } else if (mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_MIDDLE) {
                    mode = PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_FINAL;
                    session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state + " " + mode, factoryCount });
                    return null;
                }
                // mode == PersistenceUnitProcessor.Mode.ALL || mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_FINAL
                // clear mode and proceed
                mode = null;
                if (session.getIntegrityChecker().hasErrors()) {
                    session.handleException(new IntegrityException(session.getIntegrityChecker()));
                }
                // be returned if we we are mean to process these mappings
                if (enableWeaving) {
                    // build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
                    Collection<MetadataClass> entities = PersistenceUnitProcessor.buildEntityList(processor, classLoaderToUse);
                    this.weaver = TransformerFactory.createTransformerAndModifyProject(session, entities, classLoaderToUse, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal, weaveRest, weaveMappedSuperClass);
                    session.getProject().setClassNamesForWeaving(new ArrayList<>(processor.getProject().getWeavableClassNames()));
                }
                // moved from deployment:
                processor.addNamedQueries();
                processor.addStructConverterNames();
            }
        } else {
            // be returned if we we are meant to process these mappings.
            if (enableWeaving) {
                Collection<MetadataClass> persistenceClasses = new ArrayList<>();
                MetadataAsmFactory factory = new MetadataAsmFactory(new MetadataLogger(session), classLoaderToUse);
                if (shouldBuildProject) {
                    // build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
                    for (Iterator<Class<?>> iterator = session.getProject().getDescriptors().keySet().iterator(); iterator.hasNext(); ) {
                        persistenceClasses.add(factory.getMetadataClass(iterator.next().getName()));
                    }
                } else {
                    // build a list of entities the persistence unit represented by this EntityManagerSetupImpl will use
                    for (String className : session.getProject().getClassNamesForWeaving()) {
                        persistenceClasses.add(factory.getMetadataClass(className));
                    }
                }
                this.weaver = TransformerFactory.createTransformerAndModifyProject(session, persistenceClasses, classLoaderToUse, weaveLazy, weaveChangeTracking, weaveFetchGroups, weaveInternal, weaveRest, weaveMappedSuperClass);
            }
        }
        // composite member never has a factory - it is predeployed by the composite.
        if (!isCompositeMember()) {
            // but rather done by JavaSECMPInitializer.callPredeploy (typically in preMain).
            if (state != STATE_INITIAL || this.isInContainerMode()) {
                factoryCount++;
            }
            preInitializeMetamodel();
        }
        state = STATE_PREDEPLOYED;
        session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state, factoryCount });
        // gf3146: if static weaving is used, we should not return a transformer.  Transformer should still be created though as it modifies descriptors
        if (isWeavingStatic) {
            return null;
        } else {
            return this.weaver;
        }
    } catch (Throwable ex) {
        state = STATE_PREDEPLOY_FAILED;
        // cache this.persistenceException before slow logging
        PersistenceException persistenceEx = createPredeployFailedPersistenceException(ex);
        // If session exists, use it for logging
        if (session != null) {
            session.log(SessionLog.FINEST, SessionLog.JPA, "predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), session.getName(), state, factoryCount });
        // If at least staticWeaveInfo exists, use it for logging
        } else if (staticWeaveInfo != null && staticWeaveInfo.getLogLevel() <= SessionLog.FINEST) {
            Writer logWriter = staticWeaveInfo.getLogWriter();
            if (logWriter != null) {
                String message = LoggingLocalization.buildMessage("predeploy_end", new Object[] { getPersistenceUnitInfo().getPersistenceUnitName(), "N/A", state, factoryCount });
                try {
                    logWriter.write(message);
                    logWriter.write(Helper.cr());
                } catch (IOException ioex) {
                // Ignore IOException
                }
            }
        }
        session = null;
        mode = null;
        throw persistenceEx;
    }
}
Also used : ArrayList(java.util.ArrayList) MetadataAsmFactory(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAsmFactory) EntityManagerFactoryProvider.getConfigPropertyAsString(org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.getConfigPropertyAsString) MetadataLogger(org.eclipse.persistence.internal.jpa.metadata.MetadataLogger) JPAClassLoaderHolder(org.eclipse.persistence.internal.helper.JPAClassLoaderHolder) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) DynamicClassLoader(org.eclipse.persistence.dynamic.DynamicClassLoader) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) JPAConversionManager(org.eclipse.persistence.internal.helper.JPAConversionManager) RMIServerSessionManager(org.eclipse.persistence.sessions.remote.rmi.RMIServerSessionManager) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) IOException(java.io.IOException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) EclipseLinkException(org.eclipse.persistence.exceptions.EclipseLinkException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) OptimisticLockException(jakarta.persistence.OptimisticLockException) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) DescriptorException(org.eclipse.persistence.exceptions.DescriptorException) RemoteException(java.rmi.RemoteException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) EntityManagerSetupException(org.eclipse.persistence.exceptions.EntityManagerSetupException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConversionException(org.eclipse.persistence.exceptions.ConversionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PersistenceException(jakarta.persistence.PersistenceException) MalformedURLException(java.net.MalformedURLException) PersistenceUnitLoadingException(org.eclipse.persistence.exceptions.PersistenceUnitLoadingException) MetadataProject(org.eclipse.persistence.internal.jpa.metadata.MetadataProject) Project(org.eclipse.persistence.sessions.Project) DatabaseLogin(org.eclipse.persistence.sessions.DatabaseLogin) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) PersistenceException(jakarta.persistence.PersistenceException) XMLSessionConfigLoader(org.eclipse.persistence.sessions.factories.XMLSessionConfigLoader) PrivilegedNewInstanceFromClass(org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) PersistenceUnitTransactionType(jakarta.persistence.spi.PersistenceUnitTransactionType) Map(java.util.Map) ConcurrentMap(java.util.concurrent.ConcurrentMap) IdentityMap(org.eclipse.persistence.internal.identitymaps.IdentityMap) HashMap(java.util.HashMap) MetadataProcessor(org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor) Writer(java.io.Writer) FileWriter(java.io.FileWriter) Session(org.eclipse.persistence.sessions.Session) RemoteSession(org.eclipse.persistence.sessions.remote.RemoteSession) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 4 with SessionManager

use of org.eclipse.persistence.sessions.factories.SessionManager in project eclipselink by eclipse-ee4j.

the class EntityManagerSetupImpl method addSessionToGlobalSessionManager.

/**
 * Put the given session into the session manager so it can be looked up later
 */
protected void addSessionToGlobalSessionManager() {
    SessionManager sm = SessionManager.getManager();
    ConcurrentMap<String, Session> sessions = sm.getSessions();
    AbstractSession oldSession = (AbstractSession) sessions.get(session.getName());
    if (oldSession != null) {
        throw new PersistenceException(EntityManagerSetupException.attemptedRedeployWithoutClose(session.getName()));
    }
    sm.addSession(session);
}
Also used : RMIServerSessionManager(org.eclipse.persistence.sessions.remote.rmi.RMIServerSessionManager) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerFactoryProvider.getConfigPropertyAsString(org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.getConfigPropertyAsString) Session(org.eclipse.persistence.sessions.Session) RemoteSession(org.eclipse.persistence.sessions.remote.RemoteSession) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 5 with SessionManager

use of org.eclipse.persistence.sessions.factories.SessionManager in project eclipselink by eclipse-ee4j.

the class SessionManagerTest method testInvalidPlatform.

@Test
public void testInvalidPlatform() {
    // platform class name can be invalid/not found
    reinitManager(true, false);
    SessionManager sm = SessionManager.getManager();
    LogWrapper logger = (LogWrapper) getField(SessionManager.class, "LOG", null);
    Assert.assertEquals(SessionLog.WARNING, logger.getLastLevel());
    Assert.assertEquals(SessionLog.CONNECTION, logger.getLastCategory());
    Throwable t = logger.getLastThrowable();
    Assert.assertTrue("invalid excpetion type: " + t, t instanceof ServerPlatformException);
    Assert.assertTrue("invalid excpetion type: " + t.getCause(), t.getCause() instanceof ClassNotFoundException);
}
Also used : ServerPlatformException(org.eclipse.persistence.exceptions.ServerPlatformException) SessionManager(org.eclipse.persistence.sessions.factories.SessionManager) Test(org.junit.Test)

Aggregations

SessionManager (org.eclipse.persistence.sessions.factories.SessionManager)13 HashMap (java.util.HashMap)6 Map (java.util.Map)4 Session (org.eclipse.persistence.sessions.Session)4 ServerSession (org.eclipse.persistence.sessions.server.ServerSession)4 EntityManagerSetupImpl (org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl)3 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)3 RMIServerSessionManager (org.eclipse.persistence.sessions.remote.rmi.RMIServerSessionManager)3 Test (org.junit.Test)3 PersistenceException (jakarta.persistence.PersistenceException)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 DynamicClassLoader (org.eclipse.persistence.dynamic.DynamicClassLoader)2 PersistenceUnitLoadingException (org.eclipse.persistence.exceptions.PersistenceUnitLoadingException)2 ServerPlatformException (org.eclipse.persistence.exceptions.ServerPlatformException)2 EntityManagerFactoryProvider.getConfigPropertyAsString (org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.getConfigPropertyAsString)2 XMLSessionConfigLoader (org.eclipse.persistence.sessions.factories.XMLSessionConfigLoader)2 RemoteSession (org.eclipse.persistence.sessions.remote.RemoteSession)2 OptimisticLockException (jakarta.persistence.OptimisticLockException)1 PersistenceUnitTransactionType (jakarta.persistence.spi.PersistenceUnitTransactionType)1 FileWriter (java.io.FileWriter)1