Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 937b71aa659df8cd158ca8d24bed3f4a2e663b26 (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
/**
 * <copyright>
 *
 * Copyright (c) 2005, 2006, 2007, 2008 Springsite BV (The Netherlands) 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
 * </copyright>
 *
 * $Id: HbSessionDataStore.java,v 1.32 2011/07/05 05:09:41 mtaal Exp $
 */

package org.eclipse.emf.teneo.hibernate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.emf.teneo.PackageRegistryProvider;
import org.eclipse.emf.teneo.annotations.mapper.PersistenceFileProvider;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEClass;
import org.eclipse.emf.teneo.annotations.pamodel.PAnnotatedEPackage;
import org.eclipse.emf.teneo.hibernate.auditing.AuditProcessHandler;
import org.eclipse.emf.teneo.hibernate.mapper.MappingUtil;
import org.eclipse.emf.teneo.hibernate.mapping.EMFInitializeCollectionEventListener;
import org.eclipse.emf.teneo.hibernate.mapping.eav.EAVGenericIDUserType;
import org.hibernate.Cache;
import org.hibernate.Interceptor;
import org.hibernate.SessionBuilder;
import org.hibernate.StatelessSessionBuilder;
import org.hibernate.TypeHelper;
import org.hibernate.cfg.Configuration;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.service.ServiceRegistry;

/**
 * Holds the SessionFactory and performs different initialization related actions. Initializes the
 * database and offers xml import and export methods. In addition can be used to retrieve all
 * referers to a certain eobject.
 * <p>
 * The behavior can be overridden by overriding the protected methods and implementing/registering
 * your own HbDataStoreFactory in the HibernateHelper.
 * 
 * @author <a href="mailto:mtaal@elver.org">Martin Taal</a>
 * @version $Revision: 1.32 $
 */

@SuppressWarnings("unchecked")
public class HbSessionDataStore extends HbBaseSessionDataStore {

	private static final long serialVersionUID = 1L;

	/** The logger */
	private static Log log = LogFactory.getLog(HbSessionDataStore.class);

	/** The used Hibernate configuration */
	private Configuration hbConfiguration;

	private AuditProcessHandler auditProcessHandler;

	@Override
	public void close() {
		super.close();
		hbConfiguration = null;
	}

	/** Initializes this Data Store */
	@Override
	public void initialize() {

		// start with a fresh one
		setAuditHandler(null);

		if (hbConfiguration != null && isResetConfigurationOnInitialization()) {
			hbConfiguration = null;
		}

		MappingUtil.registerHbExtensions(getExtensionManager());

		PackageRegistryProvider.getInstance().setThreadPackageRegistry(getPackageRegistry());

		try {
			if (log.isDebugEnabled()) {
				log.debug("Initializing Hb Session DataStore");
			}

			// check a few things
			if (getEPackages() == null) {
				throw new HbMapperException("EPackages are not set");
				// if (getName() == null)
				// throw new HbStoreException("Name is not set");
			}

			// reset interceptor
			setInterceptor(null);

			if (log.isDebugEnabled()) {
				log.debug(">>>>> Creating HB Configuration");
			}

			getConfiguration();

			mapModel();

			setPropertiesInConfiguration();

			initializeDataStore();

			// will close the current sessionfactory if it was set
			closeSessionFactory();

			buildSessionFactory();

			setInitialized(true);

			setEventListeners();
		} finally {
			PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
		}
	}

	/** Set the event listener, can be overridden */
	@Override
	protected void setEventListeners() {
		final EMFInitializeCollectionEventListener initializeCollectionEventListener = getExtensionManager()
				.getExtension(EMFInitializeCollectionEventListener.class);
		final ServiceRegistry serviceRegistry = ((SessionFactoryImpl) getSessionFactory())
				.getServiceRegistry();
		final EventListenerRegistry eventListenerRegistry = serviceRegistry
				.getService(EventListenerRegistry.class);
		eventListenerRegistry.appendListeners(EventType.INIT_COLLECTION,
				initializeCollectionEventListener);

		if (isAuditing()) {
			auditProcessHandler = getExtensionManager().getExtension(AuditProcessHandler.class);
			auditProcessHandler.setDataStore(this);
			eventListenerRegistry.appendListeners(EventType.POST_DELETE, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.POST_INSERT, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.POST_UPDATE, auditProcessHandler);
			eventListenerRegistry.appendListeners(EventType.FLUSH, auditProcessHandler);
		}
	}

	/**
	 * Note the audit process handler is set in the {@link #setEventListeners()} method.
	 * 
	 * To override the auditprocess handler use Teneo's extension mechanism.
	 */
	public AuditProcessHandler getAuditProcessHandler() {
		return auditProcessHandler;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.emf.teneo.hibernate.HbContext#createConfiguration()
	 */
	protected Configuration createConfiguration() {
		return new Configuration();
	}

	/** Return the Classmappings as an iterator */
	@Override
	public Iterator<?> getClassMappings() {
		return getConfiguration().getClassMappings();
	}

	/** Build the mappings in the configuration */
	@Override
	protected void buildMappings() {
		getConfiguration().buildMappings();
	}

	/** Sets the interceptor */
	@Override
	protected void setInterceptor() {
		if (getInterceptor() != null) { // probably overridden
			return;
		}
		final Interceptor interceptor = getHbContext().createInterceptor(getHibernateConfiguration(),
				getEntityNameStrategy());
		getConfiguration().setInterceptor(interceptor);
		setInterceptor(interceptor);
	}

	/** Sets the properties in the Hibernate Configuration. */
	protected void setPropertiesInConfiguration() {
		Properties properties = getDataStoreProperties();
		if (properties != null) {
			setDefaultProperties(properties);
			getConfiguration().addProperties(properties);
		}
	}

	/**
	 * Maps an ecore model of one ore more epackages into a hibernate xml String which is added to the
	 * passed configuration
	 */
	protected void mapModel() {

		if (getPersistenceOptions().getMappingFilePath() != null
				|| getPersistenceOptions().isUseMappingFile()) {
			final String[] fileList = getMappingFileList();
			for (String element : fileList) {
				if (log.isDebugEnabled()) {
					log.debug("Adding file " + element + " to Hibernate Configuration");
				}
				final PersistenceFileProvider pfp = getExtensionManager().getExtension(
						PersistenceFileProvider.class);
				final InputStream is = pfp.getFileContent(this.getClass(), element);
				if (is == null) {
					throw new HbStoreException("Path to mapping file: " + element + " does not exist!");
				}
				getConfiguration().addInputStream(is);
			}
		} else {
			setMappingXML(mapEPackages());

			boolean hasEAVMapping = false;
			for (PAnnotatedEPackage aPackage : getPaModel().getPaEPackages()) {
				for (PAnnotatedEClass aClass : aPackage.getPaEClasses()) {
					if (aClass.getEavMapping() != null) {
						hasEAVMapping = true;
						break;
					}
				}
			}
			if (hasEAVMapping) {
				try {
					if (getPersistenceOptions().getEAVMappingFile() != null) {
						final PersistenceFileProvider pfp = getExtensionManager().getExtension(
								PersistenceFileProvider.class);
						final InputStream is = pfp.getFileContent(this.getClass(), getPersistenceOptions()
								.getEAVMappingFile());
						getConfiguration().addXML(processEAVMapping(is));
						is.close();
					} else {
						final PersistenceFileProvider pfp = getExtensionManager().getExtension(
								PersistenceFileProvider.class);
						final InputStream is = pfp.getFileContent(EAVGenericIDUserType.class, "eav.hbm.xml");
						getConfiguration().addXML(processEAVMapping(is));
						is.close();
					}
				} catch (IOException e) {
					throw new IllegalStateException(e);
				}
			}

			// System.err.println(getMappingXML());

			getConfiguration().addXML(getMappingXML());
		}
	}

	/** Build the session factory */
	@SuppressWarnings("deprecation")
	protected void buildSessionFactory() {

		// SchemaExport export = new SchemaExport(getConfiguration());
		// export.create(true, true);

		setSessionFactory(getConfiguration().buildSessionFactory());
	}

	/** Return a new session wrapper */
	@Override
	public SessionWrapper createSessionWrapper() {
		return new HbSessionWrapper(this);
	}

	/**
	 * @return the hbConfiguration
	 */
	public Configuration getConfiguration() {
		if (hbConfiguration == null) {
			hbConfiguration = createConfiguration();
		}
		return hbConfiguration;
	}

	public void setConfiguration(Configuration configuration) {
		hbConfiguration = configuration;
	}

	/**
	 * @return the hbConfiguration
	 */
	@Override
	public Configuration getHibernateConfiguration() {
		return getConfiguration();
	}

	public boolean containsFetchProfileDefinition(String arg0) {
		return getSessionFactory().containsFetchProfileDefinition(arg0);
	}

	public Cache getCache() {
		return getSessionFactory().getCache();
	}

	public TypeHelper getTypeHelper() {
		return getSessionFactory().getTypeHelper();
	}

	public SessionFactoryOptions getSessionFactoryOptions() {
		return getSessionFactory().getSessionFactoryOptions();
	}

	public SessionBuilder withOptions() {
		return getSessionFactory().withOptions();
	}

	public StatelessSessionBuilder withStatelessOptions() {
		return getSessionFactory().withStatelessOptions();
	}
}

Back to the top