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

The following examples show how to use org.eclipse.emf.ecore.EObject#eResource() . 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: Bpmn2ResourceImpl.java    From fixflow with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares this resource for saving.
 * 
 * Sets all ID attributes of contained and referenced objects 
 * that are not yet set, to a generated UUID.
 */
protected void prepareSave() {
    EObject cur;
    Definitions thisDefinitions = ImportHelper.getDefinitions(this);
    for (Iterator<EObject> iter = getAllContents(); iter.hasNext();) {
        cur = iter.next();

        setIdIfNotSet(cur);

        for (EObject referenced : cur.eCrossReferences()) {
            setIdIfNotSet(referenced);
            if (thisDefinitions != null) {
                Resource refResource = referenced.eResource();
                if (refResource != null && refResource != this) {
                    createImportIfNecessary(thisDefinitions, refResource);
                }
            }
        }
    }
}
 
Example 2
Source File: ModelHelper.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public static Diagram getDiagramFor(final EObject element, EditingDomain domain) {
    if (element == null) {
        return null;
    }
    Resource resource = element.eResource();
    if (resource == null) {
        if (domain == null) {
            domain = TransactionUtil.getEditingDomain(element);
            if (domain != null) {
                resource = domain.getResourceSet().getResource(element.eResource().getURI(), true);
            }
        } else if (domain.getResourceSet() != null) {
            resource = domain.getResourceSet().getResource(element.eResource().getURI(), true);
        }
    }
    if (resource == null) {
        throw new IllegalStateException(String.format("No resource attached to EObject %s", element));
    }
    return getDiagramFor(element, resource);
}
 
Example 3
Source File: EObjectUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the fie location of a given object in a text resource as the path to the file and the line number.
 * <p>
 * This is very similar to {@link #getLocationString(EObject)} but it will not include the {@link Object#toString()} representation of the object.
 *
 * @param object
 *          any EObject
 * @return a string representation of the location of this object in its file, never {@code null}
 */
public static String getFileLocation(final EObject object) {
  if (object == null || object.eResource() == null) {
    return ""; //$NON-NLS-1$
  }

  URI uri = object.eResource().getURI();
  // CHECKSTYLE:CHECK-OFF MagicNumber
  String path = uri.isPlatform() ? '/' + String.join("/", uri.segmentsList().subList(3, uri.segmentCount())) : uri.path(); //$NON-NLS-1$
  // CHECKSTYLE:CHECK-ON MagicNumber
  StringBuilder result = new StringBuilder(path);
  final ICompositeNode node = NodeModelUtils.getNode(object);
  if (node != null) {
    result.append(':').append(node.getStartLine());
  }

  return result.toString();
}
 
Example 4
Source File: AbstractDeclarativeValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.4
 */
protected void checkIsFromCurrentlyCheckedResource(EObject object) {
	State currentState = this.state.get();
	if (object != null && currentState != null && currentState.currentObject != null
			&& object.eResource() != currentState.currentObject.eResource()) {
		URI uriGiven = null;
		if (object.eResource() != null)
			uriGiven = object.eResource().getURI();
		URI uri = null;
		if (currentState.currentObject.eResource() != null)
			uri = currentState.currentObject.eResource().getURI();
		throw new IllegalArgumentException(
				"You can only add issues for EObjects contained in the currently validated resource '" + uri
						+ "'. But the given EObject was contained in '" + uriGiven + "'");
	}
}
 
Example 5
Source File: JvmModelAssociator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void removeAssociation(EObject sourceElement, EObject jvmElement) {
	Preconditions.checkArgument(sourceElement != null, "source element cannot be null");
	Preconditions.checkArgument(jvmElement != null, "jvm element cannot be null");
	
	Resource resource = jvmElement.eResource();
	Preconditions.checkArgument(resource != null, "jvm element cannot be dangling");
	Preconditions.checkArgument(resource == sourceElement.eResource(), "source and jvm elements should belong to the same resource");
	checkLanguageResource(sourceElement.eResource());
	checkLanguageResource(jvmElement.eResource());
	checkSameResource(sourceElement.eResource(), jvmElement.eResource());
	
	Set<EObject> sources = targetToSourceMap(resource).get(jvmElement);
	if (sources != null && sources.remove(sourceElement)) {
		Set<EObject> targets = sourceToTargetMap(resource).get(sourceElement);
		targets.remove(jvmElement);
	}
}
 
Example 6
Source File: DefaultRenameElementHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isRefactoringEnabled(IRenameElementContext renameElementContext, XtextResource resource) {
	ResourceSet resourceSet = resource.getResourceSet();
	if (renameElementContext != null && resourceSet != null) {
		EObject targetElement = resourceSet.getEObject(renameElementContext.getTargetElementURI(), true);
		if (targetElement != null && !targetElement.eIsProxy()) {
			if(targetElement.eResource() == resource && renameElementContext.getTriggeringEditorSelection() instanceof ITextSelection) {
				ITextSelection textSelection = (ITextSelection) renameElementContext.getTriggeringEditorSelection();
				ITextRegion selectedRegion = new TextRegion(textSelection.getOffset(), textSelection.getLength());
				INode crossReferenceNode = eObjectAtOffsetHelper.getCrossReferenceNode(resource, selectedRegion);
				if(crossReferenceNode == null) {
					// selection is on the declaration. make sure it's the name
					ITextRegion significantRegion = locationInFileProvider.getSignificantTextRegion(targetElement);
					if(!significantRegion.contains(selectedRegion)) 
						return false;
				}
			}
			IRenameStrategy.Provider renameStrategyProvider = globalServiceProvider.findService(targetElement,
					IRenameStrategy.Provider.class);
			try {
				if (renameStrategyProvider.get(targetElement, renameElementContext) != null) {
					return true;
				} else {
					IRenameStrategy2 strategy2 = globalServiceProvider.findService(targetElement, IRenameStrategy2.class); 
					ISimpleNameProvider simpleNameProvider = globalServiceProvider.findService(targetElement, ISimpleNameProvider.class); 
					return strategy2 != null && simpleNameProvider.canRename(targetElement);
				}
					
			} catch (NoSuchStrategyException e) {
				MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Cannot rename element",
						e.getMessage());
			}
		}
	}
	return false;
}
 
