Java Code Examples for org.eclipse.emf.ecore.EObject#eAllContents()

The following examples show how to use org.eclipse.emf.ecore.EObject#eAllContents() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProxyCompositeNode.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Uninstalls the proxy node model in the given resource (if present).
 *
 * @param resource
 *          resource, must not be {@code null}
 * @return original EObject ID map or {@code null} if no proxied node model was present
 */
static List<EObject> uninstallProxyNodeModel(final Resource resource) {
  List<EObject> result = null;
  if (!resource.getContents().isEmpty()) {
    EObject root = resource.getContents().get(0);
    ProxyCompositeNode proxyNode = uninstallProxyNode(root);
    if (proxyNode != null) {
      result = proxyNode.idToEObjectMap;
      for (TreeIterator<EObject> it = root.eAllContents(); it.hasNext();) {
        uninstallProxyNode(it.next());
      }
    }
  }

  if (resource instanceof XtextResource) {
    ((XtextResource) resource).setParseResult(null);
  }
  return result;
}
 
Example 2
Source File: TypeUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static Set<TypeVariable> collectReferencedTypeVars(EObject obj, boolean includeChildren,
		Set<TypeVariable> addHere) {
	final Type declType = obj instanceof TypeRef ? ((TypeRef) obj).getDeclaredType() : null;
	if (declType instanceof TypeVariable) {
		addHere.add((TypeVariable) declType);
	}
	if (obj instanceof StructuralTypeRef) {
		for (TStructMember m : ((StructuralTypeRef) obj).getStructuralMembers()) {
			collectReferencedTypeVars(m, true, addHere);
		}
	}
	if (includeChildren) {
		final Iterator<EObject> iter = obj.eAllContents();
		while (iter.hasNext()) {
			collectReferencedTypeVars(iter.next(), false, addHere);
		}
	}
	return addHere;
}
 
Example 3
Source File: TranspilerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Search entire containment tree below 'root' for objects of type 'cls'. If last argument is <code>false</code>,
 * then sub trees below a matching node won't be searched.
 */
public static final <T extends EObject> List<T> collectNodes(EObject root, Class<T> cls,
		boolean searchForNestedNodes) {
	final List<T> result = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject obj = iter.next();
		if (cls.isAssignableFrom(obj.getClass())) {
			@SuppressWarnings("unchecked")
			final T objCasted = (T) obj;
			result.add(objCasted);
			if (!searchForNestedNodes)
				iter.prune();
		}
	}
	return result;
}
 
Example 4
Source File: TranspilerUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * root usually a function or other ThisProviding environment.
 *
 * @param root
 *            function or method.
 * @param cls
 *            Type of element to report.
 * @return nodes of (sub-)type cls in the same this-environment
 */
public static final <T extends EObject> List<T> collectNodesWithinSameThisEnvironment(EObject root, Class<T> cls) {
	final List<T> result = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject obj = iter.next();
		if (cls.isAssignableFrom(obj.getClass())) {
			@SuppressWarnings("unchecked")
			final T objCasted = (T) obj;
			result.add(objCasted);
		}
		// check for same environment
		if (obj instanceof ThisArgProvider) {
			iter.prune();
		}
	}
	return result;
}
 
Example 5
Source File: N4JSPostProcessor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static void exposeTypesReferencedBy(EObject root) {
	final TreeIterator<EObject> i = root.eAllContents();
	while (i.hasNext()) {
		final EObject object = i.next();
		for (EReference currRef : object.eClass().getEAllReferences()) {
			if (!currRef.isContainment() && !currRef.isContainer()) {
				final Object currTarget = object.eGet(currRef);
				if (currTarget instanceof Collection<?>) {
					for (Object currObj : (Collection<?>) currTarget) {
						exposeType(currObj);
					}
				} else {
					exposeType(currTarget);
				}
			}
		}
	}
}
 
Example 6
Source File: ValidationRunner.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public boolean run ( final EObject element, final DiagnosticChain diagnostics, final Map<Object, Object> context )
{
    if ( element == null )
    {
        return true;
    }

    boolean result = runElement ( element, diagnostics, context );

    final TreeIterator<EObject> it = element.eAllContents ();
    while ( it.hasNext () )
    {
        if ( !runElement ( it.next (), diagnostics, context ) )
        {
            result = false;
        }
    }

    return result;
}
 
