Java Code Examples for org.eclipse.emf.common.util.URI#trimFragment()

The following examples show how to use org.eclipse.emf.common.util.URI#trimFragment() . 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: EditorContentExtractor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Optional<TModule> loadTModuleFromURI(final URI uri) {
	if (null == uri) {
		return absent();
	}

	final URI trimmedUri = uri.hasFragment() ? uri.trimFragment() : uri;
	final IN4JSProject project = core.findProject(trimmedUri).orNull();
	if (project == null) {
		return absent();
	}
	final ResourceSet resSet = core.createResourceSet(Optional.of(project));
	final IResourceDescriptions index = core.getXtextIndex(resSet);
	final IResourceDescription resDesc = index.getResourceDescription(trimmedUri);

	if (null == resDesc) {
		return absent();
	}

	final TModule module = core.loadModuleFromIndex(resSet, resDesc, false);
	if (null == module || null == module.eResource() || null == module.eResource().getResourceSet()) {
		return absent();
	}
	return Optional.of(module);
}
 
Example 2
Source File: TestResultsView.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void openTestClass(TestSuite testSuite) {
	Optional<TestCase> foundTestCase = testSuite.getTestCases().stream().findFirst();
	if (foundTestCase.isPresent()) {
		final URI testCaseURI = foundTestCase.get().getURI();
		final URI moduleLocation = testCaseURI.trimFragment();
		if (!openErrorIfProblem(moduleLocation)) {
			String caseFragment = testCaseURI.fragment();
			if (caseFragment != null) {
				int lastAt = caseFragment.lastIndexOf("/@");
				if (lastAt >= 0) { // open at class
					String classFragment = caseFragment.substring(0, lastAt);
					URI classLocation = moduleLocation.appendFragment(classFragment);
					uriOpener.open(classLocation, true);
				}
			} else { // just open the file
				uriOpener.open(moduleLocation, true);
			}
		}
	}
}
 
Example 3
Source File: ResourceStorageWritable.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void writeContents(StorageAwareResource storageAwareResource, OutputStream outputStream)
		throws IOException {
	BinaryResourceImpl.EObjectOutputStream out = new BinaryResourceImpl.EObjectOutputStream(outputStream,
			Collections.emptyMap()) {
		@Override
		public void writeURI(URI uri, String fragment) throws IOException {
			URI fullURI = uri.appendFragment(fragment);
			URI portableURI = storageAwareResource.getPortableURIs().toPortableURI(storageAwareResource, fullURI);
			URI uriToWrite = portableURI == null ? fullURI : portableURI;
			super.writeURI(uriToWrite.trimFragment(), uriToWrite.fragment());
		}

		@Override
		public void saveEObject(InternalEObject internalEObject, BinaryResourceImpl.EObjectOutputStream.Check check)
				throws IOException {
			beforeSaveEObject(internalEObject, this);
			super.saveEObject(internalEObject, check);
			handleSaveEObject(internalEObject, this);
		}
	};
	try {
		out.saveResource(storageAwareResource);
	} finally {
		out.flush();
	}
}
 
Example 4
Source File: GlobalDerivedMemberAwareURIEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IEditorPart open(URI uri, Object context, boolean select) {
	try {
		if (context instanceof IMember) {
			if(uri != null) {
				URI sourceResourceURI = uri.trimFragment();
				IResourceServiceProvider serviceProvider = resourceServiceProviderRegistry
						.getResourceServiceProvider(sourceResourceURI);
				if (serviceProvider != null) {
					IDerivedMemberAwareEditorOpener opener = serviceProvider.get(IDerivedMemberAwareEditorOpener.class);
					if (opener != null) {
						return opener.open(sourceResourceURI, (IMember) context, select);
					}
				}
			}
			return JavaUI.openInEditor((IJavaElement) context, true, true);
		}
	} catch(Exception exc) {
		LOG.error("Error opening Java editor", exc);
	}
	return super.open(uri, select);
}
 
