Skip to main content
summaryrefslogtreecommitdiffstats
blob: d52939ac3d793c254b05cbe3eaf6c7cba3b27fff (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
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.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;
  }
}

Back to the top