Example 7
Source File: EditModelHelper.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public static String getEObjectID(EObject eObject) {
	Resource eResource = eObject.eResource();
	if (eResource != null) {
		return eResource.getURIFragment(eObject);
	}
	return null;
}
 
Example 8
Source File: XbaseBatchScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IScope getScope(EObject context, EReference reference) {
	if (context == null || context.eResource() == null || context.eResource().getResourceSet() == null) {
		return IScope.NULLSCOPE;
	}
	if (isFeatureCallScope(reference)) {
		IExpressionScope.Anchor anchor = IExpressionScope.Anchor.BEFORE;
		if (context instanceof XAbstractFeatureCall) {
			EObject proxyOrResolved = (EObject) context.eGet(reference, false);
			if (proxyOrResolved != null && !proxyOrResolved.eIsProxy()) {
				XExpression receiver = ((XAbstractFeatureCall) context).getActualReceiver();
				if (receiver == null && context instanceof XMemberFeatureCall) {
					receiver = ((XMemberFeatureCall) context).getMemberCallTarget();
				}
				if (receiver != null) {
					anchor = IExpressionScope.Anchor.RECEIVER;
					context = receiver;
				}
			} else if (context instanceof XBinaryOperation) {
				context = ((XBinaryOperation) context).getLeftOperand();
				anchor = IExpressionScope.Anchor.RECEIVER;
			} else if (context instanceof XMemberFeatureCall) {
				context = ((XMemberFeatureCall) context).getMemberCallTarget();
				anchor = IExpressionScope.Anchor.RECEIVER;
			}
		}
		IExpressionScope expressionScope = typeResolver.resolveTypes(context).getExpressionScope(context, anchor);
		return expressionScope.getFeatureScope();
	}
	if (isTypeScope(reference)) {
		return typeScopes.createTypeScope(context, reference);
	}
	return delegateGetScope(context, reference);
}
 
Example 9
Source File: AbstractCleaningLinker.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void beforeModelLinked(EObject model, IDiagnosticConsumer diagnosticsConsumer) {
	Resource resource = model.eResource();
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).clearLazyProxyInformation();
	}
	ImportedNamesAdapter adapter = ImportedNamesAdapter.find(resource);
	if (adapter!=null)
		adapter.clear();
}
 
Example 10
Source File: GamlLinkingService.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Override default in order to supply a stub object. If the default implementation isn't able to resolve the link,
 * assume it to be a local resource.
 */
@Override
public List<EObject> getLinkedObjects(final EObject context, final EReference ref, final INode node)
		throws IllegalNodeException {
	final List<EObject> result = super.getLinkedObjects(context, ref, node);
	// If the default implementation resolved the link, return it
	if (null != result && !result.isEmpty()) { return result; }
	final String name = getCrossRefNodeAsString(node);
	if (GamlPackage.eINSTANCE.getTypeDefinition()
			.isSuperTypeOf(ref.getEReferenceType())) { return addSymbol(name, ref.getEReferenceType()); }
	if (GamlPackage.eINSTANCE.getVarDefinition()
			.isSuperTypeOf(ref.getEReferenceType())) { return addSymbol(name, ref.getEReferenceType());
	// if (name.startsWith("pref_")) {
	// return addSymbol(name, ref.getEReferenceType());
	// } else {
	// if (context.eContainer() instanceof Parameter) {
	// final Parameter p = (Parameter) context.eContainer();
	// if (p.getLeft() == context) { return addSymbol(name, ref.getEReferenceType()); }
	// }
	// }
	// if (stubbedRefs.containsKey(name)) { return stubbedRefs.get(name); }
	}
	final GamlResource resource = (GamlResource) context.eResource();
	final IExecutionContext additionalContext = resource.getCache().getOrCreate(resource).get("linking");
	if (additionalContext != null) {
		if (additionalContext
				.hasLocalVar(name)) { return Collections.singletonList(create(name, ref.getEReferenceType())); }
	}
	return Collections.EMPTY_LIST;
}
 