Example 7
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> List<T> findByNestedRuleCall(Class<T> clazz, AbstractRule... rule) {
	Set<AbstractRule> rls = new HashSet<AbstractRule>(Arrays.asList(rule));
	ArrayList<T> r = new ArrayList<T>();
	for (AbstractRule ar : getRules()) {
		TreeIterator<EObject> i = ar.eAllContents();
		while (i.hasNext()) {
			EObject o = i.next();
			if (clazz.isInstance(o)) {
				TreeIterator<EObject> ct = o.eAllContents();
				while (ct.hasNext()) {
					EObject cto = ct.next();
					if (cto instanceof RuleCall && rls.contains(((RuleCall) cto).getRule())) {
						r.add((T) o);
						break;
					}
				}
				i.prune();
			}
		}
	}
	return r;
}
 
Example 8
Source File: DotFoldingRegionProvider.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
protected void computeObjectFolding(XtextResource xtextResource,
		IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) {
	acceptedRegions.clear();

	IParseResult parseResult = xtextResource.getParseResult();
	if (parseResult != null) {
		EObject rootASTElement = parseResult.getRootASTElement();
		if (rootASTElement != null) {
			TreeIterator<EObject> allContents = rootASTElement
					.eAllContents();
			while (allContents.hasNext()) {
				EObject eObject = allContents.next();
				if (isHandled(eObject)) {
					computeObjectFolding(eObject, foldingRegionAcceptor);
				}
				if (eObject instanceof Attribute) {
					computeDotAttributeValueFolding((Attribute) eObject,
							foldingRegionAcceptor);
				}
				if (!shouldProcessContent(eObject)) {
					allContents.prune();
				}
			}
		}
	}
}
 
Example 9
Source File: Oven.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void fireproof(String input) throws Exception {
	try {
		EObject file = parseHelper.parse(input);
		IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
		Assert.assertNotNull(resolvedTypes);
		if (file != null) {
			TreeIterator<EObject> allContents = file.eAllContents();
			while (allContents.hasNext()) {
				EObject content = allContents.next();
				if (content instanceof XAbstractFeatureCall) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
					XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
					if (abstractFeatureCall.getImplicitReceiver() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(), resolvedTypes);
					}
					if (abstractFeatureCall.getImplicitFirstArgument() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(), resolvedTypes);
					}
				} else if (content instanceof XClosure) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
					for (JvmFormalParameter p : ((XClosure) content).getImplicitFormalParameters()) {
						assertIdentifiableTypeIsResolved(p, resolvedTypes);
					}
				} else if (content instanceof XExpression) {
					assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
				} else if (content instanceof JvmIdentifiableElement) {
					assertIdentifiableTypeIsResolved((JvmIdentifiableElement) content, resolvedTypes);
				}
			}
		}
	} catch (Throwable e) {
		ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
		error.setStackTrace(e.getStackTrace());
		throw error;
	}
}
 
Example 10
Source File: NodeModelTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testNavigabilityAst2Node() throws Exception {
	EObject object = getModel(MODEL);
	checkNavigabilityAst2Node(object);
	for (Iterator<EObject> i = object.eAllContents(); i.hasNext();) {
		checkNavigabilityAst2Node(i.next());
	}
}
 
Example 11
Source File: ChartWizard.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private void removeAllAdapters( EObject chart )
{
	chart.eAdapters( ).remove( adapter );
	TreeIterator<EObject> iterator = chart.eAllContents( );
	while ( iterator.hasNext( ) )
	{
		EObject oModel = iterator.next( );
		oModel.eAdapters( ).remove( adapter );
	}
}
 
Example 12
Source File: ConcreteSyntaxValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean validateRecursive(EObject obj, IDiagnosticAcceptor acceptor, Map<Object, Object> context) {
	boolean r = true;
	r &= validateObject(obj, acceptor, context);
	TreeIterator<EObject> i = obj.eAllContents();
	while (i.hasNext())
		r &= validateObject(i.next(), acceptor, context);
	return r;
}
 
