Java Code Examples for org.eclipse.xtext.resource.XtextResource#getResourceSet()

The following examples show how to use org.eclipse.xtext.resource.XtextResource#getResourceSet() . 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: N4JSDirtyStateEditorSupport.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private List<Resource> collectTransitivelyDependentResources(XtextResource resource,
		Set<URI> deltaURIs) {
	List<Resource> result = Lists.newArrayList();
	ResourceSet resourceSet = resource.getResourceSet();
	for (Resource candidate : resourceSet.getResources()) {
		if (candidate != resource) {
			URI uri = candidate.getURI();
			if (deltaURIs.contains(uri)) {
				// the candidate is contained in the delta list
				// schedule it for unloading
				result.add(candidate);
			} else if (candidate instanceof N4JSResource) {
				// the candidate does depend on one of the changed resources
				// schedule it for unloading
				if (canLoadFromDescriptionHelper.dependsOnAny(candidate, deltaURIs)) {
					result.add(candidate);
				}
			}
		}
	}
	return result;
}
 
Example 2
Source File: HighlightingReconciler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Update the presentation.
 * 
 * @param textPresentation
 *            the text presentation
 * @param addedPositions
 *            the added positions
 * @param removedPositions
 *            the removed positions
 * @param resource
 *            the resource for which the positions have been computed 
 */
private void updatePresentation(TextPresentation textPresentation, List<AttributedPosition> addedPositions,
		List<AttributedPosition> removedPositions, XtextResource resource) {
	final Runnable runnable = presenter.createUpdateRunnable(textPresentation, addedPositions, removedPositions);
	if (runnable == null)
		return;
	final XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet();
	final int modificationStamp = resourceSet.getModificationStamp();
	Display display = getDisplay();
	display.asyncExec(new Runnable() {
		@Override
		public void run() {
			// never apply outdated highlighting
			if(sourceViewer != null	&& modificationStamp == resourceSet.getModificationStamp())
				runnable.run();
		}
	});
}
 
Example 3
Source File: SerializationUtil.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public static String getCompleteContent(XtextResource xr) throws IOException, UnsupportedEncodingException {
	XtextResourceSet resourceSet = (XtextResourceSet) xr.getResourceSet();
	URIConverter uriConverter = resourceSet.getURIConverter();
	URI uri = xr.getURI();
	String encoding = xr.getEncoding();

	InputStream inputStream = null;

	try {
		inputStream = uriConverter.createInputStream(uri);

		return getCompleteContent(encoding, inputStream);
	} finally {
		tryClose(inputStream, null);
	}
}
 
Example 4
Source File: FixedHighlightingReconciler.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Update the presentation.
 *
 * @param textPresentation
 *          the text presentation
 * @param addedPositions
 *          the added positions
 * @param removedPositions
 *          the removed positions
 * @param resource
 *          the resource for which the positions have been computed
 */
private void updatePresentation(final TextPresentation textPresentation, final List<AttributedPosition> addedPositions, final List<AttributedPosition> removedPositions, final XtextResource resource) {
  final Runnable runnable = presenter.createUpdateRunnable(textPresentation, addedPositions, removedPositions);
  if (runnable == null) {
    return;
  }
  final XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet();
  final int modificationStamp = resourceSet.getModificationStamp();
  Display display = getDisplay();
  display.asyncExec(new Runnable() {
    @Override
    public void run() {
      // never apply outdated highlighting
      if (sourceViewer != null && modificationStamp == resourceSet.getModificationStamp()) {
        runnable.run();
      }
    }
  });
}
 
Example 5
Source File: HyperlinkXpectMethod.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private EObject getTarget(XtextResource resource, IHyperlink hyperlink) {
	final ResourceSet resourceSet = resource != null ? resource.getResourceSet() : null;
	final URI uri = getURI(hyperlink);
	final EObject target = resourceSet != null && uri != null && uri.fragment() != null
			? resourceSet.getEObject(uri, true)
			: null;
	if (target instanceof SyntaxRelatedTElement)
		return ((SyntaxRelatedTElement) target).getAstElement();
	return target;
}
 
Example 6
Source File: DomainmodelHyperlinkHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) {
	super.createHyperlinksByOffset(resource, offset, acceptor);
	EObject eObject = getEObjectAtOffsetHelper().resolveElementAt(resource, offset);
	if (eObject instanceof Entity) {
		List<INode> nodes = NodeModelUtils.findNodesForFeature(eObject, DomainmodelPackage.Literals.ABSTRACT_ELEMENT__NAME);
		if (!nodes.isEmpty()) {
			INode node = nodes.get(0);
			if (node.getOffset() <= offset && node.getOffset() + node.getLength() > offset) {
				String qualifiedJavaName = qualifiedNameConverter.toString(qualifiedNameProvider.getFullyQualifiedName(eObject));
				if (resource.getResourceSet() instanceof XtextResourceSet) {
					XtextResourceSet resourceSet = (XtextResourceSet) resource.getResourceSet();
					Object uriContext = resourceSet.getClasspathURIContext();
					if (uriContext instanceof IJavaProject) {
						IJavaProject javaProject = (IJavaProject) uriContext;
						try {
							IType type = javaProject.findType(qualifiedJavaName);
							if (type != null) {
								JdtHyperlink hyperlink = jdtHyperlinkProvider.get();
								hyperlink.setJavaElement(type);
								hyperlink.setTypeLabel("Navigate to generated source code.");
								hyperlink.setHyperlinkText("Go to type " + qualifiedJavaName);
								hyperlink.setHyperlinkRegion((IRegion) new Region(node.getOffset(), node.getLength()));
								acceptor.accept(hyperlink);
							}
						} catch(JavaModelException e) {
							logger.error(e.getMessage(), e);
						}
					}
				}
			}
		}
	}
}
 
