Search in sources :

Example 1 with Project

use of org.eclipse.persistence.sessions.Project 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 > 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 2 with Project

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

the class CanonicalModelProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (!roundEnv.processingOver() && !roundEnv.errorRaised()) {
        MetadataMirrorFactory factory = null;
        try {
            if (useStaticFactory) {
                if (staticFactory == null) {
                    // We must remember some state from one round to another.
                    // In some rounds, the user may only change one class
                    // meaning we only have one root element from the round.
                    // If it is a child class to an existing already generated
                    // parent class we need to know about this class, so the
                    // factory will also hang onto static projects for each
                    // persistence unit. Doing this is going to need careful
                    // cleanup thoughts though. Adding classes ok, but what
                    // about removing some?
                    AbstractSession session = new ServerSession(new Project(new DatabaseLogin()));
                    session.setSessionLog(log);
                    final MetadataLogger logger = new MetadataLogger(session);
                    staticFactory = new MetadataMirrorFactory(logger, Thread.currentThread().getContextClassLoader());
                    log(SessionLog.INFO, "Creating static metadata factory ...");
                }
                factory = staticFactory;
            } else {
                if (nonStaticFactory == null) {
                    AbstractSession session = new ServerSession(new Project(new DatabaseLogin()));
                    session.setSessionLog(log);
                    final MetadataLogger logger = new MetadataLogger(session);
                    nonStaticFactory = new MetadataMirrorFactory(logger, Thread.currentThread().getContextClassLoader());
                    log(SessionLog.INFO, "Creating non-static metadata factory ...");
                }
                factory = nonStaticFactory;
            }
            final MetadataLogger logger = factory.getLogger();
            // Step 1 - The factory is passed around so those who want the
            // processing or round env can get it off the factory. This
            // saves us from having to pass around multiple objects.
            factory.setEnvironments(processingEnv, roundEnv);
            // Step 2 - read the persistence xml classes (gives us extra
            // classes and mapping files. From them we get transients and
            // access). Metadata read from XML causes new accessors to be
            // created and override existing ones (causing them to be un-
            // pre-processed. We can never tell what changes in XML so we
            // have to do this.
            final PersistenceUnitReader puReader = new PersistenceUnitReader(logger, processingEnv);
            puReader.initPersistenceUnits(factory);
            // their canonical model classes.
            for (PersistenceUnit persistenceUnit : factory.getPersistenceUnits()) {
                // being compiled.
                for (Element element : roundEnv.getElementsAnnotatedWith(Entity.class)) {
                    persistenceUnit.addEntityAccessor(element);
                }
                // being compiled.
                for (Element element : roundEnv.getElementsAnnotatedWith(Embeddable.class)) {
                    persistenceUnit.addEmbeddableAccessor(element);
                }
                // that are being compiled.
                for (Element element : roundEnv.getElementsAnnotatedWith(MappedSuperclass.class)) {
                    persistenceUnit.addMappedSuperclassAccessor(element);
                }
                // Step 3d - tell the persistence unit to pre-process itself.
                persistenceUnit.preProcessForCanonicalModel();
                // Step 3e - We're set, generate the canonical model classes.
                generateCanonicalModelClasses(factory, persistenceUnit);
            }
        } catch (Exception e) {
            log.logThrowable(SessionLog.SEVERE, SessionLog.PROCESSOR, e);
            throw new RuntimeException(e);
        }
    }
    // Don't claim any annotations
    return false;
}
Also used : MetadataProject(org.eclipse.persistence.internal.jpa.metadata.MetadataProject) Project(org.eclipse.persistence.sessions.Project) DatabaseLogin(org.eclipse.persistence.sessions.DatabaseLogin) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) MetadataLogger(org.eclipse.persistence.internal.jpa.metadata.MetadataLogger) PersistenceUnit(org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceUnit) TypeElement(javax.lang.model.element.TypeElement) MetadataAnnotatedElement(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotatedElement) Element(javax.lang.model.element.Element) PersistenceUnitReader(org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceUnitReader) IOException(java.io.IOException) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 3 with Project

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

the class MetadataMirrorFactory method getMetadataProject.

/**
 * INTERNAL:
 * We preserve state from each processor run by holding static references
 * to projects.
 */