Example 5
Source File: ResourceAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <R> R readOnly(URI targetURI, IUnitOfWork<R, ResourceSet> work) {
	URI resourceURI = targetURI.trimFragment();
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(resourceURI);
	Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
	ResourceSet resourceSet = fallBackResourceSet; 
	while(iterator.hasNext()) {
		Pair<IStorage, IProject> pair = iterator.next();
		IProject project = pair.getSecond();
		if (project != null) {
			resourceSet = getResourceSet(project);
			break;
		}
	}
	if(resourceSet != null) {
		resourceSet.getResource(resourceURI, true);
		try {
			return work.exec(resourceSet);
		} catch (Exception e) {
			throw new WrappedException(e);
		}
	}
	return null;
}
 
Example 6
Source File: LoadingResourceAccess.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public <R> R readOnly(URI targetURI, IUnitOfWork<R, ResourceSet> work) {
	URI resourceURI = targetURI.trimFragment();
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(resourceURI);
	Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
	while(iterator.hasNext()) {
		Pair<IStorage, IProject> pair = iterator.next();
		IProject project = pair.getSecond();
		if (project != null) {
			ResourceSet resourceSet = resourceSetProvider.get(project);
			if(resourceSet != null)
				resourceSet.getResource(resourceURI, true);
				try {
					return work.exec(resourceSet);
				} catch (Exception e) {
					throw new WrappedException(e);
				}
		}
	}
	return null;
}
 
Example 7
Source File: AbstractLaunchConfigurationMainTab.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the name of the class and method if the USER_SELECTION URI refers to a method. Otherwise an empty string
 * is returned.
 */
public String getTestMethod(ILaunchConfiguration configuration) {
	try {
		String uriStr = configuration.getAttribute(RunConfiguration.USER_SELECTION, "");
		if (uriStr == null) {
			return "";
		}
		final URI uri = uriStr.trim().length() > 0 ? URI.createURI(uriStr) : null;
		if (uri == null) {
			return "";
		}
		final URI trimmedUri = uri.hasFragment() ? uri.trimFragment() : uri;
		final IN4JSProject project = in4jsCore.findProject(trimmedUri).orNull();
		if (project != null) {
			ResourceSet resSet = in4jsCore.createResourceSet(Optional.of(project));
			if (resSet != null) {
				EObject eobject = resSet.getEObject(uri, true);
				if (eobject instanceof N4MethodDeclaration) {
					N4MethodDeclaration method = (N4MethodDeclaration) eobject;
					String name = ((N4MethodDeclaration) eobject).getName();
					if (method.getOwner() instanceof N4ClassDeclaration) {
						return ((N4ClassDeclaration) method.getOwner()).getName() + "." + name;
					}
					return name;
				}
			}
		}
	} catch (Exception ex) {
		// be robust here
	}
	return "";

}
 
Example 8
Source File: ModificationContextRegistry.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
public ICoreXtextDocument getXtextDocument(final URI uri) {
  final URI trimmedUri = uri.trimFragment();
  ICoreXtextDocument xtextDocument = xtextDocuments.get().get(trimmedUri);
  if (xtextDocument == null) {
    XtextResource xtextResource = getXtextResource(trimmedUri);
    xtextDocument = createDocument(xtextResource);
    xtextDocuments.get().put(trimmedUri, xtextDocument);
  }
  return xtextDocument;
}
 
Example 9
Source File: WorkspaceManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Find the resource and the document with the given URI and performa a read operation.
 */
public <T> T doRead(URI uri, Function2<? super Document, ? super XtextResource, ? extends T> work) {
	URI resourceURI = uri.trimFragment();
	ProjectManager projectMnr = getProjectManager(resourceURI);
	if (projectMnr != null) {
		XtextResource resource = (XtextResource) projectMnr.getResource(resourceURI);
		Document doc = getDocument(resource);
		return work.apply(doc, resource);
	}
	return work.apply(null, null);
}
 
