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

The following examples show how to use org.eclipse.emf.ecore.EObject#eIsProxy() . 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: ConcreteSyntaxAwareReferenceFinder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected EObject toValidInstanceOrNull(Resource resource, Predicate<URI> targetURIs, EObject value) {
	EObject result = value;
	if (result.eIsProxy()) {
		URI proxyURI = EcoreUtil.getURI(result);
		if (uriEncoder.isCrossLinkFragment(resource, proxyURI.fragment())) {
			INode node = uriEncoder.decode(resource, proxyURI.fragment()).getThird();
			try {
				String string = linkingHelper.getCrossRefNodeAsString(node, true);
				if (((TargetURIs) targetURIs).getUserData(TargetURIKey.KEY).isMatchingConcreteSyntax(string)) {
					result = resolveInternalProxy(value, resource);
				} else {
					result = null;
				}
			} catch (IllegalNodeException ine) {
				// illegal nodes exist in broken ASTs
				// fired in linkingHelper.getCrossRefNodeAsString(...)
				result = null;
			}
		} else {
			result = resolveInternalProxy(value, resource);
		}
	}
	return result;
}
 
Example 2
Source File: AbstractStreamingFingerprintComputer.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generate a fingerprint for the target object using its URI.
 *
 * @param target
 *          The target object
 * @param context
 *          The object containing the reference
 * @param hasher
 *          hasher to stream to
 */
private void fingerprintEObject(final EObject target, final EObject context, final Hasher hasher) {
  if (target == null) {
    hasher.putUnencodedChars(NULL_STRING);
  } else if (target.eIsProxy()) {
    if (context.eResource() instanceof LazyLinkingResource) {
      final URI proxyUri = ((InternalEObject) target).eProxyURI();
      if (!((LazyLinkingResource) context.eResource()).getEncoder().isCrossLinkFragment(context.eResource(), proxyUri.fragment())) {
        hasher.putUnencodedChars(proxyUri.toString());
        return;
      }
    }
    hasher.putUnencodedChars(UNRESOLVED_STRING);
  } else {
    hasher.putUnencodedChars(EcoreUtil.getURI(target).toString());
  }
}
 
Example 3
Source File: AnonymousClassUtil.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public JvmDeclaredType getSuperTypeNonResolving(AnonymousClass anonymousClass, IScope typeScope) {
	XConstructorCall constructorCall = anonymousClass.getConstructorCall();
	EObject constructorProxy = (EObject) constructorCall.eGet(XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, false);
	IEObjectDescription description = null;
	if (constructorProxy != null) {
		if (!constructorProxy.eIsProxy()) {
			return getSuperType(anonymousClass);
		}
		String fragment = EcoreUtil.getURI(constructorProxy).fragment();
		INode node = uriEncoder.getNode(constructorCall, fragment);
		String name = linkingHelper.getCrossRefNodeAsString(node, true);
		QualifiedName superTypeName = qualifiedNameConverter.toQualifiedName(name);
		description = typeScope.getSingleElement(superTypeName);
	}
	if (description == null || !EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_DECLARED_TYPE, description.getEClass())) {
		description = typeScope.getSingleElement(QualifiedName.create("java", "lang", "Object"));
	}
	if (description != null && EcoreUtil2.isAssignableFrom(TypesPackage.Literals.JVM_DECLARED_TYPE, description.getEClass())) {
		JvmDeclaredType type = (JvmDeclaredType) description.getEObjectOrProxy();
		if (!type.eIsProxy())
			return type;
		return (JvmDeclaredType) EcoreUtil.resolve(type, anonymousClass);
	}
	return null;
}
 
