Skip to main content
summaryrefslogtreecommitdiffstats
blob: 4b235845138927d820fb48006e771a1ac9e9e999 (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
/**
 * <copyright>
 *
 * Copyright (c) 2005-2006 Sven Efftinge (http://www.efftinge.de) 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:
 *     Sven Efftinge (http://www.efftinge.de) - Initial API and implementation
 *
 * </copyright>
 */
package org.eclipse.xtend.typesystem.emf;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.mwe.core.ConfigurationException;
import org.eclipse.emf.mwe.core.resources.ResourceLoaderFactory;

/**
 * Provides useful functions for usage of EMF.
 * @since 4.0
 */
public class EcoreUtil2 {

	private final static Log log = LogFactory.getLog(EcoreUtil2.class);

	static {
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
		EPackage.Registry.INSTANCE.put(EcorePackage.eINSTANCE.getNsURI(), EcorePackage.eINSTANCE);
	}

	public final static EPackage getEPackage(final String pathToEcoreFile) {
		EPackage result = null;
		final URI fileURI = getURI(pathToEcoreFile);
		if (fileURI == null)
			throw new RuntimeException("cannot resolve EPackage for " + pathToEcoreFile + ". Probably cannot find the .ecore file.");
		try {
			final Resource res = new ResourceSetImpl().createResource(fileURI);
			if (res == null)
				throw new ConfigurationException("No ecore model file '" + pathToEcoreFile + "' found! (" + fileURI.toString() + ")");
			res.load(new HashMap());
			result = (EPackage) res.getContents().get(0);
			if (result.getNsURI() != null) {
				if (EPackage.Registry.INSTANCE.containsKey(result.getNsURI())) {
					result = EPackage.Registry.INSTANCE.getEPackage(result.getNsURI());
				} else {
					EPackage.Registry.INSTANCE.put(result.getNsURI(), result);
					URIConverter.URI_MAP.put(URI.createURI(result.getNsURI()), fileURI);
				}
			}
			return result;
		} catch (final IOException e) {
			throw new ConfigurationException(e);
		} finally {
			logPackages();
		}
	}

	private static void logPackages() {
		// if (log.isDebugEnabled()) {
		// Set s = EPackage.Registry.INSTANCE.keySet();
		// log.debug("registered EPackages:");
		// List l = new ArrayList(s);
		// for (int i = 0, x = l.size(); i < x; i++) {
		// Object o = l.get(i);
		// log.debug((i + 1) + ") " + o + " : " + ((EPackage)
		// EPackage.Registry.INSTANCE.get(o)).getName());
		// }
		// }
	}

	/**
	 * Finds all elements within a collection of a specific type.
	 * @param iter An iterator over the source collection.
	 * @param type The type which should be selected.
	 * @return A set with all elements of the specified type.
	 */
	public static Set<EObject> findAllByType(final Iterator iter, final Class type) {
		final Set<EObject> result = new HashSet<EObject>();
		while (iter.hasNext()) {
			final EObject curr = (EObject) iter.next();
			if (type.isInstance(curr))
				result.add(curr);
		}
		return result;
	}

	/**
	 * Clones a list.
	 * @param list The list that should be cloned.
	 * @return A copy of the original list
	 */
	public static List clone(final EList list) {
		if (list==null)
			return null;
		final List res = new ArrayList();
		res.addAll(list);
		return res;
	}

	/**
	 * Finds an EMF EPackage instance by its class name. The EPackage class must be loadable by the
	 * ResourceLoader 
	 * @param ePackage The class name of the EPackage interface
	 * @return The EPackage instance. Returns <code>null</code> if any exception occurs after the class
	 * was successfully loaded. 
	 * @throws ConifgurationException If the class specified by <tt>ePackage</tt> cannot be loaded.
	 */
	public static EPackage getEPackageByClassName(final String ePackage) throws ConfigurationException {
		Class clazz;
		try {
			// try to load the EPackage class with the ResourceLoader
			clazz = ResourceLoaderFactory.createResourceLoader().loadClass(ePackage);
			if (clazz == null)
				throw new ConfigurationException("Couldn't find class " + ePackage);
			// each EPackage class has an 'eINSTANCE' field which holds the implementation instance
			final Field f = clazz.getField("eINSTANCE");
			// retrieve the EPackage instance from the eINSTANCE field
			final EPackage result = (EPackage) f.get(null);
			// register the EPackage instance in the EPackage Registry 
			EPackage.Registry.INSTANCE.put(result.getNsURI(), result);
			return result;
		} catch (final SecurityException e) {
			log.error(e);
			return null;
		} catch (final NoSuchFieldException e) {
			log.error(e);
			return null;
		} catch (final IllegalArgumentException e) {
			log.error(e);
			return null;
		} catch (final IllegalAccessException e) {
			log.error(e);
			return null;
		} finally {
			logPackages();
		}
	}

	/**
	 * Finds an EPackage by the class name of the Package Descriptor.
	 * @param ePackageDescriptor The Package Descriptor's classname
	 * @return The EPackage instance. Returns <code>null</code> on any exception occuring while retrieval.
	 */
	public static EPackage getEPackageByDescriptorClassName(final String ePackageDescriptor) {
		Class clazz;
		try {
			clazz = ResourceLoaderFactory.createResourceLoader().loadClass(ePackageDescriptor);
			final EPackage.Descriptor descriptor = (EPackage.Descriptor) clazz.newInstance();
			final Field f = clazz.getField("eNS_URI");
			final String uri = (String) f.get(null);
			EPackage.Registry.INSTANCE.put(uri, descriptor);
			return EPackage.Registry.INSTANCE.getEPackage(uri);
		} catch (final Exception e) {
			log.error("Couldn't load ePackage '" + ePackageDescriptor, e);
			return null;
		} finally {
			logPackages();
		}
	}

	/**
	 * Creates an URI from a file name.
	 * @param file The file's path
	 * @return The URI representing the file
	 */
	public static URI getURI(final String file) {
		// try to load the resource specified by 'file'
		final URL url = ResourceLoaderFactory.createResourceLoader().getResource(file);
		// if the ResourceLoader cannot locate this file create a URI from the file
		if (url == null)
			return URI.createURI(file);
		// the ResourceLoader has successfully located the file. Return the external form of the path
		return URI.createURI(url.toExternalForm());
	}

}

Back to the top