Example 10
Source File: XtendBatchCompiler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private StringBuilder createIssueMessage(Issue issue) {
	StringBuilder issueBuilder = new StringBuilder("\n");
	issueBuilder.append(issue.getSeverity()).append(": \t");
	URI uriToProblem = issue.getUriToProblem();
	if (uriToProblem != null) {
		URI resourceUri = uriToProblem.trimFragment();
		issueBuilder.append(resourceUri.lastSegment()).append(" - ");
		if (resourceUri.isFile()) {
			issueBuilder.append(resourceUri.toFileString());
		}
	}
	issueBuilder.append("\n").append(issue.getLineNumber()).append(": ").append(issue.getMessage());
	return issueBuilder;
}
 
Example 11
Source File: IndexedJvmTypeAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public EObject getIndexedJvmType(URI javaObjectURI, ResourceSet resourceSet, boolean throwShadowedException) throws UnknownNestedTypeException {
	if (resourceSet != null) {
		URI withoutFragment = javaObjectURI.trimFragment();
		if (resourceSet instanceof ResourceSetImpl) {
			// if the resource uri is already available in the resource set, try to find it directly
			Map<URI, Resource> resourceMap = ((ResourceSetImpl) resourceSet).getURIResourceMap();
			if (resourceMap != null && resourceMap.containsKey(withoutFragment)) {
				EObject result = resourceSet.getEObject(javaObjectURI, true);
				if (result != null) {
					return result;
				}
			}
		}
		String fqn = withoutFragment.segment(withoutFragment.segmentCount() - 1);
		final String base = fqn;
		Iterator<String> variants = innerClassNameVariants.variantsFor(base);
		EObject jvmType = null;
		while (jvmType == null && variants.hasNext()) {
			fqn = variants.next();
			List<String> fqnSegments = Strings.split(fqn, '.');
			QualifiedName qualifiedName = QualifiedName.create(fqnSegments);
			jvmType = getIndexedJvmType(qualifiedName, javaObjectURI.fragment(), resourceSet, throwShadowedException);
		}
		return jvmType;
	}
	return null;
}
 
Example 12
Source File: EObjectUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a location string for an EObject suitable to include in debugging error messages.
 *
 * @param obj
 *          object
 * @return location string including URI of object
 */
