diff options
author | Martin Taal | 2012-05-21 04:39:02 +0000 |
---|---|---|
committer | Eike Stepper | 2012-05-21 04:39:02 +0000 |
commit | 840ae1d25617d61b8a72cdd6ae7be75aefc341a4 (patch) | |
tree | 5518b81bfc1c369b277faf83bc61ad386cb7211f /plugins/org.eclipse.emf.cdo.server.hibernate/src | |
parent | 4f25e989c838b93a714efb3e6e61dccf85b00252 (diff) | |
download | cdo-840ae1d25617d61b8a72cdd6ae7be75aefc341a4.tar.gz cdo-840ae1d25617d61b8a72cdd6ae7be75aefc341a4.tar.xz cdo-840ae1d25617d61b8a72cdd6ae7be75aefc341a4.zip |
[380042] [Hibernate] upgrade the CDO Hibernate Store to Teneo 2.0 and Hibernate 4.1
https://bugs.eclipse.org/bugs/show_bug.cgi?id=380042
Diffstat (limited to 'plugins/org.eclipse.emf.cdo.server.hibernate/src')
37 files changed, 5247 insertions, 5189 deletions
diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateCDOPackageUnitDTO.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateCDOPackageUnitDTO.java index 5772a54a06..0db766d833 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateCDOPackageUnitDTO.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateCDOPackageUnitDTO.java @@ -1,162 +1,166 @@ -/*
- * 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 and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate;
-
-import org.eclipse.emf.cdo.common.model.CDOModelUtil;
-import org.eclipse.emf.cdo.common.model.CDOPackageInfo;
-import org.eclipse.emf.cdo.common.model.CDOPackageUnit;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit;
-
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import org.hibernate.Hibernate;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.sql.Blob;
-
-/**
- * A DTO for convenience of storing a CDOPackageUnit in the db.
- *
- * @author Martin Taal
- */
-public class HibernateCDOPackageUnitDTO
-{
- private CDOPackageUnit.Type originalType;
-
- private long timeStamp;
-
- private InternalCDOPackageInfo[] packageInfos;
-
- private byte[] ePackageByteArray;
-
- public HibernateCDOPackageUnitDTO()
- {
- }
-
- public HibernateCDOPackageUnitDTO(CDOPackageUnit cdoPackageUnit)
- {
- setPackageInfos((InternalCDOPackageInfo[])cdoPackageUnit.getPackageInfos());
- setOriginalType(cdoPackageUnit.getOriginalType());
- setTimeStamp(cdoPackageUnit.getTimeStamp());
- }
-
- public CDOPackageUnit.Type getOriginalType()
- {
- return originalType;
- }
-
- public void setOriginalType(CDOPackageUnit.Type originalType)
- {
- this.originalType = originalType;
- }
-
- public long getTimeStamp()
- {
- return timeStamp;
- }
-
- public void setTimeStamp(long timeStamp)
- {
- this.timeStamp = timeStamp;
- }
-
- public InternalCDOPackageInfo[] getPackageInfos()
- {
- return packageInfos;
- }
-
- public void setPackageInfos(InternalCDOPackageInfo[] packageInfos)
- {
- this.packageInfos = packageInfos;
- }
-
- public byte[] getEPackageByteArray()
- {
- return ePackageByteArray;
- }
-
- public void setEPackageByteArray(byte[] ePackageByteArray)
- {
- this.ePackageByteArray = ePackageByteArray;
- }
-
- public void setEPackageBlob(Blob ePackageBlob)
- {
- ePackageByteArray = toByteArray(ePackageBlob);
- }
-
- private byte[] toByteArray(Blob blob)
- {
- try
- {
- final InputStream is = blob.getBinaryStream();
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- int dataSize;
- final byte[] buffer = new byte[4000];
-
- try
- {
- while ((dataSize = is.read(buffer)) != -1)
- {
- bos.write(buffer, 0, dataSize);
- }
- }
- finally
- {
- IOUtil.close(is);
- }
-
- return bos.toByteArray();
- }
- catch (Exception e)
- {
- throw WrappedException.wrap(e);
- }
- }
-
- @SuppressWarnings("deprecation")
- public Blob getEPackageBlob()
- {
- // deprecated usage, non-deprecated api uses a session
- // TODO: research which session to use
- return Hibernate.createBlob(getEPackageByteArray());
- }
-
- public InternalCDOPackageUnit createCDOPackageUnit(InternalCDOPackageRegistry packageRegistry)
- {
- InternalCDOPackageUnit packageUnit = (InternalCDOPackageUnit)CDOModelUtil.createPackageUnit();
- packageUnit.setOriginalType(originalType);
- packageUnit.setTimeStamp(timeStamp);
- packageUnit.setPackageRegistry(packageRegistry);
- packageUnit.setPackageInfos(packageInfos);
- for (CDOPackageInfo packageInfo : packageInfos)
- {
- ((InternalCDOPackageInfo)packageInfo).setPackageUnit(packageUnit);
- }
-
- return packageUnit;
- }
-
- public String getNsUri()
- {
- return getPackageInfos()[0].getPackageURI();
- }
-
- public void setNsUri(String nsUri)
- {
- // ignore
- }
-}
+/* + * 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 and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate; + +import org.eclipse.emf.cdo.common.model.CDOModelUtil; +import org.eclipse.emf.cdo.common.model.CDOPackageInfo; +import org.eclipse.emf.cdo.common.model.CDOPackageUnit; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; + +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.io.IOUtil; + +import org.hibernate.Session; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.sql.Blob; + +/** + * A DTO for convenience of storing a CDOPackageUnit in the db. + * + * @author Martin Taal + */ +public class HibernateCDOPackageUnitDTO +{ + private CDOPackageUnit.Type originalType; + + private long timeStamp; + + private InternalCDOPackageInfo[] packageInfos; + + private byte[] ePackageByteArray; + + private Blob ePackageBlob; + + public HibernateCDOPackageUnitDTO() + { + } + + public HibernateCDOPackageUnitDTO(CDOPackageUnit cdoPackageUnit) + { + setPackageInfos((InternalCDOPackageInfo[])cdoPackageUnit.getPackageInfos()); + setOriginalType(cdoPackageUnit.getOriginalType()); + setTimeStamp(cdoPackageUnit.getTimeStamp()); + } + + public CDOPackageUnit.Type getOriginalType() + { + return originalType; + } + + public void setOriginalType(CDOPackageUnit.Type originalType) + { + this.originalType = originalType; + } + + public long getTimeStamp() + { + return timeStamp; + } + + public void setTimeStamp(long timeStamp) + { + this.timeStamp = timeStamp; + } + + public InternalCDOPackageInfo[] getPackageInfos() + { + return packageInfos; + } + + public void setPackageInfos(InternalCDOPackageInfo[] packageInfos) + { + this.packageInfos = packageInfos; + } + + public byte[] getEPackageByteArray() + { + return ePackageByteArray; + } + + public void setEPackageByteArray(Session session, byte[] ePackageByteArray) + { + this.ePackageByteArray = ePackageByteArray; + ePackageBlob = session.getLobHelper().createBlob(ePackageByteArray); + } + + public void setEPackageBlob(Blob ePackageBlob) + { + ePackageByteArray = toByteArray(ePackageBlob); + } + + private byte[] toByteArray(Blob blob) + { + try + { + final InputStream is = blob.getBinaryStream(); + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int dataSize; + final byte[] buffer = new byte[4000]; + + try + { + while ((dataSize = is.read(buffer)) != -1) + { + bos.write(buffer, 0, dataSize); + } + } + finally + { + IOUtil.close(is); + } + + return bos.toByteArray(); + } + catch (Exception e) + { + throw WrappedException.wrap(e); + } + } + + /** + * NOTE: should not be called directly only by Hibernate when persisting + * use {@link #setEPackageByteArray(Session, byte[])} + */ + public Blob getEPackageBlob() + { + return ePackageBlob; + } + + public InternalCDOPackageUnit createCDOPackageUnit(InternalCDOPackageRegistry packageRegistry) + { + InternalCDOPackageUnit packageUnit = (InternalCDOPackageUnit)CDOModelUtil.createPackageUnit(); + packageUnit.setOriginalType(originalType); + packageUnit.setTimeStamp(timeStamp); + packageUnit.setPackageRegistry(packageRegistry); + packageUnit.setPackageInfos(packageInfos); + for (CDOPackageInfo packageInfo : packageInfos) + { + ((InternalCDOPackageInfo)packageInfo).setPackageUnit(packageUnit); + } + + return packageUnit; + } + + public String getNsUri() + { + return getPackageInfos()[0].getPackageURI(); + } + + public void setNsUri(String nsUri) + { + // ignore + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernatePackageHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernatePackageHandler.java index 031028834c..3d3b84cc91 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernatePackageHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernatePackageHandler.java @@ -1,508 +1,509 @@ -/*
- * 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 - moved code from HibernateStore to this class
- */
-package org.eclipse.emf.cdo.server.internal.hibernate;
-
-import org.eclipse.emf.cdo.common.model.CDOModelUtil;
-import org.eclipse.emf.cdo.common.model.EMFUtil;
-import org.eclipse.emf.cdo.server.IStoreAccessor.CommitContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;
-import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit;
-import org.eclipse.emf.cdo.spi.server.InternalRepository;
-
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.hibernate.tool.hbm2ddl.SchemaUpdate;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Delegate which stores and retrieves cdo packages.
- * <p>
- * TODO extend {@link Lifecycle}. See {@link #doActivate()} and {@link #doDeactivate()}.
- *
- * @author Eike Stepper
- * @author Martin Taal
- */
-public class HibernatePackageHandler extends Lifecycle
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernatePackageHandler.class);
-
- private static final boolean ZIP_PACKAGE_BYTES = true;
-
- private static final String CDO_PACKAGE_UNIT_ENTITY_NAME = "CDOPackageUnit"; //$NON-NLS-1$
-
- private static final String META_HBM_PATH = "mappings/meta.hbm.xml"; //$NON-NLS-1$
-
- private static final String HBM2DLL_UPDATE = "update"; //$NON-NLS-1$
-
- private static final String HBM2DLL_CREATE = "create"; //$NON-NLS-1$
-
- // made static and synchronized because apparently there can be multiple package handlers
- // in some test cases: TestExternalReferenceTest.testOneXMIResourceManyViewsOnOneResourceSet
- private static synchronized boolean writePackageUnits(InternalCDOPackageUnit[] packageUnits,
- SessionFactory sessionFactory, EPackage.Registry registry)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Persisting new EPackages"); //$NON-NLS-1$
- }
-
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- boolean err = true;
- boolean updated = false;
-
- try
- {
- // first store and update the packageunits and the epackages
- for (InternalCDOPackageUnit packageUnit : packageUnits)
- {
- final HibernateCDOPackageUnitDTO hbPackageUnitDTO = new HibernateCDOPackageUnitDTO(packageUnit);
-
- if (packageUnit.getPackageInfos().length > 0)
- {
- final String rootNSUri = packageUnit.getTopLevelPackageInfo().getPackageURI();
- final EPackage rootEPackage = registry.getEPackage(rootNSUri);
- hbPackageUnitDTO.setEPackageByteArray(EMFUtil.getEPackageBytes(rootEPackage, true, registry));
- }
-
- if (session.get(CDO_PACKAGE_UNIT_ENTITY_NAME, hbPackageUnitDTO.getNsUri()) == null)
- {
- session.saveOrUpdate(CDO_PACKAGE_UNIT_ENTITY_NAME, hbPackageUnitDTO);
- }
-
- updated = true;
- }
-
- tx.commit();
- err = false;
- }
- catch (Exception e)
- {
- e.printStackTrace(System.err);
- throw WrappedException.wrap(e);
- }
- finally
- {
- if (err)
- {
- tx.rollback();
- }
-
- session.close();
- }
-
- return updated;
- }
-
- private Configuration configuration;
-
- private SessionFactory sessionFactory;
-
- private int nextPackageID;
-
- private int nextClassID;
-
- private int nextFeatureID;
-
- private Collection<InternalCDOPackageUnit> packageUnits;
-
- private Map<String, byte[]> ePackageBlobsByRootUri = new HashMap<String, byte[]>();
-
- private Map<String, EPackage[]> ePackagesByRootUri = new HashMap<String, EPackage[]>();
-
- private HibernateStore hibernateStore;
-
- private boolean doDropSchema;
-
- /**
- * TODO Necessary to pass/store/dump the properties from the store?
- */
- public HibernatePackageHandler(HibernateStore store)
- {
- hibernateStore = store;
- }
-
- /**
- * @return the full list of EPackages registered in the PackageRegistry of the commit context as well as the EPackages
- * registered earlier.
- * @see CommitContext#getPackageRegistry()
- * @see InternalRepository#getPackageRegistry()
- */
- public List<EPackage> getEPackages()
- {
- List<EPackage> ePackages = new ArrayList<EPackage>();
- final InternalRepository localRepository = hibernateStore.getRepository();
-
- for (EPackage ePackage : localRepository.getPackageRegistry(false).getEPackages())
- {
- ePackages.add(ePackage);
- }
-
- for (EPackage ePackage : localRepository.getPackageRegistry(true).getEPackages())
- {
- boolean alreadyPresent = false;
- for (EPackage ePackagePresent : ePackages)
- {
- if (ePackagePresent.getNsURI().equals(ePackage.getNsURI()))
- {
- alreadyPresent = true;
- break;
- }
- }
-
- if (!alreadyPresent)
- {
- ePackages.add(ePackage);
- }
- }
-
- return ePackages;
- }
-
- private InternalCDOPackageRegistry getPackageRegistry()
- {
- return hibernateStore.getRepository().getPackageRegistry();
- }
-
- public void writePackageUnits(InternalCDOPackageUnit[] packageUnits)
- {
- final boolean updated = writePackageUnits(packageUnits, getSessionFactory(), getPackageRegistry());
- if (updated)
- {
- reset();
- hibernateStore.reInitialize();
- }
- }
-
- public Collection<InternalCDOPackageUnit> getPackageUnits()
- {
- readPackageUnits();
- return packageUnits;
- }
-
- public EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit)
- {
- final String nsUri = packageUnit.getTopLevelPackageInfo().getPackageURI();
- if (TRACER.isEnabled())
- {
- TRACER.trace("Reading EPackages with root uri " + nsUri + " from db"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- EPackage[] epacks = ePackagesByRootUri.get(nsUri);
- if (epacks == null)
- {
- final byte[] ePackageBlob = ePackageBlobsByRootUri.get(nsUri);
- if (ePackageBlob == null)
- {
- throw new IllegalArgumentException("EPackages with root uri " + nsUri + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- ResourceSet resourceSet = EMFUtil.newEcoreResourceSet(getPackageRegistry());
- final EPackage rootEPackage = EMFUtil.createEPackage(nsUri, ePackageBlob, ZIP_PACKAGE_BYTES, resourceSet, false);
- epacks = EMFUtil.getAllPackages(rootEPackage);
- ePackagesByRootUri.put(nsUri, epacks);
- }
-
- return epacks;
- }
-
- @SuppressWarnings("unchecked")
- protected void readPackageUnits()
- {
- if (packageUnits == null || packageUnits.size() == 0)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Reading Package Units from db"); //$NON-NLS-1$
- }
-
- Session session = getSessionFactory().openSession();
-
- try
- {
- Criteria criteria = session.createCriteria(CDO_PACKAGE_UNIT_ENTITY_NAME);
- List<?> list = criteria.list();
- if (TRACER.isEnabled())
- {
- TRACER.trace("Found " + list.size() + " CDOPackageUnits in DB"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- CDOModelUtil.createPackageUnit();
-
- packageUnits = new ArrayList<InternalCDOPackageUnit>();
- for (HibernateCDOPackageUnitDTO dto : (Collection<HibernateCDOPackageUnitDTO>)list)
- {
- packageUnits.add(dto.createCDOPackageUnit(getPackageRegistry()));
- // cache the blob because resolving the epackages right away gives errors
- ePackageBlobsByRootUri.put(dto.getNsUri(), dto.getEPackageByteArray());
- }
- }
- finally
- {
- session.close();
- }
- }
-
- if (TRACER.isEnabled())
- {
- TRACER.trace("Finished reading Package Units"); //$NON-NLS-1$
- }
- }
-
- public synchronized SessionFactory getSessionFactory()
- {
- if (sessionFactory == null)
- {
- sessionFactory = configuration.buildSessionFactory();
- }
-
- return sessionFactory;
- }
-
- public synchronized int getNextPackageID()
- {
- return nextPackageID++;
- }
-
- public synchronized int getNextClassID()
- {
- return nextClassID++;
- }
-
- public synchronized int getNextFeatureID()
- {
- return nextFeatureID++;
- }
-
- public void reset()
- {
- packageUnits = null;
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- initConfiguration();
- initSchema();
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- if (sessionFactory != null)
- {
- sessionFactory.close();
- sessionFactory = null;
- }
-
- if (doDropSchema)
- {
- final SchemaExport se = new SchemaExport(configuration);
- se.drop(false, true);
- }
-
- configuration = null;
- super.doDeactivate();
- }
-
- protected void initConfiguration()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Initializing configuration for CDO metadata"); //$NON-NLS-1$
- }
-
- InputStream in = null;
-
- try
- {
- in = OM.BUNDLE.getInputStream(META_HBM_PATH);
- configuration = new Configuration();
- configuration.addInputStream(in);
-
- // note this store adapts the properties so create a copy from the
- // one received from the hibernate store
- final Properties props = new Properties();
- props.putAll(hibernateStore.getProperties());
- configuration.setProperties(props);
-
- // prevent the drop at session factory close...
- // the drop is done by the de-activate
- if (configuration.getProperty(Environment.HBM2DDL_AUTO) != null
- && configuration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE))
- {
- doDropSchema = true;
- // note that the value create also re-creates the db and drops the old one
- configuration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
- }
- else
- {
- doDropSchema = false;
- }
- }
- catch (Exception ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- IOUtil.close(in);
- }
- }
-
- SystemInformation getSystemInformation()
- {
- Session session = getSessionFactory().openSession();
- session.beginTransaction();
- try
- {
- final Criteria c = session.createCriteria(SystemInformation.class);
- List<?> l = c.list();
- int records = l.size();
-
- final SystemInformation systemInformation;
- if (records == 0)
- {
- systemInformation = new SystemInformation();
- systemInformation.setFirstTime(true);
- systemInformation.setCreationTime(System.currentTimeMillis());
- session.save(systemInformation);
- }
- else if (records == 1)
- {
- systemInformation = (SystemInformation)l.get(0);
- systemInformation.setFirstTime(false);
- }
- else
- {
- throw new IllegalStateException("More than one record in the cdo_system_information table");
- }
-
- return systemInformation;
- }
- finally
- {
- session.getTransaction().commit();
- session.close();
- }
- }
-
- Map<String, String> getSystemProperties()
- {
- Session session = getSessionFactory().openSession();
- session.beginTransaction();
-
- try
- {
- final Map<String, String> result = new HashMap<String, String>();
- final Criteria c = session.createCriteria(SystemProperty.class);
- for (Object o : c.list())
- {
- final SystemProperty systemProperty = (SystemProperty)o;
- result.put(systemProperty.getName(), systemProperty.getValue());
- }
-
- return result;
- }
- finally
- {
- session.getTransaction().commit();
- session.close();
- }
- }
-
- void setSystemProperties(Map<String, String> properties)
- {
- Session session = getSessionFactory().openSession();
- session.beginTransaction();
-
- try
- {
- final Map<String, SystemProperty> currentValues = new HashMap<String, SystemProperty>();
- final Criteria c = session.createCriteria(SystemProperty.class);
- for (Object o : c.list())
- {
- final SystemProperty systemProperty = (SystemProperty)o;
- currentValues.put(systemProperty.getName(), systemProperty);
- }
-
- // update remove currentones
- final Map<String, String> newValues = new HashMap<String, String>();
- for (String key : properties.keySet())
- {
- if (currentValues.containsKey(key))
- {
- final SystemProperty systemProperty = currentValues.get(key);
- if (properties.get(key) == null)
- {
- session.delete(systemProperty);
- }
- else
- {
- systemProperty.setValue(properties.get(key));
- session.update(systemProperty);
- }
- }
- else
- {
- newValues.put(key, properties.get(key));
- }
- }
-
- // store the new ones
- for (String key : newValues.keySet())
- {
- final SystemProperty systemProperty = new SystemProperty();
- systemProperty.setName(key);
- systemProperty.setValue(newValues.get(key));
- session.save(systemProperty);
- }
- }
- finally
- {
- session.getTransaction().commit();
- session.close();
- }
- }
-
- protected void initSchema()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Updating db schema for Hibernate PackageHandler"); //$NON-NLS-1$
- }
-
- new SchemaUpdate(configuration).execute(true, true);
- }
-}
+/* + * 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 - moved code from HibernateStore to this class + */ +package org.eclipse.emf.cdo.server.internal.hibernate; + +import org.eclipse.emf.cdo.common.model.CDOModelUtil; +import org.eclipse.emf.cdo.common.model.EMFUtil; +import org.eclipse.emf.cdo.server.IStoreAccessor.CommitContext; +import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; +import org.eclipse.emf.cdo.spi.server.InternalRepository; + +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.lifecycle.Lifecycle; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.resource.ResourceSet; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.hbm2ddl.SchemaUpdate; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Delegate which stores and retrieves cdo packages. + * <p> + * TODO extend {@link Lifecycle}. See {@link #doActivate()} and {@link #doDeactivate()}. + * + * @author Eike Stepper + * @author Martin Taal + */ +public class HibernatePackageHandler extends Lifecycle +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernatePackageHandler.class); + + private static final boolean ZIP_PACKAGE_BYTES = true; + + private static final String CDO_PACKAGE_UNIT_ENTITY_NAME = "CDOPackageUnit"; //$NON-NLS-1$ + + private static final String META_HBM_PATH = "mappings/meta.hbm.xml"; //$NON-NLS-1$ + + private static final String HBM2DLL_UPDATE = "update"; //$NON-NLS-1$ + + private static final String HBM2DLL_CREATE = "create"; //$NON-NLS-1$ + + // made static and synchronized because apparently there can be multiple package handlers + // in some test cases: TestExternalReferenceTest.testOneXMIResourceManyViewsOnOneResourceSet + private static synchronized boolean writePackageUnits(InternalCDOPackageUnit[] packageUnits, + SessionFactory sessionFactory, EPackage.Registry registry) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Persisting new EPackages"); //$NON-NLS-1$ + } + + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + boolean err = true; + boolean updated = false; + + try + { + // first store and update the packageunits and the epackages + for (InternalCDOPackageUnit packageUnit : packageUnits) + { + final HibernateCDOPackageUnitDTO hbPackageUnitDTO = new HibernateCDOPackageUnitDTO(packageUnit); + + if (packageUnit.getPackageInfos().length > 0) + { + final String rootNSUri = packageUnit.getTopLevelPackageInfo().getPackageURI(); + final EPackage rootEPackage = registry.getEPackage(rootNSUri); + hbPackageUnitDTO.setEPackageByteArray(session, EMFUtil.getEPackageBytes(rootEPackage, true, registry)); + } + + if (session.get(CDO_PACKAGE_UNIT_ENTITY_NAME, hbPackageUnitDTO.getNsUri()) == null) + { + session.saveOrUpdate(CDO_PACKAGE_UNIT_ENTITY_NAME, hbPackageUnitDTO); + } + + updated = true; + } + + tx.commit(); + err = false; + } + catch (Exception e) + { + e.printStackTrace(System.err); + throw WrappedException.wrap(e); + } + finally + { + if (err) + { + tx.rollback(); + } + + session.close(); + } + + return updated; + } + + private Configuration configuration; + + private SessionFactory sessionFactory; + + private int nextPackageID; + + private int nextClassID; + + private int nextFeatureID; + + private Collection<InternalCDOPackageUnit> packageUnits; + + private Map<String, byte[]> ePackageBlobsByRootUri = new HashMap<String, byte[]>(); + + private Map<String, EPackage[]> ePackagesByRootUri = new HashMap<String, EPackage[]>(); + + private HibernateStore hibernateStore; + + private boolean doDropSchema; + + /** + * TODO Necessary to pass/store/dump the properties from the store? + */ + public HibernatePackageHandler(HibernateStore store) + { + hibernateStore = store; + } + + /** + * @return the full list of EPackages registered in the PackageRegistry of the commit context as well as the EPackages + * registered earlier. + * @see CommitContext#getPackageRegistry() + * @see InternalRepository#getPackageRegistry() + */ + public List<EPackage> getEPackages() + { + List<EPackage> ePackages = new ArrayList<EPackage>(); + final InternalRepository localRepository = hibernateStore.getRepository(); + + for (EPackage ePackage : localRepository.getPackageRegistry(false).getEPackages()) + { + ePackages.add(ePackage); + } + + for (EPackage ePackage : localRepository.getPackageRegistry(true).getEPackages()) + { + boolean alreadyPresent = false; + for (EPackage ePackagePresent : ePackages) + { + if (ePackagePresent.getNsURI().equals(ePackage.getNsURI())) + { + alreadyPresent = true; + break; + } + } + + if (!alreadyPresent) + { + ePackages.add(ePackage); + } + } + + return ePackages; + } + + private InternalCDOPackageRegistry getPackageRegistry() + { + return hibernateStore.getRepository().getPackageRegistry(); + } + + public void writePackageUnits(InternalCDOPackageUnit[] packageUnits) + { + final boolean updated = writePackageUnits(packageUnits, getSessionFactory(), getPackageRegistry()); + if (updated) + { + reset(); + hibernateStore.reInitialize(); + } + } + + public Collection<InternalCDOPackageUnit> getPackageUnits() + { + readPackageUnits(); + return packageUnits; + } + + public EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit) + { + final String nsUri = packageUnit.getTopLevelPackageInfo().getPackageURI(); + if (TRACER.isEnabled()) + { + TRACER.trace("Reading EPackages with root uri " + nsUri + " from db"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + EPackage[] epacks = ePackagesByRootUri.get(nsUri); + if (epacks == null) + { + final byte[] ePackageBlob = ePackageBlobsByRootUri.get(nsUri); + if (ePackageBlob == null) + { + throw new IllegalArgumentException("EPackages with root uri " + nsUri + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + ResourceSet resourceSet = EMFUtil.newEcoreResourceSet(getPackageRegistry()); + final EPackage rootEPackage = EMFUtil.createEPackage(nsUri, ePackageBlob, ZIP_PACKAGE_BYTES, resourceSet, false); + epacks = EMFUtil.getAllPackages(rootEPackage); + ePackagesByRootUri.put(nsUri, epacks); + } + + return epacks; + } + + @SuppressWarnings("unchecked") + protected void readPackageUnits() + { + if (packageUnits == null || packageUnits.size() == 0) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Reading Package Units from db"); //$NON-NLS-1$ + } + + Session session = getSessionFactory().openSession(); + + try + { + Criteria criteria = session.createCriteria(CDO_PACKAGE_UNIT_ENTITY_NAME); + List<?> list = criteria.list(); + if (TRACER.isEnabled()) + { + TRACER.trace("Found " + list.size() + " CDOPackageUnits in DB"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + CDOModelUtil.createPackageUnit(); + + packageUnits = new ArrayList<InternalCDOPackageUnit>(); + for (HibernateCDOPackageUnitDTO dto : (Collection<HibernateCDOPackageUnitDTO>)list) + { + packageUnits.add(dto.createCDOPackageUnit(getPackageRegistry())); + // cache the blob because resolving the epackages right away gives errors + ePackageBlobsByRootUri.put(dto.getNsUri(), dto.getEPackageByteArray()); + } + } + finally + { + session.close(); + } + } + + if (TRACER.isEnabled()) + { + TRACER.trace("Finished reading Package Units"); //$NON-NLS-1$ + } + } + + @SuppressWarnings("deprecation") + public synchronized SessionFactory getSessionFactory() + { + if (sessionFactory == null) + { + sessionFactory = configuration.buildSessionFactory(); + } + + return sessionFactory; + } + + public synchronized int getNextPackageID() + { + return nextPackageID++; + } + + public synchronized int getNextClassID() + { + return nextClassID++; + } + + public synchronized int getNextFeatureID() + { + return nextFeatureID++; + } + + public void reset() + { + packageUnits = null; + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + initConfiguration(); + initSchema(); + } + + @Override + protected void doDeactivate() throws Exception + { + if (sessionFactory != null) + { + sessionFactory.close(); + sessionFactory = null; + } + + if (doDropSchema) + { + final SchemaExport se = new SchemaExport(configuration); + se.drop(false, true); + } + + configuration = null; + super.doDeactivate(); + } + + protected void initConfiguration() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Initializing configuration for CDO metadata"); //$NON-NLS-1$ + } + + InputStream in = null; + + try + { + in = OM.BUNDLE.getInputStream(META_HBM_PATH); + configuration = new Configuration(); + configuration.addInputStream(in); + + // note this store adapts the properties so create a copy from the + // one received from the hibernate store + final Properties props = new Properties(); + props.putAll(hibernateStore.getProperties()); + configuration.setProperties(props); + + // prevent the drop at session factory close... + // the drop is done by the de-activate + if (configuration.getProperty(Environment.HBM2DDL_AUTO) != null + && configuration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE)) + { + doDropSchema = true; + // note that the value create also re-creates the db and drops the old one + configuration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE); + } + else + { + doDropSchema = false; + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + finally + { + IOUtil.close(in); + } + } + + SystemInformation getSystemInformation() + { + Session session = getSessionFactory().openSession(); + session.beginTransaction(); + try + { + final Criteria c = session.createCriteria(SystemInformation.class); + List<?> l = c.list(); + int records = l.size(); + + final SystemInformation systemInformation; + if (records == 0) + { + systemInformation = new SystemInformation(); + systemInformation.setFirstTime(true); + systemInformation.setCreationTime(System.currentTimeMillis()); + session.save(systemInformation); + } + else if (records == 1) + { + systemInformation = (SystemInformation)l.get(0); + systemInformation.setFirstTime(false); + } + else + { + throw new IllegalStateException("More than one record in the cdo_system_information table"); + } + + return systemInformation; + } + finally + { + session.getTransaction().commit(); + session.close(); + } + } + + Map<String, String> getSystemProperties() + { + Session session = getSessionFactory().openSession(); + session.beginTransaction(); + + try + { + final Map<String, String> result = new HashMap<String, String>(); + final Criteria c = session.createCriteria(SystemProperty.class); + for (Object o : c.list()) + { + final SystemProperty systemProperty = (SystemProperty)o; + result.put(systemProperty.getName(), systemProperty.getValue()); + } + + return result; + } + finally + { + session.getTransaction().commit(); + session.close(); + } + } + + void setSystemProperties(Map<String, String> properties) + { + Session session = getSessionFactory().openSession(); + session.beginTransaction(); + + try + { + final Map<String, SystemProperty> currentValues = new HashMap<String, SystemProperty>(); + final Criteria c = session.createCriteria(SystemProperty.class); + for (Object o : c.list()) + { + final SystemProperty systemProperty = (SystemProperty)o; + currentValues.put(systemProperty.getName(), systemProperty); + } + + // update remove currentones + final Map<String, String> newValues = new HashMap<String, String>(); + for (String key : properties.keySet()) + { + if (currentValues.containsKey(key)) + { + final SystemProperty systemProperty = currentValues.get(key); + if (properties.get(key) == null) + { + session.delete(systemProperty); + } + else + { + systemProperty.setValue(properties.get(key)); + session.update(systemProperty); + } + } + else + { + newValues.put(key, properties.get(key)); + } + } + + // store the new ones + for (String key : newValues.keySet()) + { + final SystemProperty systemProperty = new SystemProperty(); + systemProperty.setName(key); + systemProperty.setValue(newValues.get(key)); + session.save(systemProperty); + } + } + finally + { + session.getTransaction().commit(); + session.close(); + } + } + + protected void initSchema() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Updating db schema for Hibernate PackageHandler"); //$NON-NLS-1$ + } + + new SchemaUpdate(configuration).execute(true, true); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStore.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStore.java index 6078a0da97..d52939ac3d 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStore.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/HibernateStore.java @@ -1,580 +1,584 @@ -/*
- * 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 - moved cdopackage handler to other class, changed configuration
- */
-package org.eclipse.emf.cdo.server.internal.hibernate;
-
-import org.eclipse.emf.cdo.common.branch.CDOBranchPoint;
-import org.eclipse.emf.cdo.common.id.CDOID;
-import org.eclipse.emf.cdo.common.id.CDOID.ObjectType;
-import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
-import org.eclipse.emf.cdo.server.ISession;
-import org.eclipse.emf.cdo.server.ITransaction;
-import org.eclipse.emf.cdo.server.IView;
-import org.eclipse.emf.cdo.server.hibernate.IHibernateMappingProvider;
-import org.eclipse.emf.cdo.server.hibernate.IHibernateStore;
-import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDOInterceptor;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDOMergeEventListener;
-import org.eclipse.emf.cdo.spi.server.Store;
-import org.eclipse.emf.cdo.spi.server.StoreAccessorPool;
-
-import org.eclipse.net4j.db.DBException;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
-import org.eclipse.net4j.util.om.log.OMLogger;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import org.eclipse.emf.ecore.EAnnotation;
-import org.eclipse.emf.ecore.EClass;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.event.MergeEventListener;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.hibernate.type.StandardBasicTypes;
-
-import java.io.InputStream;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- * @author Martin Taal
- */
-public class HibernateStore extends Store implements IHibernateStore
-{
- public static final String TYPE = "hibernate"; //$NON-NLS-1$
-
- public static final String ID_TYPE_EANNOTATION_SOURCE = "teneo.cdo";
-
- public static final String ID_TYPE_EANNOTATION_KEY = "id_type";
-
- public static final Set<ObjectType> OBJECT_ID_TYPES = new HashSet<ObjectType>(Arrays.asList(
- CDOID.ObjectType.STRING_WITH_CLASSIFIER, CDOID.ObjectType.LONG_WITH_CLASSIFIER));
-
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernateStore.class);
-
- private static final String RESOURCE_HBM_PATH = "mappings/resource.hbm.xml"; //$NON-NLS-1$
-
- private static final String HBM2DLL_UPDATE = "update"; //$NON-NLS-1$
-
- private static final String HBM2DLL_CREATE = "create"; //$NON-NLS-1$
-
- /**
- * Used to give different extensions of Hibernate a context when initializing
- */
- private static ThreadLocal<HibernateStore> currentHibernateStore = new ThreadLocal<HibernateStore>();
-
- private Configuration hibernateConfiguration;
-
- private SessionFactory hibernateSessionFactory;
-
- private HibernatePackageHandler packageHandler;
-
- private IHibernateMappingProvider mappingProvider;
-
- private boolean doDropSchema;
-
- private SystemInformation systemInformation;
-
- private Map<String, EClass> entityNameToEClass;
-
- private Map<String, String> eClassToEntityName;
-
- private Map<String, String> identifierPropertyNameByEntity;
-
- private Properties properties;
-
- // is initialized on get
- private CDOBranchPoint mainBranchHead;
-
- private String mappingXml = null;
-
- public HibernateStore(IHibernateMappingProvider mappingProvider)
- {
- this(mappingProvider, null);
- }
-
- public HibernateStore(IHibernateMappingProvider mappingProvider, Properties properties)
- {
- super(TYPE, OBJECT_ID_TYPES, set(ChangeFormat.REVISION), set(RevisionTemporality.NONE),
- set(RevisionParallelism.NONE));
- this.mappingProvider = mappingProvider;
- packageHandler = new HibernatePackageHandler(this);
- this.properties = properties;
-
- if (TRACER.isEnabled() && mappingProvider != null)
- {
- TRACER.trace("HibernateStore with mappingProvider " + mappingProvider.getClass().getName()); //$NON-NLS-1$
- }
- }
-
- public CDOBranchPoint getMainBranchHead()
- {
- if (mainBranchHead == null)
- {
- mainBranchHead = getRepository().getBranchManager().getMainBranch().getHead();
- }
-
- return mainBranchHead;
- }
-
- public String getIdentifierPropertyName(String entityName)
- {
- return identifierPropertyNameByEntity.get(entityName);
- }
-
- public void addEntityNameEClassMapping(String entityName, EClass eClass)
- {
- if (entityNameToEClass.get(entityName) != null)
- {
- final EClass currentEClass = entityNameToEClass.get(entityName);
- throw new IllegalArgumentException("There is a entity name collision for EClasses " //$NON-NLS-1$
- + currentEClass.getEPackage().getName() + "." + currentEClass.getName() + "/" //$NON-NLS-1$ //$NON-NLS-2$
- + eClass.getEPackage().getName() + "." + eClass.getName()); //$NON-NLS-1$
- }
-
- entityNameToEClass.put(entityName, eClass);
- eClassToEntityName.put(eClass.getEPackage().getNsURI() + CDOClassifierRef.URI_SEPARATOR + eClass.getName(),
- entityName);
- }
-
- public Properties getProperties()
- {
- if (properties == null || properties.isEmpty())
- {
- properties = new Properties();
-
- final Map<String, String> storeProps = getRepository().getProperties();
- for (String key : storeProps.keySet())
- {
- properties.setProperty(key, storeProps.get(key));
- }
- }
-
- return properties;
- }
-
- public String getEntityName(EClass eClass)
- {
- if (eClass == null)
- {
- throw new IllegalArgumentException("EClass argument is null"); //$NON-NLS-1$
- }
-
- final String entityName = eClassToEntityName.get(eClass.getEPackage().getNsURI() + CDOClassifierRef.URI_SEPARATOR
- + eClass.getName());
- if (entityName == null)
- {
- throw new IllegalArgumentException("EClass " + eClass.getName() //$NON-NLS-1$
- + " does not have an entity name, has it been mapped to Hibernate?"); //$NON-NLS-1$
- }
-
- return entityName;
- }
-
- public String getEntityName(CDOClassifierRef classifierRef)
- {
- if (classifierRef == null)
- {
- throw new IllegalArgumentException("classifierRef argument is null"); //$NON-NLS-1$
- }
-
- final String entityName = eClassToEntityName.get(classifierRef.getPackageURI() + CDOClassifierRef.URI_SEPARATOR
- + classifierRef.getClassifierName());
- if (entityName == null)
- {
- throw new IllegalArgumentException("EClass " + classifierRef //$NON-NLS-1$
- + " does not have an entity name, has it been mapped to Hibernate?"); //$NON-NLS-1$
- }
-
- return entityName;
- }
-
- public EClass getEClass(String entityName)
- {
- if (entityName == null)
- {
- throw new IllegalArgumentException("entityname argument is null"); //$NON-NLS-1$
- }
-
- final EClass eClass = entityNameToEClass.get(entityName);
- if (eClass == null)
- {
- throw new IllegalArgumentException("entityname " + entityName //$NON-NLS-1$
- + " does not map to an EClass, has it been mapped to Hibernate?"); //$NON-NLS-1$
- }
-
- return eClass;
- }
-
- public Configuration getHibernateConfiguration()
- {
- return hibernateConfiguration;
- }
-
- public synchronized SessionFactory getHibernateSessionFactory()
- {
- if (hibernateSessionFactory == null)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Initializing SessionFactory for HibernateStore"); //$NON-NLS-1$
- }
-
- currentHibernateStore.set(this);
-
- entityNameToEClass = new HashMap<String, EClass>();
- eClassToEntityName = new HashMap<String, String>();
- identifierPropertyNameByEntity = new HashMap<String, String>();
-
- try
- {
- initConfiguration();
-
- // this has to be done before the classmapping is iterated
- // otherwise it is not initialized
- hibernateSessionFactory = hibernateConfiguration.buildSessionFactory();
-
- final Iterator<?> iterator = hibernateConfiguration.getClassMappings();
- while (iterator.hasNext())
- {
- final PersistentClass pc = (PersistentClass)iterator.next();
- if (pc.getIdentifierProperty() == null)
- {
- // happens for featuremaps for now...
- continue;
- }
-
- identifierPropertyNameByEntity.put(pc.getEntityName(), pc.getIdentifierProperty().getName());
- }
- }
- finally
- {
- currentHibernateStore.set(null);
- }
- }
-
- return hibernateSessionFactory;
- }
-
- public Connection getConnection()
- {
- String connectionURL = getProperties().getProperty("hibernate.connection.url");
- String userName = getProperties().getProperty("hibernate.connection.username");
- String passWord = getProperties().getProperty("hibernate.connection.password");
-
- try
- {
- Connection connection = DriverManager.getConnection(connectionURL, userName, passWord);
- if (connection == null)
- {
- throw new DBException("No connection from driver manager: " + connectionURL); //$NON-NLS-1$
- }
-
- String autoCommit = getProperties().getProperty("hibernate.connection.autocommit");
- if (autoCommit != null)
- {
- connection.setAutoCommit(Boolean.valueOf(autoCommit));
- }
-
- return connection;
- }
- catch (SQLException ex)
- {
- throw new DBException(ex);
- }
- }
-
- public boolean isLocal(CDOID id)
- {
- return false;
- }
-
- public CDOID createObjectID(String val)
- {
- final int index = val.lastIndexOf(CDOClassifierRef.URI_SEPARATOR);
- if (index == -1)
- {
- throw new IllegalArgumentException("Id string " + val + " is not a valid id");
- }
-
- final String uriPart = val.substring(0, index);
- final String idPart = val.substring(index + 1);
- final CDOClassifierRef classifierRef = new CDOClassifierRef(uriPart);
- final String entityName = getEntityName(classifierRef);
- final EClass eClass = getEClass(entityName);
- final EAnnotation typeEAnnotation = eClass.getEAnnotation(ID_TYPE_EANNOTATION_SOURCE);
- if (typeEAnnotation == null)
- {
- throw new IllegalStateException("EClass " + eClass + " does not have a type annotation");
- }
-
- final String idTypeStr = typeEAnnotation.getDetails().get(ID_TYPE_EANNOTATION_KEY);
- if (StandardBasicTypes.STRING.getName().equals(idTypeStr))
- {
- return HibernateUtil.getInstance().createCDOID(classifierRef, idPart);
- }
- else if (StandardBasicTypes.LONG.getName().equals(idTypeStr))
- {
- return HibernateUtil.getInstance().createCDOID(classifierRef, new Long(idPart));
- }
- else
- {
- throw new IllegalArgumentException("ID type " + idTypeStr + " not supported ");
- }
- }
-
- @Override
- public HibernateStoreAccessor createReader(ISession session)
- {
- return new HibernateStoreAccessor(this, session);
- }
-
- @Override
- public HibernateStoreAccessor createWriter(ITransaction transaction)
- {
- return new HibernateStoreAccessor(this, transaction);
- }
-
- public Map<String, String> getPersistentProperties(Set<String> names)
- {
- final Map<String, String> result = packageHandler.getSystemProperties();
- if (names == null || names.isEmpty())
- {
- return result;
- }
- final Map<String, String> filteredResult = new HashMap<String, String>();
- for (String name : names)
- {
- if (result.containsKey(name))
- {
- filteredResult.put(name, result.get(name));
- }
- }
- return filteredResult;
- }
-
- public void setPersistentProperties(Map<String, String> properties)
- {
- packageHandler.setSystemProperties(properties);
- }
-
- public void removePersistentProperties(Set<String> names)
- {
- final Map<String, String> props = getPersistentProperties(null);
- for (String name : names)
- {
- props.remove(name);
- }
- setPersistentProperties(props);
- }
-
- public synchronized int getNextPackageID()
- {
- return packageHandler.getNextPackageID();
- }
-
- public synchronized int getNextClassID()
- {
- return packageHandler.getNextClassID();
- }
-
- public synchronized int getNextFeatureID()
- {
- return packageHandler.getNextFeatureID();
- }
-
- public long getCreationTime()
- {
- return getSystemInformation().getCreationTime();
- }
-
- public void setCreationTime(long creationTime)
- {
- getSystemInformation().setCreationTime(creationTime);
- }
-
- public HibernatePackageHandler getPackageHandler()
- {
- return packageHandler;
- }
-
- // TODO: synchronize??
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- packageHandler.activate();
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- if (hibernateSessionFactory != null)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$
- }
-
- hibernateSessionFactory.close();
- hibernateSessionFactory = null;
- }
-
- // and now do the drop action
- if (doDropSchema)
- {
- final Configuration conf = getHibernateConfiguration();
- final SchemaExport se = new SchemaExport(conf);
- se.drop(false, true);
- }
-
- hibernateConfiguration = null;
- LifecycleUtil.deactivate(packageHandler, OMLogger.Level.WARN);
- super.doDeactivate();
- }
-
- @Override
- protected StoreAccessorPool getReaderPool(ISession session, boolean forReleasing)
- {
- // TODO Consider usings multiple pools for readers (e.g. bound to the session context)
- return null;
- }
-
- @Override
- protected StoreAccessorPool getWriterPool(IView view, boolean forReleasing)
- {
- // TODO Consider usings multiple pools for writers (e.g. bound to the session context)
- return null;
- }
-
- // is called after a new package has been added
- // TODO: synchronize??
- // TODO: combine with doActivate/doDeactivate??
- // TODO: assumes that packageHandler has been reset
- protected void reInitialize()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Re-Initializing HibernateStore"); //$NON-NLS-1$
- }
-
- if (hibernateSessionFactory != null)
- {
- if (!hibernateSessionFactory.isClosed())
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$
- }
-
- hibernateSessionFactory.close();
- }
-
- hibernateSessionFactory = null;
- }
- }
-
- protected void initConfiguration()
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Initializing Configuration"); //$NON-NLS-1$
- }
-
- InputStream in = null;
-
- try
- {
- hibernateConfiguration = new Configuration();
- if (mappingProvider != null)
- {
- mappingProvider.setHibernateStore(this);
- mappingXml = mappingProvider.getMapping();
- hibernateConfiguration.addXML(mappingXml);
- }
-
- if (TRACER.isEnabled())
- {
- TRACER.trace("Adding resource.hbm.xml to configuration"); //$NON-NLS-1$
- }
-
- in = OM.BUNDLE.getInputStream(RESOURCE_HBM_PATH);
- hibernateConfiguration.addInputStream(in);
- hibernateConfiguration.setInterceptor(new CDOInterceptor());
-
- hibernateConfiguration.getEventListeners().setMergeEventListeners(
- new MergeEventListener[] { new CDOMergeEventListener() });
-
- // make a local copy as it is adapted in the next if-statement
- // and we want to keep the original one untouched, if not
- // subsequent test runs will fail as they use the same
- // properties object
- final Properties props = new Properties();
- props.putAll(getProperties());
- hibernateConfiguration.setProperties(props);
-
- // prevent the drop on close because the sessionfactory is also closed when
- // new packages are written to the db, so only do a real drop at deactivate
- if (hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO) != null
- && hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE))
- {
- doDropSchema = true;
- // note that the value create also re-creates the db and drops the old one
- hibernateConfiguration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
- }
- else
- {
- doDropSchema = false;
- }
- }
- catch (Exception ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- IOUtil.close(in);
- }
- }
-
- public static HibernateStore getCurrentHibernateStore()
- {
- return currentHibernateStore.get();
- }
-
- public boolean isFirstStart()
- {
- return getSystemInformation().isFirstTime();
- }
-
- private SystemInformation getSystemInformation()
- {
- if (systemInformation == null)
- {
- systemInformation = getPackageHandler().getSystemInformation();
- }
-
- return systemInformation;
- }
-}
+/* + * 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 - moved cdopackage handler to other class, changed configuration + */ +package org.eclipse.emf.cdo.server.internal.hibernate; + +import org.eclipse.emf.cdo.common.branch.CDOBranchPoint; +import org.eclipse.emf.cdo.common.id.CDOID; +import org.eclipse.emf.cdo.common.id.CDOID.ObjectType; +import org.eclipse.emf.cdo.common.model.CDOClassifierRef; +import org.eclipse.emf.cdo.server.ISession; +import org.eclipse.emf.cdo.server.ITransaction; +import org.eclipse.emf.cdo.server.IView; +import org.eclipse.emf.cdo.server.hibernate.IHibernateMappingProvider; +import org.eclipse.emf.cdo.server.hibernate.IHibernateStore; +import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDOInterceptor; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDOMergeEventListener; +import org.eclipse.emf.cdo.spi.server.Store; +import org.eclipse.emf.cdo.spi.server.StoreAccessorPool; + +import org.eclipse.net4j.db.DBException; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.lifecycle.LifecycleUtil; +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EClass; + +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.event.service.spi.EventListenerRegistry; +import org.hibernate.event.spi.EventType; +import org.hibernate.internal.SessionFactoryImpl; +import org.hibernate.mapping.PersistentClass; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.type.StandardBasicTypes; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +/** + * @author Eike Stepper + * @author Martin Taal + */ +public class HibernateStore extends Store implements IHibernateStore +{ + public static final String TYPE = "hibernate"; //$NON-NLS-1$ + + public static final String ID_TYPE_EANNOTATION_SOURCE = "teneo.cdo"; + + public static final String ID_TYPE_EANNOTATION_KEY = "id_type"; + + public static final Set<ObjectType> OBJECT_ID_TYPES = new HashSet<ObjectType>(Arrays.asList( + CDOID.ObjectType.STRING_WITH_CLASSIFIER, CDOID.ObjectType.LONG_WITH_CLASSIFIER)); + + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, HibernateStore.class); + + private static final String RESOURCE_HBM_PATH = "mappings/resource.hbm.xml"; //$NON-NLS-1$ + + private static final String HBM2DLL_UPDATE = "update"; //$NON-NLS-1$ + + private static final String HBM2DLL_CREATE = "create"; //$NON-NLS-1$ + + /** + * Used to give different extensions of Hibernate a context when initializing + */ + private static ThreadLocal<HibernateStore> currentHibernateStore = new ThreadLocal<HibernateStore>(); + + private Configuration hibernateConfiguration; + + private SessionFactory hibernateSessionFactory; + + private HibernatePackageHandler packageHandler; + + private IHibernateMappingProvider mappingProvider; + + private boolean doDropSchema; + + private SystemInformation systemInformation; + + private Map<String, EClass> entityNameToEClass; + + private Map<String, String> eClassToEntityName; + + private Map<String, String> identifierPropertyNameByEntity; + + private Properties properties; + + // is initialized on get + private CDOBranchPoint mainBranchHead; + + private String mappingXml = null; + + public HibernateStore(IHibernateMappingProvider mappingProvider) + { + this(mappingProvider, null); + } + + public HibernateStore(IHibernateMappingProvider mappingProvider, Properties properties) + { + super(TYPE, OBJECT_ID_TYPES, set(ChangeFormat.REVISION), set(RevisionTemporality.NONE), + set(RevisionParallelism.NONE)); + this.mappingProvider = mappingProvider; + packageHandler = new HibernatePackageHandler(this); + this.properties = properties; + + if (TRACER.isEnabled() && mappingProvider != null) + { + TRACER.trace("HibernateStore with mappingProvider " + mappingProvider.getClass().getName()); //$NON-NLS-1$ + } + } + + public CDOBranchPoint getMainBranchHead() + { + if (mainBranchHead == null) + { + mainBranchHead = getRepository().getBranchManager().getMainBranch().getHead(); + } + + return mainBranchHead; + } + + public String getIdentifierPropertyName(String entityName) + { + return identifierPropertyNameByEntity.get(entityName); + } + + public void addEntityNameEClassMapping(String entityName, EClass eClass) + { + if (entityNameToEClass.get(entityName) != null) + { + final EClass currentEClass = entityNameToEClass.get(entityName); + throw new IllegalArgumentException("There is a entity name collision for EClasses " //$NON-NLS-1$ + + currentEClass.getEPackage().getName() + "." + currentEClass.getName() + "/" //$NON-NLS-1$ //$NON-NLS-2$ + + eClass.getEPackage().getName() + "." + eClass.getName()); //$NON-NLS-1$ + } + + entityNameToEClass.put(entityName, eClass); + eClassToEntityName.put(eClass.getEPackage().getNsURI() + CDOClassifierRef.URI_SEPARATOR + eClass.getName(), + entityName); + } + + public Properties getProperties() + { + if (properties == null || properties.isEmpty()) + { + properties = new Properties(); + + final Map<String, String> storeProps = getRepository().getProperties(); + for (String key : storeProps.keySet()) + { + properties.setProperty(key, storeProps.get(key)); + } + } + + return properties; + } + + public String getEntityName(EClass eClass) + { + if (eClass == null) + { + throw new IllegalArgumentException("EClass argument is null"); //$NON-NLS-1$ + } + + final String entityName = eClassToEntityName.get(eClass.getEPackage().getNsURI() + CDOClassifierRef.URI_SEPARATOR + + eClass.getName()); + if (entityName == null) + { + throw new IllegalArgumentException("EClass " + eClass.getName() //$NON-NLS-1$ + + " does not have an entity name, has it been mapped to Hibernate?"); //$NON-NLS-1$ + } + + return entityName; + } + + public String getEntityName(CDOClassifierRef classifierRef) + { + if (classifierRef == null) + { + throw new IllegalArgumentException("classifierRef argument is null"); //$NON-NLS-1$ + } + + final String entityName = eClassToEntityName.get(classifierRef.getPackageURI() + CDOClassifierRef.URI_SEPARATOR + + classifierRef.getClassifierName()); + if (entityName == null) + { + throw new IllegalArgumentException("EClass " + classifierRef //$NON-NLS-1$ + + " does not have an entity name, has it been mapped to Hibernate?"); //$NON-NLS-1$ + } + + return entityName; + } + + public EClass getEClass(String entityName) + { + if (entityName == null) + { + throw new IllegalArgumentException("entityname argument is null"); //$NON-NLS-1$ + } + + final EClass eClass = entityNameToEClass.get(entityName); + if (eClass == null) + { + throw new IllegalArgumentException("entityname " + entityName //$NON-NLS-1$ + + " does not map to an EClass, has it been mapped to Hibernate?"); //$NON-NLS-1$ + } + + return eClass; + } + + public Configuration getHibernateConfiguration() + { + return hibernateConfiguration; + } + + @SuppressWarnings("deprecation") + public synchronized SessionFactory getHibernateSessionFactory() + { + if (hibernateSessionFactory == null) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Initializing SessionFactory for HibernateStore"); //$NON-NLS-1$ + } + + currentHibernateStore.set(this); + + entityNameToEClass = new HashMap<String, EClass>(); + eClassToEntityName = new HashMap<String, String>(); + identifierPropertyNameByEntity = new HashMap<String, String>(); + + try + { + initConfiguration(); + + // this has to be done before the classmapping is iterated + // otherwise it is not initialized + hibernateSessionFactory = hibernateConfiguration.buildSessionFactory(); + ServiceRegistry serviceRegistry = ((SessionFactoryImpl)hibernateSessionFactory).getServiceRegistry(); + final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService(EventListenerRegistry.class); + eventListenerRegistry.setListeners(EventType.MERGE, new CDOMergeEventListener()); + + final Iterator<?> iterator = hibernateConfiguration.getClassMappings(); + while (iterator.hasNext()) + { + final PersistentClass pc = (PersistentClass)iterator.next(); + if (pc.getIdentifierProperty() == null) + { + // happens for featuremaps for now... + continue; + } + + identifierPropertyNameByEntity.put(pc.getEntityName(), pc.getIdentifierProperty().getName()); + } + } + finally + { + currentHibernateStore.set(null); + } + } + + return hibernateSessionFactory; + } + + public Connection getConnection() + { + String connectionURL = getProperties().getProperty("hibernate.connection.url"); + String userName = getProperties().getProperty("hibernate.connection.username"); + String passWord = getProperties().getProperty("hibernate.connection.password"); + + try + { + Connection connection = DriverManager.getConnection(connectionURL, userName, passWord); + if (connection == null) + { + throw new DBException("No connection from driver manager: " + connectionURL); //$NON-NLS-1$ + } + + String autoCommit = getProperties().getProperty("hibernate.connection.autocommit"); + if (autoCommit != null) + { + connection.setAutoCommit(Boolean.valueOf(autoCommit)); + } + + return connection; + } + catch (SQLException ex) + { + throw new DBException(ex); + } + } + + public boolean isLocal(CDOID id) + { + return false; + } + + public CDOID createObjectID(String val) + { + final int index = val.lastIndexOf(CDOClassifierRef.URI_SEPARATOR); + if (index == -1) + { + throw new IllegalArgumentException("Id string " + val + " is not a valid id"); + } + + final String uriPart = val.substring(0, index); + final String idPart = val.substring(index + 1); + final CDOClassifierRef classifierRef = new CDOClassifierRef(uriPart); + final String entityName = getEntityName(classifierRef); + final EClass eClass = getEClass(entityName); + final EAnnotation typeEAnnotation = eClass.getEAnnotation(ID_TYPE_EANNOTATION_SOURCE); + if (typeEAnnotation == null) + { + throw new IllegalStateException("EClass " + eClass + " does not have a type annotation"); + } + + final String idTypeStr = typeEAnnotation.getDetails().get(ID_TYPE_EANNOTATION_KEY); + if (StandardBasicTypes.STRING.getName().equals(idTypeStr)) + { + return HibernateUtil.getInstance().createCDOID(classifierRef, idPart); + } + else if (StandardBasicTypes.LONG.getName().equals(idTypeStr)) + { + return HibernateUtil.getInstance().createCDOID(classifierRef, new Long(idPart)); + } + else + { + throw new IllegalArgumentException("ID type " + idTypeStr + " not supported "); + } + } + + @Override + public HibernateStoreAccessor createReader(ISession session) + { + return new HibernateStoreAccessor(this, session); + } + + @Override + public HibernateStoreAccessor createWriter(ITransaction transaction) + { + return new HibernateStoreAccessor(this, transaction); + } + + public Map<String, String> getPersistentProperties(Set<String> names) + { + final Map<String, String> result = packageHandler.getSystemProperties(); + if (names == null || names.isEmpty()) + { + return result; + } + final Map<String, String> filteredResult = new HashMap<String, String>(); + for (String name : names) + { + if (result.containsKey(name)) + { + filteredResult.put(name, result.get(name)); + } + } + return filteredResult; + } + + public void setPersistentProperties(Map<String, String> properties) + { + packageHandler.setSystemProperties(properties); + } + + public void removePersistentProperties(Set<String> names) + { + final Map<String, String> props = getPersistentProperties(null); + for (String name : names) + { + props.remove(name); + } + setPersistentProperties(props); + } + + public synchronized int getNextPackageID() + { + return packageHandler.getNextPackageID(); + } + + public synchronized int getNextClassID() + { + return packageHandler.getNextClassID(); + } + + public synchronized int getNextFeatureID() + { + return packageHandler.getNextFeatureID(); + } + + public long getCreationTime() + { + return getSystemInformation().getCreationTime(); + } + + public void setCreationTime(long creationTime) + { + getSystemInformation().setCreationTime(creationTime); + } + + public HibernatePackageHandler getPackageHandler() + { + return packageHandler; + } + + // TODO: synchronize?? + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + packageHandler.activate(); + } + + @Override + protected void doDeactivate() throws Exception + { + if (hibernateSessionFactory != null) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$ + } + + hibernateSessionFactory.close(); + hibernateSessionFactory = null; + } + + // and now do the drop action + if (doDropSchema) + { + final Configuration conf = getHibernateConfiguration(); + final SchemaExport se = new SchemaExport(conf); + se.drop(false, true); + } + + hibernateConfiguration = null; + LifecycleUtil.deactivate(packageHandler, OMLogger.Level.WARN); + super.doDeactivate(); + } + + @Override + protected StoreAccessorPool getReaderPool(ISession session, boolean forReleasing) + { + // TODO Consider usings multiple pools for readers (e.g. bound to the session context) + return null; + } + + @Override + protected StoreAccessorPool getWriterPool(IView view, boolean forReleasing) + { + // TODO Consider usings multiple pools for writers (e.g. bound to the session context) + return null; + } + + // is called after a new package has been added + // TODO: synchronize?? + // TODO: combine with doActivate/doDeactivate?? + // TODO: assumes that packageHandler has been reset + protected void reInitialize() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Re-Initializing HibernateStore"); //$NON-NLS-1$ + } + + if (hibernateSessionFactory != null) + { + if (!hibernateSessionFactory.isClosed()) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$ + } + + hibernateSessionFactory.close(); + } + + hibernateSessionFactory = null; + } + } + + protected void initConfiguration() + { + if (TRACER.isEnabled()) + { + TRACER.trace("Initializing Configuration"); //$NON-NLS-1$ + } + + InputStream in = null; + + try + { + hibernateConfiguration = new Configuration(); + if (mappingProvider != null) + { + mappingProvider.setHibernateStore(this); + mappingXml = mappingProvider.getMapping(); + hibernateConfiguration.addXML(mappingXml); + } + + if (TRACER.isEnabled()) + { + TRACER.trace("Adding resource.hbm.xml to configuration"); //$NON-NLS-1$ + } + + in = OM.BUNDLE.getInputStream(RESOURCE_HBM_PATH); + hibernateConfiguration.addInputStream(in); + hibernateConfiguration.setInterceptor(new CDOInterceptor()); + + // make a local copy as it is adapted in the next if-statement + // and we want to keep the original one untouched, if not + // subsequent test runs will fail as they use the same + // properties object + final Properties props = new Properties(); + props.putAll(getProperties()); + hibernateConfiguration.setProperties(props); + + // prevent the drop on close because the sessionfactory is also closed when + // new packages are written to the db, so only do a real drop at deactivate + if (hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO) != null + && hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE)) + { + doDropSchema = true; + // note that the value create also re-creates the db and drops the old one + hibernateConfiguration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE); + } + else + { + doDropSchema = false; + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + finally + { + IOUtil.close(in); + } + } + + public static HibernateStore getCurrentHibernateStore() + { + return currentHibernateStore.get(); + } + + public boolean isFirstStart() + { + return getSystemInformation().isFirstTime(); + } + + private SystemInformation getSystemInformation() + { + if (systemInformation == null) + { + systemInformation = getPackageHandler().getSystemInformation(); + } + + return systemInformation; + } +} 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 befb139e90..4739a5c7d9 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 @@ -66,7 +66,6 @@ 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; @@ -973,7 +972,6 @@ public class HibernateStoreAccessor extends StoreAccessor implements IHibernateS } } - @SuppressWarnings("deprecation") @Override protected void writeBlob(byte[] id, long size, InputStream inputStream) throws IOException { @@ -986,14 +984,13 @@ public class HibernateStoreAccessor extends StoreAccessor implements IHibernateS { // deprecated usage, non-deprecated api uses a session // TODO: research which session to use - lob.setBlob(Hibernate.createBlob(inputStream, (int)size)); + lob.setBlob(getHibernateSession().getLobHelper().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 { @@ -1006,7 +1003,7 @@ public class HibernateStoreAccessor extends StoreAccessor implements IHibernateS { // deprecated usage, non-deprecated api uses a session // TODO: research which session to use - lob.setClob(Hibernate.createClob(reader, (int)size)); + lob.setClob(getHibernateSession().getLobHelper().createClob(reader, (int)size)); lob.setSize((int)size); lob.setBlob(null); getHibernateSession().saveOrUpdate(lob); diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOBranchTimeStampSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOBranchTimeStampSetter.java index 6221932b72..8fe521e32e 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOBranchTimeStampSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOBranchTimeStampSetter.java @@ -1,56 +1,56 @@ -/*
- * 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
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.server.internal.hibernate.CDOHibernateBranchPointImpl;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-/**
- * Sets the time stamp information in the revision.
- *
- * @see CDOHibernateBranchPointImpl
- * @author Martin Taal
- */
-public class CDOBranchTimeStampSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOBranchTimeStampSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- final InternalCDORevision revision = (InternalCDORevision)target;
- final long timeStamp;
- if (value == null)
- {
- timeStamp = 0;
- }
- else
- {
- timeStamp = (Long)value;
- }
- final CDOHibernateBranchPointImpl branchPoint = new CDOHibernateBranchPointImpl(timeStamp);
- revision.setBranchPoint(branchPoint);
- }
-
- @Override
- protected boolean isVirtualPropertyAllowed()
- {
- return true;
- }
-}
+/* + * 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 + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.server.internal.hibernate.CDOHibernateBranchPointImpl; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +/** + * Sets the time stamp information in the revision. + * + * @see CDOHibernateBranchPointImpl + * @author Martin Taal + */ +public class CDOBranchTimeStampSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOBranchTimeStampSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + final InternalCDORevision revision = (InternalCDORevision)target; + final long timeStamp; + if (value == null) + { + timeStamp = 0; + } + else + { + timeStamp = (Long)value; + } + final CDOHibernateBranchPointImpl branchPoint = new CDOHibernateBranchPointImpl(timeStamp); + revision.setBranchPoint(branchPoint); + } + + @Override + protected boolean isVirtualPropertyAllowed() + { + return true; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOContainerSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOContainerSetter.java index a795e51c0d..5c3ab686e4 100755 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOContainerSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOContainerSetter.java @@ -1,46 +1,46 @@ -/*
- * 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
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.server.internal.hibernate.ContainerInfoConverter;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-/**
- * Sets the container information from the String (stored in the db) back into the CDORevision.
- *
- * @see ContainerInfoConverter
- * @author Martin Taal
- */
-public class CDOContainerSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOContainerSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- final InternalCDORevision revision = (InternalCDORevision)target;
- ContainerInfoConverter.getInstance().setContainerRelationFromString(revision, (String)value);
- }
-
- @Override
- protected boolean isVirtualPropertyAllowed()
- {
- return true;
- }
-}
+/* + * 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 + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.server.internal.hibernate.ContainerInfoConverter; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +/** + * Sets the container information from the String (stored in the db) back into the CDORevision. + * + * @see ContainerInfoConverter + * @author Martin Taal + */ +public class CDOContainerSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOContainerSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + final InternalCDORevision revision = (InternalCDORevision)target; + ContainerInfoConverter.getInstance().setContainerRelationFromString(revision, (String)value); + } + + @Override + protected boolean isVirtualPropertyAllowed() + { + return true; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOCustomTypeUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOCustomTypeUserType.java index a878803f5b..4c859345f0 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOCustomTypeUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOCustomTypeUserType.java @@ -1,125 +1,128 @@ -/*
- * 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.hibernate.type.StandardBasicTypes;
-import org.hibernate.usertype.ParameterizedType;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.Properties;
-
-/**
- * Standard user type used for all custom types.
- */
-public class CDOCustomTypeUserType implements UserType, ParameterizedType
-{
- private static final int[] SQL_TYPES = { Types.VARCHAR };
-
- public void setParameterValues(Properties arg0)
- {
- }
-
- public Class<?> returnedClass()
- {
- return Object.class;
- }
-
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- public Object deepCopy(Object value)
- {
- return value;
- }
-
- public boolean equals(Object x, Object y)
- {
- if (x == y)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException
- {
- try
- {
- final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- return value;
- }
- catch (Exception e)
- {
- throw new IllegalStateException(e);
- }
- }
-
- public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException
- {
- try
- {
- if (value == null)
- {
- statement.setNull(index, Types.VARCHAR);
- return;
- }
- statement.setString(index, value.toString());
- }
- catch (Exception e)
- {
- throw new IllegalStateException(e);
- }
- }
-
- public Serializable disassemble(Object value)
- {
- return (Serializable)value;
- }
-
- public Object assemble(Serializable cachedValue, Object owner)
- {
- return cachedValue;
- }
-
- public Object replace(Object original, Object target, Object owner)
- {
- return original;
- }
-
- public int hashCode(Object x)
- {
- return x.hashCode();
- }
-}
+/* + * 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.hibernate.engine.spi.SessionImplementor; +import org.hibernate.type.StandardBasicTypes; +import org.hibernate.usertype.ParameterizedType; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Properties; + +/** + * Standard user type used for all custom types. + */ +public class CDOCustomTypeUserType implements UserType, ParameterizedType +{ + private static final int[] SQL_TYPES = { Types.VARCHAR }; + + public void setParameterValues(Properties arg0) + { + } + + public Class<?> returnedClass() + { + return Object.class; + } + + public int[] sqlTypes() + { + return SQL_TYPES; + } + + public boolean isMutable() + { + return false; + } + + public Object deepCopy(Object value) + { + return value; + } + + public boolean equals(Object x, Object y) + { + if (x == y) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + return x.equals(y); + } + + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException + { + try + { + final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0], sessionImplementor); + if (rs.wasNull()) + { + return null; + } + + return value; + } + catch (Exception e) + { + throw new IllegalStateException(e); + } + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException + { + try + { + if (value == null) + { + statement.setNull(index, Types.VARCHAR); + return; + } + statement.setString(index, value.toString()); + } + catch (Exception e) + { + throw new IllegalStateException(e); + } + } + + public Serializable disassemble(Object value) + { + return (Serializable)value; + } + + public Object assemble(Serializable cachedValue, Object owner) + { + return cachedValue; + } + + public Object replace(Object original, Object target, Object owner) + { + return original; + } + + public int hashCode(Object x) + { + return x.hashCode(); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumIntegerType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumIntegerType.java index 99a1c4f521..c8654894ba 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumIntegerType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumIntegerType.java @@ -1,90 +1,93 @@ -/*
- * 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 and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.common.util.Enumerator;
-
-import org.hibernate.HibernateException;
-
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.HashMap;
-
-/**
- * Implements the EMF UserType for an Enum in a dynamic model, for an integer field.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class CDOENumIntegerType extends CDOENumStringType
-{
- /** The sql types used for enums */
- private static final int[] SQL_TYPES = new int[] { Types.INTEGER };
-
- /** Hashmap with string to enum mappings */
- private final HashMap<Integer, Enumerator> localCache = new HashMap<Integer, Enumerator>();
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object)
- */
- @Override
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException
- {
- final int value = rs.getInt(names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- Integer objValue = new Integer(value);
- Enumerator enumValue = localCache.get(objValue);
- if (enumValue != null)
- {
- return enumValue.getValue();
- }
-
- enumValue = getEEnum().getEEnumLiteral(objValue.intValue());
- localCache.put(objValue, enumValue);
- return enumValue.getValue();
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int)
- */
- @Override
- public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException
- {
- if (value == null)
- {
- st.setNull(index, Types.INTEGER);
- }
-
- if (value instanceof Integer)
- {
- st.setInt(index, (Integer)value);
- }
- else
- {
- st.setInt(index, ((Enumerator)value).getValue());
- }
- }
-
- /** An enum is stored in one varchar */
- @Override
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-}
+/* + * 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 and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.common.util.Enumerator; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; + +/** + * Implements the EMF UserType for an Enum in a dynamic model, for an integer field. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class CDOENumIntegerType extends CDOENumStringType +{ + /** The sql types used for enums */ + private static final int[] SQL_TYPES = new int[] { Types.INTEGER }; + + /** Hashmap with string to enum mappings */ + private final HashMap<Integer, Enumerator> localCache = new HashMap<Integer, Enumerator>(); + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object) + */ + @Override + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws HibernateException, SQLException + { + final int value = rs.getInt(names[0]); + if (rs.wasNull()) + { + return null; + } + + Integer objValue = new Integer(value); + Enumerator enumValue = localCache.get(objValue); + if (enumValue != null) + { + return enumValue.getValue(); + } + + enumValue = getEEnum().getEEnumLiteral(objValue.intValue()); + localCache.put(objValue, enumValue); + return enumValue.getValue(); + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int) + */ + @Override + public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImplementor) + throws HibernateException, SQLException + { + if (value == null) + { + st.setNull(index, Types.INTEGER); + } + + if (value instanceof Integer) + { + st.setInt(index, (Integer)value); + } + else + { + st.setInt(index, ((Enumerator)value).getValue()); + } + } + + /** An enum is stored in one varchar */ + @Override + public int[] sqlTypes() + { + return SQL_TYPES; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumStringType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumStringType.java index 5e2bc0e682..90951aea72 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumStringType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOENumStringType.java @@ -1,243 +1,246 @@ -/*
- * 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 and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.model.CDOPackageRegistry;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-
-import org.eclipse.emf.common.util.Enumerator;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EEnum;
-import org.eclipse.emf.ecore.EEnumLiteral;
-import org.eclipse.emf.ecore.EPackage;
-
-import org.hibernate.HibernateException;
-import org.hibernate.usertype.ParameterizedType;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.HashMap;
-import java.util.Properties;
-
-/**
- * Implements the EMF UserType for an Enum
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class CDOENumStringType implements UserType, ParameterizedType
-{
- private static final String EPACKAGE_META = "epackage"; //$NON-NLS-1$
-
- private static final String ECLASSIFIER_META = "eclassifier"; //$NON-NLS-1$
-
- /** The sql types used for enums */
- private static final int[] SQL_TYPES = new int[] { Types.VARCHAR };
-
- /** The enum type we are handling here */
- protected EEnum eEnum;
-
- private String ePackageNsUri;
-
- private String eClassifierName;
-
- /** Hashmap with string to enum mappings */
- private final HashMap<String, Enumerator> localCache = new HashMap<String, Enumerator>();
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, java.lang.Object)
- */
- public Object assemble(Serializable cached, Object owner) throws HibernateException
- {
- return cached;
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object)
- */
- public Object deepCopy(Object value) throws HibernateException
- {
- return value;
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object)
- */
- public Serializable disassemble(Object value) throws HibernateException
- {
- return (Serializable)value;
- }
-
- /** Compares the int values of the enumerates */
- public boolean equals(Object x, Object y) throws HibernateException
- {
- // todo: check compare on null values
- if (x == null && y == null)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- if (x.getClass() != y.getClass())
- {
- return false;
- }
-
- if (x instanceof Integer && y instanceof Integer)
- {
- return ((Integer)x).intValue() == ((Integer)y).intValue();
- }
-
- if (x instanceof String && y instanceof String)
- {
- return ((String)x).equals(y);
- }
-
- return ((Enumerator)x).getValue() == ((Enumerator)y).getValue();
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object)
- */
- public int hashCode(Object x) throws HibernateException
- {
- return x.hashCode();
- }
-
- /** Not mutable */
- public boolean isMutable()
- {
- return false;
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object)
- */
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException
- {
- final String literal = rs.getString(names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- Enumerator enumValue = localCache.get(literal);
- if (enumValue != null)
- {
- return enumValue;
- }
-
- enumValue = getEEnum().getEEnumLiteralByLiteral(literal.trim());
- if (enumValue == null)
- {
- throw new IllegalStateException("The enum value " + literal + " is invalid for enumerator: " //$NON-NLS-1$ //$NON-NLS-2$
- + getEEnum().getName());
- }
-
- localCache.put(literal, enumValue);
- return enumValue;
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int)
- */
- public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException
- {
- if (value == null)
- {
- // st.setString(index, ((Enumerator)getEEnum().getDefaultValue()).getLiteral());
- st.setNull(index, Types.VARCHAR);
- }
- else
- {
- if (value instanceof Integer)
- {
- final EEnumLiteral literal = getEEnum().getEEnumLiteral((Integer)value);
- st.setString(index, literal.getLiteral());
- }
- else if (value instanceof String)
- {
- final EEnumLiteral literal = getEEnum().getEEnumLiteral((String)value);
- st.setString(index, literal.getLiteral());
- }
- else
- {
- st.setString(index, ((Enumerator)value).getLiteral());
- }
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.usertype.UserType#replace(java.lang.Object, java.lang.Object, java.lang.Object)
- */
- public Object replace(Object original, Object target, Object owner) throws HibernateException
- {
- return original;
- }
-
- /** Returns the parameterizezd enumType */
- public Class<?> returnedClass()
- {
- return getEEnum().getClass();
- }
-
- /** An enum is stored in one varchar */
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- protected EEnum getEEnum()
- {
- if (eEnum == null)
- {
- final CDOPackageRegistry packageRegistry = HibernateUtil.getInstance().getPackageRegistry();
- final EPackage ePackage = packageRegistry.getEPackage(ePackageNsUri);
- if (ePackage == null)
- {
- throw new IllegalStateException("EPackage with nsuri " + ePackageNsUri + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final EClassifier eClassifier = ePackage.getEClassifier(eClassifierName);
- if (eClassifier == null || !(eClassifier instanceof EEnum))
- {
- throw new IllegalStateException("EPackage " + ePackage.getName() + " does not have an EEnum with name " //$NON-NLS-1$ //$NON-NLS-2$
- + eClassifierName);
- }
-
- eEnum = (EEnum)eClassifier;
- }
-
- return eEnum;
- }
-
- /** Sets the enumclass */
- public void setParameterValues(Properties parameters)
- {
- ePackageNsUri = parameters.getProperty(EPACKAGE_META);
- eClassifierName = parameters.getProperty(ECLASSIFIER_META);
- }
-}
+/* + * 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 and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.model.CDOPackageRegistry; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; + +import org.eclipse.emf.common.util.Enumerator; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EPackage; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.usertype.ParameterizedType; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; +import java.util.Properties; + +/** + * Implements the EMF UserType for an Enum + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class CDOENumStringType implements UserType, ParameterizedType +{ + private static final String EPACKAGE_META = "epackage"; //$NON-NLS-1$ + + private static final String ECLASSIFIER_META = "eclassifier"; //$NON-NLS-1$ + + /** The sql types used for enums */ + private static final int[] SQL_TYPES = new int[] { Types.VARCHAR }; + + /** The enum type we are handling here */ + protected EEnum eEnum; + + private String ePackageNsUri; + + private String eClassifierName; + + /** Hashmap with string to enum mappings */ + private final HashMap<String, Enumerator> localCache = new HashMap<String, Enumerator>(); + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, java.lang.Object) + */ + public Object assemble(Serializable cached, Object owner) throws HibernateException + { + return cached; + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object) + */ + public Object deepCopy(Object value) throws HibernateException + { + return value; + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object) + */ + public Serializable disassemble(Object value) throws HibernateException + { + return (Serializable)value; + } + + /** Compares the int values of the enumerates */ + public boolean equals(Object x, Object y) throws HibernateException + { + // todo: check compare on null values + if (x == null && y == null) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + if (x.getClass() != y.getClass()) + { + return false; + } + + if (x instanceof Integer && y instanceof Integer) + { + return ((Integer)x).intValue() == ((Integer)y).intValue(); + } + + if (x instanceof String && y instanceof String) + { + return ((String)x).equals(y); + } + + return ((Enumerator)x).getValue() == ((Enumerator)y).getValue(); + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object) + */ + public int hashCode(Object x) throws HibernateException + { + return x.hashCode(); + } + + /** Not mutable */ + public boolean isMutable() + { + return false; + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object) + */ + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws HibernateException, SQLException + { + final String literal = rs.getString(names[0]); + if (rs.wasNull()) + { + return null; + } + + Enumerator enumValue = localCache.get(literal); + if (enumValue != null) + { + return enumValue; + } + + enumValue = getEEnum().getEEnumLiteralByLiteral(literal.trim()); + if (enumValue == null) + { + throw new IllegalStateException("The enum value " + literal + " is invalid for enumerator: " //$NON-NLS-1$ //$NON-NLS-2$ + + getEEnum().getName()); + } + + localCache.put(literal, enumValue); + return enumValue; + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int) + */ + public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImplementor) + throws HibernateException, SQLException + { + if (value == null) + { + // st.setString(index, ((Enumerator)getEEnum().getDefaultValue()).getLiteral()); + st.setNull(index, Types.VARCHAR); + } + else + { + if (value instanceof Integer) + { + final EEnumLiteral literal = getEEnum().getEEnumLiteral((Integer)value); + st.setString(index, literal.getLiteral()); + } + else if (value instanceof String) + { + final EEnumLiteral literal = getEEnum().getEEnumLiteral((String)value); + st.setString(index, literal.getLiteral()); + } + else + { + st.setString(index, ((Enumerator)value).getLiteral()); + } + } + } + + /* + * (non-Javadoc) + * @see org.hibernate.usertype.UserType#replace(java.lang.Object, java.lang.Object, java.lang.Object) + */ + public Object replace(Object original, Object target, Object owner) throws HibernateException + { + return original; + } + + /** Returns the parameterizezd enumType */ + public Class<?> returnedClass() + { + return getEEnum().getClass(); + } + + /** An enum is stored in one varchar */ + public int[] sqlTypes() + { + return SQL_TYPES; + } + + protected EEnum getEEnum() + { + if (eEnum == null) + { + final CDOPackageRegistry packageRegistry = HibernateUtil.getInstance().getPackageRegistry(); + final EPackage ePackage = packageRegistry.getEPackage(ePackageNsUri); + if (ePackage == null) + { + throw new IllegalStateException("EPackage with nsuri " + ePackageNsUri + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final EClassifier eClassifier = ePackage.getEClassifier(eClassifierName); + if (eClassifier == null || !(eClassifier instanceof EEnum)) + { + throw new IllegalStateException("EPackage " + ePackage.getName() + " does not have an EEnum with name " //$NON-NLS-1$ //$NON-NLS-2$ + + eClassifierName); + } + + eEnum = (EEnum)eClassifier; + } + + return eEnum; + } + + /** Sets the enumclass */ + public void setParameterValues(Properties parameters) + { + ePackageNsUri = parameters.getProperty(EPACKAGE_META); + eClassifierName = parameters.getProperty(ECLASSIFIER_META); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDAnyUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDAnyUserType.java index 551eb8cc3c..1de67ffd4f 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDAnyUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDAnyUserType.java @@ -1,149 +1,152 @@ -/*
- * 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.net4j.util.WrappedException;
-
-import org.hibernate.type.StandardBasicTypes;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.lang.reflect.Constructor;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.HashMap;
-
-/**
- * Persists a CDOID in the DB in the contents of a resource, a many-to-any mapping.
- */
-public class CDOIDAnyUserType implements UserType
-{
- private static final int[] SQL_TYPES = { Types.VARCHAR };
-
- private static final String SEPARATOR = "__;__"; //$NON-NLS-1$
-
- /** Constructor by id */
- private final HashMap<String, Constructor<?>> constructors = new HashMap<String, Constructor<?>>();
-
- public CDOIDAnyUserType()
- {
- }
-
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- public Class<?> returnedClass()
- {
- return CDOID.class;
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- public Object deepCopy(Object value)
- {
- return value;
- }
-
- public boolean equals(Object x, Object y)
- {
- if (x == y)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException
- {
- final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- final int end1 = value.indexOf(SEPARATOR);
- final int start2 = end1 + SEPARATOR.length();
-
- final String idStr = value.substring(0, end1);
- final String idClassName = value.substring(start2);
- final Serializable id = getId(idStr, idClassName);
- return id;
- }
-
- public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException
- {
- if (value == null || value instanceof CDOID && ((CDOID)value).isNull())
- {
- statement.setNull(index, Types.VARCHAR);
- }
- else
- {
- statement.setString(index, value.toString() + SEPARATOR + value.getClass().getName());
- }
- }
-
- public Serializable disassemble(Object value)
- {
- return (Serializable)value;
- }
-
- public Object assemble(Serializable cachedValue, Object owner)
- {
- return cachedValue;
- }
-
- public Object replace(Object original, Object target, Object owner)
- {
- return original;
- }
-
- public int hashCode(Object x)
- {
- return x.hashCode();
- }
-
- /** Creates an id object of the correct type */
- private Serializable getId(String idStr, String idType)
- {
- try
- {
- Constructor<?> constructor = constructors.get(idType);
- if (constructor == null)
- {
- final Class<?> idClass = Thread.currentThread().getContextClassLoader().loadClass(idType);
- constructor = idClass.getConstructor(new Class[] { String.class });
- constructors.put(idType, constructor);
- }
-
- return (Serializable)constructor.newInstance(new Object[] { idStr });
- }
- catch (Exception e)
- {
- throw WrappedException.wrap(e);
- }
- }
-}
+/* + * 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.net4j.util.WrappedException; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.type.StandardBasicTypes; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; + +/** + * Persists a CDOID in the DB in the contents of a resource, a many-to-any mapping. + */ +public class CDOIDAnyUserType implements UserType +{ + private static final int[] SQL_TYPES = { Types.VARCHAR }; + + private static final String SEPARATOR = "__;__"; //$NON-NLS-1$ + + /** Constructor by id */ + private final HashMap<String, Constructor<?>> constructors = new HashMap<String, Constructor<?>>(); + + public CDOIDAnyUserType() + { + } + + public int[] sqlTypes() + { + return SQL_TYPES; + } + + public Class<?> returnedClass() + { + return CDOID.class; + } + + public boolean isMutable() + { + return false; + } + + public Object deepCopy(Object value) + { + return value; + } + + public boolean equals(Object x, Object y) + { + if (x == y) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + return x.equals(y); + } + + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException + { + final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0], sessionImplementor); + if (rs.wasNull()) + { + return null; + } + + final int end1 = value.indexOf(SEPARATOR); + final int start2 = end1 + SEPARATOR.length(); + + final String idStr = value.substring(0, end1); + final String idClassName = value.substring(start2); + final Serializable id = getId(idStr, idClassName); + return id; + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException + { + if (value == null || value instanceof CDOID && ((CDOID)value).isNull()) + { + statement.setNull(index, Types.VARCHAR); + } + else + { + statement.setString(index, value.toString() + SEPARATOR + value.getClass().getName()); + } + } + + public Serializable disassemble(Object value) + { + return (Serializable)value; + } + + public Object assemble(Serializable cachedValue, Object owner) + { + return cachedValue; + } + + public Object replace(Object original, Object target, Object owner) + { + return original; + } + + public int hashCode(Object x) + { + return x.hashCode(); + } + + /** Creates an id object of the correct type */ + private Serializable getId(String idStr, String idType) + { + try + { + Constructor<?> constructor = constructors.get(idType); + if (constructor == null) + { + final Class<?> idClass = Thread.currentThread().getContextClassLoader().loadClass(idType); + constructor = idClass.getConstructor(new Class[] { String.class }); + constructors.put(idType, constructor); + } + + return (Serializable)constructor.newInstance(new Object[] { idStr }); + } + catch (Exception e) + { + throw WrappedException.wrap(e); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDExternalUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDExternalUserType.java index 6631b6872b..3c471c5f02 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDExternalUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDExternalUserType.java @@ -1,139 +1,142 @@ -/*
- * 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
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.id.CDOID;
-import org.eclipse.emf.cdo.common.id.CDOIDExternal;
-import org.eclipse.emf.cdo.common.id.CDOIDUtil;
-import org.eclipse.emf.cdo.common.revision.CDORevision;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-
-import org.hibernate.usertype.ParameterizedType;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.Properties;
-
-/**
- * A user type which can handle {@link CDOIDExternal}. It's stored in a single varchar field.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class CDOIDExternalUserType implements UserType, ParameterizedType
-{
- private static final int[] SQL_TYPES = { Types.VARCHAR };
-
- public CDOIDExternalUserType()
- {
- }
-
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- public Class<?> returnedClass()
- {
- return CDOID.class;
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- public Object deepCopy(Object value)
- {
- return value;
- }
-
- public boolean equals(Object x, Object y)
- {
- if (x == y)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws SQLException
- {
- final String data = resultSet.getString(names[0]);
- if (data == null)
- {
- return null;
- }
-
- return CDOIDUtil.createExternal(data);
- }
-
- public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException
- {
- if (value == null)
- {
- statement.setNull(index, Types.VARCHAR);
- return;
- }
-
- final Object localValue;
- if (value instanceof CDORevision)
- {
- localValue = HibernateUtil.getInstance().getCDOID(value);
- }
- else
- {
- localValue = value;
- }
-
- if (localValue instanceof CDOIDExternal)
- {
- statement.setString(index, ((CDOIDExternal)localValue).getURI());
- }
- else
- {
- throw new IllegalArgumentException("CDOID type " + localValue.getClass().getName() + " not supported here"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- public Serializable disassemble(Object value)
- {
- return (Serializable)value;
- }
-
- public Object assemble(Serializable cachedValue, Object owner)
- {
- return cachedValue;
- }
-
- public Object replace(Object original, Object target, Object owner)
- {
- return original;
- }
-
- public int hashCode(Object x)
- {
- return x.hashCode();
- }
-
- public void setParameterValues(Properties parameters)
- {
- }
-}
+/* + * 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 + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.id.CDOID; +import org.eclipse.emf.cdo.common.id.CDOIDExternal; +import org.eclipse.emf.cdo.common.id.CDOIDUtil; +import org.eclipse.emf.cdo.common.revision.CDORevision; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.usertype.ParameterizedType; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.Properties; + +/** + * A user type which can handle {@link CDOIDExternal}. It's stored in a single varchar field. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class CDOIDExternalUserType implements UserType, ParameterizedType +{ + private static final int[] SQL_TYPES = { Types.VARCHAR }; + + public CDOIDExternalUserType() + { + } + + public int[] sqlTypes() + { + return SQL_TYPES; + } + + public Class<?> returnedClass() + { + return CDOID.class; + } + + public boolean isMutable() + { + return false; + } + + public Object deepCopy(Object value) + { + return value; + } + + public boolean equals(Object x, Object y) + { + if (x == y) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + return x.equals(y); + } + + public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException + { + final String data = resultSet.getString(names[0]); + if (data == null) + { + return null; + } + + return CDOIDUtil.createExternal(data); + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException + { + if (value == null) + { + statement.setNull(index, Types.VARCHAR); + return; + } + + final Object localValue; + if (value instanceof CDORevision) + { + localValue = HibernateUtil.getInstance().getCDOID(value); + } + else + { + localValue = value; + } + + if (localValue instanceof CDOIDExternal) + { + statement.setString(index, ((CDOIDExternal)localValue).getURI()); + } + else + { + throw new IllegalArgumentException("CDOID type " + localValue.getClass().getName() + " not supported here"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + public Serializable disassemble(Object value) + { + return (Serializable)value; + } + + public Object assemble(Serializable cachedValue, Object owner) + { + return cachedValue; + } + + public Object replace(Object original, Object target, Object owner) + { + return original; + } + + public int hashCode(Object x) + { + return x.hashCode(); + } + + public void setParameterValues(Properties parameters) + { + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDPropertySetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDPropertySetter.java index 9f21e98d5a..a701d8eb2e 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDPropertySetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDPropertySetter.java @@ -1,93 +1,93 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * 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.id.CDOIDTemp;
-import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateCommitContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-import java.io.Serializable;
-
-/**
- * @author Martin Taal
- */
-public class CDOIDPropertySetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOIDPropertySetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- final InternalCDORevision revision = (InternalCDORevision)target;
- if (value == null)
- {
- if (getEStructuralFeature().isUnsettable())
- {
- revision.unset(getEStructuralFeature());
- }
-
- return;
- }
-
- final CDOID revisionID = HibernateUtil.getInstance().getCDOID(revision);
- if (revisionID == null || revisionID instanceof CDOIDTemp)
- {
- final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value);
- revision.setID(newCDOID);
- if (HibernateThreadContext.isCommitContextSet())
- {
- final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext();
- commitContext.setNewID(revisionID, newCDOID);
- if (revisionID instanceof CDOIDTemp)
- {
- commitContext.getCommitContext().addIDMapping(revisionID, newCDOID);
- }
- }
- }
- else
- {
- final Serializable idValue = HibernateUtil.getInstance().getIdValue(revisionID);
- if (idValue == null)
- {
- throw new IllegalStateException("ID value is null for revision " + revision); //$NON-NLS-1$
- }
-
- if (!idValue.equals(value))
- {
- throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- if (!isVirtualProperty())
- {
- super.set(target, value, factory);
- }
- }
-
- @Override
- protected boolean isVirtualPropertyAllowed()
- {
- return true;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * 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.id.CDOIDTemp; +import org.eclipse.emf.cdo.common.model.CDOClassifierRef; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateCommitContext; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +import java.io.Serializable; + +/** + * @author Martin Taal + */ +public class CDOIDPropertySetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOIDPropertySetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + final InternalCDORevision revision = (InternalCDORevision)target; + if (value == null) + { + if (getEStructuralFeature().isUnsettable()) + { + revision.unset(getEStructuralFeature()); + } + + return; + } + + final CDOID revisionID = HibernateUtil.getInstance().getCDOID(revision); + if (revisionID == null || revisionID instanceof CDOIDTemp) + { + final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value); + revision.setID(newCDOID); + if (HibernateThreadContext.isCommitContextSet()) + { + final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext(); + commitContext.setNewID(revisionID, newCDOID); + if (revisionID instanceof CDOIDTemp) + { + commitContext.getCommitContext().addIDMapping(revisionID, newCDOID); + } + } + } + else + { + final Serializable idValue = HibernateUtil.getInstance().getIdValue(revisionID); + if (idValue == null) + { + throw new IllegalStateException("ID value is null for revision " + revision); //$NON-NLS-1$ + } + + if (!idValue.equals(value)) + { + throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + if (!isVirtualProperty()) + { + super.set(target, value, factory); + } + } + + @Override + protected boolean isVirtualPropertyAllowed() + { + return true; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDUserType.java index 29a6d43215..f32f88e1d1 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOIDUserType.java @@ -1,136 +1,139 @@ -/*
- * 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.id.CDOIDExternal;
-import org.eclipse.emf.cdo.common.id.CDOIDTemp;
-import org.eclipse.emf.cdo.common.revision.CDORevision;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-
-import org.hibernate.type.StandardBasicTypes;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-/**
- * Persists a CDOID in the DB. Currently {@link CDOIDExternal} is supported.
- */
-public class CDOIDUserType implements UserType
-{
- private static final int[] SQL_TYPES = { Types.VARCHAR };
-
- public CDOIDUserType()
- {
- }
-
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- public Class<?> returnedClass()
- {
- return CDOID.class;
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- public Object deepCopy(Object value)
- {
- return value;
- }
-
- public boolean equals(Object x, Object y)
- {
- if (x == y)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException
- {
- final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- return HibernateUtil.getInstance().convertStringToCDOID(value);
- }
-
- public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException
- {
- if (value == null || value instanceof CDOID && ((CDOID)value).isNull())
- {
- statement.setNull(index, Types.VARCHAR);
- return;
- }
- else if (value instanceof CDOIDTemp)
- {
- // try to resolve the temp id
- final CDORevision revision = HibernateUtil.getInstance().getCDORevisionNullable((CDOID)value);
- if (revision != null)
- {
- value = HibernateUtil.getInstance().getCDOID(revision);
- }
- }
- else if (value instanceof CDORevision)
- {
- value = HibernateUtil.getInstance().getCDOIDHibernate((CDORevision)value);
- }
-
- final String strValue = HibernateUtil.getInstance().convertCDOIDToString((CDOID)value);
- if (strValue == null)
- {
- statement.setNull(index, Types.VARCHAR);
- return;
- }
-
- statement.setString(index, strValue);
- }
-
- public Serializable disassemble(Object value)
- {
- return (Serializable)value;
- }
-
- public Object assemble(Serializable cachedValue, Object owner)
- {
- return cachedValue;
- }
-
- public Object replace(Object original, Object target, Object owner)
- {
- return original;
- }
-
- public int hashCode(Object x)
- {
- return x.hashCode();
- }
-}
+/* + * 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.id.CDOIDExternal; +import org.eclipse.emf.cdo.common.id.CDOIDTemp; +import org.eclipse.emf.cdo.common.revision.CDORevision; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.type.StandardBasicTypes; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +/** + * Persists a CDOID in the DB. Currently {@link CDOIDExternal} is supported. + */ +public class CDOIDUserType implements UserType +{ + private static final int[] SQL_TYPES = { Types.VARCHAR }; + + public CDOIDUserType() + { + } + + public int[] sqlTypes() + { + return SQL_TYPES; + } + + public Class<?> returnedClass() + { + return CDOID.class; + } + + public boolean isMutable() + { + return false; + } + + public Object deepCopy(Object value) + { + return value; + } + + public boolean equals(Object x, Object y) + { + if (x == y) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + return x.equals(y); + } + + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException + { + final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0], sessionImplementor); + if (rs.wasNull()) + { + return null; + } + + return HibernateUtil.getInstance().convertStringToCDOID(value); + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException + { + if (value == null || value instanceof CDOID && ((CDOID)value).isNull()) + { + statement.setNull(index, Types.VARCHAR); + return; + } + else if (value instanceof CDOIDTemp) + { + // try to resolve the temp id + final CDORevision revision = HibernateUtil.getInstance().getCDORevisionNullable((CDOID)value); + if (revision != null) + { + value = HibernateUtil.getInstance().getCDOID(revision); + } + } + else if (value instanceof CDORevision) + { + value = HibernateUtil.getInstance().getCDOIDHibernate((CDORevision)value); + } + + final String strValue = HibernateUtil.getInstance().convertCDOIDToString((CDOID)value); + if (strValue == null) + { + statement.setNull(index, Types.VARCHAR); + return; + } + + statement.setString(index, strValue); + } + + public Serializable disassemble(Object value) + { + return (Serializable)value; + } + + public Object assemble(Serializable cachedValue, Object owner) + { + return cachedValue; + } + + public Object replace(Object original, Object target, Object owner) + { + return original; + } + + public int hashCode(Object x) + { + return x.hashCode(); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOLobUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOLobUserType.java index f9d9a5638d..94c00c4496 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOLobUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOLobUserType.java @@ -17,6 +17,7 @@ import org.eclipse.emf.cdo.common.lob.CDOLob; import org.eclipse.net4j.util.HexUtil; +import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.type.StandardBasicTypes; import org.hibernate.usertype.ParameterizedType; import org.hibernate.usertype.UserType; @@ -75,11 +76,12 @@ public abstract class CDOLobUserType implements UserType, ParameterizedType return x.equals(y); } - public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException { try { - final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0]); + final String value = StandardBasicTypes.STRING.nullSafeGet(rs, names[0], sessionImplementor); if (rs.wasNull()) { return null; @@ -93,7 +95,8 @@ public abstract class CDOLobUserType implements UserType, ParameterizedType } } - public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException { try { diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeGetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeGetter.java index 4b7260b753..751b665882 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeGetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeGetter.java @@ -1,77 +1,77 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.revision.CDOList;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.collection.PersistentCollection;
-
-/**
- * @author Martin Taal
- */
-// Howto handle hibernate lists:
-// - a new owner: the owner is persisted and its lists are replaced with hibernate
-// persistentlist, the hibernate persitentlist will have a delegate (internally) which is the list which was previously
-// present in the owner.
-// - an existing owner: the owner is read from the db and hibernate will set a persistentlist
-// directly
-//
-// The solution also needs to handle the following:
-// - cdo does not have direct java references but stores cdoids in the list while hibernate expects real java object
-// references.
-// - cdo uses a moveablearraylist and not the standard arraylist
-//
-// The solution:
-// - never return null when hibernate asks for the current value of the manyreference, always
-// return a MoveableArrayList so that hibernate uses that as the delegate, set the MoveableArrayList
-public class CDOManyAttributeGetter extends CDOPropertyGetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOManyAttributeGetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public Object get(Object target) throws HibernateException
- {
- // Check if there is already a persistentcollection
- PersistentCollection collection = PersistableListHolder.getInstance().getListMapping(target,
- getEStructuralFeature());
- if (collection != null)
- {
- return collection;
- }
-
- InternalCDORevision revision = (InternalCDORevision)target;
- CDOList list = revision.getList(getEStructuralFeature(), 10);
-
- if (list instanceof WrappedHibernateList)
- {
- final Object delegate = ((WrappedHibernateList)list).getDelegate();
- if (delegate instanceof PersistentCollection)
- {
- return delegate;
- }
- }
-
- // Wrap the moveablearraylist
- HibernateMoveableListWrapper wrapper = new HibernateMoveableListWrapper();
- wrapper.setDelegate(list);
-
- // And return it
- return wrapper;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.revision.CDOList; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.collection.spi.PersistentCollection; + +/** + * @author Martin Taal + */ +// Howto handle hibernate lists: +// - a new owner: the owner is persisted and its lists are replaced with hibernate +// persistentlist, the hibernate persitentlist will have a delegate (internally) which is the list which was previously +// present in the owner. +// - an existing owner: the owner is read from the db and hibernate will set a persistentlist +// directly +// +// The solution also needs to handle the following: +// - cdo does not have direct java references but stores cdoids in the list while hibernate expects real java object +// references. +// - cdo uses a moveablearraylist and not the standard arraylist +// +// The solution: +// - never return null when hibernate asks for the current value of the manyreference, always +// return a MoveableArrayList so that hibernate uses that as the delegate, set the MoveableArrayList +public class CDOManyAttributeGetter extends CDOPropertyGetter +{ + private static final long serialVersionUID = 1L; + + public CDOManyAttributeGetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public Object get(Object target) throws HibernateException + { + // Check if there is already a persistentcollection + PersistentCollection collection = PersistableListHolder.getInstance().getListMapping(target, + getEStructuralFeature()); + if (collection != null) + { + return collection; + } + + InternalCDORevision revision = (InternalCDORevision)target; + CDOList list = revision.getList(getEStructuralFeature(), 10); + + if (list instanceof WrappedHibernateList) + { + final Object delegate = ((WrappedHibernateList)list).getDelegate(); + if (delegate instanceof PersistentCollection) + { + return delegate; + } + } + + // Wrap the moveablearraylist + HibernateMoveableListWrapper wrapper = new HibernateMoveableListWrapper(); + wrapper.setDelegate(list); + + // And return it + return wrapper; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeSetter.java index 560ea592d7..fe09573f80 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyAttributeSetter.java @@ -1,72 +1,72 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.collection.PersistentCollection;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-import java.util.List;
-
-/**
- * @author Martin Taal
- */
-public class CDOManyAttributeSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOManyAttributeSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- // Do some checking
- if (value instanceof HibernateMoveableListWrapper)
- {
- super.set(target, ((HibernateMoveableListWrapper)value).getDelegate(), factory);
- return;
- }
-
- if (!(value instanceof PersistentCollection))
- {
- throw new IllegalArgumentException("Value is not a PersistentCollection but a " + value.getClass().getName()); //$NON-NLS-1$
- }
-
- if (!(value instanceof List<?>))
- {
- throw new IllegalArgumentException("Value is not a list but a " + value.getClass().getName()); //$NON-NLS-1$
- }
-
- // Only set it in the listholder
- PersistableListHolder.getInstance().putListMapping(target, getEStructuralFeature(), (PersistentCollection)value);
-
- // check if deep inside the persistentlist there is not already a delegate which is a hibernatemoveable list
- // which contains the list which should really be set in the cdorevision
- // persistentlist, hibernatemoveablelistwrapper, real list, if so then the real list should be set
- final InternalCDORevision revision = (InternalCDORevision)target;
- final Object currentValue = revision.getValue(getEStructuralFeature());
- if (currentValue == null || !(currentValue instanceof List<?>))
- {
- @SuppressWarnings("unchecked")
- List<Object> valueList = (List<Object>)value;
-
- final WrappedHibernateList whl = new WrappedHibernateList();
- whl.setDelegate(valueList);
- super.set(target, whl, factory);
- }
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.collection.spi.PersistentCollection; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +import java.util.List; + +/** + * @author Martin Taal + */ +public class CDOManyAttributeSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOManyAttributeSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + // Do some checking + if (value instanceof HibernateMoveableListWrapper) + { + super.set(target, ((HibernateMoveableListWrapper)value).getDelegate(), factory); + return; + } + + if (!(value instanceof PersistentCollection)) + { + throw new IllegalArgumentException("Value is not a PersistentCollection but a " + value.getClass().getName()); //$NON-NLS-1$ + } + + if (!(value instanceof List<?>)) + { + throw new IllegalArgumentException("Value is not a list but a " + value.getClass().getName()); //$NON-NLS-1$ + } + + // Only set it in the listholder + PersistableListHolder.getInstance().putListMapping(target, getEStructuralFeature(), (PersistentCollection)value); + + // check if deep inside the persistentlist there is not already a delegate which is a hibernatemoveable list + // which contains the list which should really be set in the cdorevision + // persistentlist, hibernatemoveablelistwrapper, real list, if so then the real list should be set + final InternalCDORevision revision = (InternalCDORevision)target; + final Object currentValue = revision.getValue(getEStructuralFeature()); + if (currentValue == null || !(currentValue instanceof List<?>)) + { + @SuppressWarnings("unchecked") + List<Object> valueList = (List<Object>)value; + + final WrappedHibernateList whl = new WrappedHibernateList(); + whl.setDelegate(valueList); + super.set(target, whl, factory); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceGetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceGetter.java index 5e9eec35f3..1bd990ec14 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceGetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceGetter.java @@ -1,77 +1,77 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.revision.CDOList;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.collection.PersistentCollection;
-
-/**
- * @author Martin Taal
- */
-// Howto handle hibernate lists:
-// - a new owner: the owner is persisted and its lists are replaced with hibernate
-// persistentlist, the hibernate persitentlist will have a delegate (internally) which is the list which was previously
-// present in the owner.
-// - an existing owner: the owner is read from the db and hibernate will set a persistentlist
-// directly
-//
-// The solution also needs to handle the following:
-// - cdo does not have direct java references but stores cdoids in the list while hibernate expects real java object
-// references.
-// - cdo uses a moveablearraylist and not the standard arraylist
-//
-// The solution:
-// - never return null when hibernate asks for the current value of the manyreference, always
-// return a MoveableArrayList so that hibernate uses that as the delegate, set the MoveableArrayList
-public class CDOManyReferenceGetter extends CDOPropertyGetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOManyReferenceGetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public Object get(Object target) throws HibernateException
- {
- // Check if there is already a persistentcollection
- PersistentCollection collection = PersistableListHolder.getInstance().getListMapping(target,
- getEStructuralFeature());
- if (collection != null)
- {
- return collection;
- }
-
- InternalCDORevision revision = (InternalCDORevision)target;
- CDOList list = revision.getList(getEStructuralFeature(), 10);
-
- if (list instanceof WrappedHibernateList)
- {
- final Object delegate = ((WrappedHibernateList)list).getDelegate();
- if (delegate instanceof PersistentCollection)
- {
- return delegate;
- }
- }
-
- // Wrap the moveablearraylist
- HibernateMoveableListWrapper wrapper = new HibernateMoveableListWrapper();
- wrapper.setDelegate(list);
-
- // And return it
- return wrapper;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.revision.CDOList; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.collection.spi.PersistentCollection; + +/** + * @author Martin Taal + */ +// Howto handle hibernate lists: +// - a new owner: the owner is persisted and its lists are replaced with hibernate +// persistentlist, the hibernate persitentlist will have a delegate (internally) which is the list which was previously +// present in the owner. +// - an existing owner: the owner is read from the db and hibernate will set a persistentlist +// directly +// +// The solution also needs to handle the following: +// - cdo does not have direct java references but stores cdoids in the list while hibernate expects real java object +// references. +// - cdo uses a moveablearraylist and not the standard arraylist +// +// The solution: +// - never return null when hibernate asks for the current value of the manyreference, always +// return a MoveableArrayList so that hibernate uses that as the delegate, set the MoveableArrayList +public class CDOManyReferenceGetter extends CDOPropertyGetter +{ + private static final long serialVersionUID = 1L; + + public CDOManyReferenceGetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public Object get(Object target) throws HibernateException + { + // Check if there is already a persistentcollection + PersistentCollection collection = PersistableListHolder.getInstance().getListMapping(target, + getEStructuralFeature()); + if (collection != null) + { + return collection; + } + + InternalCDORevision revision = (InternalCDORevision)target; + CDOList list = revision.getList(getEStructuralFeature(), 10); + + if (list instanceof WrappedHibernateList) + { + final Object delegate = ((WrappedHibernateList)list).getDelegate(); + if (delegate instanceof PersistentCollection) + { + return delegate; + } + } + + // Wrap the moveablearraylist + HibernateMoveableListWrapper wrapper = new HibernateMoveableListWrapper(); + wrapper.setDelegate(list); + + // And return it + return wrapper; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceSetter.java index 9d2eea03e3..2f0b6fb75f 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOManyReferenceSetter.java @@ -1,72 +1,72 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.collection.PersistentCollection;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-import java.util.List;
-
-/**
- * @author Martin Taal
- */
-public class CDOManyReferenceSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOManyReferenceSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- // Do some checking
- if (value instanceof HibernateMoveableListWrapper)
- {
- super.set(target, ((HibernateMoveableListWrapper)value).getDelegate(), factory);
- return;
- }
-
- if (!(value instanceof PersistentCollection))
- {
- throw new IllegalArgumentException("Value is not a PersistentCollection but a " + value.getClass().getName()); //$NON-NLS-1$
- }
-
- if (!(value instanceof List<?>))
- {
- throw new IllegalArgumentException("Value is not a list but a " + value.getClass().getName()); //$NON-NLS-1$
- }
-
- // Only set it in the listholder
- PersistableListHolder.getInstance().putListMapping(target, getEStructuralFeature(), (PersistentCollection)value);
-
- // check if deep inside the persistentlist there is not already a delegate which is a hibernatemoveable list
- // which contains the list which should really be set in the cdorevision
- // persistentlist, hibernatemoveablelistwrapper, real list, if so then the real list should be set
- final InternalCDORevision revision = (InternalCDORevision)target;
- final Object currentValue = revision.getValue(getEStructuralFeature());
- if (currentValue == null)
- {
- @SuppressWarnings("unchecked")
- List<Object> valueList = (List<Object>)value;
-
- final WrappedHibernateList whl = new WrappedHibernateList();
- whl.setDelegate(valueList);
- super.set(target, whl, factory);
- }
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.collection.spi.PersistentCollection; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +import java.util.List; + +/** + * @author Martin Taal + */ +public class CDOManyReferenceSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOManyReferenceSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + // Do some checking + if (value instanceof HibernateMoveableListWrapper) + { + super.set(target, ((HibernateMoveableListWrapper)value).getDelegate(), factory); + return; + } + + if (!(value instanceof PersistentCollection)) + { + throw new IllegalArgumentException("Value is not a PersistentCollection but a " + value.getClass().getName()); //$NON-NLS-1$ + } + + if (!(value instanceof List<?>)) + { + throw new IllegalArgumentException("Value is not a list but a " + value.getClass().getName()); //$NON-NLS-1$ + } + + // Only set it in the listholder + PersistableListHolder.getInstance().putListMapping(target, getEStructuralFeature(), (PersistentCollection)value); + + // check if deep inside the persistentlist there is not already a delegate which is a hibernatemoveable list + // which contains the list which should really be set in the cdorevision + // persistentlist, hibernatemoveablelistwrapper, real list, if so then the real list should be set + final InternalCDORevision revision = (InternalCDORevision)target; + final Object currentValue = revision.getValue(getEStructuralFeature()); + if (currentValue == null) + { + @SuppressWarnings("unchecked") + List<Object> valueList = (List<Object>)value; + + final WrappedHibernateList whl = new WrappedHibernateList(); + whl.setDelegate(valueList); + super.set(target, whl, factory); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOMergeEventListener.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOMergeEventListener.java index dce7b1f92d..0f7dce45e3 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOMergeEventListener.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOMergeEventListener.java @@ -1,36 +1,36 @@ -/*
- * 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
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.event.def.DefaultMergeEventListener;
-import org.hibernate.persister.entity.EntityPersister;
-
-import java.util.Map;
-
-/**
- * The CDOMergeEventListener prevents copying of values of an existing entity to itself.
- */
-public class CDOMergeEventListener extends DefaultMergeEventListener
-{
- private static final long serialVersionUID = 1L;
-
- @SuppressWarnings("rawtypes")
- @Override
- protected void copyValues(final EntityPersister persister, final Object entity, final Object target,
- final SessionImplementor source, final Map copyCache)
- {
- if (entity != target)
- {
- super.copyValues(persister, entity, target, source, copyCache);
- }
- }
-}
+/* + * 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 + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.event.internal.DefaultMergeEventListener; +import org.hibernate.persister.entity.EntityPersister; + +import java.util.Map; + +/** + * The CDOMergeEventListener prevents copying of values of an existing entity to itself. + */ +public class CDOMergeEventListener extends DefaultMergeEventListener +{ + private static final long serialVersionUID = 1L; + + @SuppressWarnings("rawtypes") + @Override + protected void copyValues(final EntityPersister persister, final Object entity, final Object target, + final SessionImplementor source, final Map copyCache) + { + if (entity != target) + { + super.copyValues(persister, entity, target, source, copyCache); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertyGetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertyGetter.java index 75ee1be1b0..dd3fc4ef2f 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertyGetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertyGetter.java @@ -1,137 +1,137 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.revision.CDORevisionData;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDORevisionPropertyAccessor.CDORevisionSetter;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.eclipse.emf.common.util.Enumerator;
-import org.eclipse.emf.ecore.EEnum;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * TODO How does this differ from {@link CDORevisionSetter}? Both needed?
- *
- * @author Martin Taal
- */
-public class CDOPropertyGetter extends CDOPropertyHandler implements Getter
-{
- private static final long serialVersionUID = 1L;
-
- private final boolean isEEnum;
-
- private final EEnum eEnum;
-
- public CDOPropertyGetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- if (getEStructuralFeature() != null)
- {
- isEEnum = getEStructuralFeature().getEType() instanceof EEnum;
- if (isEEnum)
- {
- eEnum = (EEnum)getEStructuralFeature().getEType();
- }
- else
- {
- eEnum = null;
- }
- }
- else
- {
- isEEnum = false;
- eEnum = null;
- }
- }
-
- public Object get(Object target) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
- Object value = revision.getValue(getEStructuralFeature());
- if (value == CDORevisionData.NIL)
- {
- // explicitly set to null
- return null;
- }
-
- if (value == null)
- {
- if (getEStructuralFeature().getDefaultValue() == null)
- {
- return null;
- }
-
- if (getEStructuralFeature().isUnsettable())
- {
- return null;
- }
-
- if (isEEnum)
- {
- // handle it a few lines lower
- value = getEStructuralFeature().getDefaultValue();
- }
- else
- {
- return null;
- }
- }
-
- // hibernate sees eenums, CDO sees int
- if (isEEnum && value != null)
- {
- if (value instanceof Enumerator)
- {
- return value;
- }
-
- return eEnum.getEEnumLiteral((Integer)value);
- }
-
- return value;
- }
-
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object target, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- return get(target);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- public Member getMember()
- {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return Object.class;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.revision.CDORevisionData; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDORevisionPropertyAccessor.CDORevisionSetter; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.eclipse.emf.common.util.Enumerator; +import org.eclipse.emf.ecore.EEnum; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * TODO How does this differ from {@link CDORevisionSetter}? Both needed? + * + * @author Martin Taal + */ +public class CDOPropertyGetter extends CDOPropertyHandler implements Getter +{ + private static final long serialVersionUID = 1L; + + private final boolean isEEnum; + + private final EEnum eEnum; + + public CDOPropertyGetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + if (getEStructuralFeature() != null) + { + isEEnum = getEStructuralFeature().getEType() instanceof EEnum; + if (isEEnum) + { + eEnum = (EEnum)getEStructuralFeature().getEType(); + } + else + { + eEnum = null; + } + } + else + { + isEEnum = false; + eEnum = null; + } + } + + public Object get(Object target) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + Object value = revision.getValue(getEStructuralFeature()); + if (value == CDORevisionData.NIL) + { + // explicitly set to null + return null; + } + + if (value == null) + { + if (getEStructuralFeature().getDefaultValue() == null) + { + return null; + } + + if (getEStructuralFeature().isUnsettable()) + { + return null; + } + + if (isEEnum) + { + // handle it a few lines lower + value = getEStructuralFeature().getDefaultValue(); + } + else + { + return null; + } + } + + // hibernate sees eenums, CDO sees int + if (isEEnum && value != null) + { + if (value instanceof Enumerator) + { + return value; + } + + return eEnum.getEEnumLiteral((Integer)value); + } + + return value; + } + + @SuppressWarnings("rawtypes") + public Object getForInsert(Object target, Map mergeMap, SessionImplementor session) throws HibernateException + { + return get(target); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + public Member getMember() + { + return null; + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return Object.class; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertySetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertySetter.java index ae84a6aaa6..41a92b7564 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertySetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOPropertySetter.java @@ -1,148 +1,148 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.revision.CDORevisionData;
-import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDORevisionPropertyAccessor.CDORevisionSetter;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.eclipse.emf.common.util.Enumerator;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EEnum;
-import org.eclipse.emf.ecore.EEnumLiteral;
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.property.Setter;
-
-import java.lang.reflect.Method;
-
-/**
- * TODO How does this differ from {@link CDORevisionSetter}? Both needed?
- *
- * @author Martin Taal
- */
-public class CDOPropertySetter extends CDOPropertyHandler implements Setter
-{
- private static final long serialVersionUID = 1L;
-
- private final boolean convertByteArray;
-
- public CDOPropertySetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
-
- // handle a special case CDO/EMF expect a byte[] but Hibernate
- // will return a Byte[]
- final EStructuralFeature eFeature = getEStructuralFeature();
- if (eFeature instanceof EAttribute)
- {
- final EAttribute eAttribute = (EAttribute)eFeature;
- if (eAttribute.getEAttributeType().getInstanceClass() != null
- && byte[].class.isAssignableFrom(eAttribute.getEAttributeType().getInstanceClass()))
- {
- convertByteArray = true;
- }
- else
- {
- convertByteArray = false;
- }
- }
- else
- {
- convertByteArray = false;
- }
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
-
- // handle a special case: the byte array.
- // hibernate will pass a Byte[] while CDO wants a byte[] (object vs. primitive array)
- final Object newValue;
- if (value instanceof Byte[] && convertByteArray)
- {
- final Byte[] objectArray = (Byte[])value;
- final byte[] newByteValue = new byte[objectArray.length];
- int i = 0;
- for (byte b : objectArray)
- {
- newByteValue[i++] = b;
- }
- newValue = newByteValue;
- }
- else
- {
- // hibernate sees enums, cdo sees int's
- if (value instanceof Enumerator)
- {
- newValue = ((Enumerator)value).getValue();
- }
- else if (value instanceof EEnumLiteral)
- {
- newValue = ((EEnumLiteral)value).getValue();
- }
- else if (value == null)
- {
- final Object defaultValue = getEStructuralFeature().getDefaultValue();
- if (defaultValue == null)
- {
- newValue = null;
- }
- else if (getEStructuralFeature().isUnsettable())
- {
- newValue = null;
- }
- else
- {
- // there was a default value so was explicitly set to null
- // otherwise the default value would be in the db
- newValue = CDORevisionData.NIL;
- }
- }
- else
- {
- newValue = value;
- }
- }
- final Object currentValue = revision.getValue(getEStructuralFeature());
- final boolean notChanged = currentValue == newValue || currentValue == null && newValue == CDORevisionData.NIL
- || isEenumDefaultValue(value) || currentValue != null && newValue != null && currentValue.equals(newValue);
- final boolean hasChanged = !notChanged;
- if (hasChanged)
- {
- revision.setValue(getEStructuralFeature(), newValue);
- }
- }
-
- private boolean isEenumDefaultValue(Object value)
- {
- if (getEStructuralFeature().getEType() instanceof EEnum)
- {
- final Object defaultValue = getEStructuralFeature().getDefaultValue();
- return defaultValue == value;
- }
- return false;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.revision.CDORevisionData; +import org.eclipse.emf.cdo.server.internal.hibernate.tuplizer.CDORevisionPropertyAccessor.CDORevisionSetter; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.eclipse.emf.common.util.Enumerator; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.property.Setter; + +import java.lang.reflect.Method; + +/** + * TODO How does this differ from {@link CDORevisionSetter}? Both needed? + * + * @author Martin Taal + */ +public class CDOPropertySetter extends CDOPropertyHandler implements Setter +{ + private static final long serialVersionUID = 1L; + + private final boolean convertByteArray; + + public CDOPropertySetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + + // handle a special case CDO/EMF expect a byte[] but Hibernate + // will return a Byte[] + final EStructuralFeature eFeature = getEStructuralFeature(); + if (eFeature instanceof EAttribute) + { + final EAttribute eAttribute = (EAttribute)eFeature; + if (eAttribute.getEAttributeType().getInstanceClass() != null + && byte[].class.isAssignableFrom(eAttribute.getEAttributeType().getInstanceClass())) + { + convertByteArray = true; + } + else + { + convertByteArray = false; + } + } + else + { + convertByteArray = false; + } + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + + // handle a special case: the byte array. + // hibernate will pass a Byte[] while CDO wants a byte[] (object vs. primitive array) + final Object newValue; + if (value instanceof Byte[] && convertByteArray) + { + final Byte[] objectArray = (Byte[])value; + final byte[] newByteValue = new byte[objectArray.length]; + int i = 0; + for (byte b : objectArray) + { + newByteValue[i++] = b; + } + newValue = newByteValue; + } + else + { + // hibernate sees enums, cdo sees int's + if (value instanceof Enumerator) + { + newValue = ((Enumerator)value).getValue(); + } + else if (value instanceof EEnumLiteral) + { + newValue = ((EEnumLiteral)value).getValue(); + } + else if (value == null) + { + final Object defaultValue = getEStructuralFeature().getDefaultValue(); + if (defaultValue == null) + { + newValue = null; + } + else if (getEStructuralFeature().isUnsettable()) + { + newValue = null; + } + else + { + // there was a default value so was explicitly set to null + // otherwise the default value would be in the db + newValue = CDORevisionData.NIL; + } + } + else + { + newValue = value; + } + } + final Object currentValue = revision.getValue(getEStructuralFeature()); + final boolean notChanged = currentValue == newValue || currentValue == null && newValue == CDORevisionData.NIL + || isEenumDefaultValue(value) || currentValue != null && newValue != null && currentValue.equals(newValue); + final boolean hasChanged = !notChanged; + if (hasChanged) + { + revision.setValue(getEStructuralFeature(), newValue); + } + } + + private boolean isEenumDefaultValue(Object value) + { + if (getEStructuralFeature().getEType() instanceof EEnum) + { + final Object defaultValue = getEStructuralFeature().getDefaultValue(); + return defaultValue == value; + } + return false; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOReferenceSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOReferenceSetter.java index 91223415db..76965a823b 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOReferenceSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOReferenceSetter.java @@ -1,48 +1,48 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.id.CDOIDExternal;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-/**
- * @author Martin Taal
- */
-public class CDOReferenceSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOReferenceSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- if (value == null)
- {
- super.set(target, null, factory);
- }
- else if (value instanceof CDOIDExternal)
- {
- super.set(target, value, factory);
- }
- else
- {
- super.set(target, HibernateUtil.getInstance().getCDOID(value), factory);
- }
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.id.CDOIDExternal; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +/** + * @author Martin Taal + */ +public class CDOReferenceSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOReferenceSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + if (value == null) + { + super.set(target, null, factory); + } + else if (value instanceof CDOIDExternal) + { + super.set(target, value, factory); + } + else + { + super.set(target, HibernateUtil.getInstance().getCDOID(value), factory); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOResourceIDSetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOResourceIDSetter.java index 81427f665a..33413bbac8 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOResourceIDSetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOResourceIDSetter.java @@ -1,44 +1,44 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * 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.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-/**
- * @author Martin Taal
- */
-public class CDOResourceIDSetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOResourceIDSetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
- revision.setResourceID((CDOID)value);
- }
-
- @Override
- protected boolean isVirtualPropertyAllowed()
- {
- return true;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * 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.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +/** + * @author Martin Taal + */ +public class CDOResourceIDSetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOResourceIDSetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + revision.setResourceID((CDOID)value); + } + + @Override + protected boolean isVirtualPropertyAllowed() + { + return true; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionLazyInitializer.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionLazyInitializer.java index f7fea03fc5..811b30fd80 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionLazyInitializer.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionLazyInitializer.java @@ -1,42 +1,42 @@ -/*
- * 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.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.proxy.AbstractLazyInitializer;
-
-import java.io.Serializable;
-
-/**
- * @author Eike Stepper
- */
-public class CDORevisionLazyInitializer extends AbstractLazyInitializer implements Serializable
-{
- private static final long serialVersionUID = 1L;
-
- CDORevisionLazyInitializer(String entityName, Serializable id, SessionImplementor session)
- {
- super(entityName, id, session);
- }
-
- public InternalCDORevision getRevision()
- {
- return (InternalCDORevision)getImplementation();
- }
-
- @SuppressWarnings("rawtypes")
- public Class getPersistentClass()
- {
- throw new UnsupportedOperationException();
- }
-}
+/* + * 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.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.proxy.AbstractLazyInitializer; + +import java.io.Serializable; + +/** + * @author Eike Stepper + */ +public class CDORevisionLazyInitializer extends AbstractLazyInitializer implements Serializable +{ + private static final long serialVersionUID = 1L; + + CDORevisionLazyInitializer(String entityName, Serializable id, SessionImplementor session) + { + super(entityName, id, session); + } + + public InternalCDORevision getRevision() + { + return (InternalCDORevision)getImplementation(); + } + + @SuppressWarnings("rawtypes") + public Class getPersistentClass() + { + throw new UnsupportedOperationException(); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionPropertyAccessor.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionPropertyAccessor.java index 320eacf72a..3567f69839 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionPropertyAccessor.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionPropertyAccessor.java @@ -1,162 +1,162 @@ -/*
- * 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.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-import org.hibernate.property.PropertyAccessor;
-import org.hibernate.property.Setter;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class CDORevisionPropertyAccessor implements PropertyAccessor
-{
- private CDORevisionTuplizer tuplizer;
-
- public CDORevisionPropertyAccessor(CDORevisionTuplizer tuplizer)
- {
- this.tuplizer = tuplizer;
- }
-
- public CDORevisionTuplizer getTuplizer()
- {
- return tuplizer;
- }
-
- @SuppressWarnings("rawtypes")
- public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return new CDORevisionGetter(this, propertyName);
- }
-
- @SuppressWarnings("rawtypes")
- public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return new CDORevisionSetter(this, propertyName);
- }
-
- /**
- * @author Eike Stepper
- */
- public static class BaseAccessor
- {
- private CDORevisionPropertyAccessor propertyAccessor;
-
- private EStructuralFeature feature;
-
- public BaseAccessor(CDORevisionPropertyAccessor propertyAccessor, String propertyName)
- {
- this.propertyAccessor = propertyAccessor;
- feature = propertyAccessor.getTuplizer().getEClass().getEStructuralFeature(propertyName);
- if (feature == null)
- {
- throw new IllegalStateException("Feature not found: " + propertyName); //$NON-NLS-1$
- }
- }
-
- public CDORevisionPropertyAccessor getPropertyAccessor()
- {
- return propertyAccessor;
- }
-
- public EStructuralFeature getEStructuralFeature()
- {
- return feature;
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class CDORevisionGetter extends BaseAccessor implements Getter
- {
- private static final long serialVersionUID = 1L;
-
- public CDORevisionGetter(CDORevisionPropertyAccessor propertyAccessor, String propertyName)
- {
- super(propertyAccessor, propertyName);
- }
-
- public Object get(Object target) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
- return revision.getValue(getEStructuralFeature());
- }
-
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object target, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- return get(target);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return Object.class;
- }
-
- public Member getMember()
- {
- return null;
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class CDORevisionSetter extends BaseAccessor implements Setter
- {
- private static final long serialVersionUID = 1L;
-
- public CDORevisionSetter(CDORevisionPropertyAccessor propertyAccessor, String propertyName)
- {
- super(propertyAccessor, propertyName);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
- revision.setValue(getEStructuralFeature(), 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: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.HibernateException; +import org.hibernate.PropertyNotFoundException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; +import org.hibernate.property.PropertyAccessor; +import org.hibernate.property.Setter; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class CDORevisionPropertyAccessor implements PropertyAccessor +{ + private CDORevisionTuplizer tuplizer; + + public CDORevisionPropertyAccessor(CDORevisionTuplizer tuplizer) + { + this.tuplizer = tuplizer; + } + + public CDORevisionTuplizer getTuplizer() + { + return tuplizer; + } + + @SuppressWarnings("rawtypes") + public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return new CDORevisionGetter(this, propertyName); + } + + @SuppressWarnings("rawtypes") + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return new CDORevisionSetter(this, propertyName); + } + + /** + * @author Eike Stepper + */ + public static class BaseAccessor + { + private CDORevisionPropertyAccessor propertyAccessor; + + private EStructuralFeature feature; + + public BaseAccessor(CDORevisionPropertyAccessor propertyAccessor, String propertyName) + { + this.propertyAccessor = propertyAccessor; + feature = propertyAccessor.getTuplizer().getEClass().getEStructuralFeature(propertyName); + if (feature == null) + { + throw new IllegalStateException("Feature not found: " + propertyName); //$NON-NLS-1$ + } + } + + public CDORevisionPropertyAccessor getPropertyAccessor() + { + return propertyAccessor; + } + + public EStructuralFeature getEStructuralFeature() + { + return feature; + } + } + + /** + * @author Eike Stepper + */ + public static class CDORevisionGetter extends BaseAccessor implements Getter + { + private static final long serialVersionUID = 1L; + + public CDORevisionGetter(CDORevisionPropertyAccessor propertyAccessor, String propertyName) + { + super(propertyAccessor, propertyName); + } + + public Object get(Object target) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + return revision.getValue(getEStructuralFeature()); + } + + @SuppressWarnings("rawtypes") + public Object getForInsert(Object target, Map mergeMap, SessionImplementor session) throws HibernateException + { + return get(target); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return Object.class; + } + + public Member getMember() + { + return null; + } + } + + /** + * @author Eike Stepper + */ + public static class CDORevisionSetter extends BaseAccessor implements Setter + { + private static final long serialVersionUID = 1L; + + public CDORevisionSetter(CDORevisionPropertyAccessor propertyAccessor, String propertyName) + { + super(propertyAccessor, propertyName); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + revision.setValue(getEStructuralFeature(), value); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionProxyFactory.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionProxyFactory.java index 83cbe8ff09..7bbcc5b551 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionProxyFactory.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionProxyFactory.java @@ -1,55 +1,55 @@ -/*
- * 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.internal.hibernate.tuplizer;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.proxy.HibernateProxy;
-import org.hibernate.proxy.ProxyFactory;
-import org.hibernate.type.CompositeType;
-
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- */
-public class CDORevisionProxyFactory implements ProxyFactory
-{
- private String entityName;
-
- public CDORevisionProxyFactory()
- {
- }
-
- @SuppressWarnings("rawtypes")
- public void postInstantiate(String entityName, Class persistentClass, Set interfaces, Method getIdentifierMethod,
- Method setIdentifierMethod, CompositeType componentIdType) throws HibernateException
- {
- this.entityName = entityName;
- }
-
- public HibernateProxy getProxy(Serializable id, SessionImplementor session) throws HibernateException
- {
- return new CDORevisionProxyHibernate(new CDORevisionLazyInitializer(entityName, id, session));
- }
-
- public String getEntityName()
- {
- return entityName;
- }
-
- public void setEntityName(String entityName)
- {
- this.entityName = entityName;
- }
-}
+/* + * 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.internal.hibernate.tuplizer; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.proxy.HibernateProxy; +import org.hibernate.proxy.ProxyFactory; +import org.hibernate.type.CompositeType; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Set; + +/** + * @author Eike Stepper + */ +public class CDORevisionProxyFactory implements ProxyFactory +{ + private String entityName; + + public CDORevisionProxyFactory() + { + } + + @SuppressWarnings("rawtypes") + public void postInstantiate(String entityName, Class persistentClass, Set interfaces, Method getIdentifierMethod, + Method setIdentifierMethod, CompositeType componentIdType) throws HibernateException + { + this.entityName = entityName; + } + + public HibernateProxy getProxy(Serializable id, SessionImplementor session) throws HibernateException + { + return new CDORevisionProxyHibernate(new CDORevisionLazyInitializer(entityName, id, session)); + } + + public String getEntityName() + { + return entityName; + } + + public void setEntityName(String entityName) + { + this.entityName = entityName; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionTuplizer.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionTuplizer.java index 964457e809..6acfb42e79 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionTuplizer.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDORevisionTuplizer.java @@ -1,354 +1,380 @@ -/*
- * 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 - changed handling of propertygetters/setters
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.common.model.EMFUtil;
-import org.eclipse.emf.cdo.eresource.EresourcePackage;
-import org.eclipse.emf.cdo.server.internal.hibernate.CDOHibernateConstants;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateStore;
-import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import org.eclipse.emf.ecore.EAnnotation;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.EcoreFactory;
-
-import org.hibernate.EntityMode;
-import org.hibernate.EntityNameResolver;
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.mapping.Property;
-import org.hibernate.property.Getter;
-import org.hibernate.property.Setter;
-import org.hibernate.proxy.ProxyFactory;
-import org.hibernate.tuple.Instantiator;
-import org.hibernate.tuple.entity.AbstractEntityTuplizer;
-import org.hibernate.tuple.entity.EntityMetamodel;
-
-/**
- * @author Eike Stepper
- */
-public class CDORevisionTuplizer extends AbstractEntityTuplizer
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CDORevisionTuplizer.class);
-
- private static final String EPACKAGE_META = "epackage"; //$NON-NLS-1$
-
- private static final String ECLASSNAME_META = "eclassName"; //$NON-NLS-1$
-
- private EClass eClass;
-
- public CDORevisionTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo)
- {
- super(entityMetamodel, mappingInfo);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Created CDORevisionTuplizer for entity " + mappingInfo.getEntityName()); //$NON-NLS-1$
- }
-
- initEClass(mappingInfo);
- }
-
- private void initEClass(PersistentClass mappingInfo)
- {
- if (eClass != null)
- {
- return;
- }
-
- HibernateStore hbStore = HibernateStore.getCurrentHibernateStore();
-
- // find the EClass/Package
- String entityName = mappingInfo.getEntityName();
- String ePackageURI = mappingInfo.getMetaAttribute(EPACKAGE_META).getValue();
- String eClassName = mappingInfo.getMetaAttribute(ECLASSNAME_META).getValue();
-
- if (ePackageURI == null || eClassName == null)
- {
- throw new IllegalArgumentException("The mapping for the persistentclass " + mappingInfo.getEntityName() //$NON-NLS-1$
- + " is incorrect, there should be meta data tags for both epackage and " //$NON-NLS-1$
- + "eclassname, one or both are missing."); //$NON-NLS-1$
- }
-
- if (TRACER.isEnabled())
- {
- TRACER.trace("EntityName/eclassname/packageURI " + entityName + "/" + eClassName + "/" + ePackageURI); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- for (EPackage ePackage : hbStore.getPackageHandler().getEPackages())
- {
- if (ePackage.getNsURI().compareTo(ePackageURI) != 0)
- {
- continue;
- }
-
- for (EClass localCdoClass : EMFUtil.getPersistentClasses(ePackage))
- {
- if (localCdoClass.getName().compareTo(eClassName) == 0)
- {
- eClass = localCdoClass;
- break;
- }
- }
- }
-
- if (eClass == null && ePackageURI.compareTo(EresourcePackage.eINSTANCE.getNsURI()) == 0)
- {
- for (EClass localCdoClass : EMFUtil.getPersistentClasses(EresourcePackage.eINSTANCE))
- {
- if (localCdoClass.getName().compareTo(eClassName) == 0)
- {
- eClass = localCdoClass;
- if (TRACER.isEnabled())
- {
- TRACER.trace("Class is CDOResource class"); //$NON-NLS-1$
- }
-
- break;
- }
- }
- }
-
- // add the entityName <--> EClass mapping
- HibernateStore.getCurrentHibernateStore().addEntityNameEClassMapping(entityName, eClass);
-
- if (eClass == null)
- {
- throw new IllegalArgumentException("The mapped class " + mappingInfo.getEntityName() //$NON-NLS-1$
- + " does not have a eClass equivalent"); //$NON-NLS-1$
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.hibernate.tuple.entity.EntityTuplizer#determineConcreteSubclassEntityName(java.lang.Object,
- * org.hibernate.engine.SessionFactoryImplementor)
- */
- public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory)
- {
- final Class<?> concreteEntityClass = entityInstance.getClass();
- if (concreteEntityClass == getMappedClass())
- {
- return getEntityName();
- }
-
- String entityName = getEntityMetamodel().findEntityNameByEntityClass(concreteEntityClass);
- if (entityName == null)
- {
- throw new HibernateException("Unable to resolve entity name from Class [" + concreteEntityClass.getName() + "]" //$NON-NLS-1$ //$NON-NLS-2$
- + " expected instance/subclass of [" + getEntityName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return entityName;
- }
-
- public EntityMode getEntityMode()
- {
- return EntityMode.MAP;
- }
-
- public EntityNameResolver[] getEntityNameResolvers()
- {
- return new EntityNameResolver[] { new CDOEntityNameResolver() };
- }
-
- private class CDOEntityNameResolver implements EntityNameResolver
- {
- public String resolveEntityName(Object object)
- {
- return getEntityName();
- }
- }
-
- public EClass getEClass()
- {
- return eClass;
- }
-
- @Override
- protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity)
- {
- initEClass(mappedEntity);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Building property getter for " + eClass.getName() + "." + mappedProperty.getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (mappedProperty.isBackRef())
- {
- return mappedProperty.getGetter(mappedEntity.getMappedClass());
- }
- else if (mappedProperty == mappedEntity.getIdentifierProperty())
- {
- return new CDOIDPropertyGetter(this, mappedProperty.getName());
- }
- else if (mappedProperty.getMetaAttribute("version") != null)
- {
- return new CDOVersionPropertyGetter(this, mappedProperty.getName());
- }
- else if (mappedProperty.getName().compareTo(CDOHibernateConstants.RESOURCE_PROPERTY) == 0)
- {
- return new CDOResourceIDGetter(this, mappedProperty.getName());
- }
- else if (mappedProperty.getName().compareTo(CDOHibernateConstants.CONTAINER_PROPERTY) == 0)
- {
- return new CDOContainerGetter(this, mappedProperty.getName());
- }
- else if (mappedProperty.getName().compareTo(CDOHibernateConstants.COMMITTIMESTAMP_PROPERTY) == 0)
- {
- return new CDOBranchTimeStampGetter(this, mappedProperty.getName());
- }
-
- EStructuralFeature feature = getEClass().getEStructuralFeature(mappedProperty.getName());
- if (feature instanceof EReference && feature.isMany())
- {
- return new CDOManyReferenceGetter(this, mappedProperty.getName());
- }
- else if (feature instanceof EReference)
- {
- return new CDOReferenceGetter(this, mappedProperty.getName());
- }
- else if (feature instanceof EAttribute && feature.isMany())
- {
- return new CDOManyAttributeGetter(this, mappedProperty.getName());
- }
-
- return new CDOPropertyGetter(this, mappedProperty.getName());
- }
-
- @Override
- protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity)
- {
- initEClass(mappedEntity);
- if (TRACER.isEnabled())
- {
- TRACER.trace("Building property setter for " + eClass.getName() + "." + mappedProperty.getName()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (mappedProperty.isBackRef())
- {
- return mappedProperty.getSetter(mappedEntity.getMappedClass());
- }
-
- if (mappedProperty == mappedEntity.getIdentifierProperty())
- {
- setIdentifierTypeAsAnnotation(mappedProperty);
- return new CDOIDPropertySetter(this, mappedProperty.getName());
- }
-
- if (mappedProperty.getMetaAttribute("version") != null)
- {
- return new CDOVersionPropertySetter(this, mappedProperty.getName());
- }
-
- if (mappedProperty.getName().compareTo(CDOHibernateConstants.RESOURCE_PROPERTY) == 0)
- {
- return new CDOResourceIDSetter(this, mappedProperty.getName());
- }
-
- if (mappedProperty.getName().compareTo(CDOHibernateConstants.CONTAINER_PROPERTY) == 0)
- {
- return new CDOContainerSetter(this, mappedProperty.getName());
- }
-
- if (mappedProperty.getName().compareTo(CDOHibernateConstants.COMMITTIMESTAMP_PROPERTY) == 0)
- {
- return new CDOBranchTimeStampSetter(this, mappedProperty.getName());
- }
-
- EStructuralFeature feature = getEClass().getEStructuralFeature(mappedProperty.getName());
- if (feature instanceof EReference && feature.isMany())
- {
- // TODO Clarify feature maps
- return new CDOManyReferenceSetter(this, mappedProperty.getName());
- }
-
- if (feature instanceof EAttribute && feature.isMany())
- {
- // TODO Clarify feature maps
- return new CDOManyAttributeSetter(this, mappedProperty.getName());
- }
-
- if (feature instanceof EReference)
- {
- // TODO Clarify feature maps
- return new CDOReferenceSetter(this, mappedProperty.getName());
- }
-
- return new CDOPropertySetter(this, mappedProperty.getName());
- }
-
- @Override
- protected Instantiator buildInstantiator(PersistentClass mappingInfo)
- {
- return new CDORevisionInstantiator(this, mappingInfo);
- }
-
- @Override
- protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter)
- {
- CDORevisionProxyFactory pf = new CDORevisionProxyFactory();
- pf.setEntityName(getEntityName());
-
- try
- {
- pf.postInstantiate(getEntityName(), null, null, null, null, null);
- }
- catch (HibernateException ex)
- {
- OM.LOG.error("Could not create proxy factory for " + getEntityName(), ex); //$NON-NLS-1$
- pf = null;
- }
-
- return pf;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getMappedClass()
- {
- return InternalCDORevision.class;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getConcreteProxyClass()
- {
- return InternalCDORevision.class;
- }
-
- public boolean isInstrumented()
- {
- return false;
- }
-
- private void setIdentifierTypeAsAnnotation(Property prop)
- {
- EAnnotation eAnnotation = getEClass().getEAnnotation(HibernateStore.ID_TYPE_EANNOTATION_SOURCE);
- if (eAnnotation == null)
- {
- eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
- eAnnotation.setSource(HibernateStore.ID_TYPE_EANNOTATION_SOURCE);
- eAnnotation.getDetails().put(HibernateStore.ID_TYPE_EANNOTATION_KEY, prop.getType().getName());
- getEClass().getEAnnotations().add(eAnnotation);
- }
- else if (!eAnnotation.getDetails().containsKey(HibernateStore.ID_TYPE_EANNOTATION_KEY))
- {
- eAnnotation.getDetails().put(HibernateStore.ID_TYPE_EANNOTATION_KEY, prop.getType().getName());
- }
- }
-}
+/* + * 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 - changed handling of propertygetters/setters + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.common.model.EMFUtil; +import org.eclipse.emf.cdo.eresource.EresourcePackage; +import org.eclipse.emf.cdo.server.internal.hibernate.CDOHibernateConstants; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateStore; +import org.eclipse.emf.cdo.server.internal.hibernate.bundle.OM; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.EcoreFactory; + +import org.hibernate.EntityMode; +import org.hibernate.EntityNameResolver; +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.mapping.PersistentClass; +import org.hibernate.mapping.Property; +import org.hibernate.metamodel.binding.AttributeBinding; +import org.hibernate.metamodel.binding.EntityBinding; +import org.hibernate.property.Getter; +import org.hibernate.property.Setter; +import org.hibernate.proxy.ProxyFactory; +import org.hibernate.tuple.Instantiator; +import org.hibernate.tuple.entity.AbstractEntityTuplizer; +import org.hibernate.tuple.entity.EntityMetamodel; + +/** + * @author Eike Stepper + */ +public class CDORevisionTuplizer extends AbstractEntityTuplizer +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CDORevisionTuplizer.class); + + private static final String EPACKAGE_META = "epackage"; //$NON-NLS-1$ + + private static final String ECLASSNAME_META = "eclassName"; //$NON-NLS-1$ + + private EClass eClass; + + public CDORevisionTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo) + { + super(entityMetamodel, mappingInfo); + if (TRACER.isEnabled()) + { + TRACER.trace("Created CDORevisionTuplizer for entity " + mappingInfo.getEntityName()); //$NON-NLS-1$ + } + + initEClass(mappingInfo); + } + + private void initEClass(PersistentClass mappingInfo) + { + if (eClass != null) + { + return; + } + + HibernateStore hbStore = HibernateStore.getCurrentHibernateStore(); + + // find the EClass/Package + String entityName = mappingInfo.getEntityName(); + String ePackageURI = mappingInfo.getMetaAttribute(EPACKAGE_META).getValue(); + String eClassName = mappingInfo.getMetaAttribute(ECLASSNAME_META).getValue(); + + if (ePackageURI == null || eClassName == null) + { + throw new IllegalArgumentException("The mapping for the persistentclass " + mappingInfo.getEntityName() //$NON-NLS-1$ + + " is incorrect, there should be meta data tags for both epackage and " //$NON-NLS-1$ + + "eclassname, one or both are missing."); //$NON-NLS-1$ + } + + if (TRACER.isEnabled()) + { + TRACER.trace("EntityName/eclassname/packageURI " + entityName + "/" + eClassName + "/" + ePackageURI); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + for (EPackage ePackage : hbStore.getPackageHandler().getEPackages()) + { + if (ePackage.getNsURI().compareTo(ePackageURI) != 0) + { + continue; + } + + for (EClass localCdoClass : EMFUtil.getPersistentClasses(ePackage)) + { + if (localCdoClass.getName().compareTo(eClassName) == 0) + { + eClass = localCdoClass; + break; + } + } + } + + if (eClass == null && ePackageURI.compareTo(EresourcePackage.eINSTANCE.getNsURI()) == 0) + { + for (EClass localCdoClass : EMFUtil.getPersistentClasses(EresourcePackage.eINSTANCE)) + { + if (localCdoClass.getName().compareTo(eClassName) == 0) + { + eClass = localCdoClass; + if (TRACER.isEnabled()) + { + TRACER.trace("Class is CDOResource class"); //$NON-NLS-1$ + } + + break; + } + } + } + + // add the entityName <--> EClass mapping + HibernateStore.getCurrentHibernateStore().addEntityNameEClassMapping(entityName, eClass); + + if (eClass == null) + { + throw new IllegalArgumentException("The mapped class " + mappingInfo.getEntityName() //$NON-NLS-1$ + + " does not have a eClass equivalent"); //$NON-NLS-1$ + } + } + + /* + * (non-Javadoc) + * @see org.hibernate.tuple.entity.EntityTuplizer#determineConcreteSubclassEntityName(java.lang.Object, + * org.hibernate.engine.SessionFactoryImplementor) + */ + public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory) + { + final Class<?> concreteEntityClass = entityInstance.getClass(); + if (concreteEntityClass == getMappedClass()) + { + return getEntityName(); + } + + String entityName = getEntityMetamodel().findEntityNameByEntityClass(concreteEntityClass); + if (entityName == null) + { + throw new HibernateException("Unable to resolve entity name from Class [" + concreteEntityClass.getName() + "]" //$NON-NLS-1$ //$NON-NLS-2$ + + " expected instance/subclass of [" + getEntityName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + return entityName; + } + + public EntityMode getEntityMode() + { + return EntityMode.MAP; + } + + public EntityNameResolver[] getEntityNameResolvers() + { + return new EntityNameResolver[] { new CDOEntityNameResolver() }; + } + + private class CDOEntityNameResolver implements EntityNameResolver + { + public String resolveEntityName(Object object) + { + return getEntityName(); + } + } + + public EClass getEClass() + { + return eClass; + } + + @Override + protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) + { + initEClass(mappedEntity); + if (TRACER.isEnabled()) + { + TRACER.trace("Building property getter for " + eClass.getName() + "." + mappedProperty.getName()); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (mappedProperty.isBackRef()) + { + return mappedProperty.getGetter(mappedEntity.getMappedClass()); + } + else if (mappedProperty == mappedEntity.getIdentifierProperty()) + { + return new CDOIDPropertyGetter(this, mappedProperty.getName()); + } + else if (mappedProperty.getMetaAttribute("version") != null) + { + return new CDOVersionPropertyGetter(this, mappedProperty.getName()); + } + else if (mappedProperty.getName().compareTo(CDOHibernateConstants.RESOURCE_PROPERTY) == 0) + { + return new CDOResourceIDGetter(this, mappedProperty.getName()); + } + else if (mappedProperty.getName().compareTo(CDOHibernateConstants.CONTAINER_PROPERTY) == 0) + { + return new CDOContainerGetter(this, mappedProperty.getName()); + } + else if (mappedProperty.getName().compareTo(CDOHibernateConstants.COMMITTIMESTAMP_PROPERTY) == 0) + { + return new CDOBranchTimeStampGetter(this, mappedProperty.getName()); + } + + EStructuralFeature feature = getEClass().getEStructuralFeature(mappedProperty.getName()); + if (feature instanceof EReference && feature.isMany()) + { + return new CDOManyReferenceGetter(this, mappedProperty.getName()); + } + else if (feature instanceof EReference) + { + return new CDOReferenceGetter(this, mappedProperty.getName()); + } + else if (feature instanceof EAttribute && feature.isMany()) + { + return new CDOManyAttributeGetter(this, mappedProperty.getName()); + } + + return new CDOPropertyGetter(this, mappedProperty.getName()); + } + + @Override + protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) + { + initEClass(mappedEntity); + if (TRACER.isEnabled()) + { + TRACER.trace("Building property setter for " + eClass.getName() + "." + mappedProperty.getName()); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (mappedProperty.isBackRef()) + { + return mappedProperty.getSetter(mappedEntity.getMappedClass()); + } + + if (mappedProperty == mappedEntity.getIdentifierProperty()) + { + setIdentifierTypeAsAnnotation(mappedProperty); + return new CDOIDPropertySetter(this, mappedProperty.getName()); + } + + if (mappedProperty.getMetaAttribute("version") != null) + { + return new CDOVersionPropertySetter(this, mappedProperty.getName()); + } + + if (mappedProperty.getName().compareTo(CDOHibernateConstants.RESOURCE_PROPERTY) == 0) + { + return new CDOResourceIDSetter(this, mappedProperty.getName()); + } + + if (mappedProperty.getName().compareTo(CDOHibernateConstants.CONTAINER_PROPERTY) == 0) + { + return new CDOContainerSetter(this, mappedProperty.getName()); + } + + if (mappedProperty.getName().compareTo(CDOHibernateConstants.COMMITTIMESTAMP_PROPERTY) == 0) + { + return new CDOBranchTimeStampSetter(this, mappedProperty.getName()); + } + + EStructuralFeature feature = getEClass().getEStructuralFeature(mappedProperty.getName()); + if (feature instanceof EReference && feature.isMany()) + { + // TODO Clarify feature maps + return new CDOManyReferenceSetter(this, mappedProperty.getName()); + } + + if (feature instanceof EAttribute && feature.isMany()) + { + // TODO Clarify feature maps + return new CDOManyAttributeSetter(this, mappedProperty.getName()); + } + + if (feature instanceof EReference) + { + // TODO Clarify feature maps + return new CDOReferenceSetter(this, mappedProperty.getName()); + } + + return new CDOPropertySetter(this, mappedProperty.getName()); + } + + @Override + protected Instantiator buildInstantiator(PersistentClass mappingInfo) + { + return new CDORevisionInstantiator(this, mappingInfo); + } + + @Override + protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) + { + CDORevisionProxyFactory pf = new CDORevisionProxyFactory(); + pf.setEntityName(getEntityName()); + + try + { + pf.postInstantiate(getEntityName(), null, null, null, null, null); + } + catch (HibernateException ex) + { + OM.LOG.error("Could not create proxy factory for " + getEntityName(), ex); //$NON-NLS-1$ + pf = null; + } + + return pf; + } + + @SuppressWarnings("rawtypes") + public Class getMappedClass() + { + return InternalCDORevision.class; + } + + @SuppressWarnings("rawtypes") + public Class getConcreteProxyClass() + { + return InternalCDORevision.class; + } + + public boolean isInstrumented() + { + return false; + } + + private void setIdentifierTypeAsAnnotation(Property prop) + { + EAnnotation eAnnotation = getEClass().getEAnnotation(HibernateStore.ID_TYPE_EANNOTATION_SOURCE); + if (eAnnotation == null) + { + eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation(); + eAnnotation.setSource(HibernateStore.ID_TYPE_EANNOTATION_SOURCE); + eAnnotation.getDetails().put(HibernateStore.ID_TYPE_EANNOTATION_KEY, prop.getType().getName()); + getEClass().getEAnnotations().add(eAnnotation); + } + else if (!eAnnotation.getDetails().containsKey(HibernateStore.ID_TYPE_EANNOTATION_KEY)) + { + eAnnotation.getDetails().put(HibernateStore.ID_TYPE_EANNOTATION_KEY, prop.getType().getName()); + } + } + + @Override + protected Instantiator buildInstantiator(EntityBinding arg0) + { + return null; + } + + @Override + protected Getter buildPropertyGetter(AttributeBinding arg0) + { + return null; + } + + @Override + protected Setter buildPropertySetter(AttributeBinding arg0) + { + return null; + } + + @Override + protected ProxyFactory buildProxyFactory(EntityBinding arg0, Getter arg1, Setter arg2) + { + return null; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticIdPropertyHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticIdPropertyHandler.java index e78045bd36..23189bbe8c 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticIdPropertyHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticIdPropertyHandler.java @@ -1,131 +1,131 @@ -/*
- * 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 and implementation
- * 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.id.CDOIDTemp;
-import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateCommitContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-import org.hibernate.property.PropertyAccessor;
-import org.hibernate.property.Setter;
-
-import java.io.Serializable;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * Is only used for synthetic id's.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class CDOSyntheticIdPropertyHandler implements Getter, Setter, PropertyAccessor
-{
- private static final long serialVersionUID = 1L;
-
- @SuppressWarnings("rawtypes")
- public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- @SuppressWarnings("rawtypes")
- public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- public Member getMember()
- {
- return null;
- }
-
- public Object get(Object owner) throws HibernateException
- {
- InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(owner);
- if (revision == null)
- {
- return null;
- }
-
- if (!HibernateUtil.getInstance().isStoreCreatedID(HibernateUtil.getInstance().getCDOID(revision)))
- {
- return null;
- }
-
- return HibernateUtil.getInstance().getIdValue(HibernateUtil.getInstance().getCDOID(revision));
- }
-
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object arg0, Map arg1, SessionImplementor arg2) throws HibernateException
- {
- return get(arg0);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return null;
- }
-
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- if (value == null)
- {
- return;
- }
-
- final InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(target);
- final CDOID id = HibernateUtil.getInstance().getCDOID(revision);
- if (id == null || id instanceof CDOIDTemp)
- {
- final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value);
- revision.setID(newCDOID);
- if (HibernateThreadContext.isCommitContextSet())
- {
- final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext();
- commitContext.setNewID(id, newCDOID);
- if (id instanceof CDOIDTemp)
- {
- commitContext.getCommitContext().addIDMapping(id, newCDOID);
- }
- }
- }
- else
- {
- final Serializable idValue = HibernateUtil.getInstance().getIdValue(id);
- if (!idValue.equals(value))
- {
- throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
-}
+/* + * 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 and implementation + * 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.id.CDOIDTemp; +import org.eclipse.emf.cdo.common.model.CDOClassifierRef; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateCommitContext; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.PropertyNotFoundException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; +import org.hibernate.property.PropertyAccessor; +import org.hibernate.property.Setter; + +import java.io.Serializable; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * Is only used for synthetic id's. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class CDOSyntheticIdPropertyHandler implements Getter, Setter, PropertyAccessor +{ + private static final long serialVersionUID = 1L; + + @SuppressWarnings("rawtypes") + public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + @SuppressWarnings("rawtypes") + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + public Member getMember() + { + return null; + } + + public Object get(Object owner) throws HibernateException + { + InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(owner); + if (revision == null) + { + return null; + } + + if (!HibernateUtil.getInstance().isStoreCreatedID(HibernateUtil.getInstance().getCDOID(revision))) + { + return null; + } + + return HibernateUtil.getInstance().getIdValue(HibernateUtil.getInstance().getCDOID(revision)); + } + + @SuppressWarnings("rawtypes") + public Object getForInsert(Object arg0, Map arg1, SessionImplementor arg2) throws HibernateException + { + return get(arg0); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return null; + } + + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + if (value == null) + { + return; + } + + final InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(target); + final CDOID id = HibernateUtil.getInstance().getCDOID(revision); + if (id == null || id instanceof CDOIDTemp) + { + final CDOID newCDOID = HibernateUtil.getInstance().createCDOID(new CDOClassifierRef(revision.getEClass()), value); + revision.setID(newCDOID); + if (HibernateThreadContext.isCommitContextSet()) + { + final HibernateCommitContext commitContext = HibernateThreadContext.getCommitContext(); + commitContext.setNewID(id, newCDOID); + if (id instanceof CDOIDTemp) + { + commitContext.getCommitContext().addIDMapping(id, newCDOID); + } + } + } + else + { + final Serializable idValue = HibernateUtil.getInstance().getIdValue(id); + if (!idValue.equals(value)) + { + throw new IllegalStateException("Current id and new id are different " + value + "/" + idValue); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticVersionPropertyHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticVersionPropertyHandler.java index d6f7083de5..6bfeea278f 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticVersionPropertyHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOSyntheticVersionPropertyHandler.java @@ -1,102 +1,102 @@ -/*
- * 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 and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-import org.hibernate.property.PropertyAccessor;
-import org.hibernate.property.Setter;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * Reads the version from the internal version cache.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class CDOSyntheticVersionPropertyHandler implements Getter, Setter, PropertyAccessor
-{
- private static final long serialVersionUID = 1L;
-
- public CDOSyntheticVersionPropertyHandler()
- {
- }
-
- @SuppressWarnings("rawtypes")
- public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- @SuppressWarnings("rawtypes")
- public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- public Object get(Object owner) throws HibernateException
- {
- InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(owner);
- if (revision == null)
- {
- return null;
- }
-
- return revision.getVersion();
- }
-
- /**
- * Reads the version from the versioncache
- */
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- return get(owner);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public Member getMember()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- /** Returns Integer.class */
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return Integer.class;
- }
-
- /** Sets the version in the internal version cache */
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(target);
- revision.setVersion(((Number)value).intValue());
- }
-}
+/* + * 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 and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.PropertyNotFoundException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; +import org.hibernate.property.PropertyAccessor; +import org.hibernate.property.Setter; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * Reads the version from the internal version cache. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class CDOSyntheticVersionPropertyHandler implements Getter, Setter, PropertyAccessor +{ + private static final long serialVersionUID = 1L; + + public CDOSyntheticVersionPropertyHandler() + { + } + + @SuppressWarnings("rawtypes") + public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + @SuppressWarnings("rawtypes") + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + public Object get(Object owner) throws HibernateException + { + InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(owner); + if (revision == null) + { + return null; + } + + return revision.getVersion(); + } + + /** + * Reads the version from the versioncache + */ + @SuppressWarnings("rawtypes") + public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException + { + return get(owner); + } + + public Method getMethod() + { + return null; + } + + public Member getMember() + { + return null; + } + + public String getMethodName() + { + return null; + } + + /** Returns Integer.class */ + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return Integer.class; + } + + /** Sets the version in the internal version cache */ + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + InternalCDORevision revision = HibernateUtil.getInstance().getCDORevision(target); + revision.setVersion(((Number)value).intValue()); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOTypeUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOTypeUserType.java index 31f47ff648..afe064209d 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOTypeUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOTypeUserType.java @@ -1,119 +1,122 @@ -/*
- * 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.model.CDOModelUtil;
-import org.eclipse.emf.cdo.common.model.CDOType;
-
-import org.hibernate.type.StandardBasicTypes;
-import org.hibernate.usertype.UserType;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-/**
- * @author Martin Taal
- */
-public class CDOTypeUserType implements UserType
-{
- private static final int[] SQL_TYPES = { Types.INTEGER };
-
- public CDOTypeUserType()
- {
- }
-
- public int[] sqlTypes()
- {
- return SQL_TYPES;
- }
-
- public Class<?> returnedClass()
- {
- return CDOType.class;
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- public Object deepCopy(Object value)
- {
- return value;
- }
-
- public boolean equals(Object x, Object y)
- {
- if (x == y)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException
- {
- Integer value = StandardBasicTypes.INTEGER.nullSafeGet(rs, names[0]);
- if (rs.wasNull())
- {
- return null;
- }
-
- if (value == null)
- {
- return null;
- }
-
- return CDOModelUtil.getType((byte)(int)value);
- }
-
- public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException
- {
- if (value != null)
- {
- statement.setInt(index, ((CDOType)value).getTypeID());
- }
- else
- {
- statement.setNull(index, Types.INTEGER);
- }
- }
-
- public Serializable disassemble(Object value)
- {
- return (Serializable)value;
- }
-
- public Object assemble(Serializable cachedValue, Object owner)
- {
- return cachedValue;
- }
-
- public Object replace(Object original, Object target, Object owner)
- {
- return original;
- }
-
- public int hashCode(Object x)
- {
- return x.hashCode();
- }
-}
+/* + * 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.model.CDOModelUtil; +import org.eclipse.emf.cdo.common.model.CDOType; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.type.StandardBasicTypes; +import org.hibernate.usertype.UserType; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +/** + * @author Martin Taal + */ +public class CDOTypeUserType implements UserType +{ + private static final int[] SQL_TYPES = { Types.INTEGER }; + + public CDOTypeUserType() + { + } + + public int[] sqlTypes() + { + return SQL_TYPES; + } + + public Class<?> returnedClass() + { + return CDOType.class; + } + + public boolean isMutable() + { + return false; + } + + public Object deepCopy(Object value) + { + return value; + } + + public boolean equals(Object x, Object y) + { + if (x == y) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + return x.equals(y); + } + + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner) + throws SQLException + { + Integer value = StandardBasicTypes.INTEGER.nullSafeGet(rs, names[0], sessionImplementor); + if (rs.wasNull()) + { + return null; + } + + if (value == null) + { + return null; + } + + return CDOModelUtil.getType((byte)(int)value); + } + + public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor sessionImplementor) + throws SQLException + { + if (value != null) + { + statement.setInt(index, ((CDOType)value).getTypeID()); + } + else + { + statement.setNull(index, Types.INTEGER); + } + } + + public Serializable disassemble(Object value) + { + return (Serializable)value; + } + + public Object assemble(Serializable cachedValue, Object owner) + { + return cachedValue; + } + + public Object replace(Object original, Object target, Object owner) + { + return original; + } + + public int hashCode(Object x) + { + return x.hashCode(); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOUUIDHexGenerator.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOUUIDHexGenerator.java index 7f7bb1586a..76139d2c15 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOUUIDHexGenerator.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOUUIDHexGenerator.java @@ -1,49 +1,49 @@ -/*
- * 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.revision.CDORevision;
-
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.id.UUIDHexGenerator;
-import org.hibernate.persister.entity.EntityPersister;
-
-import java.io.Serializable;
-
-/**
- * An example of overriding the standard UUID generator of Hibernate to prevent it overwriting an already existing id in
- * an object.
- *
- * @author mtaal
- */
-
-public class CDOUUIDHexGenerator extends UUIDHexGenerator
-{
- @Override
- public Serializable generate(SessionImplementor session, Object obj)
- {
- if (!(obj instanceof CDORevision))
- {
- return super.generate(session, obj);
- }
-
- final EntityPersister entityPersister = session.getEntityPersister(null, obj);
- final Serializable id = entityPersister.getIdentifier(obj, session);
- if (id != null)
- {
- return id;
- }
-
- return super.generate(session, obj);
- }
-}
+/* + * 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.revision.CDORevision; + +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.id.UUIDHexGenerator; +import org.hibernate.persister.entity.EntityPersister; + +import java.io.Serializable; + +/** + * An example of overriding the standard UUID generator of Hibernate to prevent it overwriting an already existing id in + * an object. + * + * @author mtaal + */ + +public class CDOUUIDHexGenerator extends UUIDHexGenerator +{ + @Override + public Serializable generate(SessionImplementor session, Object obj) + { + if (!(obj instanceof CDORevision)) + { + return super.generate(session, obj); + } + + final EntityPersister entityPersister = session.getEntityPersister(null, obj); + final Serializable id = entityPersister.getIdentifier(obj, session); + if (id != null) + { + return id; + } + + return super.generate(session, obj); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOVersionPropertySetter.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOVersionPropertySetter.java index be5c6daef6..f597460a0c 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOVersionPropertySetter.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/CDOVersionPropertySetter.java @@ -1,47 +1,47 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-
-/**
- * @author Martin Taal
- */
-public class CDOVersionPropertySetter extends CDOPropertySetter
-{
- private static final long serialVersionUID = 1L;
-
- public CDOVersionPropertySetter(CDORevisionTuplizer tuplizer, String propertyName)
- {
- super(tuplizer, propertyName);
- }
-
- @Override
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- InternalCDORevision revision = (InternalCDORevision)target;
- revision.setVersion(((Number)value).intValue());
- if (!isVirtualProperty())
- {
- super.set(target, value, factory);
- }
- }
-
- @Override
- protected boolean isVirtualPropertyAllowed()
- {
- return true;
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionFactoryImplementor; + +/** + * @author Martin Taal + */ +public class CDOVersionPropertySetter extends CDOPropertySetter +{ + private static final long serialVersionUID = 1L; + + public CDOVersionPropertySetter(CDORevisionTuplizer tuplizer, String propertyName) + { + super(tuplizer, propertyName); + } + + @Override + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + InternalCDORevision revision = (InternalCDORevision)target; + revision.setVersion(((Number)value).intValue()); + if (!isVirtualProperty()) + { + super.set(target, value, factory); + } + } + + @Override + protected boolean isVirtualPropertyAllowed() + { + return true; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryFeatureURIPropertyHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryFeatureURIPropertyHandler.java index d73e3fe38b..117ba81604 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryFeatureURIPropertyHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryFeatureURIPropertyHandler.java @@ -1,150 +1,150 @@ -/*
- * 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.server.internal.hibernate.HibernateCommitContext;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext;
-import org.eclipse.emf.cdo.spi.common.revision.CDOFeatureMapEntry;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-import org.hibernate.property.PropertyAccessor;
-import org.hibernate.property.Setter;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * Handles the string representation of the feature of the feature map entry in the database.
- *
- * @see CDOFeatureMapEntry#setEStructuralFeature(EStructuralFeature)
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class FeatureMapEntryFeatureURIPropertyHandler implements PropertyAccessor, Getter, Setter
-{
- private static final String EFEATURE_SEPARATOR = "#"; //$NON-NLS-1$
-
- private static final long serialVersionUID = 1L;
-
- @SuppressWarnings("rawtypes")
- public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- @SuppressWarnings("rawtypes")
- public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- public Member getMember()
- {
- return null;
- }
-
- public Object get(Object owner) throws HibernateException
- {
- final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)owner;
- return getEStructuralFeatureAsString(cdoFeatureMapEntry);
- }
-
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- return get(owner);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return String.class;
- }
-
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)target;
- setEStructuralFeatureFromString(cdoFeatureMapEntry, (String)value);
- }
-
- /**
- * Set the EStructuralFeature (see {@link #setEStructuralFeature(EStructuralFeature)}) from its String representation.
- *
- * @param eFeatureURI
- * a String representation, must be created by the {@link #getEStructuralFeatureAsString()} method
- * @see #getEStructuralFeatureAsString()
- */
- private void setEStructuralFeatureFromString(CDOFeatureMapEntry fmEntry, String eFeatureURI)
- {
- final int firstSeparator = eFeatureURI.indexOf(EFEATURE_SEPARATOR);
- final int lastSeparator = eFeatureURI.lastIndexOf(EFEATURE_SEPARATOR);
- if (firstSeparator == -1 || lastSeparator == -1 || firstSeparator == lastSeparator)
- {
- throw new IllegalArgumentException("EFeature URI " + eFeatureURI + " has an illegal format"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final String ePackageURI = eFeatureURI.substring(0, firstSeparator);
- final String eClassName = eFeatureURI.substring(1 + firstSeparator, lastSeparator);
- final String eFeatureName = eFeatureURI.substring(1 + lastSeparator);
-
- final HibernateCommitContext hbCommitContext = HibernateThreadContext.getCommitContext();
- final EPackage ePackage = hbCommitContext.getCommitContext().getPackageRegistry().getEPackage(ePackageURI);
- if (ePackage == null)
- {
- throw new IllegalArgumentException("EPackage not found using " + eFeatureURI + " and EPackageURI: " + ePackageURI); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final EClass eClass = (EClass)ePackage.getEClassifier(eClassName);
- if (eClass == null)
- {
- throw new IllegalArgumentException("EClass not found using " + eFeatureURI + " and EClass name " + eClassName); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final EStructuralFeature eFeature = eClass.getEStructuralFeature(eFeatureName);
- if (eFeature == null)
- {
- throw new IllegalArgumentException("EClass not found using " + eFeatureURI + ", EClass name " + eClassName //$NON-NLS-1$ //$NON-NLS-2$
- + " and EFeature name " + eFeatureName); //$NON-NLS-1$
- }
-
- fmEntry.setEStructuralFeature(eFeature);
- }
-
- /**
- * @return a unique String version for an EStructuralFeature
- */
- private String getEStructuralFeatureAsString(CDOFeatureMapEntry fmEntry)
- {
- final EStructuralFeature eFeature = fmEntry.getEStructuralFeature();
- final EClass eClass = eFeature.getEContainingClass();
- return eClass.getEPackage().getNsURI() + EFEATURE_SEPARATOR + eClass.getName() + EFEATURE_SEPARATOR
- + eFeature.getName();
- }
-}
+/* + * 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.server.internal.hibernate.HibernateCommitContext; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateThreadContext; +import org.eclipse.emf.cdo.spi.common.revision.CDOFeatureMapEntry; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.HibernateException; +import org.hibernate.PropertyNotFoundException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; +import org.hibernate.property.PropertyAccessor; +import org.hibernate.property.Setter; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * Handles the string representation of the feature of the feature map entry in the database. + * + * @see CDOFeatureMapEntry#setEStructuralFeature(EStructuralFeature) + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class FeatureMapEntryFeatureURIPropertyHandler implements PropertyAccessor, Getter, Setter +{ + private static final String EFEATURE_SEPARATOR = "#"; //$NON-NLS-1$ + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("rawtypes") + public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + @SuppressWarnings("rawtypes") + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + public Member getMember() + { + return null; + } + + public Object get(Object owner) throws HibernateException + { + final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)owner; + return getEStructuralFeatureAsString(cdoFeatureMapEntry); + } + + @SuppressWarnings("rawtypes") + public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException + { + return get(owner); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return String.class; + } + + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)target; + setEStructuralFeatureFromString(cdoFeatureMapEntry, (String)value); + } + + /** + * Set the EStructuralFeature (see {@link #setEStructuralFeature(EStructuralFeature)}) from its String representation. + * + * @param eFeatureURI + * a String representation, must be created by the {@link #getEStructuralFeatureAsString()} method + * @see #getEStructuralFeatureAsString() + */ + private void setEStructuralFeatureFromString(CDOFeatureMapEntry fmEntry, String eFeatureURI) + { + final int firstSeparator = eFeatureURI.indexOf(EFEATURE_SEPARATOR); + final int lastSeparator = eFeatureURI.lastIndexOf(EFEATURE_SEPARATOR); + if (firstSeparator == -1 || lastSeparator == -1 || firstSeparator == lastSeparator) + { + throw new IllegalArgumentException("EFeature URI " + eFeatureURI + " has an illegal format"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final String ePackageURI = eFeatureURI.substring(0, firstSeparator); + final String eClassName = eFeatureURI.substring(1 + firstSeparator, lastSeparator); + final String eFeatureName = eFeatureURI.substring(1 + lastSeparator); + + final HibernateCommitContext hbCommitContext = HibernateThreadContext.getCommitContext(); + final EPackage ePackage = hbCommitContext.getCommitContext().getPackageRegistry().getEPackage(ePackageURI); + if (ePackage == null) + { + throw new IllegalArgumentException("EPackage not found using " + eFeatureURI + " and EPackageURI: " + ePackageURI); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final EClass eClass = (EClass)ePackage.getEClassifier(eClassName); + if (eClass == null) + { + throw new IllegalArgumentException("EClass not found using " + eFeatureURI + " and EClass name " + eClassName); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final EStructuralFeature eFeature = eClass.getEStructuralFeature(eFeatureName); + if (eFeature == null) + { + throw new IllegalArgumentException("EClass not found using " + eFeatureURI + ", EClass name " + eClassName //$NON-NLS-1$ //$NON-NLS-2$ + + " and EFeature name " + eFeatureName); //$NON-NLS-1$ + } + + fmEntry.setEStructuralFeature(eFeature); + } + + /** + * @return a unique String version for an EStructuralFeature + */ + private String getEStructuralFeatureAsString(CDOFeatureMapEntry fmEntry) + { + final EStructuralFeature eFeature = fmEntry.getEStructuralFeature(); + final EClass eClass = eFeature.getEContainingClass(); + return eClass.getEPackage().getNsURI() + EFEATURE_SEPARATOR + eClass.getName() + EFEATURE_SEPARATOR + + eFeature.getName(); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryPropertyHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryPropertyHandler.java index 3291997a88..a783d43ee6 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryPropertyHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/FeatureMapEntryPropertyHandler.java @@ -1,114 +1,114 @@ -/*
- * 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.spi.common.revision.CDOFeatureMapEntry;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.Getter;
-import org.hibernate.property.PropertyAccessor;
-import org.hibernate.property.Setter;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-/**
- * Implements the Hibernate accessor for mapped feature map properties. The owner object is always an instance of the
- * {@link CDOFeatureMapEntry}. Returns null if the mapped property has a different name then the current feature of the
- * owner (the CDOFeatureMapEntry), calls {@link CDOFeatureMapEntry#getValue()} in all other cases.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class FeatureMapEntryPropertyHandler implements PropertyAccessor, Getter, Setter
-{
- private static final long serialVersionUID = 1L;
-
- private String propertyName;
-
- @SuppressWarnings("rawtypes")
- public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- @SuppressWarnings("rawtypes")
- public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException
- {
- return this;
- }
-
- public Member getMember()
- {
- return null;
- }
-
- public String getPropertyName()
- {
- return propertyName;
- }
-
- public void setPropertyName(String propertyName)
- {
- this.propertyName = propertyName;
- }
-
- public Object get(Object owner) throws HibernateException
- {
- final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)owner;
- if (!isApplicable(cdoFeatureMapEntry))
- {
- return null;
- }
-
- return cdoFeatureMapEntry.getValue();
- }
-
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- return get(owner);
- }
-
- public Method getMethod()
- {
- return null;
- }
-
- public String getMethodName()
- {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getReturnType()
- {
- return CDOFeatureMapEntry.class;
- }
-
- public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException
- {
- final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)target;
- if (value != null)
- {
- cdoFeatureMapEntry.setValue(value);
- }
- }
-
- private boolean isApplicable(CDOFeatureMapEntry cdoFeatureMapEntry)
- {
- return cdoFeatureMapEntry.getEStructuralFeature().getName().equals(getPropertyName());
- }
-}
+/* + * 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.spi.common.revision.CDOFeatureMapEntry; + +import org.hibernate.HibernateException; +import org.hibernate.PropertyNotFoundException; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.property.Getter; +import org.hibernate.property.PropertyAccessor; +import org.hibernate.property.Setter; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * Implements the Hibernate accessor for mapped feature map properties. The owner object is always an instance of the + * {@link CDOFeatureMapEntry}. Returns null if the mapped property has a different name then the current feature of the + * owner (the CDOFeatureMapEntry), calls {@link CDOFeatureMapEntry#getValue()} in all other cases. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class FeatureMapEntryPropertyHandler implements PropertyAccessor, Getter, Setter +{ + private static final long serialVersionUID = 1L; + + private String propertyName; + + @SuppressWarnings("rawtypes") + public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + @SuppressWarnings("rawtypes") + public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException + { + return this; + } + + public Member getMember() + { + return null; + } + + public String getPropertyName() + { + return propertyName; + } + + public void setPropertyName(String propertyName) + { + this.propertyName = propertyName; + } + + public Object get(Object owner) throws HibernateException + { + final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)owner; + if (!isApplicable(cdoFeatureMapEntry)) + { + return null; + } + + return cdoFeatureMapEntry.getValue(); + } + + @SuppressWarnings("rawtypes") + public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException + { + return get(owner); + } + + public Method getMethod() + { + return null; + } + + public String getMethodName() + { + return null; + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() + { + return CDOFeatureMapEntry.class; + } + + public void set(Object target, Object value, SessionFactoryImplementor factory) throws HibernateException + { + final CDOFeatureMapEntry cdoFeatureMapEntry = (CDOFeatureMapEntry)target; + if (value != null) + { + cdoFeatureMapEntry.setValue(value); + } + } + + private boolean isApplicable(CDOFeatureMapEntry cdoFeatureMapEntry) + { + return cdoFeatureMapEntry.getEStructuralFeature().getName().equals(getPropertyName()); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/PersistableListHolder.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/PersistableListHolder.java index ea2d857ff7..dc345e6568 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/PersistableListHolder.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/PersistableListHolder.java @@ -1,117 +1,117 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-
-import org.hibernate.collection.PersistentCollection;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Keeps mappings from object/feature combinations to a hibernate persistable list. This works because the write action
- * is done in one thread.
- *
- * @author Martin Taal
- */
-public class PersistableListHolder
-{
- private static PersistableListHolder instance = new PersistableListHolder();
-
- private static ThreadLocal<Map<Key, PersistentCollection>> listMapping = new ThreadLocal<Map<Key, PersistentCollection>>();
-
- public PersistableListHolder()
- {
- }
-
- public void putListMapping(Object target, EStructuralFeature feature, PersistentCollection collection)
- {
- Key key = new Key(target, feature);
- final PersistentCollection currentCachedValue = getListMapping(target, feature);
- if (currentCachedValue == collection)
- {
- return;
- }
-
- if (currentCachedValue != null)
- {
- throw new IllegalStateException("There is already a list mapping present");
- }
-
- getListMapping().put(key, collection);
- }
-
- public PersistentCollection getListMapping(Object target, EStructuralFeature feature)
- {
- Key key = new Key(target, feature);
- return getListMapping().get(key);
- }
-
- private Map<Key, PersistentCollection> getListMapping()
- {
- if (listMapping.get() == null)
- {
- listMapping.set(new HashMap<Key, PersistentCollection>());
- }
-
- return listMapping.get();
- }
-
- public void clearListMapping()
- {
- listMapping.set(null);
- }
-
- public static PersistableListHolder getInstance()
- {
- return instance;
- }
-
- public static void setInstance(PersistableListHolder instance)
- {
- PersistableListHolder.instance = instance;
- }
-
- private static final class Key
- {
- private Object owner;
-
- private EStructuralFeature feature;
-
- public Key(Object owner, EStructuralFeature feature)
- {
- this.owner = owner;
- this.feature = feature;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (!(obj instanceof Key))
- {
- return false;
- }
-
- Key otherKey = (Key)obj;
- // the owner is uniquely present in mem, the same applies for the feature
- // therefore == is allowed
- return owner == otherKey.owner && feature == otherKey.feature;
- }
-
- @Override
- public int hashCode()
- {
- return owner.hashCode() + feature.hashCode();
- }
- }
-}
+/* + * 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.ecore.EStructuralFeature; + +import org.hibernate.collection.spi.PersistentCollection; + +import java.util.HashMap; +import java.util.Map; + +/** + * Keeps mappings from object/feature combinations to a hibernate persistable list. This works because the write action + * is done in one thread. + * + * @author Martin Taal + */ +public class PersistableListHolder +{ + private static PersistableListHolder instance = new PersistableListHolder(); + + private static ThreadLocal<Map<Key, PersistentCollection>> listMapping = new ThreadLocal<Map<Key, PersistentCollection>>(); + + public PersistableListHolder() + { + } + + public void putListMapping(Object target, EStructuralFeature feature, PersistentCollection collection) + { + Key key = new Key(target, feature); + final PersistentCollection currentCachedValue = getListMapping(target, feature); + if (currentCachedValue == collection) + { + return; + } + + if (currentCachedValue != null) + { + throw new IllegalStateException("There is already a list mapping present"); + } + + getListMapping().put(key, collection); + } + + public PersistentCollection getListMapping(Object target, EStructuralFeature feature) + { + Key key = new Key(target, feature); + return getListMapping().get(key); + } + + private Map<Key, PersistentCollection> getListMapping() + { + if (listMapping.get() == null) + { + listMapping.set(new HashMap<Key, PersistentCollection>()); + } + + return listMapping.get(); + } + + public void clearListMapping() + { + listMapping.set(null); + } + + public static PersistableListHolder getInstance() + { + return instance; + } + + public static void setInstance(PersistableListHolder instance) + { + PersistableListHolder.instance = instance; + } + + private static final class Key + { + private Object owner; + + private EStructuralFeature feature; + + public Key(Object owner, EStructuralFeature feature) + { + this.owner = owner; + this.feature = feature; + } + + @Override + public boolean equals(Object obj) + { + if (!(obj instanceof Key)) + { + return false; + } + + Key otherKey = (Key)obj; + // the owner is uniquely present in mem, the same applies for the feature + // therefore == is allowed + return owner == otherKey.owner && feature == otherKey.feature; + } + + @Override + public int hashCode() + { + return owner.hashCode() + feature.hashCode(); + } + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WildCardAttributePropertyHandler.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WildCardAttributePropertyHandler.java index e857019dd3..9dce0ab5cb 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WildCardAttributePropertyHandler.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/WildCardAttributePropertyHandler.java @@ -1,66 +1,66 @@ -/*
- * 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 - copied from CDORevisionPropertyHandler and adapted
- * Eike Stepper - maintenance
- */
-package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer;
-
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EDataType;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.util.FeatureMap;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionImplementor;
-
-import java.util.Map;
-
-/**
- * Implements the getter/setter for a wild card EAttribute property. This type of property is used in a feature map
- * created for wild cards. This class implements both the getter, setter and propertyaccessor interfaces. When the
- * getGetter and getSetter methods are called it returns itself.
- *
- * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
- */
-public class WildCardAttributePropertyHandler extends FeatureMapEntryPropertyHandler
-{
- private static final long serialVersionUID = -2659637883475733107L;
-
- @Override
- public Object get(Object owner) throws HibernateException
- {
- final FeatureMap.Entry fme = (FeatureMap.Entry)owner;
- final Object value = fme.getValue();
- final EStructuralFeature eFeature = fme.getEStructuralFeature();
- // not handled by this one
- if (value instanceof EObject)
- {
- return null;
- }
-
- if (value == null)
- {
- return null;
- }
-
- final EAttribute eAttribute = (EAttribute)eFeature;
- final EDataType eDataType = eAttribute.getEAttributeType();
- final String valueString = eDataType.getEPackage().getEFactoryInstance().convertToString(eDataType, value);
- return valueString;
- }
-
- @Override
- @SuppressWarnings("rawtypes")
- public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException
- {
- final Object value = get(owner);
- return 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 - copied from CDORevisionPropertyHandler and adapted + * Eike Stepper - maintenance + */ +package org.eclipse.emf.cdo.server.internal.hibernate.tuplizer; + +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EDataType; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.util.FeatureMap; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; + +import java.util.Map; + +/** + * Implements the getter/setter for a wild card EAttribute property. This type of property is used in a feature map + * created for wild cards. This class implements both the getter, setter and propertyaccessor interfaces. When the + * getGetter and getSetter methods are called it returns itself. + * + * @author <a href="mailto:mtaal@elver.org">Martin Taal</a> + */ +public class WildCardAttributePropertyHandler extends FeatureMapEntryPropertyHandler +{ + private static final long serialVersionUID = -2659637883475733107L; + + @Override + public Object get(Object owner) throws HibernateException + { + final FeatureMap.Entry fme = (FeatureMap.Entry)owner; + final Object value = fme.getValue(); + final EStructuralFeature eFeature = fme.getEStructuralFeature(); + // not handled by this one + if (value instanceof EObject) + { + return null; + } + + if (value == null) + { + return null; + } + + final EAttribute eAttribute = (EAttribute)eFeature; + final EDataType eDataType = eAttribute.getEAttributeType(); + final String valueString = eDataType.getEPackage().getEFactoryInstance().convertToString(eDataType, value); + return valueString; + } + + @Override + @SuppressWarnings("rawtypes") + public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session) throws HibernateException + { + final Object value = get(owner); + return value; + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/XMLUserType.java b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/XMLUserType.java index 41cced2c4c..98e8bdeff9 100644 --- a/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/XMLUserType.java +++ b/plugins/org.eclipse.emf.cdo.server.hibernate/src/org/eclipse/emf/cdo/server/internal/hibernate/tuplizer/XMLUserType.java @@ -1,635 +1,637 @@ -/*
- * 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.model.CDOPackageRegistry;
-import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil;
-
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EDataType;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
-
-import org.hibernate.HibernateException;
-import org.hibernate.usertype.UserType;
-
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import java.io.Serializable;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-
-/**
- * Persists the types from the {@link XMLTypePackage}.
- */
-public class XMLUserType implements UserType
-{
- private final static java.lang.String XML_TYPE_PACKAGE_NSURI = "http://www.eclipse.org/emf/2003/XMLType"; //$NON-NLS-1$
-
- private EDataType eDataType = null;
-
- private int[] sqlTypes = null;
-
- public Object assemble(Serializable arg0, Object arg1) throws HibernateException
- {
- return arg1;
- }
-
- public Object deepCopy(Object arg0) throws HibernateException
- {
- return arg0;
- }
-
- public Serializable disassemble(Object arg0) throws HibernateException
- {
- return (Serializable)arg0;
- }
-
- public boolean equals(Object x, Object y) throws HibernateException
- {
- // todo: check compare on null values
- if (x == null && y == null)
- {
- return true;
- }
-
- if (x == null || y == null)
- {
- return false;
- }
-
- if (x.getClass() != y.getClass())
- {
- return false;
- }
-
- return x.equals(y);
- }
-
- public int hashCode(Object arg0) throws HibernateException
- {
- return arg0.hashCode();
- }
-
- public boolean isMutable()
- {
- return false;
- }
-
- protected java.lang.String convertToString(Object value)
- {
- if (value == null)
- {
- return null;
- }
- if (value instanceof String)
- {
- return (java.lang.String)value;
- }
- if (getEDataType() == null)
- {
- return value.toString();
- }
- final EDataType eDataType = getEDataType();
- return eDataType.getEPackage().getEFactoryInstance().convertToString(eDataType, value);
- }
-
- protected Object convertToObject(java.lang.String value)
- {
- if (getEDataType() == null || value == null)
- {
- return value;
- }
- final EDataType eDataType = getEDataType();
- return eDataType.getEPackage().getEFactoryInstance().createFromString(eDataType, value);
- }
-
- private EDataType getEDataType()
- {
- if (eDataType != null)
- {
- return eDataType;
- }
- final CDOPackageRegistry packageRegistry = HibernateUtil.getInstance().getPackageRegistry();
- final EPackage ePackage = packageRegistry.getEPackage(XML_TYPE_PACKAGE_NSURI);
- if (ePackage == null)
- {
- throw new IllegalStateException("EPackage with nsuri " + XML_TYPE_PACKAGE_NSURI + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- final EClassifier eClassifier = ePackage.getEClassifier(getEDataTypeName());
- if (eClassifier == null || !(eClassifier instanceof EDataType))
- {
- throw new IllegalStateException("EPackage " + ePackage.getName() + " does not have an EEnum with name " //$NON-NLS-1$ //$NON-NLS-2$
- + getEDataTypeName());
- }
-
- eDataType = (EDataType)eClassifier;
-
- return eDataType;
- }
-
- protected java.lang.String getEDataTypeName()
- {
- if (this.getClass() != XMLUserType.class)
- {
- return this.getClass().getSimpleName();
- }
-
- return "String"; //$NON-NLS-1$
- }
-
- public Object nullSafeGet(ResultSet arg0, java.lang.String[] arg1, Object arg2) throws HibernateException,
- SQLException
- {
- final Object value = arg0.getObject(arg1[0]);
- if (arg0.wasNull())
- {
- return null;
- }
-
- return convertToString(value);
- }
-
- public void nullSafeSet(PreparedStatement arg0, Object arg1, int arg2) throws HibernateException, SQLException
- {
- if (arg1 == null)
- {
- // st.setString(index, ((Enumerator)getEEnum().getDefaultValue()).getLiteral());
- arg0.setNull(arg2, sqlTypes()[0]);
- }
- else if (arg1 instanceof java.lang.String)
- {
- arg0.setObject(arg2, convertToObject((java.lang.String)arg1), getSqlType());
- }
- else
- {
- arg0.setObject(arg2, arg1, getSqlType());
- }
- }
-
- public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException
- {
- return arg0;
- }
-
- @SuppressWarnings("rawtypes")
- public Class returnedClass()
- {
- if (getEDataType() == null || getEDataType().getInstanceClass() == null)
- {
- return String.class;
- }
- return getEDataType().getInstanceClass();
- }
-
- public int[] sqlTypes()
- {
- if (sqlTypes == null)
- {
- sqlTypes = new int[] { getSqlType() };
- }
- return sqlTypes;
- }
-
- protected int getSqlType()
- {
- return Types.VARCHAR;
- }
-
- public static class AnySimpleType extends XMLUserType
- {
-
- }
-
- public static class AnyURI extends XMLUserType
- {
-
- }
-
- public static class Base64Binary extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BLOB;
- }
- }
-
- public static class Boolean extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIT;
- }
- }
-
- public static class BooleanObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BOOLEAN;
- }
- }
-
- public static class Byte extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.TINYINT;
- }
- }
-
- public static class ByteObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.TINYINT;
- }
- }
-
- public static class Date extends XMLUserType
- {
- @Override
- protected java.lang.String convertToString(Object value)
- {
- if (value == null)
- {
- return super.convertToString(value);
- }
- return super.convertToString(HibernateUtil.getInstance()
- .getXMLGregorianCalendarDate((java.util.Date)value, false));
- }
-
- @Override
- protected Object convertToObject(java.lang.String value)
- {
- return new java.sql.Date(((XMLGregorianCalendar)super.convertToObject(value)).toGregorianCalendar().getTime()
- .getTime());
- }
-
- @Override
- protected int getSqlType()
- {
- return Types.DATE;
- }
- }
-
- public static class DateTime extends XMLUserType
- {
- @Override
- protected java.lang.String convertToString(Object value)
- {
- if (value == null)
- {
- return super.convertToString(value);
- }
- return super
- .convertToString(HibernateUtil.getInstance().getXMLGregorianCalendarDate((java.util.Date)value, true));
- }
-
- @Override
- protected Object convertToObject(java.lang.String value)
- {
- return new java.sql.Timestamp(((XMLGregorianCalendar)super.convertToObject(value)).toGregorianCalendar()
- .getTime().getTime());
- }
-
- @Override
- protected int getSqlType()
- {
- return Types.TIMESTAMP;
- }
- }
-
- public static class Decimal extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.NUMERIC;
- }
- }
-
- public static class Double extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.DOUBLE;
- }
- }
-
- public static class DoubleObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.DOUBLE;
- }
- }
-
- public static class Duration extends XMLUserType
- {
- }
-
- public static class ENTITIES extends XMLUserType
- {
- }
-
- public static class ENTITIESBase extends XMLUserType
- {
- }
-
- public static class ENTITY extends XMLUserType
- {
- }
-
- public static class Float extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.FLOAT;
- }
- }
-
- public static class FloatObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.FLOAT;
- }
- }
-
- public static class GDay extends XMLUserType
- {
- }
-
- public static class GMonth extends XMLUserType
- {
- }
-
- public static class GMonthDay extends XMLUserType
- {
- }
-
- public static class GYear extends XMLUserType
- {
- }
-
- public static class GYearMonth extends XMLUserType
- {
- }
-
- public static class HexBinary extends XMLUserType
- {
- }
-
- public static class ID extends XMLUserType
- {
- }
-
- public static class IDREF extends XMLUserType
- {
- }
-
- public static class IDREFS extends XMLUserType
- {
- }
-
- public static class IDREFSBase extends XMLUserType
- {
- }
-
- public static class Int extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class Integer extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class IntObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class Language extends XMLUserType
- {
- }
-
- public static class Long extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class LongObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class Name extends XMLUserType
- {
- }
-
- public static class NCName extends XMLUserType
- {
- }
-
- public static class NMTOKEN extends XMLUserType
- {
- }
-
- public static class NMTOKENS extends XMLUserType
- {
- }
-
- public static class NMTOKENSBase extends XMLUserType
- {
- }
-
- public static class String extends XMLUserType
- {
- }
-
- public static class Token extends XMLUserType
- {
- }
-
- public static class QName extends XMLUserType
- {
- }
-
- public static class NOTATION extends XMLUserType
- {
- }
-
- public static class NegativeInteger extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class NonNegativeInteger extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class NonPositiveInteger extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class PositiveInteger extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class Short extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class ShortObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class Time extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.TIME;
- }
- }
-
- public static class UnsignedByte extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.TINYINT;
- }
- }
-
- public static class UnsignedByteObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.TINYINT;
- }
- }
-
- public static class UnsignedInt extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class UnsignedIntObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class UnsignedShort extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class UnsignedShortObject extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.INTEGER;
- }
- }
-
- public static class UnsignedLong extends XMLUserType
- {
- @Override
- protected int getSqlType()
- {
- return Types.BIGINT;
- }
- }
-
- public static class NormalizedString extends XMLUserType
- {
- }
-}
+/* + * 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.model.CDOPackageRegistry; +import org.eclipse.emf.cdo.server.internal.hibernate.HibernateUtil; + +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EDataType; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.xml.type.XMLTypePackage; + +import org.hibernate.HibernateException; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.usertype.UserType; + +import javax.xml.datatype.XMLGregorianCalendar; + +import java.io.Serializable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +/** + * Persists the types from the {@link XMLTypePackage}. + */ +public class XMLUserType implements UserType +{ + private final static java.lang.String XML_TYPE_PACKAGE_NSURI = "http://www.eclipse.org/emf/2003/XMLType"; //$NON-NLS-1$ + + private EDataType eDataType = null; + + private int[] sqlTypes = null; + + public Object assemble(Serializable arg0, Object arg1) throws HibernateException + { + return arg1; + } + + public Object deepCopy(Object arg0) throws HibernateException + { + return arg0; + } + + public Serializable disassemble(Object arg0) throws HibernateException + { + return (Serializable)arg0; + } + + public boolean equals(Object x, Object y) throws HibernateException + { + // todo: check compare on null values + if (x == null && y == null) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + if (x.getClass() != y.getClass()) + { + return false; + } + + return x.equals(y); + } + + public int hashCode(Object arg0) throws HibernateException + { + return arg0.hashCode(); + } + + public boolean isMutable() + { + return false; + } + + protected java.lang.String convertToString(Object value) + { + if (value == null) + { + return null; + } + if (value instanceof String) + { + return (java.lang.String)value; + } + if (getEDataType() == null) + { + return value.toString(); + } + final EDataType eDataType = getEDataType(); + return eDataType.getEPackage().getEFactoryInstance().convertToString(eDataType, value); + } + + protected Object convertToObject(java.lang.String value) + { + if (getEDataType() == null || value == null) + { + return value; + } + final EDataType eDataType = getEDataType(); + return eDataType.getEPackage().getEFactoryInstance().createFromString(eDataType, value); + } + + private EDataType getEDataType() + { + if (eDataType != null) + { + return eDataType; + } + final CDOPackageRegistry packageRegistry = HibernateUtil.getInstance().getPackageRegistry(); + final EPackage ePackage = packageRegistry.getEPackage(XML_TYPE_PACKAGE_NSURI); + if (ePackage == null) + { + throw new IllegalStateException("EPackage with nsuri " + XML_TYPE_PACKAGE_NSURI + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + final EClassifier eClassifier = ePackage.getEClassifier(getEDataTypeName()); + if (eClassifier == null || !(eClassifier instanceof EDataType)) + { + throw new IllegalStateException("EPackage " + ePackage.getName() + " does not have an EEnum with name " //$NON-NLS-1$ //$NON-NLS-2$ + + getEDataTypeName()); + } + + eDataType = (EDataType)eClassifier; + + return eDataType; + } + + protected java.lang.String getEDataTypeName() + { + if (this.getClass() != XMLUserType.class) + { + return this.getClass().getSimpleName(); + } + + return "String"; //$NON-NLS-1$ + } + + public Object nullSafeGet(ResultSet arg0, java.lang.String[] arg1, SessionImplementor sessionImplementor, Object arg2) + throws HibernateException, SQLException + { + final Object value = arg0.getObject(arg1[0]); + if (arg0.wasNull()) + { + return null; + } + + return convertToString(value); + } + + public void nullSafeSet(PreparedStatement arg0, Object arg1, int arg2, SessionImplementor sessionImplementor) + throws HibernateException, SQLException + { + if (arg1 == null) + { + // st.setString(index, ((Enumerator)getEEnum().getDefaultValue()).getLiteral()); + arg0.setNull(arg2, sqlTypes()[0]); + } + else if (arg1 instanceof java.lang.String) + { + arg0.setObject(arg2, convertToObject((java.lang.String)arg1), getSqlType()); + } + else + { + arg0.setObject(arg2, arg1, getSqlType()); + } + } + + public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException + { + return arg0; + } + + @SuppressWarnings("rawtypes") + public Class returnedClass() + { + if (getEDataType() == null || getEDataType().getInstanceClass() == null) + { + return String.class; + } + return getEDataType().getInstanceClass(); + } + + public int[] sqlTypes() + { + if (sqlTypes == null) + { + sqlTypes = new int[] { getSqlType() }; + } + return sqlTypes; + } + + protected int getSqlType() + { + return Types.VARCHAR; + } + + public static class AnySimpleType extends XMLUserType + { + + } + + public static class AnyURI extends XMLUserType + { + + } + + public static class Base64Binary extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BLOB; + } + } + + public static class Boolean extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIT; + } + } + + public static class BooleanObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BOOLEAN; + } + } + + public static class Byte extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.TINYINT; + } + } + + public static class ByteObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.TINYINT; + } + } + + public static class Date extends XMLUserType + { + @Override + protected java.lang.String convertToString(Object value) + { + if (value == null) + { + return super.convertToString(value); + } + return super.convertToString(HibernateUtil.getInstance() + .getXMLGregorianCalendarDate((java.util.Date)value, false)); + } + + @Override + protected Object convertToObject(java.lang.String value) + { + return new java.sql.Date(((XMLGregorianCalendar)super.convertToObject(value)).toGregorianCalendar().getTime() + .getTime()); + } + + @Override + protected int getSqlType() + { + return Types.DATE; + } + } + + public static class DateTime extends XMLUserType + { + @Override + protected java.lang.String convertToString(Object value) + { + if (value == null) + { + return super.convertToString(value); + } + return super + .convertToString(HibernateUtil.getInstance().getXMLGregorianCalendarDate((java.util.Date)value, true)); + } + + @Override + protected Object convertToObject(java.lang.String value) + { + return new java.sql.Timestamp(((XMLGregorianCalendar)super.convertToObject(value)).toGregorianCalendar() + .getTime().getTime()); + } + + @Override + protected int getSqlType() + { + return Types.TIMESTAMP; + } + } + + public static class Decimal extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.NUMERIC; + } + } + + public static class Double extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.DOUBLE; + } + } + + public static class DoubleObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.DOUBLE; + } + } + + public static class Duration extends XMLUserType + { + } + + public static class ENTITIES extends XMLUserType + { + } + + public static class ENTITIESBase extends XMLUserType + { + } + + public static class ENTITY extends XMLUserType + { + } + + public static class Float extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.FLOAT; + } + } + + public static class FloatObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.FLOAT; + } + } + + public static class GDay extends XMLUserType + { + } + + public static class GMonth extends XMLUserType + { + } + + public static class GMonthDay extends XMLUserType + { + } + + public static class GYear extends XMLUserType + { + } + + public static class GYearMonth extends XMLUserType + { + } + + public static class HexBinary extends XMLUserType + { + } + + public static class ID extends XMLUserType + { + } + + public static class IDREF extends XMLUserType + { + } + + public static class IDREFS extends XMLUserType + { + } + + public static class IDREFSBase extends XMLUserType + { + } + + public static class Int extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class Integer extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class IntObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class Language extends XMLUserType + { + } + + public static class Long extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class LongObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class Name extends XMLUserType + { + } + + public static class NCName extends XMLUserType + { + } + + public static class NMTOKEN extends XMLUserType + { + } + + public static class NMTOKENS extends XMLUserType + { + } + + public static class NMTOKENSBase extends XMLUserType + { + } + + public static class String extends XMLUserType + { + } + + public static class Token extends XMLUserType + { + } + + public static class QName extends XMLUserType + { + } + + public static class NOTATION extends XMLUserType + { + } + + public static class NegativeInteger extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class NonNegativeInteger extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class NonPositiveInteger extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class PositiveInteger extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class Short extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class ShortObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class Time extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.TIME; + } + } + + public static class UnsignedByte extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.TINYINT; + } + } + + public static class UnsignedByteObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.TINYINT; + } + } + + public static class UnsignedInt extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class UnsignedIntObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class UnsignedShort extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class UnsignedShortObject extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.INTEGER; + } + } + + public static class UnsignedLong extends XMLUserType + { + @Override + protected int getSqlType() + { + return Types.BIGINT; + } + } + + public static class NormalizedString extends XMLUserType + { + } +} |