Example 13
Source File: DefaultFoldingRegionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void computeObjectFolding(XtextResource xtextResource, IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor) {
	IParseResult parseResult = xtextResource.getParseResult();
	if(parseResult != null){
		EObject rootASTElement = parseResult.getRootASTElement();
		if(rootASTElement != null){
			if (cancelIndicator.isCanceled())
				throw new OperationCanceledException();
			if (isHandled(rootASTElement)) {
				computeObjectFolding(rootASTElement, foldingRegionAcceptor);
			}
			if (shouldProcessContent(rootASTElement)) {
				TreeIterator<EObject> allContents = rootASTElement.eAllContents();
				while (allContents.hasNext()) {
					if (cancelIndicator.isCanceled())
						throw new OperationCanceledException();
					EObject eObject = allContents.next();
					if (isHandled(eObject)) {
						computeObjectFolding(eObject, foldingRegionAcceptor);
					}
					if (!shouldProcessContent(eObject)) {
						allContents.prune();
					}
				}
			}
		}
	}
}
 
Example 14
Source File: N4JSValidationTestHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Asserts that root and the entire object tree below root does not contain any dangling references, i.e.
 * cross-references to target {@link EObject}s that are not contained in a {@link Resource}.
 */
public void assertNoDanglingReferences(EObject root) {
	final List<String> errMsgs = new ArrayList<>();
	final TreeIterator<EObject> iter = root.eAllContents();
	while (iter.hasNext()) {
		final EObject currObj = iter.next();
		if (currObj != null && !currObj.eIsProxy()) {
			for (EReference currRef : currObj.eClass().getEAllReferences()) {
				if (!currRef.isContainment() && !currRef.isContainer() && currRef.getEOpposite() == null) {
					if (currRef.isMany()) {
						@SuppressWarnings("unchecked")
						final EList<? extends EObject> targets = (EList<? extends EObject>) currObj.eGet(currRef,
								false);
						for (EObject currTarget : targets) {
							if (isDangling(currTarget)) {
								errMsgs.add(getErrorInfoForDanglingEObject(currObj, currRef));
								break;
							}
						}
					} else {
						final EObject target = (EObject) currObj.eGet(currRef, false);
						if (isDangling(target))
							errMsgs.add(getErrorInfoForDanglingEObject(currObj, currRef));
					}
				}
			}
		}
	}
	if (!errMsgs.isEmpty())
		fail("Expected no dangling references, but found the following: " + Joiner.on("; ").join(errMsgs) + ".");
}
 
Example 15
Source File: Oven.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void fireproof(String input) throws Exception {
	try {
		EObject file = parseHelper.parse(input);
		IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
		Assert.assertNotNull(resolvedTypes);
		if (file != null) {
			TreeIterator<EObject> allContents = file.eAllContents();
			while (allContents.hasNext()) {
				EObject content = allContents.next();
				if (content instanceof XAbstractFeatureCall) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
					XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
					if (abstractFeatureCall.getImplicitReceiver() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(),
								resolvedTypes);
					}
					if (abstractFeatureCall.getImplicitFirstArgument() != null) {
						assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(),
								resolvedTypes);
					}
				} else if (content instanceof XClosure) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
					for (JvmFormalParameter it : ((XClosure) content).getImplicitFormalParameters()) {
						assertIdentifiableTypeIsResolved(it, resolvedTypes);
					}
				} else if (content instanceof XExpression) {
					assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
				} else if (content instanceof JvmIdentifiableElement) {
					assertIdentifiableTypeIsResolved(((JvmIdentifiableElement) content), resolvedTypes);
				}
			}
		}
	} catch (Throwable e) {
		ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
		error.setStackTrace(e.getStackTrace());
		throw error;
	}
}
 
Example 16
Source File: EcoreUtilN4.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> List<T> getAllContentsOfTypeStopAt(boolean findFirst, EObject eobj, final Class<T> filterType,
		final EReference... stopReferences) {

	if (eobj == null) {
		return Collections.EMPTY_LIST;
	}

	List<EReference> stopReferencesL = Arrays.asList(stopReferences);
	List<T> contentList = new LinkedList<>();
	TreeIterator<EObject> tIter = eobj.eAllContents();

	while (tIter.hasNext()) {
		EObject eObj = tIter.next();
		EReference eRef = eObj.eContainmentFeature();
		if (stopReferencesL != null && stopReferencesL.contains(eRef)) {
			tIter.prune();
		} else {
			if (filterType.isInstance(eObj)) {
				contentList.add((T) eObj);
				if (findFirst) {
					return contentList;
				}
			}
		}
	}

	return contentList;
}
 