Example 7
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 8
Source File: PartialParserCrossContainmentSingleTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setCrossResourceContainer(XtextResource resource) {
	ResourceSet resourceSet = resource.getResourceSet();
	Resource containerResource = resourceSet.createResource(URI.createFileURI("sample.xmi"));
	CrossResourceContainerOneChild container = PartialParsingTestUtilFactory.eINSTANCE.createCrossResourceContainerOneChild();
	containerResource.getContents().add(container);
	assertEquals(1, resource.getContents().size());
	container.setChild(resource.getContents().get(0));
}
 
Example 9
Source File: PartialParserCrossContainmentMultiTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setCrossResourceContainer(XtextResource resource) {
	ResourceSet resourceSet = resource.getResourceSet();
	Resource containerResource = resourceSet.createResource(URI.createFileURI("sample.xmi"));
	CrossResourceContainerManyChildren container = PartialParsingTestUtilFactory.eINSTANCE.createCrossResourceContainerManyChildren();
	containerResource.getContents().add(container);
	container.getChildren().addAll(resource.getContents());
}
 
Example 10
Source File: RelatedXtextResourceUpdater.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyChange(Deltas deltas, IAcceptor<IEmfResourceChange> changeAcceptor) {
	XtextResource res = (XtextResource) lifecycleManager.openAndApplyReferences(getResourceSet(), getResource());
	if (!referenceUpdater.isAffected(deltas, getResource())) {
		return;
	}
	ITextRegionAccess base = textRegionBuilderProvider.get().forNodeModel(res).create();
	ITextRegionDiffBuilder rewriter = new StringBasedTextRegionAccessDiffBuilder(base);
	ReferenceUpdaterContext context = new ReferenceUpdaterContext(deltas, rewriter, getResource());
	referenceUpdater.update(context);
	if (!context.getModifications().isEmpty()) {
		ChangeRecorder rec = createChangeRecorder(res);
		try {
			for (Runnable run : context.getModifications()) {
				run.run();
			}
			ChangeDescription recording = rec.endRecording();
			ResourceSet rs = res.getResourceSet();
			ResourceSetRecording tree = changeTreeProvider.createChangeTree(rs, Collections.emptyList(), recording);
			ResourceRecording recordedResource = tree.getRecordedResource(res);
			if (recordedResource != null) {
				serializer.serializeChanges(recordedResource, rewriter);
			}
		} finally {
			rec.dispose();
		}
	}
	for (IUpdatableReference upd : context.getUpdatableReferences()) {
		referenceUpdater.updateReference(rewriter, upd);
	}
	ITextRegionAccessDiff rewritten = rewriter.create();
	List<ITextReplacement> rep = formatter.format(rewritten);
	TextDocumentChange change = new TextDocumentChange(rewritten, getResource().getUri(), rep);
	changeAcceptor.accept(change);
}
 
Example 11
Source File: OrganizeImportXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(
		String ambiguous, // arg0
		@StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation,
		@ThisResource XtextResource resource) throws Exception {

	logger.info("organize imports ...");
	boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
	Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;

	try {

		if (expectation == null /* || expectation.isEmpty() */) {
			// TODO throw exception if empty.
			// Hey, I want to ask the expectation if it's empty.
			// Cannot access the region which could be asked for it's length.
			throw new AssertionFailedError(
					"The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
		}

		// capture text for comparison:
		String beforeApplication = resource.getParseResult().getRootNode().getText();

		N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
				.createTestBuilderForResource(resource);

		IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);

		// in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
		final ResourceSet resSet = resource.getResourceSet();
		for (Resource currRes : new ArrayList<>(resSet.getResources())) {
			N4JSResource.postProcess(currRes);
		}

		// Calling organize imports
		Display.getDefault().syncExec(
				() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));

		if (bAmbiguityCheck) {
			// should fail if here
			assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
		}

		// checking that no errors are left.
		String textAfterApplication = xtextDoc.get();

		// compare with expectation, it's a multiline-diff expectation.
		String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
		String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);

		expectation.assertDiffEquals(before, after);
	} catch (Exception exc) {
		if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
			String breakMessage = exc.getCause().getMessage();
			assertEquals(ambiguous, breakMessage);
		} else {
			throw exc;
		}
	}
}
 
Example 12
Source File: AbstractXbaseContentAssistBugTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected void initializeTypeProvider(XtextResource result) {
	XtextResourceSet resourceSet = (XtextResourceSet) result.getResourceSet();
	JdtTypeProviderFactory typeProviderFactory = new JdtTypeProviderFactory(this);
	typeProviderFactory.findOrCreateTypeProvider(resourceSet);
	resourceSet.setClasspathURIContext(getJavaProject(resourceSet));
}
 
Example 13
Source File: AbstractXtendContentAssistBugTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void initializeTypeProvider(XtextResource result) {
	XtextResourceSet resourceSet = (XtextResourceSet) result.getResourceSet();
	IJvmTypeProvider.Factory typeProviderFactory = new JdtTypeProviderFactory(this);
	typeProviderFactory.findOrCreateTypeProvider(resourceSet);
	resourceSet.setClasspathURIContext(getJavaProject(resourceSet));
}