Example 11
Source File: SerializerTester.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected String getTextFromNodeModel(EObject semanticObject) {
	Resource res = semanticObject.eResource();
	if (res instanceof XtextResource && res.getContents().contains(semanticObject))
		return ((XtextResource) res).getParseResult().getRootNode().getText();
	INode node = NodeModelUtils.getNode(semanticObject);
	Assert.assertNotNull(node);
	return node.getText();
}
 
Example 12
Source File: AbstractDiagnostic.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public URI getUriToProblem() {
	INode node = getNode();
	if (node == null)
		return null;
	EObject eObject = node.getSemanticElement();
	if (eObject==null || eObject.eResource()==null)
		return null;
	return EcoreUtil.getURI(eObject);
}
 
Example 13
Source File: ComparisonExpressionEditor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public ComparisonExpressionEditor(final EObject context) {
    this.context = context;
    adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
    adapterLabelProvider = new AdapterFactoryLabelProvider(adapterFactory);
    final Injector injector = ConditionModelActivator.getInstance()
            .getInjector(ConditionModelActivator.ORG_BONITASOFT_STUDIO_CONDITION_CONDITIONMODEL);
    if (context != null && context.eResource() != null) {
        final ConditionModelJavaValidator validator = injector.getInstance(ConditionModelJavaValidator.class);
        validator.setCurrentResourceSet(context.eResource().getResourceSet());
    }
}
 
Example 14
Source File: GamlResourceServices.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public synchronized static GamlResource getTemporaryResource(final IDescription existing) {
	ResourceSet rs = null;
	GamlResource r = null;
	if (existing != null) {
		final ModelDescription desc = existing.getModelDescription();
		if (desc != null) {
			final EObject e = desc.getUnderlyingElement();
			if (e != null) {
				r = (GamlResource) e.eResource();
				if (r != null) {
					rs = r.getResourceSet();
				}
			}
		}
	}
	if (rs == null) {
		rs = poolSet;
	}
	final URI uri = URI.createURI(IKeyword.SYNTHETIC_RESOURCES_PREFIX + resourceCount++ + ".gaml", false);
	// TODO Modifier le cache de la resource ici ?
	final GamlResource result = (GamlResource) rs.createResource(uri);
	final IMap<URI, String> imports = GamaMapFactory.create();
	imports.put(uri, null);
	if (r != null) {
		imports.put(r.getURI(), null);
		final Map<URI, String> uris = GamlResourceIndexer.allLabeledImportsOf(r);
		imports.putAll(uris);
	}
	result.getCache().getOrCreate(result).set(GamlResourceIndexer.IMPORTED_URIS, imports);
	return result;
}
 
Example 15
Source File: AbstractTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void diagnose(EObject object) {
	Resource resource = object.eResource();
	for (EObject content : resource.getContents()) {
		Diagnostic diagnostic = diagnostician.validate(content);
		if (diagnostic.getSeverity() != Diagnostic.OK) {
			diagnose(diagnostic);
		}

	}
}
 
Example 16
Source File: AbstractTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void diagnose(EObject object) {
	Resource resource = object.eResource();
	for (EObject content : resource.getContents()) {
		Diagnostic diagnostic = diagnostician.validate(content);
		if (diagnostic.getSeverity() != Diagnostic.OK) {
			diagnose(diagnostic);
		}

	}
}
 
Example 17
Source File: XbaseInformationControl.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Xbase - modification added detailPane
 */
