Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: bd47766f2c92b49a04270041f89a890f9af54494 (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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
/*
 * Copyright (c) 2008-2013, 2015 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.common.model.CDOModelUtil;
import org.eclipse.emf.cdo.eresource.EresourcePackage;
import org.eclipse.emf.cdo.etypes.EtypesPackage;
import org.eclipse.emf.cdo.internal.server.TransactionCommitContext.TransactionPackageRegistry;
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.common.revision.InternalCDORevision;
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.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.teneo.Constants;
import org.eclipse.emf.teneo.PackageRegistryProvider;
import org.eclipse.emf.teneo.PersistenceOptions;
import org.eclipse.emf.teneo.annotations.mapper.PersistenceMappingBuilder;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedModel;
import org.eclipse.emf.teneo.hibernate.EMFInterceptor;
import org.eclipse.emf.teneo.hibernate.HbDataStore;
import org.eclipse.emf.teneo.hibernate.HbSessionDataStore;
import org.eclipse.emf.teneo.hibernate.auditing.AuditHandler;
import org.eclipse.emf.teneo.hibernate.auditing.AuditProcessHandler;
import org.eclipse.emf.teneo.hibernate.auditing.model.teneoauditing.TeneoAuditEntry;
import org.eclipse.emf.teneo.hibernate.auditing.model.teneoauditing.TeneoauditingPackage;
import org.eclipse.emf.teneo.hibernate.mapper.HibernateMappingGenerator;

import org.hibernate.Session;
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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
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 PERSISTENCE_XML = PersistenceOptions.PERSISTENCE_XML;

  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 HbSessionDataStore cdoDataStore;

  private HibernateAuditHandler hibernateAuditHandler;

  private HibernatePackageHandler packageHandler;

  private IHibernateMappingProvider mappingProvider;

  private boolean doDropSchema;

  private SystemInformation systemInformation;

  private List<EPackage> auditEPackages;

  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, RevisionTemporality.AUDITING), 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 boolean isAuditing()
  {
    return getRevisionTemporality() == RevisionTemporality.AUDITING;
  }

  public CDOBranchPoint getMainBranchHead()
  {
    if (mainBranchHead == null)
    {
      mainBranchHead = getRepository().getBranchManager().getMainBranch().getHead();
    }

    return mainBranchHead;
  }

  public String getIdentifierPropertyName(String entityName)
  {
    return identifierPropertyNameByEntity.get(entityName);
  }

  public boolean isMapped(EClass eClass)
  {
    return null != cdoDataStore.toEntityName(eClass);
  }

  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 void addEntityNameEClassMapping(String entityName, EClass eClass)
  {
    cdoDataStore.addEntityNameEClassMapping(entityName, eClass);
  }

  /**
   * Returns all model epackages, so no audit epackages or system
   * epackages.
   */
  public List<EPackage> getModelEPackages()
  {
    final List<EPackage> epacks = getPackageHandler().getEPackages();
    final ListIterator<EPackage> iterator = epacks.listIterator();
    while (iterator.hasNext())
    {
      final EPackage epack = iterator.next();
      if (CDOModelUtil.isSystemPackage(epack) && epack != EtypesPackage.eINSTANCE)
      {
        iterator.remove();
      }
      else if (isAuditEPackage(epack))
      {
        // an auditing package
        iterator.remove();
      }
    }
    return epacks;
  }

  private boolean isAuditEPackage(EPackage ePackage)
  {
    return TeneoauditingPackage.eNS_URI.equals(ePackage.getNsURI())
        || ePackage.getEAnnotation(Constants.ANNOTATION_SOURCE_AUDITING) != null;
  }

  public String getEntityName(EClass eClass)
  {
    if (eClass == null)
    {
      throw new IllegalArgumentException("EClass argument is null"); //$NON-NLS-1$
    }
    final String entityName = cdoDataStore.toEntityName(eClass);
    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$
    }

    EClass eClass = (EClass)classifierRef.resolve(getRepository().getPackageRegistry());

    // initialize everything
    getHibernateSessionFactory();

    final String entityName = cdoDataStore.toEntityName(eClass);
    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 = cdoDataStore.toEClass(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 cdoDataStore.getConfiguration();
  }

  public synchronized SessionFactory getHibernateSessionFactory()
  {
    if (cdoDataStore == null)
    {
      if (TRACER.isEnabled())
      {
        TRACER.trace("Initializing SessionFactory for HibernateStore"); //$NON-NLS-1$
      }

      currentHibernateStore.set(this);

      identifierPropertyNameByEntity = new HashMap<String, String>();

      try
      {
        initDataStore();

        // this has to be done before the classmapping is iterated
        // otherwise it is not initialized
        SessionFactory hibernateSessionFactory = cdoDataStore.getSessionFactory();
        ServiceRegistry serviceRegistry = ((SessionFactoryImpl)hibernateSessionFactory).getServiceRegistry();
        final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService(EventListenerRegistry.class);
        eventListenerRegistry.setListeners(EventType.MERGE, new CDOMergeEventListener());

        final Iterator<?> iterator = cdoDataStore.getConfiguration().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());
        }
      }
      catch (Throwable t)
      {
        t.printStackTrace(System.err);
        if (TRACER.isEnabled())
        {
          TRACER.trace(t);
        }
        throw new RuntimeException(t);
      }
      finally
      {
        currentHibernateStore.set(null);
      }
    }

    return cdoDataStore.getSessionFactory();
  }

  public void ensureCorrectPackageRegistry()
  {
    if (cdoDataStore == null)
    {
      return;
    }
    if (cdoDataStore.getPackageRegistry() instanceof TransactionPackageRegistry)
    {
      setInternalPackageRegistry();
    }
  }

  private synchronized void setInternalPackageRegistry()
  {
    cdoDataStore.setPackageRegistry(getRepository().getPackageRegistry(false));
  }

  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);
    }
  }

  @Deprecated
  public boolean isLocal(CDOID id)
  {
    throw new UnsupportedOperationException();
  }

  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
  {
    Configuration configuration = null;
    if (cdoDataStore != null)
    {
      configuration = cdoDataStore.getConfiguration();
      if (TRACER.isEnabled())
      {
        TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$
      }
      cdoDataStore.close();
    }

    // and now do the drop action
    if (configuration != null && doDropSchema)
    {
      final SchemaExport se = new SchemaExport(configuration);
      se.drop(false, true);
    }

    cdoDataStore = null;
    hibernateAuditHandler = null;
    // get rid of the audit epackages
    if (auditEPackages != null)
    {
      for (EPackage ePackage : auditEPackages)
      {
        getRepository().getPackageRegistry().remove(ePackage.getNsURI());
      }
      auditEPackages = 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 (cdoDataStore != null)
    {
      if (!cdoDataStore.isClosed())
      {
        if (TRACER.isEnabled())
        {
          TRACER.trace("Closing SessionFactory"); //$NON-NLS-1$
        }

        cdoDataStore.close();
      }

      cdoDataStore = null;
    }
  }

  protected void initDataStore()
  {
    if (TRACER.isEnabled())
    {
      TRACER.trace("Initializing Configuration"); //$NON-NLS-1$
    }

    InputStream in = null;

    try
    {
      PackageRegistryProvider.getInstance().setThreadPackageRegistry(getRepository().getPackageRegistry());

      cdoDataStore = new CDODataStore();
      hibernateAuditHandler = new HibernateAuditHandler();
      hibernateAuditHandler.setCdoDataStore(cdoDataStore);
      hibernateAuditHandler.setHibernateStore(this);

      cdoDataStore.setResetConfigurationOnInitialization(false);
      cdoDataStore.setName("cdo");
      cdoDataStore.setPackageRegistry(getRepository().getPackageRegistry());
      cdoDataStore.getExtensionManager().registerExtension(EMFInterceptor.class.getName(),
          CDOInterceptor.class.getName());
      cdoDataStore.getExtensionManager().registerExtension(AuditHandler.class.getName(),
          CDOAuditHandler.class.getName());
      cdoDataStore.getExtensionManager().registerExtension(AuditProcessHandler.class.getName(),
          CDOAuditProcessHandler.class.getName());

      // don't do any persistence xml mapping in this datastore
      // 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());
      props.remove(PersistenceOptions.PERSISTENCE_XML);

      if (!props.containsKey(PersistenceOptions.HANDLE_UNSET_AS_NULL))
      {
        props.setProperty(PersistenceOptions.HANDLE_UNSET_AS_NULL, "true");
      }

      cdoDataStore.setDataStoreProperties(props);
      Configuration hibernateConfiguration = cdoDataStore.getConfiguration();

      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.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);
        cdoDataStore.getDataStoreProperties().setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
      }
      else
      {
        doDropSchema = false;
      }

      final List<EPackage> ePackages = new ArrayList<EPackage>(packageHandler.getEPackages());

      // get rid of the system packages
      for (EPackage ePackage : packageHandler.getEPackages())
      {
        if (CDOModelUtil.isSystemPackage(ePackage) && ePackage != EtypesPackage.eINSTANCE)
        {
          ePackages.remove(ePackage);
        }
      }
      // remove the persistence xml if no epackages as this won't work without
      // epackages
      if (ePackages.size() == 0 && props.getProperty(PersistenceOptions.PERSISTENCE_XML) != null)
      {
        cdoDataStore.getDataStoreProperties().remove(PersistenceOptions.PERSISTENCE_XML);
      }

      if (isAuditing())
      {
        auditEPackages = createAuditEPackages(cdoDataStore);
        final String auditMapping = mapAuditingEPackages(cdoDataStore, auditEPackages);
        // System.err.println(auditMapping);
        hibernateConfiguration.addXML(auditMapping);
        cdoDataStore.setAuditing(true);
      }
      cdoDataStore.setEPackages(ePackages.toArray(new EPackage[0]));
    }
    catch (Exception ex)
    {
      throw WrappedException.wrap(ex);
    }
    finally
    {
      PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
      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;
  }

  public String getMappingXml()
  {
    return mappingXml;
  }

  private List<EPackage> createAuditEPackages(HbDataStore dataStore)
  {
    final PersistenceOptions po = dataStore.getPersistenceOptions();

    final List<EPackage> epacks = new ArrayList<EPackage>();
    for (EPackage ePackage : getModelEPackages())
    {
      if (!CDOModelUtil.isSystemPackage(ePackage) && !isAuditEPackage(ePackage))
      {
        epacks.add(dataStore.getAuditHandler().createAuditingEPackage(dataStore, ePackage,
            getRepository().getPackageRegistry(), po));
      }
    }
    epacks.add(dataStore.getAuditHandler().createAuditingEPackage(dataStore,
        getRepository().getPackageRegistry().getEPackage(EresourcePackage.eNS_URI),
        getRepository().getPackageRegistry(), po));

    epacks.add(TeneoauditingPackage.eINSTANCE);

    getRepository().getPackageRegistry().put(TeneoauditingPackage.eNS_URI, TeneoauditingPackage.eINSTANCE);

    // also register them all in the non-transaction registry
    for (EPackage ePackage : epacks)
    {
      getRepository().getPackageRegistry(false).put(ePackage.getNsURI(), ePackage);
    }
    return epacks;
  }

  public String mapAuditingEPackages(HbDataStore dataStore, List<EPackage> auditEPackages)
  {
    // create a new persistence options to not change the original
    final Properties props = new Properties();
    props.putAll(dataStore.getPersistenceOptions().getProperties());
    props.remove(PersistenceOptions.PERSISTENCE_XML);
    if (props.containsKey(PersistenceOptions.AUDITING_PERSISTENCE_XML))
    {
      props.setProperty(PersistenceOptions.PERSISTENCE_XML, PersistenceOptions.AUDITING_PERSISTENCE_XML);
    }
    final PersistenceOptions po = dataStore.getExtensionManager().getExtension(PersistenceOptions.class,
        new Object[] { props });
    PAnnotatedModel paModel = dataStore.getExtensionManager().getExtension(PersistenceMappingBuilder.class)
        .buildMapping(auditEPackages, po, dataStore.getExtensionManager(), dataStore.getPackageRegistry());
    final HibernateMappingGenerator hmg = dataStore.getExtensionManager().getExtension(HibernateMappingGenerator.class);
    hmg.setPersistenceOptions(po);
    final String hbm = hmg.generateToString(paModel);

    return hbm;
  }

  private class CDODataStore extends HbSessionDataStore
  {

    private static final long serialVersionUID = 1L;

    @Override
    protected void addContainerMapping(PersistentClass pc)
    {
      // prevent container mapping for cdo objects
      if (pc.getTuplizerMap() != null)
      {
        for (Object tuplizerName : pc.getTuplizerMap().values())
        {
          if (((String)tuplizerName).contains("org.eclipse.emf.cdo"))
          {
            return;
          }
        }
      }
      super.addContainerMapping(pc);
    }

    @Override
    protected void mapModel()
    {
      if (getPersistenceOptions().getMappingFilePath() != null || getPersistenceOptions().isUseMappingFile())
      {
        super.mapModel();
      }
    }
  }

  public HibernateAuditHandler getHibernateAuditHandler()
  {
    ensureCorrectPackageRegistry();
    return hibernateAuditHandler;
  }

  public void setHibernateAuditHandler(HibernateAuditHandler hibernateAuditHandler)
  {
    this.hibernateAuditHandler = hibernateAuditHandler;
  }

  public static class CDOAuditProcessHandler extends AuditProcessHandler
  {

    private static final long serialVersionUID = 1L;

    @Override
    protected long getCommitTime()
    {
      if (HibernateThreadContext.isCommitContextSet())
      {
        return HibernateThreadContext.getCommitContext().getCommitContext().getBranchPoint().getTimeStamp();
      }
      return super.getCommitTime();
    }

    @Override
    protected void doAuditWorkInSession(Session session, List<AuditWork> auditWorks)
    {
      try
      {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(getDataStore().getPackageRegistry());

        if (HibernateThreadContext.isCommitContextSet())
        {
          AuditProcessHandler
              .setCurrentUserName(HibernateThreadContext.getCommitContext().getCommitContext().getUserID());
          AuditProcessHandler
              .setCurrentComment(HibernateThreadContext.getCommitContext().getCommitContext().getCommitComment());
        }
        super.doAuditWorkInSession(session, auditWorks);
      }
      finally
      {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
        AuditProcessHandler.setCurrentUserName(null);
        AuditProcessHandler.setCurrentComment(null);
      }
    }

    @Override
    protected void setContainerInfo(Session session, TeneoAuditEntry auditEntry, Object entity)
    {
      if (!(entity instanceof InternalCDORevision))
      {
        return;
      }
      final InternalCDORevision cdoRevision = (InternalCDORevision)entity;

      // set the resource id
      if (cdoRevision.getResourceID() != null)
      {
        auditEntry.setTeneo_resourceid(getAuditHandler().entityToIdString(session, cdoRevision.getResourceID()));
      }

      if (cdoRevision.getContainerID() == null || cdoRevision.getContainerID() == CDOID.NULL)
      {
        return;
      }

      auditEntry.setTeneo_container_id(getAuditHandler().entityToIdString(session, cdoRevision.getContainerID()));
      auditEntry.setTeneo_container_feature_id(cdoRevision.getContainingFeatureID());
    }

    @Override
    protected boolean performVersionCheck()
    {
      return true;
    }
  }

  public HbSessionDataStore getCDODataStore()
  {
    return cdoDataStore;
  }
}

Back to the top