Example 4
Source File: N4JSDocHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get JSDoc comment for the given element. The element may be an AST node such as <code>N4MethodDeclaration</code>
 * or a type model element such as <code>TMethod</code>. In the latter case, this method will follow the link to the
 * AST which may cause a load of the N4JS resource if it is not fully loaded (i.e. if only the TModule was loaded
 * from the Xtext index).
 * <p>
 * Thus, <b>this method may have a side effect on the containing resource of the given element</b>. If that is not
 * desired, use method {@link #getDocSafely(ResourceSet, EObject)} instead.
 */
public String getDoc(EObject element) {
	if (element == null)
		throw new IllegalArgumentException("element must not be null");
	if (element.eIsProxy()) {
		return null;
		// throw new IllegalArgumentException("element must not be proxy: " + element.toString());
	}

	final List<INode> docNodes = documentationProviderExt.getDocumentationNodes(element);
	if (!docNodes.isEmpty()) {
		final StringBuilder sb = new StringBuilder(docNodes.get(0).getText());
		for (int idx = 1; idx < docNodes.size(); idx++) {
			sb.append("\n").append(docNodes.get(idx).getText());
		}
		return sb.toString();
	}
	return null;
}
 
Example 5
Source File: N4JSReplacementTextApplier.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the to-be-inserted string if an existing import is present.
 */
@Override
public String getActualReplacementString(ConfigurableCompletionProposal proposal) {
	String syntacticReplacementString = proposal.getReplacementString();
	if (scope != null) {
		final QualifiedName qualifiedName = applyValueConverter(syntacticReplacementString);
		if (qualifiedName.getSegmentCount() == 1) {
			return syntacticReplacementString;
		}
		final IEObjectDescription element = scope.getSingleElement(qualifiedName);
		if (element != null) {
			EObject resolved = EcoreUtil.resolve(element.getEObjectOrProxy(), context);
			if (!resolved.eIsProxy()) {
				IEObjectDescription description = findApplicableDescription(resolved, qualifiedName, true);
				if (description != null) {
					String multisegmentProposal = applyValueConverter(description.getName());
					return multisegmentProposal;
				}
			}
		}
	}
	return syntacticReplacementString;
}
 
Example 6
Source File: JvmTypesBuilder.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a deep copy of the given object and associates each copied instance with the
 * clone. Does not resolve any proxies.
 *	
 * @param original the root element to be cloned.
 * @return a clone of tree rooted in original associated with the original, <code>null</code> if original is <code>null</code>. 
 */
protected <T extends EObject> T cloneAndAssociate(T original) {
	final boolean canAssociate = languageInfo.isLanguage(original.eResource());
	EcoreUtil.Copier copier = new EcoreUtil.Copier(false) {
		private static final long serialVersionUID = 1L;

		@Override/* @Nullable */ 
		protected EObject createCopy(/* @Nullable */ EObject eObject) {
			EObject result = super.createCopy(eObject);
			if (canAssociate && result != null && eObject != null && !eObject.eIsProxy()) {
				associator.associate(eObject, result);
			}
			return result;
		}
	};
	@SuppressWarnings("unchecked")
	T copy = (T) copier.copy(original);
	copier.copyReferences();
	return copy;
}
 
Example 7
Source File: NonVersionAwareContextScope.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Instantiates a new {@link FailedToInferContextVersionWrappingScope} that wraps around the given scope and
 * decorates all of its descriptions.
 *
 * @param parent
 *            The parent scope to wrap around
 * @param versionAwareContextSupport
 *            Specifies whether the scope context allows for <code>@VersionAware</code> contexts (e.g. N4IDL).
 * @param messageHelper
 *            An injected instance of {@link ValidatorMessageHelper}
 *
 */
public NonVersionAwareContextScope(IScope parent, boolean versionAwareContextSupport,
		ValidatorMessageHelper messageHelper) {
	super(parent, d -> {
		EObject element = d.getEObjectOrProxy();
		if (null != element && !element.eIsProxy()) {
			// wrap all elements that are in a version-aware context
			return !VersionUtils.isVersionAwareContext(element);
		} else {
			// leave all non-version-aware descriptions un-decorated
			return true;
		}
	});

	// store service dependencies in fields
	this.messageHelper = messageHelper;

	// store whether context supports versioned types
	this.versionAwareContextSupport = versionAwareContextSupport;

}
 
Example 8
Source File: PendingLinkingCandidateResolver.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void resolveLinkingProxy(InternalEObject owner, JvmIdentifiableElement newValue, EReference structuralFeature, int featureId) {
	EObject oldFeature = (EObject) owner.eGet(structuralFeature, false);
	if (oldFeature == null || !(oldFeature.eIsProxy())) {
		throw new IllegalStateException("Feature was already resolved to " + oldFeature);
	}
	if (owner.eNotificationRequired()) {
		boolean wasDeliver = owner.eDeliver();
		owner.eSetDeliver(false);
		internalSetValue(owner, structuralFeature, newValue);
		owner.eSetDeliver(wasDeliver);
		if (newValue != oldFeature) {
			owner.eNotify(new ENotificationImpl(owner, Notification.RESOLVE, featureId, oldFeature, newValue));
		}
	} else {
		internalSetValue(owner, structuralFeature, newValue);
	}
}
 
Example 9
Source File: ScopeProviderAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a bunch of descriptions most of which are actually {@link IIdentifiableElementDescription describing identifiables}. 
 * The provided iterable is never empty but it may contain a single {@link ErrorDescription error description}.
 * 
 * @return the available descriptions.
 */
public Iterable<IEObjectDescription> getCandidateDescriptions(XExpression expression, EReference reference, /* @Nullable */ EObject toBeLinked,
		IFeatureScopeSession session, IResolvedTypes types) throws IllegalNodeException {
	if (toBeLinked == null) {
		return Collections.emptyList();
	}
	if (!toBeLinked.eIsProxy()) {
		throw new IllegalStateException(expression + " was already linked to " + toBeLinked);
	}
	URI uri = EcoreUtil.getURI(toBeLinked);
	String fragment = uri.fragment();
	if (encoder.isCrossLinkFragment(expression.eResource(), fragment)) {
		INode node = encoder.getNode(expression, fragment);
		final EClass requiredType = reference.getEReferenceType();
		if (requiredType == null)
			return Collections.emptyList();

		final String crossRefString = linkingHelper.getCrossRefNodeAsString(node, true);
		if (crossRefString != null && !crossRefString.equals("")) {
			QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
			if (!qualifiedLinkName.isEmpty()) {
				final IScope scope = session.getScope(expression, reference, types);
				Iterable<IEObjectDescription> descriptions = scope.getElements(qualifiedLinkName);
				if (Iterables.isEmpty(descriptions)) {
					INode errorNode = getErrorNode(expression, node);
					if (errorNode != node) {
						qualifiedLinkName = getErrorName(errorNode);
					}
					return Collections.<IEObjectDescription>singletonList(new ErrorDescription(getErrorNode(expression, node), qualifiedLinkName));
				}
				return descriptions;
			} else {
				return Collections.<IEObjectDescription>singletonList(new ErrorDescription(null /* followUp problem */));
			}
		}
		return Collections.emptyList();
	} else {
		throw new IllegalStateException(expression + " uses unsupported uri fragment " + uri);
	}
}
 
Example 10
Source File: N4JSExternalReferenceChecker.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the second EObject is resolved and contained in a different resource than the first given resource.If
 * the second EObject is a proxy than its proxy URI fragment is used to check. The first resource is expected to be
 * already resolved.
 *
 * @param resource
 *            the resource
 * @param to
 *            The EObject that should be checked if it is located in a resource other than the given resource
 * @return true, if the EObject is resolved and not in the same resource.
 */
public boolean isResolvedAndExternal(Resource resource, EObject to) {
	if (to == null)
		return false;
	if (!to.eIsProxy()) {
		if (to.eResource() == null) {
			LOG.error("The target is not contained in a resource.");
			return false;
		}
		return resource != to.eResource();
	}
	return !uriEncoder
			.isCrossLinkFragment(resource, ((InternalEObject) to).eProxyURI().fragment());
}
 
Example 11
Source File: ScopeResourceDescriptionStrategy.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private String getSourceText(final EObject obj) {
  if (obj.eIsProxy()) {
    LOG.warn("Could not resolve scope model " + EcoreUtil.getURI(obj));
    return "";
  }
  return ((XtextResource) obj.eResource()).getParseResult().getRootNode().getText();
}
 
Example 12
Source File: XtextComparisonExpressionLoader.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public Operation_Compare resolveProxies(final Resource resource, final ResourceSet resourceSet) {
    EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
    final Operation_Compare compareOp = (Operation_Compare) resource.getContents().get(0);
    final List<Expression_ProcessRef> allRefs = modelSearch.getAllItemsOfType(compareOp, Expression_ProcessRef.class);
    for (final Expression_ProcessRef ref : allRefs) {
        final EObject proxy = ref.getValue();
        if (proxy.eIsProxy()) {
            ref.eSet(ConditionModelPackage.Literals.EXPRESSION_PROCESS_REF__VALUE, EcoreUtil.resolve(proxy, resourceSet));
        }
    }
    return compareOp;
}
 
Example 13
Source File: ErrorAwareLinkingService.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<EObject> getLinkedObjects(EObject context, EReference ref, INode node) throws IllegalNodeException {
	final EClass requiredType = ref.getEReferenceType();
	if (requiredType == null)
		return Collections.<EObject> emptyList();

	final String crossRefString = getCrossRefNodeAsString(context, ref, node);
	if (crossRefString != null && !crossRefString.equals("")) {
		final IScope scope = getScope(context, ref);
		QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
		IEObjectDescription eObjectDescription = scope.getSingleElement(qualifiedLinkName);
		IEObjectDescriptionWithError errorDescr;
		Resource resource = context.eResource();
		if (resource != null
				&& (errorDescr = IEObjectDescriptionWithError
						.getDescriptionWithError(eObjectDescription)) != null
				// isNoValidate traverses the file system so it should be the last part of the check
				&& !n4jsCore.isNoValidate(resource.getURI())) {
			addError(context, node, errorDescr);
		} else if (eObjectDescription instanceof UnresolvableObjectDescription) {
			return Collections.<EObject> singletonList((EObject) context.eGet(ref, false));
		}

		if (eObjectDescription != null) {
			EObject candidate = eObjectDescription.getEObjectOrProxy();
			if (!candidate.eIsProxy() && candidate.eResource() == null) {
				// Error is necessary since EMF catches all exceptions in EcoreUtil#resolve
				throw new AssertionError("Found an instance without resource and without URI");
			}

			// if supported, mark object description as used
			if (eObjectDescription instanceof IUsageAwareEObjectDescription) {
				((IUsageAwareEObjectDescription) eObjectDescription).markAsUsed();
			}

			return Collections.singletonList(candidate);
		}
	}
	return Collections.emptyList();
}
 
Example 14
Source File: ConstructorTypeScopeWrapper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected EObject getResolvedProxy(IEObjectDescription description) {
	EObject proxy = description.getEObjectOrProxy();
	if (proxy.eIsProxy()) {
		proxy = EcoreUtil.resolve(proxy, context);
	}
	return proxy;
}
 
Example 15
Source File: DotEObjectFormatter.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
protected String formatCrossRefValue(EObject object, EReference feature,
		EObject value) {
	if (value == null)
		return "null";
	if (value.eIsProxy())
		return "proxy (URI: " + ((InternalEObject) value).eProxyURI() + ")";
	if (value.eResource() == object.eResource())
		return value.eClass().getName() + " "
				+ object.eResource().getURIFragment(value);
	URI uri = EcoreUtil.getURI(value);
	uri = uri.deresolve(object.eResource().getURI());
	return value.eClass().getName() + " " + uri.toString();
}
 
Example 16
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Set<EPackage> getReferencedEPackages(final List<EPackage> packs) {
  final HashSet<EPackage> result = CollectionLiterals.<EPackage>newHashSet();
  for (final EPackage pkg : packs) {
    {
      final TreeIterator<EObject> iterator = pkg.eAllContents();
      while (iterator.hasNext()) {
        {
          final EObject obj = iterator.next();
          EList<EObject> _eCrossReferences = obj.eCrossReferences();
          for (final EObject crossRef : _eCrossReferences) {
            boolean _eIsProxy = crossRef.eIsProxy();
            if (_eIsProxy) {
              URI _eProxyURI = ((InternalEObject) crossRef).eProxyURI();
              String _plus = ("Proxy \'" + _eProxyURI);
              String _plus_1 = (_plus + "\' could not be resolved");
              EMFGeneratorFragment2.LOG.error(_plus_1);
            } else {
              final EPackage p = EcoreUtil2.<EPackage>getContainerOfType(crossRef, EPackage.class);
              if ((p != null)) {
                result.add(p);
              }
            }
          }
        }
      }
    }
  }
  result.removeAll(packs);
  result.remove(EcorePackage.eINSTANCE);
  result.remove(XMLTypePackage.eINSTANCE);
  result.remove(XMLNamespacePackage.eINSTANCE);
  return result;
}
 
Example 17
Source File: BatchLinkableResourceStorageWritable.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected String getFragment(final EObject obj) {
  String _xblockexpression = null;
  {
    if ((((obj == null) || obj.eIsProxy()) || (obj.eResource() == null))) {
      return "none";
    }
    _xblockexpression = obj.eResource().getURIFragment(obj);
  }
  return _xblockexpression;
}
 
Example 18
Source File: XtextLinkingService.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private EPackage getResolvedEPackage(IEObjectDescription description, EObject context) {
	EObject resolved = EcoreUtil.resolve(description.getEObjectOrProxy(), context);
	if (resolved != null && !resolved.eIsProxy() && resolved instanceof EPackage)
		return (EPackage) resolved;
	return null;
}
 
Example 19
Source File: ConnectorViewPostPasteChildOperation.java    From statecharts with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @return
 * @throws Exception
 */
private EObject doPaste()
	throws Exception {

	View sourceView = getConnectorViewPasteOperation().getSourceView();
	View targetView = getConnectorViewPasteOperation().getTargetView();

	if ((sourceView == null) || (targetView == null)) {
		return null;
	}

	EObject sourceViewContainer = sourceView.eContainer();
	EObject targetViewContainer = targetView.eContainer();

	if ((sourceViewContainer == null) || (targetViewContainer == null)) {
		return null;
	}

	if (sourceViewContainer.equals(targetViewContainer) == false) {
		//not in the same container, let's try to see if they are in the
		// same diagram at least
		Diagram sourceViewDiagram = NotationClipboardOperationHelper
			.getContainingDiagram((View) sourceViewContainer);
		Diagram targetViewDiagram = NotationClipboardOperationHelper
			.getContainingDiagram((View) targetViewContainer);
		if ((sourceViewDiagram == null) || (targetViewDiagram == null)
			|| (sourceViewDiagram.equals(targetViewDiagram) == false)) {
			return null;
		}
	}
	
	Edge connectorView = getConnectorViewPasteOperation()
		.getConnectorView();

	if (pasteSemanticElement) {			
		EObject semanticElement = connectorView.getElement();
		if (semanticElement != null) {
			if (semanticElement.eIsProxy()) {
				semanticElement = ClipboardSupportUtil.resolve(semanticElement,
					getParentPasteProcess().getLoadedIDToEObjectMapCopy());
			}
			String loadedId = getLoadedEObjectID(semanticElement);
			if (loadedId != null) {
				//even if we failed to paste the semantic element, we'll
				// proceed to paste the edge view
				doPasteSemanticElement();
				//should have been pasted by now, if not then return
				String newId = getEObjectID(semanticElement);
				if (newId == null) {
					return null;
				}
			}
		}
	}
	EObject pastedElement = null;
	Diagram pasteTargetDiagram = NotationClipboardOperationHelper
		.getContainingDiagram((View) sourceViewContainer);
	if (pasteTargetDiagram != null) {
		//if we reached here then we should paste the connector and set
		// refs to it accordingly
		pastedElement = ClipboardSupportUtil.appendEObjectAt(
			pasteTargetDiagram, getContainmentFeature(), connectorView);
		if (pastedElement != null) {
			ClipboardSupportUtil.appendEObjectAt(sourceView,
				NotationPackage.eINSTANCE.getView_SourceEdges(),
				connectorView);
			ClipboardSupportUtil.appendEObjectAt(targetView,
				NotationPackage.eINSTANCE.getView_TargetEdges(),
				connectorView);
		}
	}

	return pastedElement;
}
 
Example 20
Source File: PortableURIs.java    From xtext-core with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates and returns a portable URI from the global scope. Returns <code>null</code> if no portable URI can be
 * constructed, which is the case if the targetObject is not itself exported or is a child of an exported EObject.
 * 
 * @param sourceResource
 *            the resource from which the EObject should later be resolved
 * @param targetObject
 *            the target object that should be resolvable by the created portable URI
 * 
 * @return a portable URI or <code>null</code>
 */
public URI toPortableURI(StorageAwareResource sourceResource, EObject targetObject) {
	if (targetObject == null || targetObject.eIsProxy()) {
		return sourceResource.getURI().appendFragment(StorageAwareResource.UNRESOLVABLE_FRAGMENT);
	}
	String portableFragment = getPortableURIFragment(targetObject);
	if (portableFragment != null) {
		return sourceResource.getURI().appendFragment(portableFragment);
	}
	return null;
}