diff options
author | Eike Stepper | 2012-04-20 06:44:31 +0000 |
---|---|---|
committer | Eike Stepper | 2012-04-20 06:44:31 +0000 |
commit | 47d969e972089caf5e58fef905a63180db2ce51d (patch) | |
tree | 764a886817a9c20e8b5de129df5591e751685454 | |
parent | 8bcfb2190e11eb139e8453a3b484294cfe57d66e (diff) | |
download | cdo-47d969e972089caf5e58fef905a63180db2ce51d.tar.gz cdo-47d969e972089caf5e58fef905a63180db2ce51d.tar.xz cdo-47d969e972089caf5e58fef905a63180db2ce51d.zip |
[339492] [Hibernate] Support backup/restore (export/import) feature
https://bugs.eclipse.org/bugs/show_bug.cgi?id=339492
5 files changed, 2519 insertions, 2491 deletions
diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/hibernate/IHibernateStoreAccessor.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/hibernate/IHibernateStoreAccessor.java index eb2c477a01..6a8de001b5 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/hibernate/IHibernateStoreAccessor.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/hibernate/IHibernateStoreAccessor.java @@ -1,35 +1,35 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.emf.cdo.server.hibernate;
-
-import org.eclipse.emf.cdo.server.IStoreAccessor;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.Session;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface IHibernateStoreAccessor extends IStoreAccessor
-{
- public IHibernateStore getStore();
-
- /**
- * @since 2.0
- */
- public IHibernateStoreChunkReader createChunkReader(InternalCDORevision revision, EStructuralFeature feature);
-
- public Session getHibernateSession();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.emf.cdo.server.hibernate; + +import org.eclipse.emf.cdo.server.IStoreAccessor; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.Session; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface IHibernateStoreAccessor extends IStoreAccessor.Raw +{ + public IHibernateStore getStore(); + + /** + * @since 2.0 + */ + public IHibernateStoreChunkReader createChunkReader(InternalCDORevision revision, EStructuralFeature feature); + + public Session getHibernateSession(); +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStoreAccessor.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStoreAccessor.java index 7fdf5a3142..1b5b532020 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStoreAccessor.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStoreAccessor.java @@ -1,1068 +1,1120 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- * Martin Taal - specific hibernate functionality
- */
-package org.eclipse.emf.cdo.server.internal.hibernate;
-
-import org.eclipse.emf.cdo.common.branch.CDOBranch;
-import org.eclipse.emf.cdo.common.branch.CDOBranchHandler;
-import org.eclipse.emf.cdo.common.branch.CDOBranchPoint;
-import org.eclipse.emf.cdo.common.branch.CDOBranchVersion;
-import org.eclipse.emf.cdo.common.commit.CDOCommitInfoHandler;
-import org.eclipse.emf.cdo.common.id.CDOID;
-import org.eclipse.emf.cdo.common.id.CDOIDTemp;
-import org.eclipse.emf.cdo.common.id.CDOIDUtil;
-import org.eclipse.emf.cdo.common.lob.CDOLobHandler;
-import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
-import org.eclipse.emf.cdo.common.revision.CDORevision;
-import org.eclipse.emf.cdo.common.revision.CDORevisionCacheAdder;
-import org.eclipse.emf.cdo.common.revision.CDORevisionData;
-import org.eclipse.emf.cdo.common.revision.CDORevisionHandler;
-import org.eclipse.emf.cdo.common.util.CDOQueryInfo;
-import org.eclipse.emf.cdo.eresource.EresourcePackage;
-import org.eclipse.emf.cdo.server.IQueryHandler;
-import org.eclipse.emf.cdo.server.ISession;
-import org.eclipse.emf.cdo.server.ITransaction;
-import org.eclipse.emf.cdo.server.hibernate.IHibernateStore;
-import org.eclipse.emf.cdo.server.hibernate.IHibernateStoreAccessor;
-import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.PersistableListHolder;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.WrappedHibernateList;
-import org.eclipse.emf.cdo.spi.common.commit.CDOChangeSetSegment;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit;
-import org.eclipse.emf.cdo.spi.common.revision.DetachedCDORevision;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevisionDelta;
-import org.eclipse.emf.cdo.spi.server.InternalCommitContext;
-import org.eclipse.emf.cdo.spi.server.Store;
-import org.eclipse.emf.cdo.spi.server.StoreAccessor;
-import org.eclipse.emf.cdo.spi.server.StoreChunkReader;
-
-import org.eclipse.net4j.util.HexUtil;
-import org.eclipse.net4j.util.ObjectUtil;
-import org.eclipse.net4j.util.StringUtil;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.collection.Pair;
-import org.eclipse.net4j.util.io.ExtendedDataInputStream;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.om.monitor.OMMonitor;
-import org.eclipse.net4j.util.om.monitor.OMMonitor.Async;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.Criteria;
-import org.hibernate.FlushMode;
-import org.hibernate.Hibernate;
-import org.hibernate.Query;
-import org.hibernate.ScrollMode;
-import org.hibernate.ScrollableResults;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Implements the runtime behavior of accessing the hibernate store using queries and doing write and commit. The
- * HibernateStoreAccessor corresponds roughly to a Hibernate session. It offers methods to create and close them and
- * implements transaction handling. The main update/create/delete operations are done in the
- * {@link #write(InternalCommitContext, OMMonitor)} method.
- *
- * @see HibernateStore
- * @see HibernatePackageHandler
- * @author Eike Stepper
- * @author Martin Taal
- */
-public class HibernateStoreAccessor extends StoreAccessor implements IHibernateStoreAccessor
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernateStoreAccessor.class);
-
- private static final String NAME_EFEATURE_NAME = "name";//$NON-NLS-1$
-
- private Session hibernateSession;
-
- private boolean errorOccured;
-
- public void addToRevisionCache(Object object)
- {
- if (object instanceof CDORevision)
- {
- getStore().getRepository().getRevisionManager().addRevision((CDORevision)object);
- }
- else if (object instanceof Object[])
- {
- // handle hibernate query result
- final Object[] objects = (Object[])object;
- for (Object o : objects)
- {
- addToRevisionCache(o);
- }
- }
-
- // also primitive types can get here, ignore those
- }
-
- /**
- * Constructor
- *
- * @param store
- * the {@link Store} used by the accessor.
- * @param session
- * the client session (not a Hibernate Session)
- */
- public HibernateStoreAccessor(HibernateStore store, ISession session)
- {
- super(store, session);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Created " + this.getClass().getName() + " for repository " + store.getRepository().getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- /**
- * Constructor for a specific transaction
- *
- * @param store
- * the HibernateStore backing this accessor
- * @param transaction
- * the client transaction (not the a Hibernate transaction)
- */
- public HibernateStoreAccessor(HibernateStore store, ITransaction transaction)
- {
- super(store, transaction);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Created " + this.getClass().getName() + " for repository " + store.getRepository().getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- /** Clears the current hibernate session and sets a new one in the thread context */
- public void resetHibernateSession()
- {
- endHibernateSession();
- beginHibernateSession();
- }
-
- /**
- * @return the backing store
- */
- @Override
- public HibernateStore getStore()
- {
- return (HibernateStore)super.getStore();
- }
-
- /**
- * Starts a hibernate session and begins a transaction.
- *
- * @since 2.0
- */
- public void beginHibernateSession()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Creating hibernate session and transaction"); //$NON-NLS-1$
- }
-
- assert hibernateSession == null;
- final SessionFactory sessionFactory = getStore().getHibernateSessionFactory();
- hibernateSession = sessionFactory.openSession();
- hibernateSession.beginTransaction();
- }
-
- /**
- * Calls {@link #endHibernateSession()}, commits the transaction and closes the session.
- *
- * @since 2.0
- */
- public void commitRollbackHibernateSession()
- {
- endHibernateSession();
- }
-
- /**
- * Commits/rollbacks and closes the session
- *
- * @since 2.0
- */
- public void endHibernateSession()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Closing hibernate session"); //$NON-NLS-1$
- }
-
- if (hibernateSession != null && hibernateSession.isOpen())
- {
- try
- {
- if (hibernateSession.getTransaction().isActive())
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Commiting hibernate session"); //$NON-NLS-1$
- }
-
- if (isErrorOccured())
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Rolling back hb transaction"); //$NON-NLS-1$
- }
-
- hibernateSession.getTransaction().rollback();
- }
- else
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Committing hb transaction"); //$NON-NLS-1$
- }
-
- hibernateSession.getTransaction().commit();
- }
- }
- }
- finally
- {
- hibernateSession.close();
- }
- }
-
- hibernateSession = null;
- }
-
- /**
- * @return the current hibernate session. If there is none then a new one is created and a transaction is started
- */
- public Session getHibernateSession()
- {
- if (hibernateSession == null)
- {
- beginHibernateSession();
- }
-
- return hibernateSession;
- }
-
- /**
- * Closes/commits the current hibernate session if there is one, and starts a new one and begins a transaction.
- *
- * @return a newly created Hibernate Session
- */
- public Session getNewHibernateSession()
- {
- if (hibernateSession != null)
- {
- endHibernateSession();
- }
-
- if (hibernateSession != null)
- {
- throw new IllegalStateException("Hibernate session should be null"); //$NON-NLS-1$
- }
-
- beginHibernateSession();
- return hibernateSession;
- }
-
- /**
- * @return true if an error occured during database actions. Normally means that the transaction will be rolled back
- * and not committed.
- * @since 2.0
- */
- public boolean isErrorOccured()
- {
- return errorOccured;
- }
-
- /**
- * @since 2.0
- */
- public void setErrorOccured(boolean errorOccured)
- {
- this.errorOccured = errorOccured;
- }
-
- /**
- * Note: the Hibernate store does not support the {@link StoreChunkReader} concept!.
- *
- * @return a {@link HibernateStoreChunkReader} (which throws UnsupportedOperationExceptions for most methods
- */
- public HibernateStoreChunkReader createChunkReader(InternalCDORevision revision, EStructuralFeature feature)
- {
- return new HibernateStoreChunkReader(this, revision, feature);
- }
-
- /**
- * @return the current collection of package units.
- * @see HibernateStore
- * @see HibernatePackageHandler
- */
- public Collection<InternalCDOPackageUnit> readPackageUnits()
- {
- return getStore().getPackageHandler().getPackageUnits();
- }
-
- /**
- * Loads the package units from the database and returns the EPackage instances.
- *
- * @return the loaded EPackage instances.
- * @see HibernatePackageHandler
- */
- public EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit)
- {
- return getStore().getPackageHandler().loadPackageUnit(packageUnit);
- }
-
- /**
- * Reads the revision from the database. using the passed id.
- *
- * @param id
- * identifies the CDORevision to read
- * @param branchPoint
- * ignored until auditing is supported.
- * @param listChunk
- * not used by Hibernate
- * @param cache
- * the revision cache, the read revision is added to the cache
- * @return the read revision
- */
- public InternalCDORevision readRevision(CDOID id, CDOBranchPoint branchPoint, int listChunk,
- CDORevisionCacheAdder cache)
- {
- if (!HibernateUtil.getInstance().isStoreCreatedID(id))
- {
- return null;
- }
-
- final InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(id);
- if (revision == null)
- {
- final CDOClassifierRef classifierRef = CDOIDUtil.getClassifierRef(id);
- if (classifierRef == null)
- {
- throw new IllegalArgumentException("This CDOID type of " + id + " is not supported by this store."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final EClass eClass = HibernateUtil.getInstance().getEClass(classifierRef);
- return new DetachedCDORevision(eClass, id, branchPoint.getBranch(), 0, 0);
- }
-
- revision.setBranchPoint(getStore().getMainBranchHead());
- return revision;
- }
-
- public Pair<Integer, Long> createBranch(int branchID, BranchInfo branchInfo)
- {
- // TODO: implement HibernateStoreAccessor.createBranch(branchID, branchInfo)
- throw new UnsupportedOperationException();
- }
-
- public BranchInfo loadBranch(int branchID)
- {
- // TODO: implement HibernateStoreAccessor.loadBranch(branchID)
- throw new UnsupportedOperationException();
- }
-
- public SubBranchInfo[] loadSubBranches(int branchID)
- {
- // TODO: implement HibernateStoreAccessor.loadSubBranches(branchID)
- throw new UnsupportedOperationException();
- }
-
- public int loadBranches(int startID, int endID, CDOBranchHandler branchHandler)
- {
- // TODO: implement HibernateStoreAccessor.loadBranches(startID, endID, branchHandler)
- throw new UnsupportedOperationException();
- }
-
- public void loadCommitInfos(CDOBranch branch, long startTime, long endTime, CDOCommitInfoHandler handler)
- {
- // TODO: implement HibernateStoreAccessor.loadCommitInfos(branch, startTime, endTime, handler)
- // throw new UnsupportedOperationException();
- }
-
- public Set<CDOID> readChangeSet(OMMonitor monitor, CDOChangeSetSegment... segments)
- {
- // TODO: implement HibernateStoreAccessor.readChangeSet(segments)
- throw new UnsupportedOperationException();
- }
-
- public void handleRevisions(EClass eClass, CDOBranch branch, long timeStamp, boolean exactTime,
- CDORevisionHandler handler)
- {
- if (eClass != null)
- {
- handleRevisionsByEClass(eClass, handler);
- }
- else
- {
- for (EPackage ePackage : getStore().getPackageHandler().getEPackages())
- {
- for (EClassifier eClassifier : ePackage.getEClassifiers())
- {
- if (eClassifier instanceof EClass)
- {
- final EClass eClazz = (EClass)eClassifier;
- try
- {
- getStore().getEntityName(eClazz);
- }
- catch (IllegalArgumentException ex)
- {
- // a non-mapped eclass
- continue;
- }
- handleRevisionsByEClass(eClazz, handler);
- }
- }
- }
- }
- }
-
- private void handleRevisionsByEClass(EClass eClass, CDORevisionHandler handler)
- {
- // get a transaction, the hibernateStoreAccessor is placed in a threadlocal
- // so all db access uses the same session.
- final Session session = getHibernateSession();
-
- // create the query
- final Query query = session.createQuery("select e from " + getStore().getEntityName(eClass) + " e");
- for (Object o : query.list())
- {
- handler.handleRevision((CDORevision)o);
- }
- session.clear();
- }
-
- /**
- * Not supported by the Hibernate Store, auditing is not supported. Currently ignores the branchVersion and calls the
- * {@readRevision(CDOID, CDOBranchPoint, int, CDORevisionCacheAdder)} .
- */
- public InternalCDORevision readRevisionByVersion(CDOID id, CDOBranchVersion branchVersion, int listChunk,
- CDORevisionCacheAdder cache)
- {
- InternalCDORevision revision = readRevision(id, branchVersion.getBranch().getPoint(System.currentTimeMillis()),
- listChunk, cache);
- if (revision != null)
- {
- revision.freeze();
- }
-
- return revision;
- }
-
- /**
- * Queries for resources in a certain folder and returns them in the context object
- *
- * @param context
- * the context provides input parameters (the folder) and is used to store the results of the query.
- * @since 2.0
- */
- public void queryResources(QueryResourcesContext context)
- {
- final CDOID folderID = getHibernateID(context.getFolderID());
- String name = context.getName();
- boolean exactMatch = context.exactMatch();
-
- final Session session = getHibernateSession();
- final Criteria criteria = session.createCriteria(EresourcePackage.eINSTANCE.getCDOResourceNode().getName());
- if (folderID == null)
- {
- criteria.add(org.hibernate.criterion.Restrictions.isNull(CDOHibernateConstants.CONTAINER_PROPERTY));
- }
- else
- {
- criteria.add(org.hibernate.criterion.Restrictions.eq(CDOHibernateConstants.CONTAINER_PROPERTY, folderID));
- }
-
- List<?> result = criteria.list();
- for (Object o : result)
- {
- final CDORevision revision = (CDORevision)o;
- final EStructuralFeature feature = revision.getEClass().getEStructuralFeature(NAME_EFEATURE_NAME);
- if (feature != null)
- {
- Object value = revision.data().get(feature, 0);
- if (value == CDORevisionData.NIL)
- {
- value = null;
- }
-
- final String revisionName = (String)value;
- final boolean match = exactMatch || revisionName == null || name == null ? ObjectUtil
- .equals(revisionName, name) : revisionName.startsWith(name);
-
- if (match && !context.addResource(HibernateUtil.getInstance().getCDOID(revision)))
- {
- // No more results allowed
- break;
- }
- }
- }
- }
-
- public void queryXRefs(QueryXRefsContext context)
- {
- final Session session = getHibernateSession();
- for (CDOID targetCdoId : context.getTargetObjects().keySet())
- {
- final CDORevision revision = HibernateUtil.getInstance().getCDORevision(targetCdoId);
- final EClass targetEClass = context.getTargetObjects().get(targetCdoId);
- final String targetEntityName = getStore().getEntityName(targetEClass);
- final Map<EClass, List<EReference>> sourceCandidates = context.getSourceCandidates();
- for (EClass sourceEClass : sourceCandidates.keySet())
- {
- final String sourceEntityName = getStore().getEntityName(sourceEClass);
- for (EReference eref : sourceCandidates.get(sourceEClass))
- {
- final String hql;
- if (eref.isMany())
- {
- hql = "select ref from " + sourceEntityName + " as ref, " + targetEntityName
- + " as refTo where refTo = :to and refTo in elements(ref." + eref.getName() + ")";
- }
- else
- {
- hql = "select ref from " + sourceEntityName + " as ref where :to = ref." + eref.getName();
- }
-
- final Query qry = session.createQuery(hql);
- qry.setEntity("to", revision);
- ScrollableResults result = qry.scroll(ScrollMode.FORWARD_ONLY);
- while (result.next())
- {
- final InternalCDORevision sourceRevision = (InternalCDORevision)result.get()[0];
- int sourceIndex = 0;
- if (eref.isMany())
- {
- // note this takes performance for sure as the list is read,
- // consider not supporting sourceIndex, or doing it differently
- final WrappedHibernateList cdoList = (WrappedHibernateList)sourceRevision.getList(eref);
- sourceIndex = cdoList.getDelegate().indexOf(revision);
- }
-
- boolean more = context.addXRef(targetCdoId, sourceRevision.getID(), eref, sourceIndex);
- if (!more)
- {
- return;
- }
- }
- }
- }
- }
- }
-
- private CDOID getHibernateID(CDOID id)
- {
- if (!CDOIDUtil.isNull(id))
- {
- if (HibernateUtil.getInstance().isStoreCreatedID(id))
- {
- return id;
- }
-
- // TODO Can this happen? When?
- // the folder id is always a long
- final Long idValue = CDOIDUtil.getLong(id);
- return CDOIDUtil.createLongWithClassifier(new CDOClassifierRef(EresourcePackage.eINSTANCE.getCDOResourceNode()),
- idValue);
- }
-
- return null;
- }
-
- /**
- * @param info
- * the query information, is not used actively in this method.
- * @return a new instance of {@link HibernateQueryHandler}
- */
- public IQueryHandler getQueryHandler(CDOQueryInfo info)
- {
- String queryLanguage = info.getQueryLanguage();
- if (StringUtil.equalsUpperOrLowerCase(queryLanguage, IHibernateStore.QUERY_LANGUAGE))
- {
- final HibernateQueryHandler queryHandler = new HibernateQueryHandler();
- queryHandler.setHibernateStoreAccessor(this);
- return queryHandler;
- }
-
- return null;
- }
-
- /**
- * Commits the session, see {@link #commitRollbackHibernateSession()}.
- *
- * @param monitor
- * not used
- */
- @Override
- protected void doCommit(OMMonitor monitor)
- {
- commitRollbackHibernateSession();
- HibernateThreadContext.setCommitContext(null);
- }
-
- /**
- * Performs the main write and update actions. Persists new EPackages, updates changed objects, creates new ones and
- * removes deleted objects. Updates both container as well as resource associations.
- *
- * @param context
- * the context contains the changed, new and to-be-removed objects
- * @param monitor
- * not used by this method
- */
- @Override
- public void doWrite(InternalCommitContext context, OMMonitor monitor)
- {
- // NOTE: the same flow is also present in the super class (StoreAccessor)
- // changes in flow can mean that the flow here also has to change
-
- monitor.begin(3);
- HibernateThreadContext.setCommitContext(context);
- if (context.getNewPackageUnits().length > 0)
- {
- writePackageUnits(context.getNewPackageUnits(), monitor.fork());
- }
-
- // Note: instead of an Async here, we could do much more fine-grained monitoring below. But this
- // simplistic solution is sufficient to prevent timeout errors.
- final Async async = monitor.forkAsync();
- try
- {
- // start with fresh hibernate session to prevent side effects
- final Session session = getNewHibernateSession();
- session.setFlushMode(FlushMode.MANUAL);
-
- // order is 1) insert, 2) update and then delete
- // this order is the most stable! Do not change it without testing
-
- final List<InternalCDORevision> repairContainerIDs = new ArrayList<InternalCDORevision>();
- final List<InternalCDORevision> repairResourceIDs = new ArrayList<InternalCDORevision>();
- for (InternalCDORevision revision : context.getNewObjects())
- {
- // keep track for which cdoRevisions the container id needs to be repaired afterwards
- final CDOID containerID = (CDOID)revision.getContainerID();
- if (containerID instanceof CDOIDTemp && !containerID.isNull())
- {
- repairContainerIDs.add(revision);
- }
-
- final CDOID resourceID = revision.getResourceID();
- if (resourceID instanceof CDOIDTemp && !resourceID.isNull())
- {
- repairResourceIDs.add(revision);
- }
-
- final String entityName = getStore().getEntityName(revision.getEClass());
- session.saveOrUpdate(entityName, revision);
- }
-
- session.flush();
-
- for (CDORevision revision : context.getDirtyObjects())
- {
- final String entityName = HibernateUtil.getInstance().getEntityName(revision.getID());
- session.merge(entityName, revision);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Updated Object " + revision.getEClass().getName() + " id: " + revision.getID()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- session.flush();
-
- // delete all objects
- for (CDOID id : context.getDetachedObjects())
- {
- try
- {
- final CDORevision revision = HibernateUtil.getInstance().getCDORevision(id);
-
- // maybe deleted in parallell?
- if (revision != null)
- {
- session.delete(revision);
- }
- }
- catch (org.hibernate.ObjectNotFoundException ex)
- {
- // ignore these, an object can be removed through cascade deletes
- }
- }
-
- session.flush();
-
- // now do an update of the container without incrementing the version
- repairContainerIDs(repairContainerIDs, session);
- repairResourceIDs(repairResourceIDs, session);
-
- session.flush();
-
- // write the blobs
- ExtendedDataInputStream in = context.getLobs();
- if (in != null)
- {
- try
- {
- int count = in.readInt();
- for (int i = 0; i < count; i++)
- {
- byte[] id = in.readByteArray();
- long size = in.readLong();
- if (size > 0)
- {
- writeBlob(id, size, in);
- }
- else
- {
- writeClob(id, -size, new InputStreamReader(in));
- }
- }
- }
- catch (IOException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- session.flush();
-
- }
- catch (Exception e)
- {
- OM.LOG.error(e);
- throw WrappedException.wrap(e);
- }
- finally
- {
- async.stop();
- }
-
- context.applyIDMappings(monitor.fork());
- monitor.done();
- }
-
- private void repairContainerIDs(List<InternalCDORevision> repairContainerIDs, Session session)
- {
- for (InternalCDORevision revision : repairContainerIDs)
- {
- final CDORevision container = HibernateUtil.getInstance().getCDORevision((CDOID)revision.getContainerID());
- final String entityName = getStore().getEntityName(revision.getEClass());
- final CDOID id = revision.getID();
- final String hqlUpdate = "update " + entityName + " set " + CDOHibernateConstants.CONTAINER_PROPERTY //$NON-NLS-1$ //$NON-NLS-2$
- + " = :containerInfo where " + getStore().getIdentifierPropertyName(entityName) + " = :id"; //$NON-NLS-1$ //$NON-NLS-2$
- final Query qry = session.createQuery(hqlUpdate);
- qry.setParameter("containerInfo", ContainerInfoConverter.getInstance().convertContainerRelationToString(revision, //$NON-NLS-1$
- container.getID()));
- qry.setParameter("id", HibernateUtil.getInstance().getIdValue(id)); //$NON-NLS-1$
- if (qry.executeUpdate() != 1)
- {
- // OM.LOG.error("Not able to update container columns of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$
- throw new IllegalStateException("Not able to update container columns of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
-
- private void repairResourceIDs(List<InternalCDORevision> repairResourceIDs, Session session)
- {
- for (InternalCDORevision revision : repairResourceIDs)
- {
- final CDORevision resource = HibernateUtil.getInstance().getCDORevision(revision.getResourceID());
- final String entityName = getStore().getEntityName(revision.getEClass());
- final CDOID id = revision.getID();
- final String hqlUpdate = "update " + entityName + " set " + CDOHibernateConstants.RESOURCE_PROPERTY //$NON-NLS-1$ //$NON-NLS-2$
- + " = :resourceInfo where " + getStore().getIdentifierPropertyName(entityName) + " = :id"; //$NON-NLS-1$ //$NON-NLS-2$
- final Query qry = session.createQuery(hqlUpdate);
- qry.setParameter("resourceInfo", resource.getID()); //$NON-NLS-1$
- qry.setParameter("id", HibernateUtil.getInstance().getIdValue(id)); //$NON-NLS-1$
- if (qry.executeUpdate() != 1)
- {
- // OM.LOG.error("Not able to update resource ids of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$
- throw new IllegalStateException("Not able to update resource ids of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
-
- @Override
- protected void detachObjects(CDOID[] detachedObjects, CDOBranch branch, long timeStamp, OMMonitor monitor)
- {
- // handled by the write method
- }
-
- @Override
- protected void doRollback(CommitContext context)
- {
- setErrorOccured(true);
- endHibernateSession();
- HibernateThreadContext.setCommitContext(null);
- }
-
- /**
- * Writes package units to the datbaase.
- *
- * @param packageUnits
- * the package units to write to the database
- * @param monitor
- * not used by the store
- * @see HibernatePackageHandler
- */
- public void writePackageUnits(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor)
- {
- if (packageUnits != null && packageUnits.length != 0)
- {
- getStore().getPackageHandler().writePackageUnits(packageUnits);
- }
- }
-
- @Override
- protected void writeCommitInfo(CDOBranch branch, long timeStamp, long previousTimeStamp, String userID,
- String comment, OMMonitor monitor)
- {
- // Do nothing
- }
-
- @Override
- protected void writeRevisions(InternalCDORevision[] revisions, CDOBranch branch, OMMonitor monitor)
- {
- // Doesn't do anything. It is done in commit().
- }
-
- @Override
- public void addIDMappings(InternalCommitContext commitContext, OMMonitor monitor)
- {
- // Do nothing
- }
-
- @Override
- public CDOID getNextCDOID(CDORevision revision)
- {
- // Never called
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected void writeRevisionDeltas(InternalCDORevisionDelta[] revisionDeltas, CDOBranch branch, long created,
- OMMonitor monitor)
- {
- // TODO: implement HibernateStoreAccessor.writeRevisionDeltas(revisionDeltas, branch, created, monitor)
- throw new UnsupportedOperationException();
- }
-
- public void queryLobs(List<byte[]> ids)
- {
- for (Iterator<byte[]> it = ids.iterator(); it.hasNext();)
- {
- byte[] id = it.next();
- final HibernateStoreLob lob = getCreateHibernateStoreLob(id);
- if (lob.isNew())
- {
- it.remove();
- }
- }
- }
-
- public void handleLobs(long fromTime, long toTime, CDOLobHandler handler) throws IOException
- {
- final Session session = getHibernateSession();
- final Query qry = session.createQuery("select c from " + HibernateStoreLob.class.getName() + " as c");
-
- try
- {
- for (Object o : qry.list())
- {
- final HibernateStoreLob lob = (HibernateStoreLob)o;
- if (lob.getBlob() != null)
- {
- final OutputStream out = handler.handleBlob(HexUtil.hexToBytes(lob.getId()), lob.getSize());
- if (out != null)
- {
- final InputStream in = lob.getBlob().getBinaryStream();
- try
- {
- IOUtil.copyBinary(in, out, lob.getSize());
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- }
- else
- {
- final Clob clob = lob.getClob();
- Reader in = clob.getCharacterStream();
- Writer out = handler.handleClob(HexUtil.hexToBytes(lob.getId()), lob.getSize());
- if (out != null)
- {
- try
- {
- IOUtil.copyCharacter(in, out, lob.getSize());
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- }
- }
- }
- catch (SQLException ex)
- {
- throw new IllegalStateException(ex);
- }
- }
-
- public void loadLob(byte[] id, OutputStream out) throws IOException
- {
- final HibernateStoreLob lob = getCreateHibernateStoreLob(id);
- // can this ever occur?
- // TODO: how should non-existence be handled? Currently results in a timeout
- // on the client.
- if (lob.isNew())
- {
- throw new IllegalStateException("Lob with id " + HexUtil.bytesToHex(id) + " does not exist");
- }
-
- final long size = lob.getSize();
- try
- {
- if (lob.getBlob() != null)
- {
- InputStream in = lob.getBlob().getBinaryStream();
- IOUtil.copyBinary(in, out, size);
- }
- else
- {
- Clob clob = lob.getClob();
- Reader in = clob.getCharacterStream();
- IOUtil.copyCharacter(in, new OutputStreamWriter(out), size);
- }
- }
- catch (Exception e)
- {
- throw new IllegalStateException(e);
- }
- }
-
- @SuppressWarnings("deprecation")
- @Override
- protected void writeBlob(byte[] id, long size, InputStream inputStream) throws IOException
- {
- final HibernateStoreLob lob = getCreateHibernateStoreLob(id);
- if ((inputStream == null || size == 0) && !lob.isNew())
- {
- getHibernateSession().delete(lob);
- }
- else
- {
- // deprecated usage, non-deprecated api uses a session
- // TODO: research which session to use
- lob.setBlob(Hibernate.createBlob(inputStream, (int)size));
- lob.setSize((int)size);
- lob.setClob(null);
- getHibernateSession().saveOrUpdate(lob);
- }
- }
-
- @SuppressWarnings("deprecation")
- @Override
- protected void writeClob(byte[] id, long size, Reader reader) throws IOException
- {
- final HibernateStoreLob lob = getCreateHibernateStoreLob(id);
- if ((reader == null || size == 0) && !lob.isNew())
- {
- getHibernateSession().delete(lob);
- }
- else
- {
- // deprecated usage, non-deprecated api uses a session
- // TODO: research which session to use
- lob.setClob(Hibernate.createClob(reader, (int)size));
- lob.setSize((int)size);
- lob.setBlob(null);
- getHibernateSession().saveOrUpdate(lob);
- }
- }
-
- private HibernateStoreLob getCreateHibernateStoreLob(byte[] idBytes)
- {
- final String id = HexUtil.bytesToHex(idBytes);
- final Session session = getHibernateSession();
- HibernateStoreLob lob = (HibernateStoreLob)session.get(HibernateStoreLob.class, id);
- if (lob == null)
- {
- lob = new HibernateStoreLob();
- lob.setId(id);
- }
-
- return lob;
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- // TODO This method is called when this accessor is not needed anymore
- if (TRACER.isEnabled())
- {
- TRACER.trace("Committing/rollback and closing hibernate session"); //$NON-NLS-1$
- }
-
- try
- {
- endHibernateSession();
- }
- finally
- {
- clearThreadState();
- }
- }
-
- @Override
- protected void doPassivate() throws Exception
- {
- clearThreadState();
- }
-
- private void clearThreadState()
- {
- PersistableListHolder.getInstance().clearListMapping();
- HibernateThreadContext.setCommitContext(null);
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- }
-
- @Override
- protected void doUnpassivate() throws Exception
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + * Martin Taal - specific hibernate functionality + */ +package org.eclipse.emf.cdo.server.internal.hibernate; + +import org.eclipse.emf.cdo.common.branch.CDOBranch; +import org.eclipse.emf.cdo.common.branch.CDOBranchHandler; +import org.eclipse.emf.cdo.common.branch.CDOBranchPoint; +import org.eclipse.emf.cdo.common.branch.CDOBranchVersion; +import org.eclipse.emf.cdo.common.commit.CDOCommitInfoHandler; +import org.eclipse.emf.cdo.common.id.CDOID; +import org.eclipse.emf.cdo.common.id.CDOIDTemp; +import org.eclipse.emf.cdo.common.id.CDOIDUtil; +import org.eclipse.emf.cdo.common.lob.CDOLobHandler; +import org.eclipse.emf.cdo.common.model.CDOClassifierRef; +import org.eclipse.emf.cdo.common.protocol.CDODataInput; +import org.eclipse.emf.cdo.common.protocol.CDODataOutput; +import org.eclipse.emf.cdo.common.revision.CDORevision; +import org.eclipse.emf.cdo.common.revision.CDORevisionCacheAdder; +import org.eclipse.emf.cdo.common.revision.CDORevisionData; +import org.eclipse.emf.cdo.common.revision.CDORevisionHandler; +import org.eclipse.emf.cdo.common.util.CDOQueryInfo; +import org.eclipse.emf.cdo.eresource.EresourcePackage; +import org.eclipse.emf.cdo.server.IQueryHandler; +import org.eclipse.emf.cdo.server.ISession; +import org.eclipse.emf.cdo.server.ITransaction; +import org.eclipse.emf.cdo.server.hibernate.IHibernateStore; +import org.eclipse.emf.cdo.server.hibernate.IHibernateStoreAccessor; +import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.PersistableListHolder; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.WrappedHibernateList; +import org.eclipse.emf.cdo.spi.common.commit.CDOChangeSetSegment; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; +import org.eclipse.emf.cdo.spi.common.revision.DetachedCDORevision; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevisionDelta; +import org.eclipse.emf.cdo.spi.server.InternalCommitContext; +import org.eclipse.emf.cdo.spi.server.Store; +import org.eclipse.emf.cdo.spi.server.StoreAccessor; +import org.eclipse.emf.cdo.spi.server.StoreChunkReader; + +import org.eclipse.net4j.util.HexUtil; +import org.eclipse.net4j.util.ObjectUtil; +import org.eclipse.net4j.util.StringUtil; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.collection.Pair; +import org.eclipse.net4j.util.io.ExtendedDataInputStream; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.om.monitor.OMMonitor; +import org.eclipse.net4j.util.om.monitor.OMMonitor.Async; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.Criteria; +import org.hibernate.FlushMode; +import org.hibernate.Hibernate; +import org.hibernate.Query; +import org.hibernate.ScrollMode; +import org.hibernate.ScrollableResults; +import org.hibernate.Session; +import org.hibernate.SessionFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.sql.Clob; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Implements the runtime behavior of accessing the hibernate store using queries and doing write and commit. The + * HibernateStoreAccessor corresponds roughly to a Hibernate session. It offers methods to create and close them and + * implements transaction handling. The main update/create/delete operations are done in the + * {@link #write(InternalCommitContext, OMMonitor)} method. + * + * @see HibernateStore + * @see HibernatePackageHandler + * @author Eike Stepper + * @author Martin Taal + */ +public class HibernateStoreAccessor extends StoreAccessor implements IHibernateStoreAccessor +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernateStoreAccessor.class); + + private static final String NAME_EFEATURE_NAME = "name";//$NON-NLS-1$ + + private Session hibernateSession; + + private boolean errorOccured; + + public void addToRevisionCache(Object object) + { + if (object instanceof CDORevision) + { + getStore().getRepository().getRevisionManager().addRevision((CDORevision)object); + } + else if (object instanceof Object[]) + { + // handle hibernate query result + final Object[] objects = (Object[])object; + for (Object o : objects) + { + addToRevisionCache(o); + } + } + + // also primitive types can get here, ignore those + } + + /** + * Constructor + * + * @param store + * the {@link Store} used by the accessor. + * @param session + * the client session (not a Hibernate Session) + */ + public HibernateStoreAccessor(HibernateStore store, ISession session) + { + super(store, session); + if (TRACER.isEnabled()) + { + TRACER.trace("Created " + this.getClass().getName() + " for repository " + store.getRepository().getName()); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Constructor for a specific transaction + * + * @param store + * the HibernateStore backing this accessor + * @param transaction + * the client transaction (not the a Hibernate transaction) + */ + public HibernateStoreAccessor(HibernateStore store, ITransaction transaction) + { + super(store, transaction); + if (TRACER.isEnabled()) + { + TRACER.trace("Created " + this.getClass().getName() + " for repository " + store.getRepository().getName()); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** Clears the current hibernate session and sets a new one in the thread context */ + public void resetHibernateSession() + { + endHibernateSession(); + beginHibernateSession(); + } + + /** + * @return the backing store + */ + @Override + public HibernateStore getStore() + { + return (HibernateStore)super.getStore(); + } + + /** + * Starts a hibernate session and begins a transaction. + * + * @since 2.0 + */ + public void beginHibernateSession() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Creating hibernate session and transaction"); //$NON-NLS-1$ + } + + assert hibernateSession == null; + final SessionFactory sessionFactory = getStore().getHibernateSessionFactory(); + hibernateSession = sessionFactory.openSession(); + hibernateSession.beginTransaction(); + } + + /** + * Calls {@link #endHibernateSession()}, commits the transaction and closes the session. + * + * @since 2.0 + */ + public void commitRollbackHibernateSession() + { + endHibernateSession(); + } + + /** + * Commits/rollbacks and closes the session + * + * @since 2.0 + */ + public void endHibernateSession() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Closing hibernate session"); //$NON-NLS-1$ + } + + if (hibernateSession != null && hibernateSession.isOpen()) + { + try + { + if (hibernateSession.getTransaction().isActive()) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Commiting hibernate session"); //$NON-NLS-1$ + } + + if (isErrorOccured()) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Rolling back hb transaction"); //$NON-NLS-1$ + } + + hibernateSession.getTransaction().rollback(); + } + else + { + if (TRACER.isEnabled()) + { + TRACER.trace("Committing hb transaction"); //$NON-NLS-1$ + } + + hibernateSession.getTransaction().commit(); + } + } + } + finally + { + hibernateSession.close(); + } + } + + hibernateSession = null; + } + + /** + * @return the current hibernate session. If there is none then a new one is created and a transaction is started + */ + public Session getHibernateSession() + { + if (hibernateSession == null) + { + beginHibernateSession(); + } + + return hibernateSession; + } + + /** + * Closes/commits the current hibernate session if there is one, and starts a new one and begins a transaction. + * + * @return a newly created Hibernate Session + */ + public Session getNewHibernateSession() + { + if (hibernateSession != null) + { + endHibernateSession(); + } + + if (hibernateSession != null) + { + throw new IllegalStateException("Hibernate session should be null"); //$NON-NLS-1$ + } + + beginHibernateSession(); + return hibernateSession; + } + + /** + * @return true if an error occured during database actions. Normally means that the transaction will be rolled back + * and not committed. + * @since 2.0 + */ + public boolean isErrorOccured() + { + return errorOccured; + } + + /** + * @since 2.0 + */ + public void setErrorOccured(boolean errorOccured) + { + this.errorOccured = errorOccured; + } + + /** + * Note: the Hibernate store does not support the {@link StoreChunkReader} concept!. + * + * @return a {@link HibernateStoreChunkReader} (which throws UnsupportedOperationExceptions for most methods + */ + public HibernateStoreChunkReader createChunkReader(InternalCDORevision revision, EStructuralFeature feature) + { + return new HibernateStoreChunkReader(this, revision, feature); + } + + /** + * @return the current collection of package units. + * @see HibernateStore + * @see HibernatePackageHandler + */ + public Collection<InternalCDOPackageUnit> readPackageUnits() + { + return getStore().getPackageHandler().getPackageUnits(); + } + + /** + * Loads the package units from the database and returns the EPackage instances. + * + * @return the loaded EPackage instances. + * @see HibernatePackageHandler + */ + public EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit) + { + return getStore().getPackageHandler().loadPackageUnit(packageUnit); + } + + /** + * Reads the revision from the database. using the passed id. + * + * @param id + * identifies the CDORevision to read + * @param branchPoint + * ignored until auditing is supported. + * @param listChunk + * not used by Hibernate + * @param cache + * the revision cache, the read revision is added to the cache + * @return the read revision + */ + public InternalCDORevision readRevision(CDOID id, CDOBranchPoint branchPoint, int listChunk, + CDORevisionCacheAdder cache) + { + if (!HibernateUtil.getInstance().isStoreCreatedID(id)) + { + return null; + } + + final InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(id); + if (revision == null) + { + final CDOClassifierRef classifierRef = CDOIDUtil.getClassifierRef(id); + if (classifierRef == null) + { + throw new IllegalArgumentException("This CDOID type of " + id + " is not supported by this store."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final EClass eClass = HibernateUtil.getInstance().getEClass(classifierRef); + return new DetachedCDORevision(eClass, id, branchPoint.getBranch(), 0, 0); + } + + revision.setBranchPoint(getStore().getMainBranchHead()); + return revision; + } + + public Pair<Integer, Long> createBranch(int branchID, BranchInfo branchInfo) + { + // TODO: implement HibernateStoreAccessor.createBranch(branchID, branchInfo) + throw new UnsupportedOperationException(); + } + + public BranchInfo loadBranch(int branchID) + { + // TODO: implement HibernateStoreAccessor.loadBranch(branchID) + throw new UnsupportedOperationException(); + } + + public SubBranchInfo[] loadSubBranches(int branchID) + { + // TODO: implement HibernateStoreAccessor.loadSubBranches(branchID) + throw new UnsupportedOperationException(); + } + + public int loadBranches(int startID, int endID, CDOBranchHandler branchHandler) + { + // TODO: implement HibernateStoreAccessor.loadBranches(startID, endID, branchHandler) + throw new UnsupportedOperationException(); + } + + public void loadCommitInfos(CDOBranch branch, long startTime, long endTime, CDOCommitInfoHandler handler) + { + // TODO: implement HibernateStoreAccessor.loadCommitInfos(branch, startTime, endTime, handler) + // throw new UnsupportedOperationException(); + } + + public Set<CDOID> readChangeSet(OMMonitor monitor, CDOChangeSetSegment... segments) + { + // TODO: implement HibernateStoreAccessor.readChangeSet(segments) + throw new UnsupportedOperationException(); + } + + public void handleRevisions(EClass eClass, CDOBranch branch, long timeStamp, boolean exactTime, + CDORevisionHandler handler) + { + if (eClass != null) + { + handleRevisionsByEClass(eClass, handler); + } + else + { + for (EPackage ePackage : getStore().getPackageHandler().getEPackages()) + { + for (EClassifier eClassifier : ePackage.getEClassifiers()) + { + if (eClassifier instanceof EClass) + { + final EClass eClazz = (EClass)eClassifier; + try + { + getStore().getEntityName(eClazz); + } + catch (IllegalArgumentException ex) + { + // a non-mapped eclass + continue; + } + handleRevisionsByEClass(eClazz, handler); + } + } + } + } + } + + private void handleRevisionsByEClass(EClass eClass, CDORevisionHandler handler) + { + // get a transaction, the hibernateStoreAccessor is placed in a threadlocal + // so all db access uses the same session. + final Session session = getHibernateSession(); + + // create the query + final Query query = session.createQuery("select e from " + getStore().getEntityName(eClass) + " e"); + for (Object o : query.list()) + { + handler.handleRevision((CDORevision)o); + } + session.clear(); + } + + /** + * Not supported by the Hibernate Store, auditing is not supported. Currently ignores the branchVersion and calls the + * {@readRevision(CDOID, CDOBranchPoint, int, CDORevisionCacheAdder)} . + */ + public InternalCDORevision readRevisionByVersion(CDOID id, CDOBranchVersion branchVersion, int listChunk, + CDORevisionCacheAdder cache) + { + InternalCDORevision revision = readRevision(id, branchVersion.getBranch().getPoint(System.currentTimeMillis()), + listChunk, cache); + if (revision != null) + { + revision.freeze(); + } + + return revision; + } + + /** + * Queries for resources in a certain folder and returns them in the context object + * + * @param context + * the context provides input parameters (the folder) and is used to store the results of the query. + * @since 2.0 + */ + public void queryResources(QueryResourcesContext context) + { + final CDOID folderID = getHibernateID(context.getFolderID()); + String name = context.getName(); + boolean exactMatch = context.exactMatch(); + + final Session session = getHibernateSession(); + final Criteria criteria = session.createCriteria(EresourcePackage.eINSTANCE.getCDOResourceNode().getName()); + if (folderID == null) + { + criteria.add(org.hibernate.criterion.Restrictions.isNull(CDOHibernateConstants.CONTAINER_PROPERTY)); + } + else + { + criteria.add(org.hibernate.criterion.Restrictions.eq(CDOHibernateConstants.CONTAINER_PROPERTY, folderID)); + } + + List<?> result = criteria.list(); + for (Object o : result) + { + final CDORevision revision = (CDORevision)o; + final EStructuralFeature feature = revision.getEClass().getEStructuralFeature(NAME_EFEATURE_NAME); + if (feature != null) + { + Object value = revision.data().get(feature, 0); + if (value == CDORevisionData.NIL) + { + value = null; + } + + final String revisionName = (String)value; + final boolean match = exactMatch || revisionName == null || name == null ? ObjectUtil + .equals(revisionName, name) : revisionName.startsWith(name); + + if (match && !context.addResource(HibernateUtil.getInstance().getCDOID(revision))) + { + // No more results allowed + break; + } + } + } + } + + public void queryXRefs(QueryXRefsContext context) + { + final Session session = getHibernateSession(); + for (CDOID targetCdoId : context.getTargetObjects().keySet()) + { + final CDORevision revision = HibernateUtil.getInstance().getCDORevision(targetCdoId); + final EClass targetEClass = context.getTargetObjects().get(targetCdoId); + final String targetEntityName = getStore().getEntityName(targetEClass); + final Map<EClass, List<EReference>> sourceCandidates = context.getSourceCandidates(); + for (EClass sourceEClass : sourceCandidates.keySet()) + { + final String sourceEntityName = getStore().getEntityName(sourceEClass); + for (EReference eref : sourceCandidates.get(sourceEClass)) + { + final String hql; + if (eref.isMany()) + { + hql = "select ref from " + sourceEntityName + " as ref, " + targetEntityName + + " as refTo where refTo = :to and refTo in elements(ref." + eref.getName() + ")"; + } + else + { + hql = "select ref from " + sourceEntityName + " as ref where :to = ref." + eref.getName(); + } + + final Query qry = session.createQuery(hql); + qry.setEntity("to", revision); + ScrollableResults result = qry.scroll(ScrollMode.FORWARD_ONLY); + while (result.next()) + { + final InternalCDORevision sourceRevision = (InternalCDORevision)result.get()[0]; + int sourceIndex = 0; + if (eref.isMany()) + { + // note this takes performance for sure as the list is read, + // consider not supporting sourceIndex, or doing it differently + final WrappedHibernateList cdoList = (WrappedHibernateList)sourceRevision.getList(eref); + sourceIndex = cdoList.getDelegate().indexOf(revision); + } + + boolean more = context.addXRef(targetCdoId, sourceRevision.getID(), eref, sourceIndex); + if (!more) + { + return; + } + } + } + } + } + } + + private CDOID getHibernateID(CDOID id) + { + if (!CDOIDUtil.isNull(id)) + { + if (HibernateUtil.getInstance().isStoreCreatedID(id)) + { + return id; + } + + // TODO Can this happen? When? + // the folder id is always a long + final Long idValue = CDOIDUtil.getLong(id); + return CDOIDUtil.createLongWithClassifier(new CDOClassifierRef(EresourcePackage.eINSTANCE.getCDOResourceNode()), + idValue); + } + + return null; + } + + /** + * @param info + * the query information, is not used actively in this method. + * @return a new instance of {@link HibernateQueryHandler} + */ + public IQueryHandler getQueryHandler(CDOQueryInfo info) + { + String queryLanguage = info.getQueryLanguage(); + if (StringUtil.equalsUpperOrLowerCase(queryLanguage, IHibernateStore.QUERY_LANGUAGE)) + { + final HibernateQueryHandler queryHandler = new HibernateQueryHandler(); + queryHandler.setHibernateStoreAccessor(this); + return queryHandler; + } + + return null; + } + + /** + * Commits the session, see {@link #commitRollbackHibernateSession()}. + * + * @param monitor + * not used + */ + @Override + protected void doCommit(OMMonitor monitor) + { + commitRollbackHibernateSession(); + HibernateThreadContext.setCommitContext(null); + } + + /** + * Performs the main write and update actions. Persists new EPackages, updates changed objects, creates new ones and + * removes deleted objects. Updates both container as well as resource associations. + * + * @param context + * the context contains the changed, new and to-be-removed objects + * @param monitor + * not used by this method + */ + @Override + public void doWrite(InternalCommitContext context, OMMonitor monitor) + { + // NOTE: the same flow is also present in the super class (StoreAccessor) + // changes in flow can mean that the flow here also has to change + + monitor.begin(3); + HibernateThreadContext.setCommitContext(context); + if (context.getNewPackageUnits().length > 0) + { + writePackageUnits(context.getNewPackageUnits(), monitor.fork()); + } + + // Note: instead of an Async here, we could do much more fine-grained monitoring below. But this + // simplistic solution is sufficient to prevent timeout errors. + final Async async = monitor.forkAsync(); + try + { + // start with fresh hibernate session to prevent side effects + final Session session = getNewHibernateSession(); + session.setFlushMode(FlushMode.MANUAL); + + // order is 1) insert, 2) update and then delete + // this order is the most stable! Do not change it without testing + + final List<InternalCDORevision> repairContainerIDs = new ArrayList<InternalCDORevision>(); + final List<InternalCDORevision> repairResourceIDs = new ArrayList<InternalCDORevision>(); + for (InternalCDORevision revision : context.getNewObjects()) + { + // keep track for which cdoRevisions the container id needs to be repaired afterwards + final CDOID containerID = (CDOID)revision.getContainerID(); + if (containerID instanceof CDOIDTemp && !containerID.isNull()) + { + repairContainerIDs.add(revision); + } + + final CDOID resourceID = revision.getResourceID(); + if (resourceID instanceof CDOIDTemp && !resourceID.isNull()) + { + repairResourceIDs.add(revision); + } + + final String entityName = getStore().getEntityName(revision.getEClass()); + session.saveOrUpdate(entityName, revision); + } + + session.flush(); + + for (CDORevision revision : context.getDirtyObjects()) + { + final String entityName = HibernateUtil.getInstance().getEntityName(revision.getID()); + session.merge(entityName, revision); + if (TRACER.isEnabled()) + { + TRACER.trace("Updated Object " + revision.getEClass().getName() + " id: " + revision.getID()); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + session.flush(); + + // delete all objects + for (CDOID id : context.getDetachedObjects()) + { + try + { + final CDORevision revision = HibernateUtil.getInstance().getCDORevision(id); + + // maybe deleted in parallell? + if (revision != null) + { + session.delete(revision); + } + } + catch (org.hibernate.ObjectNotFoundException ex) + { + // ignore these, an object can be removed through cascade deletes + } + } + + session.flush(); + + // now do an update of the container without incrementing the version + repairContainerIDs(repairContainerIDs, session); + repairResourceIDs(repairResourceIDs, session); + + session.flush(); + + // write the blobs + ExtendedDataInputStream in = context.getLobs(); + if (in != null) + { + try + { + int count = in.readInt(); + for (int i = 0; i < count; i++) + { + byte[] id = in.readByteArray(); + long size = in.readLong(); + if (size > 0) + { + writeBlob(id, size, in); + } + else + { + writeClob(id, -size, new InputStreamReader(in)); + } + } + } + catch (IOException ex) + { + throw WrappedException.wrap(ex); + } + } + + session.flush(); + + } + catch (Exception e) + { + OM.LOG.error(e); + throw WrappedException.wrap(e); + } + finally + { + async.stop(); + } + + context.applyIDMappings(monitor.fork()); + monitor.done(); + } + + private void repairContainerIDs(List<InternalCDORevision> repairContainerIDs, Session session) + { + for (InternalCDORevision revision : repairContainerIDs) + { + final CDORevision container = HibernateUtil.getInstance().getCDORevision((CDOID)revision.getContainerID()); + final String entityName = getStore().getEntityName(revision.getEClass()); + final CDOID id = revision.getID(); + final String hqlUpdate = "update " + entityName + " set " + CDOHibernateConstants.CONTAINER_PROPERTY //$NON-NLS-1$ //$NON-NLS-2$ + + " = :containerInfo where " + getStore().getIdentifierPropertyName(entityName) + " = :id"; //$NON-NLS-1$ //$NON-NLS-2$ + final Query qry = session.createQuery(hqlUpdate); + qry.setParameter("containerInfo", ContainerInfoConverter.getInstance().convertContainerRelationToString(revision, //$NON-NLS-1$ + container.getID())); + qry.setParameter("id", HibernateUtil.getInstance().getIdValue(id)); //$NON-NLS-1$ + if (qry.executeUpdate() != 1) + { + // OM.LOG.error("Not able to update container columns of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalStateException("Not able to update container columns of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + + private void repairResourceIDs(List<InternalCDORevision> repairResourceIDs, Session session) + { + for (InternalCDORevision revision : repairResourceIDs) + { + final CDORevision resource = HibernateUtil.getInstance().getCDORevision(revision.getResourceID()); + final String entityName = getStore().getEntityName(revision.getEClass()); + final CDOID id = revision.getID(); + final String hqlUpdate = "update " + entityName + " set " + CDOHibernateConstants.RESOURCE_PROPERTY //$NON-NLS-1$ //$NON-NLS-2$ + + " = :resourceInfo where " + getStore().getIdentifierPropertyName(entityName) + " = :id"; //$NON-NLS-1$ //$NON-NLS-2$ + final Query qry = session.createQuery(hqlUpdate); + qry.setParameter("resourceInfo", resource.getID()); //$NON-NLS-1$ + qry.setParameter("id", HibernateUtil.getInstance().getIdValue(id)); //$NON-NLS-1$ + if (qry.executeUpdate() != 1) + { + // OM.LOG.error("Not able to update resource ids of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalStateException("Not able to update resource ids of " + entityName + " with id " + id); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + + @Override + protected void detachObjects(CDOID[] detachedObjects, CDOBranch branch, long timeStamp, OMMonitor monitor) + { + // handled by the write method + } + + @Override + protected void doRollback(CommitContext context) + { + setErrorOccured(true); + endHibernateSession(); + HibernateThreadContext.setCommitContext(null); + } + + /** + * Writes package units to the datbaase. + * + * @param packageUnits + * the package units to write to the database + * @param monitor + * not used by the store + * @see HibernatePackageHandler + */ + public void writePackageUnits(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + if (packageUnits != null && packageUnits.length != 0) + { + getStore().getPackageHandler().writePackageUnits(packageUnits); + } + } + + @Override + protected void writeCommitInfo(CDOBranch branch, long timeStamp, long previousTimeStamp, String userID, + String comment, OMMonitor monitor) + { + // Do nothing + } + + @Override + protected void writeRevisions(InternalCDORevision[] revisions, CDOBranch branch, OMMonitor monitor) + { + // Doesn't do anything. It is done in commit(). + } + + @Override + public void addIDMappings(InternalCommitContext commitContext, OMMonitor monitor) + { + // Do nothing + } + + @Override + public CDOID getNextCDOID(CDORevision revision) + { + // Never called + throw new UnsupportedOperationException(); + } + + @Override + protected void writeRevisionDeltas(InternalCDORevisionDelta[] revisionDeltas, CDOBranch branch, long created, + OMMonitor monitor) + { + // TODO: implement HibernateStoreAccessor.writeRevisionDeltas(revisionDeltas, branch, created, monitor) + throw new UnsupportedOperationException(); + } + + public void queryLobs(List<byte[]> ids) + { + for (Iterator<byte[]> it = ids.iterator(); it.hasNext();) + { + byte[] id = it.next(); + final HibernateStoreLob lob = getCreateHibernateStoreLob(id); + if (lob.isNew()) + { + it.remove(); + } + } + } + + public void handleLobs(long fromTime, long toTime, CDOLobHandler handler) throws IOException + { + final Session session = getHibernateSession(); + final Query qry = session.createQuery("select c from " + HibernateStoreLob.class.getName() + " as c"); + + try + { + for (Object o : qry.list()) + { + final HibernateStoreLob lob = (HibernateStoreLob)o; + if (lob.getBlob() != null) + { + final OutputStream out = handler.handleBlob(HexUtil.hexToBytes(lob.getId()), lob.getSize()); + if (out != null) + { + final InputStream in = lob.getBlob().getBinaryStream(); + try + { + IOUtil.copyBinary(in, out, lob.getSize()); + } + finally + { + IOUtil.close(out); + } + } + } + else + { + final Clob clob = lob.getClob(); + Reader in = clob.getCharacterStream(); + Writer out = handler.handleClob(HexUtil.hexToBytes(lob.getId()), lob.getSize()); + if (out != null) + { + try + { + IOUtil.copyCharacter(in, out, lob.getSize()); + } + finally + { + IOUtil.close(out); + } + } + } + } + } + catch (SQLException ex) + { + throw new IllegalStateException(ex); + } + } + + public void loadLob(byte[] id, OutputStream out) throws IOException + { + final HibernateStoreLob lob = getCreateHibernateStoreLob(id); + // can this ever occur? + // TODO: how should non-existence be handled? Currently results in a timeout + // on the client. + if (lob.isNew()) + { + throw new IllegalStateException("Lob with id " + HexUtil.bytesToHex(id) + " does not exist"); + } + + final long size = lob.getSize(); + try + { + if (lob.getBlob() != null) + { + InputStream in = lob.getBlob().getBinaryStream(); + IOUtil.copyBinary(in, out, size); + } + else + { + Clob clob = lob.getClob(); + Reader in = clob.getCharacterStream(); + IOUtil.copyCharacter(in, new OutputStreamWriter(out), size); + } + } + catch (Exception e) + { + throw new IllegalStateException(e); + } + } + + @SuppressWarnings("deprecation") + @Override + protected void writeBlob(byte[] id, long size, InputStream inputStream) throws IOException + { + final HibernateStoreLob lob = getCreateHibernateStoreLob(id); + if ((inputStream == null || size == 0) && !lob.isNew()) + { + getHibernateSession().delete(lob); + } + else + { + // deprecated usage, non-deprecated api uses a session + // TODO: research which session to use + lob.setBlob(Hibernate.createBlob(inputStream, (int)size)); + lob.setSize((int)size); + lob.setClob(null); + getHibernateSession().saveOrUpdate(lob); + } + } + + @SuppressWarnings("deprecation") + @Override + protected void writeClob(byte[] id, long size, Reader reader) throws IOException + { + final HibernateStoreLob lob = getCreateHibernateStoreLob(id); + if ((reader == null || size == 0) && !lob.isNew()) + { + getHibernateSession().delete(lob); + } + else + { + // deprecated usage, non-deprecated api uses a session + // TODO: research which session to use + lob.setClob(Hibernate.createClob(reader, (int)size)); + lob.setSize((int)size); + lob.setBlob(null); + getHibernateSession().saveOrUpdate(lob); + } + } + + private HibernateStoreLob getCreateHibernateStoreLob(byte[] idBytes) + { + final String id = HexUtil.bytesToHex(idBytes); + final Session session = getHibernateSession(); + HibernateStoreLob lob = (HibernateStoreLob)session.get(HibernateStoreLob.class, id); + if (lob == null) + { + lob = new HibernateStoreLob(); + lob.setId(id); + } + + return lob; + } + + public void rawExport(CDODataOutput out, int fromBranchID, int toBranchID, long fromCommitTime, long toCommitTime) + throws IOException + { + throw new UnsupportedOperationException(); + } + + public void rawImport(CDODataInput in, int fromBranchID, int toBranchID, long fromCommitTime, long toCommitTime, + OMMonitor monitor) throws IOException + { + throw new UnsupportedOperationException(); + } + + public void rawStore(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + // TODO: implement HibernateStoreAccessor.rawStore(packageUnits, monitor) + throw new UnsupportedOperationException("Needed for server import!"); + } + + public void rawStore(InternalCDORevision revision, OMMonitor monitor) + { + throw new UnsupportedOperationException(); + } + + public void rawStore(byte[] id, long size, InputStream inputStream) throws IOException + { + throw new UnsupportedOperationException(); + } + + public void rawStore(byte[] id, long size, Reader reader) throws IOException + { + throw new UnsupportedOperationException(); + } + + public void rawStore(CDOBranch branch, long timeStamp, long previousTimeStamp, String userID, String comment, + OMMonitor monitor) + { + throw new UnsupportedOperationException(); + } + + public void rawCommit(double commitWork, OMMonitor monitor) + { + throw new UnsupportedOperationException(); + } + + @Deprecated + public void rawDelete(CDOID id, int version, CDOBranch branch, EClass eClass, OMMonitor monitor) + { + throw new UnsupportedOperationException(); + } + + @Override + protected void doDeactivate() throws Exception + { + // TODO This method is called when this accessor is not needed anymore + if (TRACER.isEnabled()) + { + TRACER.trace("Committing/rollback and closing hibernate session"); //$NON-NLS-1$ + } + + try + { + endHibernateSession(); + } + finally + { + clearThreadState(); + } + } + + @Override + protected void doPassivate() throws Exception + { + clearThreadState(); + } + + private void clearThreadState() + { + PersistableListHolder.getInstance().clearListMapping(); + HibernateThreadContext.setCommitContext(null); + } + + @Override + protected void doActivate() throws Exception + { + } + + @Override + protected void doUnpassivate() throws Exception + { + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WrappedHibernateList.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WrappedHibernateList.java index 8828ef49b5..3873e80bcf 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WrappedHibernateList.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WrappedHibernateList.java @@ -1,504 +1,481 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Martin Taal - initial api
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.id.CDOID;
-import org.eclipse.emf.cdo.common.model.CDOModelUtil;
-import org.eclipse.emf.cdo.common.model.CDOType;
-import org.eclipse.emf.cdo.common.revision.CDOListFactory;
-import org.eclipse.emf.cdo.common.revision.CDORevision;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-import org.eclipse.emf.cdo.spi.common.revision.CDOReferenceAdjuster;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDOList;
-
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EEnumLiteral;
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.proxy.HibernateProxy;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-
-/**
- * Wraps a moveable list so that hibernate always sees an object view while cdo always sees a cdoid view. The same for
- * EEnum: cdo wants to see an int (the ordinal), hibernate the real eenum value. This to support querying with EENum
- * parameters.
- *
- * @author Martin Taal
- */
-public class WrappedHibernateList implements InternalCDOList
-{
- private List<Object> delegate;
-
- private boolean frozen;
-
- public WrappedHibernateList()
- {
- }
-
- public void move(int newPosition, Object object)
- {
- checkFrozen();
- move(newPosition, indexOf(object));
- }
-
- public Object move(int targetIndex, int sourceIndex)
- {
- checkFrozen();
- int size = size();
- if (sourceIndex >= size)
- {
- throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (targetIndex >= size)
- {
- throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Object object = get(sourceIndex);
- if (targetIndex == sourceIndex)
- {
- return object;
- }
-
- if (targetIndex < sourceIndex)
- {
- moveUp1(targetIndex, sourceIndex - targetIndex);
- }
- else
- {
- moveDown1(targetIndex, targetIndex - sourceIndex);
- }
-
- set(targetIndex, object);
- return object;
- }
-
- private void moveUp1(int index, int count)
- {
- for (int i = count; i > 0; i--)
- {
- set(index + i, get(index + i - 1));
- }
- }
-
- private void moveDown1(int index, int count)
- {
- for (int i = count; i > 0; i--)
- {
- set(index - i, get(index - i + 1));
- }
- }
-
- /**
- * There's a duplicate of this method in CDOListImpl!!!
- */
- public boolean adjustReferences(CDOReferenceAdjuster adjuster, EStructuralFeature feature)
- {
- boolean changed = false;
-
- CDOType type = CDOModelUtil.getType(feature);
- int size = size();
- for (int i = 0; i < size; i++)
- {
- Object element = get(i);
- Object newID = type.adjustReferences(adjuster, element, feature, i);
- if (newID != element) // Just an optimization for NOOP adjusters
- {
- set(i, newID);
- changed = true;
- }
- }
-
- return changed;
- }
-
- public InternalCDOList clone(EClassifier classifier)
- {
- CDOType type = CDOModelUtil.getType(classifier);
- int size = size();
- InternalCDOList list = (InternalCDOList)CDOListFactory.DEFAULT.createList(size, 0, 0);
- for (int i = 0; i < size; i++)
- {
- list.add(type.copyValue(get(i)));
- }
-
- return list;
- }
-
- /**
- * @return the delegate
- */
- public List<Object> getDelegate()
- {
- return delegate;
- }
-
- /**
- * @param delegate
- * the delegate to set
- */
- public void setDelegate(List<Object> delegate)
- {
- this.delegate = delegate;
- }
-
- protected Object getObject(Object o)
- {
- if (o == null)
- {
- return null;
- }
-
- // is already resolved
- if (!(o instanceof CDOID))
- {
- return o;
- }
-
- return HibernateUtil.getInstance().getCDORevision((CDOID)o);
- }
-
- protected List<Object> getObjects(List<?> ids)
- {
- List<Object> result = new ArrayList<Object>();
- for (Object o : ids)
- {
- result.add(getObject(o));
- }
-
- return result;
- }
-
- protected CDOID getCDOID(Object o)
- {
- if (o instanceof CDOID)
- {
- return (CDOID)o;
- }
-
- return HibernateUtil.getInstance().getCDOID(o);
- }
-
- protected List<CDOID> getCDOIDs(Collection<?> c)
- {
- List<CDOID> newC = new ArrayList<CDOID>();
- for (Object o : c)
- {
- newC.add(getCDOID(o));
- }
-
- return newC;
- }
-
- public void add(int index, Object element)
- {
- checkFrozen();
- getDelegate().add(index, getCDOID(element));
- }
-
- public boolean add(Object o)
- {
- checkFrozen();
- return getDelegate().add(getCDOID(o));
- }
-
- public boolean addAll(Collection<? extends Object> c)
- {
- checkFrozen();
- return getDelegate().addAll(getCDOIDs(c));
- }
-
- public boolean addAll(int index, Collection<? extends Object> c)
- {
- checkFrozen();
- return getDelegate().addAll(index, getCDOIDs(c));
- }
-
- public void clear()
- {
- checkFrozen();
- getDelegate().clear();
- }
-
- public boolean contains(Object o)
- {
- return getDelegate().contains(getCDOID(o));
- }
-
- public boolean containsAll(Collection<?> c)
- {
- return getDelegate().containsAll(getCDOIDs(c));
- }
-
- public Object get(int index)
- {
- final Object delegateValue = getDelegate().get(index);
- if (delegateValue instanceof CDOID)
- {
- return delegateValue;
- }
-
- final Object value = getObject(delegateValue);
- if (value instanceof CDORevision || value instanceof HibernateProxy)
- {
- return HibernateUtil.getInstance().getCDOID(value);
- }
-
- if (value instanceof EEnumLiteral)
- {
- return ((EEnumLiteral)value).getValue();
- }
-
- return value;
- }
-
- public Object get(int index, boolean resolve)
- {
- // Since delegate is a hibernate list, it is never a CDOElementProxy
- // so the parameter resolve can be ignored
- return get(index);
- }
-
- public int indexOf(Object o)
- {
- return getDelegate().indexOf(getCDOID(o));
- }
-
- public boolean isEmpty()
- {
- return getDelegate().isEmpty();
- }
-
- public Iterator<Object> iterator()
- {
- return new CDOHibernateIterator(getDelegate().iterator());
- }
-
- public int lastIndexOf(Object o)
- {
- return getDelegate().lastIndexOf(getCDOID(o));
- }
-
- public ListIterator<Object> listIterator()
- {
- return new CDOHibernateListIterator(this, getDelegate().listIterator());
- }
-
- public ListIterator<Object> listIterator(int index)
- {
- return new CDOHibernateListIterator(this, getDelegate().listIterator(index));
- }
-
- public Object remove(int index)
- {
- checkFrozen();
- return getDelegate().remove(index);
- }
-
- public boolean remove(Object o)
- {
- checkFrozen();
- return getDelegate().remove(getCDOID(o));
- }
-
- public boolean removeAll(Collection<?> c)
- {
- checkFrozen();
- return getDelegate().removeAll(getCDOIDs(c));
- }
-
- public boolean retainAll(Collection<?> c)
- {
- return getDelegate().retainAll(getCDOIDs(c));
- }
-
- public Object set(int index, Object element)
- {
- checkFrozen();
- if (element instanceof CDOID)
- {
- return getDelegate().set(index, element);
- }
-
- return getDelegate().set(index, getCDOID(element));
- }
-
- public int size()
- {
- return getDelegate().size();
- }
-
- public List<Object> subList(int fromIndex, int toIndex)
- {
- return getObjects(getDelegate().subList(fromIndex, toIndex));
- }
-
- public Object[] toArray()
- {
- Object[] result = new Object[size()];
- int i = 0;
- for (Object o : this)
- {
- result[i++] = o;
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- public <T> T[] toArray(T[] a)
- {
- int i = 0;
- for (Object o : this)
- {
- a[i++] = (T)o;
- }
-
- return a;
- }
-
- private static final class CDOHibernateIterator implements Iterator<Object>
- {
- private final Iterator<?> delegate;
-
- public CDOHibernateIterator(Iterator<?> delegate)
- {
- this.delegate = delegate;
- }
-
- public boolean hasNext()
- {
- return delegate.hasNext();
- }
-
- public Object next()
- {
- Object o = delegate.next();
-
- if (o instanceof CDOID)
- {
- return HibernateUtil.getInstance().getCDORevision((CDOID)o);
- }
-
- // CDO always wants to have the integer for an EENUM
- if (o instanceof EEnumLiteral)
- {
- return ((EEnumLiteral)o).getValue();
- }
-
- return o;
- }
-
- public void remove()
- {
- delegate.remove();
- }
- }
-
- private static final class CDOHibernateListIterator implements ListIterator<Object>
- {
- private final ListIterator<Object> delegate;
-
- private final WrappedHibernateList owner;
-
- public CDOHibernateListIterator(WrappedHibernateList owner, ListIterator<Object> delegate)
- {
- this.delegate = delegate;
- this.owner = owner;
- }
-
- public void add(Object o)
- {
- owner.checkFrozen();
-
- delegate.add(HibernateUtil.getInstance().getCDOID(o));
- }
-
- public boolean hasNext()
- {
- return delegate.hasNext();
- }
-
- public boolean hasPrevious()
- {
- return delegate.hasPrevious();
- }
-
- public Object next()
- {
- Object o = delegate.next();
- if (o instanceof CDOID)
- {
- return HibernateUtil.getInstance().getCDORevision((CDOID)delegate.next());
- }
-
- return o;
- }
-
- public int nextIndex()
- {
- return delegate.nextIndex();
- }
-
- public Object previous()
- {
- Object o = delegate.previous();
- if (o instanceof CDOID)
- {
- return HibernateUtil.getInstance().getCDORevision((CDOID)delegate.next());
- }
-
- return o;
- }
-
- public int previousIndex()
- {
- return delegate.previousIndex();
- }
-
- public void remove()
- {
- owner.checkFrozen();
- delegate.remove();
- }
-
- public void set(Object o)
- {
- owner.checkFrozen();
- delegate.set(HibernateUtil.getInstance().getCDOID(o));
- }
- }
-
- public void freeze()
- {
- frozen = true;
- }
-
- private void checkFrozen()
- {
- if (frozen)
- {
- throw new IllegalStateException("Cannot modify a frozen list");
- }
- }
-
- public void setWithoutFrozenCheck(int i, Object value)
- {
- getDelegate().set(i, value);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Martin Taal - initial api + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.id.CDOID; +import org.eclipse.emf.cdo.common.model.CDOModelUtil; +import org.eclipse.emf.cdo.common.model.CDOType; +import org.eclipse.emf.cdo.common.revision.CDOListFactory; +import org.eclipse.emf.cdo.common.revision.CDORevision; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; +import org.eclipse.emf.cdo.spi.common.revision.CDOReferenceAdjuster; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDOList; + +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.proxy.HibernateProxy; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Wraps a moveable list so that hibernate always sees an object view while cdo always sees a cdoid view. The same for + * EEnum: cdo wants to see an int (the ordinal), hibernate the real eenum value. This to support querying with EENum + * parameters. + * + * @author Martin Taal + */ +public class WrappedHibernateList implements InternalCDOList +{ + private List<Object> delegate; + + private boolean frozen; + + public WrappedHibernateList() + { + } + + public void move(int newPosition, Object object) + { + checkFrozen(); + move(newPosition, indexOf(object)); + } + + public Object move(int targetIndex, int sourceIndex) + { + checkFrozen(); + int size = size(); + if (sourceIndex >= size) + { + throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (targetIndex >= size) + { + throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ + } + + Object object = get(sourceIndex); + if (targetIndex == sourceIndex) + { + return object; + } + + if (targetIndex < sourceIndex) + { + moveUp1(targetIndex, sourceIndex - targetIndex); + } + else + { + moveDown1(targetIndex, targetIndex - sourceIndex); + } + + set(targetIndex, object); + return object; + } + + private void moveUp1(int index, int count) + { + for (int i = count; i > 0; i--) + { + set(index + i, get(index + i - 1)); + } + } + + private void moveDown1(int index, int count) + { + for (int i = count; i > 0; i--) + { + set(index - i, get(index - i + 1)); + } + } + + /** + * There's a duplicate of this method in CDOListImpl!!! + */ + public boolean adjustReferences(CDOReferenceAdjuster adjuster, EStructuralFeature feature) + { + boolean changed = false; + + CDOType type = CDOModelUtil.getType(feature); + int size = size(); + for (int i = 0; i < size; i++) + { + Object element = get(i); + Object newID = type.adjustReferences(adjuster, element, feature, i); + if (newID != element) // Just an optimization for NOOP adjusters + { + set(i, newID); + changed = true; + } + } + + return changed; + } + + public InternalCDOList clone(EClassifier classifier) + { + CDOType type = CDOModelUtil.getType(classifier); + int size = size(); + InternalCDOList list = (InternalCDOList)CDOListFactory.DEFAULT.createList(size, 0, 0); + for (int i = 0; i < size; i++) + { + list.add(type.copyValue(get(i))); + } + + return list; + } + + /** + * @return the delegate + */ + public List<Object> getDelegate() + { + return delegate; + } + + /** + * @param delegate + * the delegate to set + */ + public void setDelegate(List<Object> delegate) + { + this.delegate = delegate; + } + + private static Object convertToCDO(Object value) + { + if (value == null) + { + return null; + } + + // Eike: This seems wrong to me: + // if (value instanceof CDOID) + // { + // return HibernateUtil.getInstance().getCDORevision((CDOID)value); + // } + + if (value instanceof CDORevision || value instanceof HibernateProxy) + { + return HibernateUtil.getInstance().getCDOID(value); + } + + if (value instanceof EEnumLiteral) + { + return ((EEnumLiteral)value).getValue(); + } + + return value; + } + + private static List<Object> convertToCDO(List<?> ids) + { + List<Object> result = new ArrayList<Object>(); + for (Object o : ids) + { + result.add(convertToCDO(o)); + } + + return result; + } + + protected CDOID getCDOID(Object o) + { + if (o instanceof CDOID) + { + return (CDOID)o; + } + + return HibernateUtil.getInstance().getCDOID(o); + } + + protected List<CDOID> getCDOIDs(Collection<?> c) + { + List<CDOID> newC = new ArrayList<CDOID>(); + for (Object o : c) + { + newC.add(getCDOID(o)); + } + + return newC; + } + + public void add(int index, Object element) + { + checkFrozen(); + getDelegate().add(index, getCDOID(element)); + } + + public boolean add(Object o) + { + checkFrozen(); + return getDelegate().add(getCDOID(o)); + } + + public boolean addAll(Collection<? extends Object> c) + { + checkFrozen(); + return getDelegate().addAll(getCDOIDs(c)); + } + + public boolean addAll(int index, Collection<? extends Object> c) + { + checkFrozen(); + return getDelegate().addAll(index, getCDOIDs(c)); + } + + public void clear() + { + checkFrozen(); + getDelegate().clear(); + } + + public boolean contains(Object o) + { + return getDelegate().contains(getCDOID(o)); + } + + public boolean containsAll(Collection<?> c) + { + return getDelegate().containsAll(getCDOIDs(c)); + } + + public Object get(int index) + { + final Object delegateValue = getDelegate().get(index); + if (delegateValue instanceof CDOID) + { + return delegateValue; + } + + return convertToCDO(delegateValue); + } + + public Object get(int index, boolean resolve) + { + // Since delegate is a hibernate list, it is never a CDOElementProxy + // so the parameter resolve can be ignored + return get(index); + } + + public int indexOf(Object o) + { + return getDelegate().indexOf(getCDOID(o)); + } + + public boolean isEmpty() + { + return getDelegate().isEmpty(); + } + + public Iterator<Object> iterator() + { + return new CDOHibernateIterator(getDelegate().iterator()); + } + + public int lastIndexOf(Object o) + { + return getDelegate().lastIndexOf(getCDOID(o)); + } + + public ListIterator<Object> listIterator() + { + return new CDOHibernateListIterator(this, getDelegate().listIterator()); + } + + public ListIterator<Object> listIterator(int index) + { + return new CDOHibernateListIterator(this, getDelegate().listIterator(index)); + } + + public Object remove(int index) + { + checkFrozen(); + return getDelegate().remove(index); + } + + public boolean remove(Object o) + { + checkFrozen(); + return getDelegate().remove(getCDOID(o)); + } + + public boolean removeAll(Collection<?> c) + { + checkFrozen(); + return getDelegate().removeAll(getCDOIDs(c)); + } + + public boolean retainAll(Collection<?> c) + { + return getDelegate().retainAll(getCDOIDs(c)); + } + + public Object set(int index, Object element) + { + checkFrozen(); + if (element instanceof CDOID) + { + return getDelegate().set(index, element); + } + + return getDelegate().set(index, getCDOID(element)); + } + + public int size() + { + return getDelegate().size(); + } + + public List<Object> subList(int fromIndex, int toIndex) + { + return convertToCDO(getDelegate().subList(fromIndex, toIndex)); + } + + public Object[] toArray() + { + Object[] result = new Object[size()]; + int i = 0; + for (Object o : this) + { + result[i++] = o; + } + + return result; + } + + @SuppressWarnings("unchecked") + public <T> T[] toArray(T[] a) + { + int i = 0; + for (Object o : this) + { + a[i++] = (T)o; + } + + return a; + } + + private static final class CDOHibernateIterator implements Iterator<Object> + { + private final Iterator<?> delegate; + + public CDOHibernateIterator(Iterator<?> delegate) + { + this.delegate = delegate; + } + + public boolean hasNext() + { + return delegate.hasNext(); + } + + public Object next() + { + Object value = delegate.next(); + return convertToCDO(value); + } + + public void remove() + { + delegate.remove(); + } + } + + private static final class CDOHibernateListIterator implements ListIterator<Object> + { + private final ListIterator<Object> delegate; + + private final WrappedHibernateList owner; + + public CDOHibernateListIterator(WrappedHibernateList owner, ListIterator<Object> delegate) + { + this.delegate = delegate; + this.owner = owner; + } + + public void add(Object o) + { + owner.checkFrozen(); + + delegate.add(HibernateUtil.getInstance().getCDOID(o)); + } + + public boolean hasNext() + { + return delegate.hasNext(); + } + + public boolean hasPrevious() + { + return delegate.hasPrevious(); + } + + public Object next() + { + Object value = delegate.next(); + return convertToCDO(value); + } + + public int nextIndex() + { + return delegate.nextIndex(); + } + + public Object previous() + { + Object value = delegate.previous(); + return convertToCDO(value); + } + + public int previousIndex() + { + return delegate.previousIndex(); + } + + public void remove() + { + owner.checkFrozen(); + delegate.remove(); + } + + public void set(Object o) + { + owner.checkFrozen(); + delegate.set(HibernateUtil.getInstance().getCDOID(o)); + } + } + + public void freeze() + { + frozen = true; + } + + private void checkFrozen() + { + if (frozen) + { + throw new IllegalStateException("Cannot modify a frozen list"); + } + } + + public void setWithoutFrozenCheck(int i, Object value) + { + getDelegate().set(i, value); + } +} diff --git a/plugins/org.eclipse.emf.cdo.tests.hibernate/src/org/eclipse/emf/cdo/tests/hibernate/AllTestsHibernate.java b/plugins/org.eclipse.emf.cdo.tests.hibernate/src/org/eclipse/emf/cdo/tests/hibernate/AllTestsHibernate.java index 3dd8548456..254416d922 100644 --- a/plugins/org.eclipse.emf.cdo.tests.hibernate/src/org/eclipse/emf/cdo/tests/hibernate/AllTestsHibernate.java +++ b/plugins/org.eclipse.emf.cdo.tests.hibernate/src/org/eclipse/emf/cdo/tests/hibernate/AllTestsHibernate.java @@ -1,353 +1,352 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.emf.cdo.tests.hibernate;
-
-import org.eclipse.emf.cdo.tests.AllConfigs;
-import org.eclipse.emf.cdo.tests.AuditSameSessionTest;
-import org.eclipse.emf.cdo.tests.AuditTest;
-import org.eclipse.emf.cdo.tests.BackupTest;
-import org.eclipse.emf.cdo.tests.BranchingSameSessionTest;
-import org.eclipse.emf.cdo.tests.BranchingTest;
-import org.eclipse.emf.cdo.tests.BranchingWithCacheClearTest;
-import org.eclipse.emf.cdo.tests.CommitInfoTest;
-import org.eclipse.emf.cdo.tests.ComplexTest;
-import org.eclipse.emf.cdo.tests.ContainmentTest;
-import org.eclipse.emf.cdo.tests.ExternalReferenceTest;
-import org.eclipse.emf.cdo.tests.LockingManagerRestartRepositoryTest;
-import org.eclipse.emf.cdo.tests.LockingManagerRestartSessionTest;
-import org.eclipse.emf.cdo.tests.LockingManagerRestartTransactionTest;
-import org.eclipse.emf.cdo.tests.LockingManagerTest;
-import org.eclipse.emf.cdo.tests.LockingNotificationsTest;
-import org.eclipse.emf.cdo.tests.MEMStoreQueryTest;
-import org.eclipse.emf.cdo.tests.MergingTest;
-import org.eclipse.emf.cdo.tests.MultiValuedOfAttributeTest;
-import org.eclipse.emf.cdo.tests.OCLQueryTest;
-import org.eclipse.emf.cdo.tests.PartialCommitTest;
-import org.eclipse.emf.cdo.tests.ResourceTest;
-import org.eclipse.emf.cdo.tests.RevisionManagerClientSideTest;
-import org.eclipse.emf.cdo.tests.RevisionManagerTest;
-import org.eclipse.emf.cdo.tests.SetFeatureTest;
-import org.eclipse.emf.cdo.tests.UnsetTest;
-import org.eclipse.emf.cdo.tests.XATransactionTest;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_252214_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_258933_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_272861_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_273565_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_279982_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_283985_1_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_283985_2_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_308895_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_316444_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_319836_Test;
-import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_322804_Test;
-import org.eclipse.emf.cdo.tests.config.IScenario;
-import org.eclipse.emf.cdo.tests.config.impl.ConfigTest;
-import org.eclipse.emf.cdo.tests.config.impl.RepositoryConfig;
-import org.eclipse.emf.cdo.util.CommitException;
-
-import java.util.List;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * @author Eike Stepper
- */
-public class AllTestsHibernate extends AllConfigs
-{
- public static final RepositoryConfig HIBERNATE = HibernateConfig.INSTANCE;
-
- public static Test suite()
- {
- return new AllTestsHibernate().getTestSuite("CDO Tests (Hibernate)");
- }
-
- @Override
- protected void initConfigSuites(TestSuite parent)
- {
- addScenario(parent, COMBINED, HIBERNATE, JVM, NATIVE);
- }
-
- @Override
- protected void initTestClasses(List<Class<? extends ConfigTest>> testClasses, IScenario scenario)
- {
- // testClasses.clear();
- // testClasses.add(HibernateTimeStampTest.class);
- // if (true)
- // {
- // return;
- // }
-
- testClasses.add(HibernateTimeStampTest.class);
- testClasses.add(Hibernate_Bugzilla_279982_Test.class);
- testClasses.add(Hibernate_ContainmentTest.class);
- testClasses.add(HibernateXATransactionTest.class);
- testClasses.add(Hibernate_Bugzilla_308895_Test.class);
- testClasses.add(HibernateExternalAnnotationTest.class);
- testClasses.add(HibernateMultiValuedOfAttributeTest.class);
- testClasses.add(HibernateXATransactionTest.class);
- testClasses.add(HibernateExternalReferenceTest.class);
- testClasses.add(HibernateQueryTest.class);
- testClasses.add(HibernateQueryNoCachingTest.class);
- testClasses.add(HibernateBugzilla_258933_Test.class);
- testClasses.add(HibernateUnsetTest.class);
- testClasses.add(HibernateBugzilla_301104_Test.class);
- testClasses.add(Hibernate_SetFeatureTest.class);
- testClasses.add(Hibernate_ResourceTest.class);
- testClasses.add(Hibernate_ComplexTest.class);
- testClasses.add(Hibernate_PartialCommitTest.class);
- testClasses.add(Hibernate_Bugzilla_316444_Test.class);
-
- super.initTestClasses(testClasses, scenario);
-
- // Teneo does not yet support lists of int arrays:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330212
- testClasses.remove(Bugzilla_322804_Test.class);
-
- testClasses.remove(Bugzilla_279982_Test.class);
-
- // locking not supported
- testClasses.remove(LockingManagerRestartRepositoryTest.class);
- testClasses.remove(LockingManagerRestartSessionTest.class);
- testClasses.remove(LockingManagerRestartTransactionTest.class);
- testClasses.remove(LockingNotificationsTest.class);
- testClasses.remove(LockingManagerRestartRepositoryTest.class);
-
- // are replaced by Hibernate specific ones, mostly
- // to prevent tests doing move from one container to another
- testClasses.remove(ContainmentTest.class);
- testClasses.remove(ComplexTest.class);
- testClasses.remove(ResourceTest.class);
- testClasses.remove(SetFeatureTest.class);
- testClasses.remove(PartialCommitTest.class);
- testClasses.remove(Bugzilla_316444_Test.class);
- testClasses.remove(Bugzilla_308895_Test.class);
-
- // contains a lot of containment move, which is not supported by Hibernate
- testClasses.remove(Bugzilla_283985_1_Test.class);
- testClasses.remove(Bugzilla_283985_2_Test.class);
- testClasses.remove(Bugzilla_319836_Test.class);
-
- // OCL querying not supported
- testClasses.remove(OCLQueryTest.class);
-
- // Backup not yet supported
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=339492
- testClasses.remove(BackupTest.class);
-
- // Branching not supported
- testClasses.remove(BranchingTest.class);
- testClasses.remove(MergingTest.class);
- testClasses.remove(BranchingSameSessionTest.class);
- testClasses.remove(BranchingWithCacheClearTest.class);
- testClasses.remove(RevisionManagerTest.class);
- testClasses.remove(RevisionManagerClientSideTest.class);
-
- // Commit info not supported
- testClasses.remove(CommitInfoTest.class);
-
- // Locking manager not supported
- testClasses.remove(LockingManagerTest.class);
-
- // results in infinite loops it seems
- // runs okay when run standalone
- testClasses.remove(Bugzilla_273565_Test.class);
-
- // audit support to do
- // bug 244141
- testClasses.remove(AuditTest.class);
- testClasses.remove(AuditSameSessionTest.class);
- testClasses.remove(Bugzilla_252214_Test.class);
-
- // replace a test with our local implementation:
- // the MultiValueOfAttributeTest class has a method
- // testListOfInteger which has a List with a null value
- // this is not nicely supported by Hibernate
- // therefore this step is removed
- testClasses.remove(MultiValuedOfAttributeTest.class);
-
- // MemStore is not relevant
- testClasses.remove(MEMStoreQueryTest.class);
-
- // replace test case to do external mapping
- testClasses.remove(XATransactionTest.class);
-
- // replace test case with one, disabling some non working testcases
- // see the HibernateExternalReferenceTest for a description
- testClasses.remove(ExternalReferenceTest.class);
-
- // this testcases removes and creates a resource with the
- // same path in one transaction, that's not supported
- // by hibernate.. because of unique key constraints
- testClasses.remove(Bugzilla_272861_Test.class);
-
- // override a testcase because the hibernate store
- // has a different meaning of unset
- testClasses.remove(Bugzilla_258933_Test.class);
-
- // remove as unsettable has to be re-visited for the hb store
- // see bugzilla 298579
- testClasses.remove(UnsetTest.class);
- }
-
- /**
- * Overridden because one testcase does not pass as Hibernate currently does not store the isset boolean values in the
- * database.
- *
- * @author Eike Stepper
- */
- public static class HibernateUnsetTest extends UnsetTest
- {
- @Override
- public void testUnsettableBaseTypeVsObjectType()
- {
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Hibernate_Bugzilla_308895_Test extends Bugzilla_308895_Test
- {
- @Override
- public void setUp() throws Exception
- {
- super.setUp();
- // final EAttribute att = getAtt();
-
- // add a teneo annotation
- // final EAnnotation eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
- // eAnnotation.setSource("teneo.jpa");
- // eAnnotation.getDetails().put("value", value)
- //
- // att.getEAnnotations().add(eAnnotation);
- }
- }
-
- // unsettable is hardly supported by the Hibernate Store
- public static class Hibernate_SetFeatureTest extends SetFeatureTest
- {
- @Override
- public void testUnsettableDateNoDefault_SetDefault() throws Exception
- {
- }
-
- @Override
- public void testUnsettableStringNoDefault_SetDefault() throws Exception
- {
- }
- }
-
- // disable some container move tests, containment move is not supported
- // by hibernate
- public static class Hibernate_ResourceTest extends ResourceTest
- {
- @Override
- public void testChangePathFromDepth3ToDepth0() throws Exception
- {
- }
-
- @Override
- public void testChangeResourceURI() throws Exception
- {
- }
-
- @Override
- public void testChangeResourceFolderURI() throws Exception
- {
- }
- }
-
- public static class Hibernate_ComplexTest extends ComplexTest
- {
- @Override
- public void testMigrateContainmentMulti()
- {
- }
-
- }
-
- public static class Hibernate_PartialCommitTest extends PartialCommitTest
- {
- @Override
- public void testMove() throws CommitException
- {
- }
-
- @Override
- public void testDoubleMove() throws CommitException
- {
- }
- }
-
- public static class Hibernate_Bugzilla_316444_Test extends Bugzilla_316444_Test
- {
- @Override
- public void testLockParentWithEAttributeChange() throws Exception
- {
- }
-
- @Override
- public void testMovingSubtree() throws Exception
- {
- }
-
- }
-
- public static class Hibernate_ContainmentTest extends ContainmentTest
- {
- // see:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330207#c1
- @Override
- public void testModeledBackPointer_Transient() throws Exception
- {
- }
-
- // see:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330207#c1
- @Override
- public void testModeledBackPointer_Transient_Load() throws Exception
- {
- }
- }
-
- // overridden because Hibernate will treat all stale references as an exception
- public static class Hibernate_Bugzilla_279982_Test extends Bugzilla_279982_Test
- {
- @Override
- public void testBugzilla_279982_Single() throws Exception
- {
- try
- {
- super.testBugzilla_279982_Single();
- }
- catch (Exception e)
- {
- assertEquals(true, e instanceof CommitException);
- assertEquals(true, e.getMessage().contains("org.hibernate.ObjectNotFoundException"));
- }
- }
-
- @Override
- public void testBugzilla_279982_Multi_RevisionPrefetchingPolicy() throws Exception
- {
- try
- {
- super.testBugzilla_279982_Multi_RevisionPrefetchingPolicy();
- }
- catch (Exception e)
- {
- assertEquals(true, e instanceof CommitException);
- assertEquals(true, e.getMessage().contains("org.hibernate.ObjectNotFoundException"));
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.emf.cdo.tests.hibernate; + +import org.eclipse.emf.cdo.tests.AllConfigs; +import org.eclipse.emf.cdo.tests.AuditSameSessionTest; +import org.eclipse.emf.cdo.tests.AuditTest; +import org.eclipse.emf.cdo.tests.BranchingSameSessionTest; +import org.eclipse.emf.cdo.tests.BranchingTest; +import org.eclipse.emf.cdo.tests.BranchingWithCacheClearTest; +import org.eclipse.emf.cdo.tests.CommitInfoTest; +import org.eclipse.emf.cdo.tests.ComplexTest; +import org.eclipse.emf.cdo.tests.ContainmentTest; +import org.eclipse.emf.cdo.tests.ExternalReferenceTest; +import org.eclipse.emf.cdo.tests.LockingManagerRestartRepositoryTest; +import org.eclipse.emf.cdo.tests.LockingManagerRestartSessionTest; +import org.eclipse.emf.cdo.tests.LockingManagerRestartTransactionTest; +import org.eclipse.emf.cdo.tests.LockingManagerTest; +import org.eclipse.emf.cdo.tests.LockingNotificationsTest; +import org.eclipse.emf.cdo.tests.MEMStoreQueryTest; +import org.eclipse.emf.cdo.tests.MergingTest; +import org.eclipse.emf.cdo.tests.MultiValuedOfAttributeTest; +import org.eclipse.emf.cdo.tests.OCLQueryTest; +import org.eclipse.emf.cdo.tests.PartialCommitTest; +import org.eclipse.emf.cdo.tests.ResourceTest; +import org.eclipse.emf.cdo.tests.RevisionManagerClientSideTest; +import org.eclipse.emf.cdo.tests.RevisionManagerTest; +import org.eclipse.emf.cdo.tests.SetFeatureTest; +import org.eclipse.emf.cdo.tests.UnsetTest; +import org.eclipse.emf.cdo.tests.XATransactionTest; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_252214_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_258933_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_272861_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_273565_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_279982_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_283985_1_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_283985_2_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_308895_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_316444_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_319836_Test; +import org.eclipse.emf.cdo.tests.bugzilla.Bugzilla_322804_Test; +import org.eclipse.emf.cdo.tests.config.IScenario; +import org.eclipse.emf.cdo.tests.config.impl.ConfigTest; +import org.eclipse.emf.cdo.tests.config.impl.RepositoryConfig; +import org.eclipse.emf.cdo.util.CommitException; + +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * @author Eike Stepper + */ +public class AllTestsHibernate extends AllConfigs +{ + public static final RepositoryConfig HIBERNATE = HibernateConfig.INSTANCE; + + public static Test suite() + { + return new AllTestsHibernate().getTestSuite("CDO Tests (Hibernate)"); + } + + @Override + protected void initConfigSuites(TestSuite parent) + { + addScenario(parent, COMBINED, HIBERNATE, JVM, NATIVE); + } + + @Override + protected void initTestClasses(List<Class<? extends ConfigTest>> testClasses, IScenario scenario) + { + // testClasses.clear(); + // testClasses.add(HibernateTimeStampTest.class); + // if (true) + // { + // return; + // } + + testClasses.add(HibernateTimeStampTest.class); + testClasses.add(Hibernate_Bugzilla_279982_Test.class); + testClasses.add(Hibernate_ContainmentTest.class); + testClasses.add(HibernateXATransactionTest.class); + testClasses.add(Hibernate_Bugzilla_308895_Test.class); + testClasses.add(HibernateExternalAnnotationTest.class); + testClasses.add(HibernateMultiValuedOfAttributeTest.class); + testClasses.add(HibernateXATransactionTest.class); + testClasses.add(HibernateExternalReferenceTest.class); + testClasses.add(HibernateQueryTest.class); + testClasses.add(HibernateQueryNoCachingTest.class); + testClasses.add(HibernateBugzilla_258933_Test.class); + testClasses.add(HibernateUnsetTest.class); + testClasses.add(HibernateBugzilla_301104_Test.class); + testClasses.add(Hibernate_SetFeatureTest.class); + testClasses.add(Hibernate_ResourceTest.class); + testClasses.add(Hibernate_ComplexTest.class); + testClasses.add(Hibernate_PartialCommitTest.class); + testClasses.add(Hibernate_Bugzilla_316444_Test.class); + + super.initTestClasses(testClasses, scenario); + + // Teneo does not yet support lists of int arrays: + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330212 + testClasses.remove(Bugzilla_322804_Test.class); + + testClasses.remove(Bugzilla_279982_Test.class); + + // locking not supported + testClasses.remove(LockingManagerRestartRepositoryTest.class); + testClasses.remove(LockingManagerRestartSessionTest.class); + testClasses.remove(LockingManagerRestartTransactionTest.class); + testClasses.remove(LockingNotificationsTest.class); + testClasses.remove(LockingManagerRestartRepositoryTest.class); + + // are replaced by Hibernate specific ones, mostly + // to prevent tests doing move from one container to another + testClasses.remove(ContainmentTest.class); + testClasses.remove(ComplexTest.class); + testClasses.remove(ResourceTest.class); + testClasses.remove(SetFeatureTest.class); + testClasses.remove(PartialCommitTest.class); + testClasses.remove(Bugzilla_316444_Test.class); + testClasses.remove(Bugzilla_308895_Test.class); + + // contains a lot of containment move, which is not supported by Hibernate + testClasses.remove(Bugzilla_283985_1_Test.class); + testClasses.remove(Bugzilla_283985_2_Test.class); + testClasses.remove(Bugzilla_319836_Test.class); + + // OCL querying not supported + testClasses.remove(OCLQueryTest.class); + + // Backup not yet supported + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=339492 + // testClasses.remove(BackupTest.class); + + // Branching not supported + testClasses.remove(BranchingTest.class); + testClasses.remove(MergingTest.class); + testClasses.remove(BranchingSameSessionTest.class); + testClasses.remove(BranchingWithCacheClearTest.class); + testClasses.remove(RevisionManagerTest.class); + testClasses.remove(RevisionManagerClientSideTest.class); + + // Commit info not supported + testClasses.remove(CommitInfoTest.class); + + // Locking manager not supported + testClasses.remove(LockingManagerTest.class); + + // results in infinite loops it seems + // runs okay when run standalone + testClasses.remove(Bugzilla_273565_Test.class); + + // audit support to do + // bug 244141 + testClasses.remove(AuditTest.class); + testClasses.remove(AuditSameSessionTest.class); + testClasses.remove(Bugzilla_252214_Test.class); + + // replace a test with our local implementation: + // the MultiValueOfAttributeTest class has a method + // testListOfInteger which has a List with a null value + // this is not nicely supported by Hibernate + // therefore this step is removed + testClasses.remove(MultiValuedOfAttributeTest.class); + + // MemStore is not relevant + testClasses.remove(MEMStoreQueryTest.class); + + // replace test case to do external mapping + testClasses.remove(XATransactionTest.class); + + // replace test case with one, disabling some non working testcases + // see the HibernateExternalReferenceTest for a description + testClasses.remove(ExternalReferenceTest.class); + + // this testcases removes and creates a resource with the + // same path in one transaction, that's not supported + // by hibernate.. because of unique key constraints + testClasses.remove(Bugzilla_272861_Test.class); + + // override a testcase because the hibernate store + // has a different meaning of unset + testClasses.remove(Bugzilla_258933_Test.class); + + // remove as unsettable has to be re-visited for the hb store + // see bugzilla 298579 + testClasses.remove(UnsetTest.class); + } + + /** + * Overridden because one testcase does not pass as Hibernate currently does not store the isset boolean values in the + * database. + * + * @author Eike Stepper + */ + public static class HibernateUnsetTest extends UnsetTest + { + @Override + public void testUnsettableBaseTypeVsObjectType() + { + } + } + + /** + * @author Eike Stepper + */ + public static class Hibernate_Bugzilla_308895_Test extends Bugzilla_308895_Test + { + @Override + public void setUp() throws Exception + { + super.setUp(); + // final EAttribute att = getAtt(); + + // add a teneo annotation + // final EAnnotation eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation(); + // eAnnotation.setSource("teneo.jpa"); + // eAnnotation.getDetails().put("value", value) + // + // att.getEAnnotations().add(eAnnotation); + } + } + + // unsettable is hardly supported by the Hibernate Store + public static class Hibernate_SetFeatureTest extends SetFeatureTest + { + @Override + public void testUnsettableDateNoDefault_SetDefault() throws Exception + { + } + + @Override + public void testUnsettableStringNoDefault_SetDefault() throws Exception + { + } + } + + // disable some container move tests, containment move is not supported + // by hibernate + public static class Hibernate_ResourceTest extends ResourceTest + { + @Override + public void testChangePathFromDepth3ToDepth0() throws Exception + { + } + + @Override + public void testChangeResourceURI() throws Exception + { + } + + @Override + public void testChangeResourceFolderURI() throws Exception + { + } + } + + public static class Hibernate_ComplexTest extends ComplexTest + { + @Override + public void testMigrateContainmentMulti() + { + } + + } + + public static class Hibernate_PartialCommitTest extends PartialCommitTest + { + @Override + public void testMove() throws CommitException + { + } + + @Override + public void testDoubleMove() throws CommitException + { + } + } + + public static class Hibernate_Bugzilla_316444_Test extends Bugzilla_316444_Test + { + @Override + public void testLockParentWithEAttributeChange() throws Exception + { + } + + @Override + public void testMovingSubtree() throws Exception + { + } + + } + + public static class Hibernate_ContainmentTest extends ContainmentTest + { + // see: + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330207#c1 + @Override + public void testModeledBackPointer_Transient() throws Exception + { + } + + // see: + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=330207#c1 + @Override + public void testModeledBackPointer_Transient_Load() throws Exception + { + } + } + + // overridden because Hibernate will treat all stale references as an exception + public static class Hibernate_Bugzilla_279982_Test extends Bugzilla_279982_Test + { + @Override + public void testBugzilla_279982_Single() throws Exception + { + try + { + super.testBugzilla_279982_Single(); + } + catch (Exception e) + { + assertEquals(true, e instanceof CommitException); + assertEquals(true, e.getMessage().contains("org.hibernate.ObjectNotFoundException")); + } + } + + @Override + public void testBugzilla_279982_Multi_RevisionPrefetchingPolicy() throws Exception + { + try + { + super.testBugzilla_279982_Multi_RevisionPrefetchingPolicy(); + } + catch (Exception e) + { + assertEquals(true, e instanceof CommitException); + assertEquals(true, e.getMessage().contains("org.hibernate.ObjectNotFoundException")); + } + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.tests/src/org/eclipse/emf/cdo/tests/BackupTest.java b/plugins/org.eclipse.emf.cdo.tests/src/org/eclipse/emf/cdo/tests/BackupTest.java index 2da42aef2b..0acc33df5f 100644 --- a/plugins/org.eclipse.emf.cdo.tests/src/org/eclipse/emf/cdo/tests/BackupTest.java +++ b/plugins/org.eclipse.emf.cdo.tests/src/org/eclipse/emf/cdo/tests/BackupTest.java @@ -1,531 +1,531 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.emf.cdo.tests;
-
-import org.eclipse.emf.cdo.common.lob.CDOBlob;
-import org.eclipse.emf.cdo.common.lob.CDOClob;
-import org.eclipse.emf.cdo.eresource.CDOResource;
-import org.eclipse.emf.cdo.server.CDOServerExporter;
-import org.eclipse.emf.cdo.server.CDOServerImporter;
-import org.eclipse.emf.cdo.session.CDOSession;
-import org.eclipse.emf.cdo.spi.server.InternalRepository;
-import org.eclipse.emf.cdo.tests.bundle.OM;
-import org.eclipse.emf.cdo.tests.config.impl.ConfigTest.CleanRepositoriesBefore;
-import org.eclipse.emf.cdo.tests.model1.Customer;
-import org.eclipse.emf.cdo.tests.model1.PurchaseOrder;
-import org.eclipse.emf.cdo.tests.model1.SalesOrder;
-import org.eclipse.emf.cdo.tests.model3.File;
-import org.eclipse.emf.cdo.tests.model3.Image;
-import org.eclipse.emf.cdo.tests.model3.Point;
-import org.eclipse.emf.cdo.tests.model3.Polygon;
-import org.eclipse.emf.cdo.tests.model5.Doctor;
-import org.eclipse.emf.cdo.tests.model5.TestFeatureMap;
-import org.eclipse.emf.cdo.transaction.CDOTransaction;
-import org.eclipse.emf.cdo.util.CommitException;
-import org.eclipse.emf.cdo.view.CDOView;
-
-import org.eclipse.net4j.util.io.IOUtil;
-
-import org.eclipse.emf.common.util.TreeIterator;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Date;
-
-/**
- * @author Eike Stepper
- */
-@CleanRepositoriesBefore
-public class BackupTest extends AbstractCDOTest
-{
- @Override
- protected void doSetUp() throws Exception
- {
- disableConsole();
- super.doSetUp();
- skipStoreWithoutRawAccess();
- }
-
- @Override
- protected void doTearDown() throws Exception
- {
- disableConsole();
- super.doTearDown();
- }
-
- public void testExport() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(createCustomer("Eike"));
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportDate() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- PurchaseOrder purchaseOrder = getModel1Factory().createPurchaseOrder();
- purchaseOrder.setDate(new Date(1234567));
- resource.getContents().add(purchaseOrder);
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportBlob() throws Exception
- {
- InputStream blobStream = null;
-
- try
- {
- blobStream = OM.BUNDLE.getInputStream("copyright.txt");
- CDOBlob blob = new CDOBlob(blobStream);
-
- Image image = getModel3Factory().createImage();
- image.setWidth(320);
- image.setHeight(200);
- image.setData(blob);
-
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(image);
- transaction.commit();
- }
- finally
- {
- IOUtil.close(blobStream);
- }
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportClob() throws Exception
- {
- InputStream clobStream = null;
-
- try
- {
- clobStream = OM.BUNDLE.getInputStream("copyright.txt");
- CDOClob clob = new CDOClob(new InputStreamReader(clobStream));
-
- File file = getModel3Factory().createFile();
- file.setName("copyright.txt");
- file.setData(clob);
-
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(file);
- transaction.commit();
- }
- finally
- {
- IOUtil.close(clobStream);
- }
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportCustomDataType() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(createPoligon(new Point(1, 2), new Point(3, 1), new Point(4, 5)));
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportFeatureMap() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
-
- addFeatureMap(resource);
-
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- public void testExportExternalReference() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
-
- ResourceSet resourceSet = transaction.getResourceSet();
- Customer customer = initExtResource(resourceSet);
-
- SalesOrder salesOrder = getModel1Factory().createSalesOrder();
- salesOrder.setCustomer(customer);
- resource.getContents().add(salesOrder);
-
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
- }
-
- private void useAfterImport(String repoName) throws CommitException
- {
- CDOSession session2 = openSession(repoName);
- CDOTransaction transaction2 = session2.openTransaction();
-
- // Read all repo contents
- TreeIterator<EObject> iter = transaction2.getRootResource().getAllContents();
- while (iter.hasNext())
- {
- iter.next();
- }
-
- // Add content from a new package
- CDOResource resource = transaction2.createResource("/r1");
- resource.getContents().add(getModel3Factory().createPolygon());
- transaction2.commit();
-
- session2.close();
- }
-
- /**
- * TODO
- * {@link org.eclipse.emf.cdo.server.IStoreAccessor.Raw#rawStore(org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision, org.eclipse.net4j.util.om.monitor.OMMonitor)
- * rawStore()} is not adequate with range-based list mappings because they need deltas!
- */
- @Skips("DB.ranges")
- public void testImport() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- Customer eike = createCustomer("Eike");
- resource.getContents().add(eike);
- resource.getContents().add(createCustomer("Jos"));
- resource.getContents().add(createCustomer("Simon"));
- transaction.commit();
- SalesOrder salesOrder = createSalesOrder(eike);
- salesOrder.getOrderDetails().add(getModel1Factory().createOrderDetail());
- resource.getContents().add(salesOrder);
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
-
- useAfterImport("repo2");
- }
-
- public void testImportDate() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- PurchaseOrder purchaseOrder = getModel1Factory().createPurchaseOrder();
- purchaseOrder.setDate(new Date(1234567));
- resource.getContents().add(purchaseOrder);
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
- }
-
- public void testImportBlob() throws Exception
- {
- InputStream blobStream = null;
-
- try
- {
- blobStream = OM.BUNDLE.getInputStream("copyright.txt");
- CDOBlob blob = new CDOBlob(blobStream);
-
- Image image = getModel3Factory().createImage();
- image.setWidth(320);
- image.setHeight(200);
- image.setData(blob);
-
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(image);
- transaction.commit();
- }
- finally
- {
- IOUtil.close(blobStream);
- }
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
- }
-
- public void testImportClob() throws Exception
- {
- InputStream clobStream = null;
-
- try
- {
- clobStream = OM.BUNDLE.getInputStream("copyright.txt");
- CDOClob clob = new CDOClob(new InputStreamReader(clobStream));
-
- File file = getModel3Factory().createFile();
- file.setName("copyright.txt");
- file.setData(clob);
-
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(file);
- transaction.commit();
- }
- finally
- {
- IOUtil.close(clobStream);
- }
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
- }
-
- public void testImportCustomDataType() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
- resource.getContents().add(createPoligon(new Point(1, 2), new Point(3, 1), new Point(4, 5)));
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
- }
-
- public void testImportFeatureMap() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
-
- addFeatureMap(resource);
-
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
- }
-
- public void testImportExternalReference() throws Exception
- {
- CDOSession session = openSession();
- CDOTransaction transaction = session.openTransaction();
- CDOResource resource = transaction.createResource(getResourcePath("/res1"));
-
- ResourceSet resourceSet = transaction.getResourceSet();
- Customer customer = initExtResource(resourceSet);
-
- SalesOrder salesOrder = getModel1Factory().createSalesOrder();
- salesOrder.setCustomer(customer);
- resource.getContents().add(salesOrder);
-
- transaction.commit();
- session.close();
-
- InternalRepository repo1 = getRepository();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1);
- exporter.exportRepository(baos);
- System.out.println(baos.toString());
-
- InternalRepository repo2 = getRepository("repo2", false);
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2);
- importer.importRepository(bais);
-
- CDOSession session2 = openSession("repo2");
- CDOView view2 = session2.openView();
- CDOResource resource2 = view2.getResource(getResourcePath("/res1"));
-
- ResourceSet resourceSet2 = view2.getResourceSet();
- initExtResource(resourceSet2);
-
- SalesOrder salesOrder2 = (SalesOrder)resource2.getContents().get(0);
- Customer customer2 = salesOrder2.getCustomer();
- System.out.println(customer2);
- }
-
- private Customer initExtResource(ResourceSet resourceSet)
- {
- resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
- Resource extResource = resourceSet.createResource(URI.createURI("ext.xmi"));
-
- Customer customer = getModel1Factory().createCustomer();
- extResource.getContents().add(customer);
- return customer;
- }
-
- private Customer createCustomer(String name)
- {
- Customer customer = getModel1Factory().createCustomer();
- customer.setName(name);
- return customer;
- }
-
- private SalesOrder createSalesOrder(Customer customer)
- {
- SalesOrder salesOrder = getModel1Factory().createSalesOrder();
- salesOrder.setId(4711);
- salesOrder.setCustomer(customer);
- return salesOrder;
- }
-
- private Polygon createPoligon(Point... points)
- {
- Polygon polygon = getModel3Factory().createPolygon();
- for (Point point : points)
- {
- polygon.getPoints().add(point);
- }
-
- return polygon;
- }
-
- private void addFeatureMap(CDOResource resource)
- {
- Doctor doctor1 = getModel5Factory().createDoctor();
- Doctor doctor2 = getModel5Factory().createDoctor();
-
- resource.getContents().add(doctor1);
- resource.getContents().add(doctor2);
-
- TestFeatureMap featureMap = getModel5Factory().createTestFeatureMap();
- featureMap.getPeople().add(getModel5Package().getTestFeatureMap_Doctors(), doctor1);
- featureMap.getPeople().add(getModel5Package().getTestFeatureMap_Doctors(), doctor2);
-
- resource.getContents().add(featureMap);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.emf.cdo.tests; + +import org.eclipse.emf.cdo.common.lob.CDOBlob; +import org.eclipse.emf.cdo.common.lob.CDOClob; +import org.eclipse.emf.cdo.eresource.CDOResource; +import org.eclipse.emf.cdo.server.CDOServerExporter; +import org.eclipse.emf.cdo.server.CDOServerImporter; +import org.eclipse.emf.cdo.session.CDOSession; +import org.eclipse.emf.cdo.spi.server.InternalRepository; +import org.eclipse.emf.cdo.tests.bundle.OM; +import org.eclipse.emf.cdo.tests.config.impl.ConfigTest.CleanRepositoriesBefore; +import org.eclipse.emf.cdo.tests.model1.Customer; +import org.eclipse.emf.cdo.tests.model1.PurchaseOrder; +import org.eclipse.emf.cdo.tests.model1.SalesOrder; +import org.eclipse.emf.cdo.tests.model3.File; +import org.eclipse.emf.cdo.tests.model3.Image; +import org.eclipse.emf.cdo.tests.model3.Point; +import org.eclipse.emf.cdo.tests.model3.Polygon; +import org.eclipse.emf.cdo.tests.model5.Doctor; +import org.eclipse.emf.cdo.tests.model5.TestFeatureMap; +import org.eclipse.emf.cdo.transaction.CDOTransaction; +import org.eclipse.emf.cdo.util.CommitException; +import org.eclipse.emf.cdo.view.CDOView; + +import org.eclipse.net4j.util.io.IOUtil; + +import org.eclipse.emf.common.util.TreeIterator; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Date; + +/** + * @author Eike Stepper + */ +@CleanRepositoriesBefore +public class BackupTest extends AbstractCDOTest +{ + @Override + protected void doSetUp() throws Exception + { + disableConsole(); + super.doSetUp(); + skipStoreWithoutRawAccess(); + } + + @Override + protected void doTearDown() throws Exception + { + disableConsole(); + super.doTearDown(); + } + + public void testExport() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(createCustomer("Eike")); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportDate() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + PurchaseOrder purchaseOrder = getModel1Factory().createPurchaseOrder(); + purchaseOrder.setDate(new Date(1234567)); + resource.getContents().add(purchaseOrder); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportBlob() throws Exception + { + InputStream blobStream = null; + + try + { + blobStream = OM.BUNDLE.getInputStream("copyright.txt"); + CDOBlob blob = new CDOBlob(blobStream); + + Image image = getModel3Factory().createImage(); + image.setWidth(320); + image.setHeight(200); + image.setData(blob); + + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(image); + transaction.commit(); + } + finally + { + IOUtil.close(blobStream); + } + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportClob() throws Exception + { + InputStream clobStream = null; + + try + { + clobStream = OM.BUNDLE.getInputStream("copyright.txt"); + CDOClob clob = new CDOClob(new InputStreamReader(clobStream)); + + File file = getModel3Factory().createFile(); + file.setName("copyright.txt"); + file.setData(clob); + + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(file); + transaction.commit(); + } + finally + { + IOUtil.close(clobStream); + } + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportCustomDataType() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(createPoligon(new Point(1, 2), new Point(3, 1), new Point(4, 5))); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportFeatureMap() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + + addFeatureMap(resource); + + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + public void testExportExternalReference() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + + ResourceSet resourceSet = transaction.getResourceSet(); + Customer customer = initExtResource(resourceSet); + + SalesOrder salesOrder = getModel1Factory().createSalesOrder(); + salesOrder.setCustomer(customer); + resource.getContents().add(salesOrder); + + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + } + + private void useAfterImport(String repoName) throws CommitException + { + CDOSession session2 = openSession(repoName); + CDOTransaction transaction2 = session2.openTransaction(); + + // Read all repo contents + TreeIterator<EObject> iter = transaction2.getRootResource().getAllContents(); + while (iter.hasNext()) + { + iter.next(); + } + + // Add content from a new package + CDOResource resource = transaction2.createResource("/r1"); + resource.getContents().add(getModel3Factory().createPolygon()); + transaction2.commit(); + + session2.close(); + } + + /** + * TODO + * {@link org.eclipse.emf.cdo.server.IStoreAccessor.Raw#rawStore(org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision, org.eclipse.net4j.util.om.monitor.OMMonitor) + * rawStore()} is not adequate with range-based list mappings because they need deltas! + */ + @Skips("DB.ranges") + public void testImport() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + Customer eike = createCustomer("Eike"); + resource.getContents().add(eike); + resource.getContents().add(createCustomer("Jos")); + resource.getContents().add(createCustomer("Simon")); + transaction.commit(); + SalesOrder salesOrder = createSalesOrder(eike); + salesOrder.getOrderDetails().add(getModel1Factory().createOrderDetail()); + resource.getContents().add(salesOrder); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + + useAfterImport("repo2"); + } + + public void testImportDate() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + PurchaseOrder purchaseOrder = getModel1Factory().createPurchaseOrder(); + purchaseOrder.setDate(new Date(1234567)); + resource.getContents().add(purchaseOrder); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + } + + public void testImportBlob() throws Exception + { + InputStream blobStream = null; + + try + { + blobStream = OM.BUNDLE.getInputStream("copyright.txt"); + CDOBlob blob = new CDOBlob(blobStream); + + Image image = getModel3Factory().createImage(); + image.setWidth(320); + image.setHeight(200); + image.setData(blob); + + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(image); + transaction.commit(); + } + finally + { + IOUtil.close(blobStream); + } + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + } + + public void testImportClob() throws Exception + { + InputStream clobStream = null; + + try + { + clobStream = OM.BUNDLE.getInputStream("copyright.txt"); + CDOClob clob = new CDOClob(new InputStreamReader(clobStream)); + + File file = getModel3Factory().createFile(); + file.setName("copyright.txt"); + file.setData(clob); + + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(file); + transaction.commit(); + } + finally + { + IOUtil.close(clobStream); + } + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + } + + public void testImportCustomDataType() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + resource.getContents().add(createPoligon(new Point(1, 2), new Point(3, 1), new Point(4, 5))); + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + } + + public void testImportFeatureMap() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + + addFeatureMap(resource); + + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + } + + public void testImportExternalReference() throws Exception + { + CDOSession session = openSession(); + CDOTransaction transaction = session.openTransaction(); + CDOResource resource = transaction.createResource(getResourcePath("/res1")); + + ResourceSet resourceSet = transaction.getResourceSet(); + Customer customer = initExtResource(resourceSet); + + SalesOrder salesOrder = getModel1Factory().createSalesOrder(); + salesOrder.setCustomer(customer); + resource.getContents().add(salesOrder); + + transaction.commit(); + session.close(); + + InternalRepository repo1 = getRepository(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CDOServerExporter.XML exporter = new CDOServerExporter.XML(repo1); + exporter.exportRepository(baos); + System.out.println(baos.toString()); + + InternalRepository repo2 = getRepository("repo2", false); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + CDOServerImporter.XML importer = new CDOServerImporter.XML(repo2); + importer.importRepository(bais); + + CDOSession session2 = openSession("repo2"); + CDOView view2 = session2.openView(); + CDOResource resource2 = view2.getResource(getResourcePath("/res1")); + + ResourceSet resourceSet2 = view2.getResourceSet(); + initExtResource(resourceSet2); + + SalesOrder salesOrder2 = (SalesOrder)resource2.getContents().get(0); + Customer customer2 = salesOrder2.getCustomer(); + System.out.println(customer2); + } + + private Customer initExtResource(ResourceSet resourceSet) + { + resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); + Resource extResource = resourceSet.createResource(URI.createURI("ext.xmi")); + + Customer customer = getModel1Factory().createCustomer(); + extResource.getContents().add(customer); + return customer; + } + + private Customer createCustomer(String name) + { + Customer customer = getModel1Factory().createCustomer(); + customer.setName(name); + return customer; + } + + private SalesOrder createSalesOrder(Customer customer) + { + SalesOrder salesOrder = getModel1Factory().createSalesOrder(); + salesOrder.setId(4711); + salesOrder.setCustomer(customer); + return salesOrder; + } + + private Polygon createPoligon(Point... points) + { + Polygon polygon = getModel3Factory().createPolygon(); + for (Point point : points) + { + polygon.getPoints().add(point); + } + + return polygon; + } + + private void addFeatureMap(CDOResource resource) + { + Doctor doctor1 = getModel5Factory().createDoctor(); + Doctor doctor2 = getModel5Factory().createDoctor(); + + resource.getContents().add(doctor1); + resource.getContents().add(doctor2); + + TestFeatureMap featureMap = getModel5Factory().createTestFeatureMap(); + featureMap.getPeople().add(getModel5Package().getTestFeatureMap_Doctors(), doctor1); + featureMap.getPeople().add(getModel5Package().getTestFeatureMap_Doctors(), doctor2); + + resource.getContents().add(featureMap); + } +} |