public static String getLocationString(final EObject obj) {
  if (obj == null) {
    return null;
  }
  ICompositeNode node = NodeModelUtils.findActualNodeFor(obj);
  URI uri = EcoreUtil.getURI(obj);
  if (node != null) {
    return uri.trimFragment() + ":" + node.getStartLine() + " (" + obj + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
  }
  return uri.toString() + " (" + obj + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example 13
Source File: XWorkspaceResourceAccess.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public <R> R readOnly(URI targetURI, IUnitOfWork<R, ResourceSet> work) {
	URI uri = targetURI.trimFragment(); // note: targetURI may point to an EObject inside an EMF resource!
	OpenFilesManager openFilesManager = languageServer.getOpenFilesManager();
	OpenFileContext currOFC = openFilesManager.currentContext();
	if (currOFC != null) {
		return doWork(currOFC.getResourceSet(), work);
	}
	// TODO GH-1774 consider making a current context mandatory by removing the following:
	CompletableFuture<R> future = openFilesManager.runInTemporaryFileContext(uri, "XWorkspaceResourceAccess", true,
			(ofc, ci) -> doWork(ofc.getResourceSet(), work));
	return FutureUtil.getCancellableResult(future);
}
 
Example 14
Source File: TestResultsView.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void openTestMethod(TestCase testCase) {
	final URI testCaseURI = testCase.getURI();
	if (testCaseURI == null) {
		return;
	}
	final URI moduleLocation = testCaseURI.trimFragment();
	if (!openErrorIfProblem(moduleLocation)) {
		uriOpener.open(testCaseURI, true);
	}
}
 
Example 15
Source File: N4JSLanguageSpecificURIEditorOpener.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IEditorPart open(final URI uri, final EReference crossReference, final int indexInList,
		final boolean select) {

	String fragment = uri.fragment();
	URI trimedFragmentUri = uri.trimFragment();
	if (trimedFragmentUri.isFile()) {
		URI platformUri = URIUtils.tryToPlatformUri(trimedFragmentUri);
		URI appendedFragmentUri = platformUri.appendFragment(fragment);
		return super.open(appendedFragmentUri, crossReference, indexInList, select);
	}

	return super.open(uri, crossReference, indexInList, select);
}
 
Example 16
Source File: ChangeManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private XtextEditor getEditor(URI uri) {
	// note: trimming fragment in previous line makes this more stable in case of changes to the
	// Xtext editor's contents (we are not interested in a particular element, just the editor)
	final URI uriToEditor = uri != null ? uri.trimFragment() : null;
	if (uriToEditor != null) {
		final IEditorPart editor = getEditorOpener().open(uriToEditor, false);
		if (editor instanceof XtextEditor)
			return (XtextEditor) editor;
	}
	return null;
}
 
Example 17
Source File: IAtomicChange.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Constructs a new atomic change.
 *
 * @see IAtomicChange
 */
public AbstractAtomicChange(URI uri, int offset, int length) {
	this.uri = uri.trimFragment();
	this.offset = offset;
	this.length = length;
}
 
Example 18
Source File: UserDataAwareScope.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private IEObjectDescription resolve(IEObjectDescription original) {
	if (original instanceof ResolvedDescription) {
		return original;
	}
	if (original != null && original.getEObjectOrProxy().eIsProxy()
			&& EcoreUtil2.isAssignableFrom(type, original.getEClass())) {
		final URI objectURI = original.getEObjectURI();
		final URI resourceURI = objectURI.trimFragment();
		Resource resource = resourceSet.getResource(resourceURI, false);
		if (resource != null && resource.isLoaded()) {
			return original;
		}
		final boolean mustLoadFromSource = canLoadFromDescriptionHelper.mustLoadFromSource(resourceURI,
				resourceSet);
		resource = resourceSet.getResource(resourceURI, mustLoadFromSource);
		if (resource != null && resource.isLoaded()) {
			return original;
		}
		if (mustLoadFromSource) {
			// error case: forced loading failed
			// --> still avoid loading from index; instead simply return 'original' as in other error cases
			return original;
		}
		if (resource == null) {
			resource = canLoadFromDescriptionHelper.createResource(resourceSet, resourceURI);
		}
		if (resource instanceof N4JSResource) {
			if (resource.getContents().isEmpty()) {
				N4JSResource casted = (N4JSResource) resource;
				IResourceDescription resourceDescription = container.getResourceDescription(resourceURI);
				if (resourceDescription != null) {
					if (casted.isLoaded()) {
						// LiveShadowingResourceDescriptions (part of Xtext's rename refactoring)
						// will load that stuff on #getResourceDescription
						return original;
					}
					try {
						if (!casted.loadFromDescription(resourceDescription)) {
							return original;
						}
					} catch (Exception e) {
						casted.unload();
						return original;
					}
				} else {
					return original;
				}
			}
			// resolveProxy is implemented recursively thus we have to avoid
			// that here by decorating the
			// description and return the resolved instance instead
			EObject resolved = resolveObject(objectURI, resource);
			if (resolved == null) {
				return original;
			}
			return new ResolvedDescription(resolved, original);
		}
	}
	return original;
}
 
Example 19
Source File: WorkbenchMarkerResolutionGenerator.java    From dsl-devkit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the context URI for a file for a given marker.
 *
 * @param marker
 *          the marker
 * @return the markers file URI , <code>null</code> if we cannot find a file.
 */
protected URI getMarkerResourceUri(final IMarker marker) {
  final URI uriToProblem = getIssueUtil().getUriToProblem(marker);
  return uriToProblem == null ? null : uriToProblem.trimFragment();
}