@Override
public void setInput(Object input) {
	Assert.isLegal(input == null || input instanceof String || input instanceof XtextBrowserInformationControlInput, String.valueOf(input));

	if (input instanceof String) {
		setInformation((String) input);
		return;
	}
	if (input instanceof XtextBrowserInformationControlInput)
		fInput = (XtextBrowserInformationControlInput) input;

	String content = null;
	if (fInput != null)
		content = fInput.getHtml();

	fBrowserHasContent = content != null && content.length() > 0;

	if (!fBrowserHasContent)
		content = "<html><body ></html>"; //$NON-NLS-1$

	boolean RTL = (getShell().getStyle() & SWT.RIGHT_TO_LEFT) != 0;
	boolean resizable = isResizable();

	// The default "overflow:auto" would not result in a predictable width for the client area
	// and the re-wrapping would cause visual noise
	String[] styles = null;
	if (RTL && resizable)
		styles = new String[] { "direction:rtl;", "overflow:scroll;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	else if (RTL && !resizable)
		styles = new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	else if (!resizable)
		//XXX: In IE, "word-wrap: break-word;" causes bogus wrapping even in non-broken words :-(see e.g. Javadoc of String).
		// Re-check whether we really still need this now that the Javadoc Hover header already sets this style.
		styles = new String[] { "overflow:hidden;"/*, "word-wrap: break-word;"*/}; //$NON-NLS-1$
	else
		styles = new String[] { "overflow:scroll;" }; //$NON-NLS-1$

	StringBuffer buffer = new StringBuffer(content);
	HTMLPrinter.insertStyles(buffer, styles);
	content = buffer.toString();

	/*
	 * XXX: Should add some JavaScript here that shows something like
	 * "(continued...)" or "..." at the end of the visible area when the page overflowed
	 * with "overflow:hidden;".
	 */

	fCompleted = false;
	fBrowser.setText(content);
	String unsugaredExpression = "";
	if (fInput != null && fInput instanceof XbaseInformationControlInput) {
		XbaseInformationControlInput castedInput = (XbaseInformationControlInput) fInput;
		unsugaredExpression = castedInput.getUnsugaredExpression();
		if(unsugaredExpression != null && unsugaredExpression.length() > 0){
			EObject element = fInput.getElement();
			if(element != null && element.eResource() != null && element.eResource().getResourceSet() != null){
				// FIXME: No arguments need when https://bugs.eclipse.org/bugs/show_bug.cgi?id=368827 is solved
				// THEN move to createContent as it was before
				if(embeddedEditorAccess == null)
					embeddedEditorAccess = embeddedEditor.createPartialEditor("", "INITIAL CONTENT", "", false);
				resourceProvider.setContext(((XtextResourceSet) element.eResource().getResourceSet()).getClasspathURIContext());
			} else
				return;
			embeddedEditorAccess.updateModel(castedInput.getPrefix() , unsugaredExpression ,castedInput.getSuffix());
		}
	}

	if (unsugaredExpression != null && unsugaredExpression.length() > 0)
		fSashForm.setWeights(new int[] { 7, 3 });
	else
		fSashForm.setWeights(new int[] { 10, 0 });
	Object[] listeners = fInputChangeListeners.getListeners();
	for (int i = 0; i < listeners.length; i++)
		((IInputChangedListener) listeners[i]).inputChanged(fInput);
	
}
 
Example 18
Source File: AbstractPolymorphicScopeProvider.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns a scope for a given context object and EReference, using a named scope definition. If none is found
 * tries to find a scope (using the same name) for the type of the reference.
 *
 * @param context
 *          the context
 * @param reference
 *          the reference
 * @param scopeName
 *          the scope name
 * @param originalResource
 *          the original resource
 * @return the scope
 */
public IScope getScope(final EObject context, final EReference reference, final String scopeName, final Resource originalResource) {
  if (context.eResource() != originalResource && context.eResource() instanceof XtextResource) {
    registerForeignObject(context, (XtextResource) context.eResource(), originalResource);
  }
  String nameToFind = scopeName == null ? SCOPE_STRING : scopeName;
  IScope scope = internalGetScope(context, reference, nameToFind, originalResource);
  if (scope == null) {
    scope = internalGetScope(context, reference.getEReferenceType(), nameToFind, originalResource);
  }
  return (scope == null) ? IScope.NULLSCOPE : scope;
}
 
Example 19
Source File: InferredJvmModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the model associations corresponding to an EObject.
 * <p>
 * Model associations are maintained per resource. This returns the model associations for the EObject's containing resource.
 * </p>
 * 
 * @param eObject
 *          the object to get the model associations from, must not be {@code null}
 * @return the model associations for {@code eObject}, or null if there are none
 */
public static IJvmModelAssociations getModelAssociations(final EObject eObject) {
  if (eObject != null) {
    final Resource resource = eObject.eResource();
    if (resource instanceof XtextResource) {
      return ((XtextResource) resource).getResourceServiceProvider().get(IJvmModelAssociations.class);
    }
  }
  return null;
}
 
Example 20
Source File: RemoveDanglingReferences.java    From bonita-studio with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Remove all dangling references of all objects that are contained by the root element.
 * 
 * @param element
 *        the root element
 */
public void removeDanglingReferences(final EObject element) {
    if (element.eResource() != null && element.eResource().getResourceSet() != null) {
        removeDanglingReferences(new DanglingReferencesDetector(element.eResource()));
    }
}