public MetadataProject getMetadataProject(SEPersistenceUnitInfo puInfo) {
    if (!metadataProjects.containsKey(puInfo.getPersistenceUnitName())) {
        AbstractSession session = new ServerSession(new Project(new DatabaseLogin()));
        session.setSessionLog(getLogger().getSession().getSessionLog());
        MetadataProject project = new MetadataProject(puInfo, session, false, false, false, false, false);
        metadataProjects.put(puInfo.getPersistenceUnitName(), project);
        return project;
    } else {
        return metadataProjects.get(puInfo.getPersistenceUnitName());
    }
}
Also used : MetadataProject(org.eclipse.persistence.internal.jpa.metadata.MetadataProject) Project(org.eclipse.persistence.sessions.Project) DatabaseLogin(org.eclipse.persistence.sessions.DatabaseLogin) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) MetadataProject(org.eclipse.persistence.internal.jpa.metadata.MetadataProject) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 4 with Project

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

the class PersistenceXMLMappings method createXMLContext.

/**
 * INTERNAL:
 */
protected static XMLContext createXMLContext(String namespaceURI) {
    Project project = new Project();
    NamespaceResolver resolver = new NamespaceResolver();
    resolver.setDefaultNamespaceURI(namespaceURI);
    project.addDescriptor(buildPersistenceXMLDescriptor(resolver));
    project.addDescriptor(buildPUInfoDescriptor(resolver));
    project.addDescriptor(buildPUPropertyDescriptor(resolver));
    return new XMLContext(project);
}
Also used : Project(org.eclipse.persistence.sessions.Project) XMLContext(org.eclipse.persistence.oxm.XMLContext) NamespaceResolver(org.eclipse.persistence.oxm.NamespaceResolver)

Example 5 with Project

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

the class PreLoginMappingAdapter method preLogin.

