Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5d16381d7920b00dda76a3c012c19f25af8d7aa5 (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
/*******************************************************************************
 * Copyright (c) 2013 CEA LIST.
 * 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:
 *     Cedric Dumoulin - cedric.dumoulin@lifl.fr
 ******************************************************************************/
package org.eclipse.papyrus.layers.stackmodel.layers.util;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.papyrus.layers.stackmodel.NotFoundException;


/**
 * @author cedric dumoulin
 *
 */
public class ECoreUtils {

	/**
	 * Check if one of the ancestor is instance of the specified type.
	 * Ancestors are classes that contains this class
	 * @param child Child for which we want to check the ancestor's type
	 * @param type The expected type
	 * @return true if one of the ancestor is of the expected type. False otherwise.
	 */
	public static boolean isAncestorInstanceOf(EObject child, EClass type) {


		try {
			lookupAncestorOfType(child, type);
			return true;
		} catch (NotFoundException e) {
			return false;
		}
		    
	}
	
	/**
	 * Lookup if one of the ancestor is instance of the specified type.
	 * Ancestors are classes that contains this class
	 * @param child Child for which we want to check the ancestor's type
	 * @param type The expected type
	 * @return the first ancestor of the specified type.
	 * @throws NotFoundException If no ancestor is found.
	 */
	public static EObject lookupAncestorOfType(EObject child, EClass type) throws NotFoundException {
		    if (child != null)
		    {
		    	if( type.isInstance(child)) {
		    		return child;
		    	}

		    	int count = 0;
		      for (EObject parent = child.eContainer(); parent != null; parent = parent.eContainer())
		      {
		        if (++count > 100000)
		        {
		          return lookupAncestorOfType(child, type);
		        }
		        // Check if this is the correct type
		        if( type.isInstance(parent)) {
		        	return parent;
		        }
		        if (parent == child)
		        {
		          throw new IllegalStateException("There is a cycle in the containment hierarchy of " + child);
		        }
		      }
		    }
		    //Nothing found
		    throw new NotFoundException("No ancestor of the specified type"	);

	}
}

Back to the top