Example 17
Source File: StatechartValidationDecorationProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected SCTIssue getSubDiagramIssue(View view) {
	if (SemanticHints.STATE.equals(view.getType())) {
		BooleanValueStyle style = GMFNotationUtil.getBooleanValueStyle(view,
				DiagramPartitioningUtil.INLINE_STYLE);
		if (style == null ? false : !style.isBooleanValue()) {
			EObject element = view.getElement();
			TreeIterator<EObject> eAllContents = element.eAllContents();
			while (eAllContents.hasNext()) {
				EObject next = eAllContents.next();
				if(next instanceof Transition && next.eContainer() == element) {
					eAllContents.prune();
					continue;
				}
				String semanticURI = EcoreUtil.getURI(next).fragment();
				List<SCTIssue> issues = store.getIssues(semanticURI);
				for (final SCTIssue issue : issues) {
					if (Severity.ERROR.equals(issue.getSeverity())) {
						IssueImpl result = new Issue.IssueImpl();
						result.setMessage(SUB_DIAGRAM_ERRORS);
						result.setSeverity(Severity.ERROR);
						return new SCTIssue(result, issue.getSemanticURI());
					}
				}
			}
		}
	}
	return null;
}
 
Example 18
Source File: EMFComponent.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Load the given File as an XMLResource.
 * 
 * @param file
 * @return whether the operation was successful
 */
public boolean load(File file) {

	// Local Declarations
	EObject documentRoot = null;

	if (xmlProcessor != null) {
		try {
			xmlResource = (XMLResource) xmlProcessor.load(new FileInputStream(file), null);
		} catch (IOException e) {
			logger.error(getClass().getName() + " Exception!", e);
			return false;
		}
	}

	if (xmlResource != null && xmlResource.getContents().size() > 0) {
		documentRoot = xmlResource.getContents().get(0);
	} else {
		logger.error("EMFComponent Error: Could not find document root for " + file.getAbsolutePath());
		return false;
	}

	// If we have a valid document root node, we should walk
	// and create the EMFTreeComposite
	if (documentRoot != null) {
		// Create the root node EMFTreeComposite
		int id = 1;
		iceEMFTree = new EMFTreeComposite(documentRoot);
		iceEMFTree.setId(id);
		
		// Create the a map to store EObject keys to their corresponding
		// EMFTreeComposite value.
		HashMap<EObject, EMFTreeComposite> map = new HashMap<EObject, EMFTreeComposite>();

		// Put the root node in the tree
		map.put(documentRoot, iceEMFTree);

		// Use the EMF tree iterator to walk the Ecore tree.
		TreeIterator<EObject> tree = documentRoot.eAllContents();
		EObject obj = null;
		EMFTreeComposite tempTree = null;
		while (tree.hasNext()){
			id++;
			obj = tree.next();
			tempTree = new EMFTreeComposite(obj);
			tempTree.setId(id);
			// Put this EObject in the map with its
			// EMFTreeComposite representation
			map.put(obj, tempTree);
		}
		
		// Loop through all the EObject keys and
		// set each EMFTreeComposite's parent
		for (EObject o : map.keySet()) {
			EObject parent = o.eContainer();
			if (parent != null) {
				map.get(parent).setNextChild(map.get(o));
			}
		}
	} else {
		return false;
	}

	return true;
}
 
Example 19
Source File: LocalUniqueNameContext.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public LocalUniqueNameContext(EObject container, boolean deep, Function<EObject, String> nameFunction, CancelIndicator ci) {
	this(deep ? () -> container.eAllContents() : container.eContents(), nameFunction, ci);
}
 
Example 20
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public static TreeIterator<EObject> eAll(final EObject obj) {
	return new TreeIterator<EObject>() {
		private TreeIterator<EObject> it = null;
		private int index = 0;

		@Override
		public void prune() {
			switch (index) {
				case 0:
					return;
				case 1:
					it = null;
					break;
				default:
					if (it != null)
						it.prune();
			}
		}

		@Override
		public boolean hasNext() {
			if (index == 0)
				return true;
			if (it != null)
				return it.hasNext();
			return false;
		}

		@Override
		public EObject next() {
			if (index++ == 0) {
				it = obj.eAllContents();
				return obj;
			}
			if (it != null)
				return it.next();
			return null;
		}

		@Override
		public void remove() {
			if (index == 0)
				EcoreUtil.remove(obj);
			if (it != null)
				it.remove();
		}
	};
}