/* (non-Javadoc)
     * @see org.eclipse.persistence.internal.jaxb.SessionEventListener#preLogin(org.eclipse.persistence.sessions.SessionEvent)
     */
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void preLogin(SessionEvent event) {
    Project project = event.getSession().getProject();
    ClassLoader cl = jpaSession.getDatasourcePlatform().getConversionManager().getLoader();
    DefaultXMLNameTransformer xmlNameTransformer = new DefaultXMLNameTransformer();
    for (Object descriptorAlias : project.getAliasDescriptors().keySet()) {
        ClassDescriptor descriptor = project.getAliasDescriptors().get(descriptorAlias);
        if (!PersistenceWeavedRest.class.isAssignableFrom(descriptor.getJavaClass())) {
            continue;
        }
        if (descriptor.isXMLDescriptor()) {
            XMLDescriptor xmlDescriptor = (XMLDescriptor) project.getAliasDescriptors().get(descriptorAlias);
            if (null != xmlDescriptor) {
                if (null == xmlDescriptor.getDefaultRootElement()) {
                    // set root element
                    xmlDescriptor.setDefaultRootElement(xmlNameTransformer.transformRootElementName(xmlDescriptor.getJavaClass().getName()));
                    // set resultAlwaysXMLRoot to false, so that the elements are not wrapped in JAXBElements when unmarshalling.
                    xmlDescriptor.setResultAlwaysXMLRoot(false);
                }
            }
        }
        XMLCompositeCollectionMapping relationshipMapping = new XMLCompositeCollectionMapping();
        relationshipMapping.setAttributeName("_persistence_relationshipInfo");
        relationshipMapping.setGetMethodName("_persistence_getRelationships");
        relationshipMapping.setSetMethodName("_persistence_setRelationships");
        relationshipMapping.setDescriptor(descriptor);
        CollectionContainerPolicy containerPolicy = new CollectionContainerPolicy(ArrayList.class);
        relationshipMapping.setContainerPolicy(containerPolicy);
        relationshipMapping.setField(new XMLField("_relationships"));
        relationshipMapping.setReferenceClass(Link.class);
        XMLJavaTypeConverter converter = new XMLJavaTypeConverter(RelationshipLinkAdapter.class);
        converter.initialize(relationshipMapping, event.getSession());
        relationshipMapping.setConverter(converter);
        descriptor.addMapping(relationshipMapping);
        XMLCompositeObjectMapping hrefMapping = new XMLCompositeObjectMapping();
        hrefMapping.setAttributeName("_persistence_href");
        hrefMapping.setGetMethodName("_persistence_getHref");
        hrefMapping.setSetMethodName("_persistence_setHref");
        hrefMapping.setDescriptor(descriptor);
        hrefMapping.setField(new XMLField("_link"));
        hrefMapping.setReferenceClass(Link.class);
        hrefMapping.setXPath(".");
        descriptor.addMapping(hrefMapping);
        XMLCompositeObjectMapping itemLinksMapping = new XMLCompositeObjectMapping();
        itemLinksMapping.setAttributeName("_persistence_links");
        itemLinksMapping.setGetMethodName("_persistence_getLinks");
        itemLinksMapping.setSetMethodName("_persistence_setLinks");
        itemLinksMapping.setDescriptor(descriptor);
        itemLinksMapping.setReferenceClass(ItemLinks.class);
        itemLinksMapping.setXPath(".");
        descriptor.addMapping(itemLinksMapping);
        ClassDescriptor jpaDescriptor = jpaSession.getDescriptorForAlias(descriptor.getAlias());
        Vector<DatabaseMapping> descriptorMappings = (Vector<DatabaseMapping>) descriptor.getMappings().clone();
        for (DatabaseMapping mapping : descriptorMappings) {
            if (mapping.isXMLMapping()) {
                if (mapping.isAbstractCompositeObjectMapping() || mapping.isAbstractCompositeCollectionMapping()) {
                    if (mapping.isAbstractCompositeCollectionMapping()) {
                        XMLInverseReferenceMapping inverseMapping = ((XMLCompositeCollectionMapping) mapping).getInverseReferenceMapping();
                        if (inverseMapping != null) {
                            break;
                        }
                    } else if (mapping.isAbstractCompositeObjectMapping()) {
                        XMLInverseReferenceMapping inverseMapping = ((XMLCompositeObjectMapping) mapping).getInverseReferenceMapping();
                        if (inverseMapping != null) {
                            break;
                        }
                    }
                    if (jpaDescriptor != null) {
                        DatabaseMapping dbMapping = jpaDescriptor.getMappingForAttributeName(mapping.getAttributeName());
                        if ((dbMapping != null) && (dbMapping instanceof ForeignReferenceMapping)) {
                            ForeignReferenceMapping jpaMapping = (ForeignReferenceMapping) dbMapping;
                            if (jpaMapping.getMappedBy() != null) {
                                ClassDescriptor inverseDescriptor = project.getDescriptorForAlias(jpaMapping.getReferenceDescriptor().getAlias());
                                if (inverseDescriptor != null) {
                                    DatabaseMapping inverseMapping = inverseDescriptor.getMappingForAttributeName(jpaMapping.getMappedBy());
                                    if (inverseMapping != null) {
                                        convertMappingToXMLInverseReferenceMapping(inverseDescriptor, inverseMapping, jpaMapping);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        InheritancePolicy inheritancePolicy = descriptor.getInheritancePolicyOrNull();
        if ((inheritancePolicy != null) && (inheritancePolicy.isRootParentDescriptor())) {
            boolean isAbstract = Modifier.isAbstract(descriptor.getJavaClass().getModifiers());
            if (isAbstract) {
                Class subClassToInstantiate = null;
                Map<?, ?> classIndicatorMapping = inheritancePolicy.getClassIndicatorMapping();
                // get one of subclasses that extends this abstract class
                for (Map.Entry<?, ?> entry : classIndicatorMapping.entrySet()) {
                    Object value = entry.getValue();
                    if (value instanceof Class) {
                        subClassToInstantiate = (Class) value;
                        isAbstract = Modifier.isAbstract(subClassToInstantiate.getModifiers());
                        if (!isAbstract) {
                            InstantiationPolicy instantiationPolicy = new InstantiationPolicy();
                            instantiationPolicy.useFactoryInstantiationPolicy(new ConcreteSubclassFactory(subClassToInstantiate), "createConcreteSubclass");
                            descriptor.setInstantiationPolicy(instantiationPolicy);
                            break;
                        }
                    }
                }
            }
        }
    }
    for (Object descriptorAlias : project.getAliasDescriptors().keySet()) {
        ClassDescriptor descriptor = project.getAliasDescriptors().get(descriptorAlias);
        ClassDescriptor jpaDescriptor = jpaSession.getDescriptorForAlias(descriptor.getAlias());
        Vector<DatabaseMapping> descriptorMappings = (Vector<DatabaseMapping>) descriptor.getMappings().clone();
        for (DatabaseMapping mapping : descriptorMappings) {
            if (mapping.isXMLMapping()) {
                if (mapping.isAbstractCompositeObjectMapping() || mapping.isAbstractCompositeCollectionMapping()) {
                    if (jpaDescriptor != null) {
                        DatabaseMapping dbMapping = jpaDescriptor.getMappingForAttributeName(mapping.getAttributeName());
                        if ((dbMapping instanceof ForeignReferenceMapping)) {
                            ForeignReferenceMapping jpaMapping = (ForeignReferenceMapping) dbMapping;
                            ClassDescriptor jaxbDescriptor = project.getDescriptorForAlias(jpaMapping.getDescriptor().getAlias());
                            convertMappingToXMLChoiceMapping(jaxbDescriptor, jpaMapping, cl, jpaSession);
                        }
                    } else if (mapping instanceof XMLCompositeObjectMapping) {
                        // Fix for Bug 403113 - JPA-RS Isn't Serializing an Embeddable defined in an ElementCollection to JSON Correctly
                        // add choice mapping for one-to-one relationships within embeddables
                        // Based on (http://wiki.eclipse.org/EclipseLink/Examples/JPA/NoSQL#Step_2_:_Map_the_data),
                        // the mappedBy option on relationships is not supported for NoSQL data, so no need to add inverse mapping
                        XMLCompositeObjectMapping jpaMapping = (XMLCompositeObjectMapping) mapping;
                        ClassDescriptor jaxbDescriptor = project.getDescriptorForAlias(jpaMapping.getDescriptor().getAlias());
                        if (jaxbDescriptor != null) {
                            Class clazz = jpaMapping.getReferenceClass();
                            if (clazz != null) {
                                if ((jpaSession.getDescriptor(clazz) != null) && (jpaSession.getDescriptor(clazz).isEISDescriptor()))
                                    convertMappingToXMLChoiceMapping(jaxbDescriptor, jpaMapping, cl, jpaSession);
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : CollectionContainerPolicy(org.eclipse.persistence.internal.queries.CollectionContainerPolicy) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) InstantiationPolicy(org.eclipse.persistence.internal.descriptors.InstantiationPolicy) XMLDescriptor(org.eclipse.persistence.oxm.XMLDescriptor) ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) XMLCompositeCollectionMapping(org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping) XMLInverseReferenceMapping(org.eclipse.persistence.oxm.mappings.XMLInverseReferenceMapping) Vector(java.util.Vector) XMLJavaTypeConverter(org.eclipse.persistence.internal.jaxb.XMLJavaTypeConverter) XMLField(org.eclipse.persistence.oxm.XMLField) PersistenceWeavedRest(org.eclipse.persistence.internal.jpa.rs.weaving.PersistenceWeavedRest) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Project(org.eclipse.persistence.sessions.Project) InheritancePolicy(org.eclipse.persistence.descriptors.InheritancePolicy) DefaultXMLNameTransformer(org.eclipse.persistence.jaxb.DefaultXMLNameTransformer) Map(java.util.Map) XMLCompositeObjectMapping(org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping)

Aggregations

Project (org.eclipse.persistence.sessions.Project)216 StringReader (java.io.StringReader)92 ObjectPersistenceWorkbenchXMLProject (org.eclipse.persistence.internal.sessions.factories.ObjectPersistenceWorkbenchXMLProject)83 Test (org.junit.Test)83 XMLContext (org.eclipse.persistence.oxm.XMLContext)80 NonJDBCTestHelper.buildTestProject (org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildTestProject)60 NonJDBCTestHelper.buildWorkbenchXMLProject (org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildWorkbenchXMLProject)60 Document (org.w3c.dom.Document)53 XMLMarshaller (org.eclipse.persistence.oxm.XMLMarshaller)49 PLSQLStoredProcedureCall (org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall)37 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)30 DatabaseLogin (org.eclipse.persistence.sessions.DatabaseLogin)28 XMLDescriptor (org.eclipse.persistence.oxm.XMLDescriptor)27 XMLLogin (org.eclipse.persistence.oxm.XMLLogin)25 SchemaModelProject (org.eclipse.persistence.internal.oxm.schema.SchemaModelProject)24 DatabaseSession (org.eclipse.persistence.sessions.DatabaseSession)23 DataModifyQuery (org.eclipse.persistence.queries.DataModifyQuery)22 Schema (org.eclipse.persistence.internal.oxm.schema.model.Schema)17 Descriptor (org.eclipse.persistence.internal.oxm.mappings.Descriptor)16 XMLUnmarshaller (org.eclipse.persistence.oxm.XMLUnmarshaller)16