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

The following examples show how to use org.eclipse.emf.common.util.URI#toPlatformString() . 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: ProjectDescriptionUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Creates a new instance. Given URI should point to an N4JS project, not a file within an N4JS project. */
public static ProjectNameInfo of(URI projectUri) {
	if (projectUri.isFile()) {
		if (projectUri.lastSegment().isEmpty()) {
			// folders end with an empty segment?
			// projectUri = projectUri.trimSegments(1);
		}
		// a file URI actually represents the file system hierarchy -> no need to look up names on disk
		return new ProjectNameInfo(
				projectUri.lastSegment(),
				projectUri.trimSegments(1).lastSegment(),
				Optional.absent() // no Eclipse project name in this case
		);
	} else if (projectUri.isPlatform()) {
		// for platform URIs (i.e. UI case) we actually have to look up the folder name on disk
		final String platformURI = projectUri.toPlatformString(true);
		final IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformURI);
		final IPath path = resource.getLocation();
		return new ProjectNameInfo(
				path.lastSegment(),
				path.removeLastSegments(1).lastSegment(),
				resource instanceof IProject ? Optional.of(resource.getName()) : Optional.absent());
	}
	throw new IllegalStateException("not a file or platform URI: " + projectUri);
}
 
Example 2
Source File: FileUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static IFile getWorkspaceFile(final URI uri) {
	final IPath uriAsPath = new Path(URI.decode(uri.toString()));
	IFile file;
	try {
		file = ROOT.getFile(uriAsPath);
	} catch (final Exception e1) {
		return null;
	}
	if (file != null && file.exists()) { return file; }
	final String uriAsText = uri.toPlatformString(true);
	final IPath path = uriAsText != null ? new Path(uriAsText) : null;
	if (path == null) { return null; }
	try {
		file = ROOT.getFile(path);
	} catch (final Exception e) {
		return null;
	}
	if (file != null && file.exists()) { return file; }
	return null;
}
 
Example 3
Source File: WorkbenchTestHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the project for the given resource.
 * 
 * @param resource the resource to search for.
 * @param createOnDemand create the project if it does not exist yet.
 * @return the project.
 */
public IProject getProject(Resource resource, boolean createOnDemand) {
	if (resource != null) {
		final URI uri = resource.getURI();
		final String platformString = uri.toPlatformString(true);
		final IPath resourcePath = new Path(platformString);
		final IFile file = this.workspace.getRoot().getFile(resourcePath);
		if (file != null) {
			final IProject project = file.getProject();
			if (project != null && project.exists()) {
				return project;
			}
		}
	}
	return getProject(createOnDemand);
}
 
Example 4
Source File: ActiveEditorTracker.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return The project which contains the file that is open in the last
 *         active editor in the current workbench page.
 */
public static IProject getLastActiveEditorProject() {
	final IEditorPart editor = getLastActiveEditor();
	if (editor == null)
		return null;
	final IEditorInput editorInput = editor.getEditorInput();
	if (editorInput instanceof IFileEditorInput) {
		final IFileEditorInput input = (IFileEditorInput) editorInput;
		return input.getFile().getProject();
	} else if (editorInput instanceof URIEditorInput) {
		final URI uri = ((URIEditorInput) editorInput).getURI();
		if (uri.isPlatformResource()) {
			final String platformString = uri.toPlatformString(true);
			return ResourcesPlugin.getWorkspace().getRoot().findMember(platformString).getProject();
		}
	}
	return null;
}
 
Example 5
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given a base URI, figure out which {@link IFolder}, if any, it refers to.
 *
 * @param baseURI
 *          to find the folder(s) for; must not be {@code null}
 * @return an array of all folders mapping to that URI, or an empty array if none do.
 */
private static IContainer[] determineContainersToCheck(final URI baseURI) {
  Preconditions.checkNotNull(baseURI);
  IContainer[] result = {};
  if (baseURI.isPlatformResource() || baseURI.isFile()) {
    IWorkspaceRoot workspace = EcorePlugin.getWorkspaceRoot();
    if (workspace != null) {
      if (baseURI.isFile()) {
        result = workspace.findContainersForLocationURI(java.net.URI.create(baseURI.toString()));
      } else {
        // Must be a platform/resource URI
        IPath platformPath = new Path(baseURI.toPlatformString(true));
        IFolder folder = workspace.getFolder(platformPath);
        if (folder != null) {
          result = new IContainer[] {folder};
        }
      }
    }
  }
  return result;
}
 
Example 6
Source File: SiriusServiceConfigurator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the {@link Session} path form the given platform resource {@link URI}.
 * 
 * @param platformResourceURI
 *            the platform resource {@link URI}
 * @return the {@link Session} path form the given platform resource {@link URI} if any, <code>null</code> otherwise
 */
private String getSessionFromPlatformResource(final URI platformResourceURI) {
    final String res;
    final String filePath = platformResourceURI.toPlatformString(true);
    final IFile genconfFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filePath));
    final IProject project = genconfFile.getProject();
    final ModelingProject modelingProject = getModelingProject(project);

    if (modelingProject != null) {
        final Session session = modelingProject.getSession();
        if (session != null) {
            final URI sessionURI = session.getSessionResource().getURI();
            res = URI.decode(sessionURI.deresolve(platformResourceURI, false, true, true).toString());
        } else {
            res = null;
        }
    } else {
        res = null;
    }
    return res;
}
 
Example 7
Source File: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void completeGrammar_Name(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	Resource resource = model.eResource();
	URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		IPath path = new Path(uri.toPlatformString(true));
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		IProject project = file.getProject();
		IJavaProject javaProject = JavaCore.create(project);
		if (javaProject != null) {
			try {
				for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
					IPath packageFragmentRootPath = packageFragmentRoot.getPath();
					if (packageFragmentRootPath.isPrefixOf(path)) {
						IPath relativePath = path.makeRelativeTo(packageFragmentRootPath);
						relativePath = relativePath.removeFileExtension();
						String result = relativePath.toString();
						result = result.replace('/', '.');
						acceptor.accept(createCompletionProposal(result, context));
						return;
					}
				}
			} catch (JavaModelException ex) {
				// nothing to do
			}
		}
	}
}
 
Example 8
Source File: ParallelResourceLoader.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Make sure that all files that are about to be loaded are synchronized with the file system
 */
private void synchronizeResources(Collection<URI> toLoad) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	for(URI uri : toLoad) {
		if (uri.isPlatformResource()) {
			Path path = new Path(uri.toPlatformString(true));
			IFile file = root.getFile(path);
			try {
				file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
 
Example 9
Source File: XtendRenameStrategy.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IPath getPathToRename(URI elementURI, ResourceSet resourceSet) {
	EObject targetObject = resourceSet.getEObject(elementURI, false);
	if (targetObject instanceof XtendTypeDeclaration) {
		URI resourceURI = EcoreUtil2.getPlatformResourceOrNormalizedURI(targetObject).trimFragment();
		if (!resourceURI.isPlatformResource())
			throw new RefactoringException("Renamed type does not reside in the workspace");
		IPath path = new Path(resourceURI.toPlatformString(true));
		if(context instanceof IChangeRedirector.Aware) { 
			if(((IChangeRedirector.Aware) context).getChangeRedirector().getRedirectedPath(path) != path)
				return null;
		}
		return path;
	}
	return null;
}
 
Example 10
Source File: EclipseFileSystemSupportImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IResource findMember(final URI uri) {
  IResource _xblockexpression = null;
  {
    final String platformResourcePath = uri.toPlatformString(true);
    org.eclipse.core.runtime.Path _path = new org.eclipse.core.runtime.Path(platformResourcePath);
    _xblockexpression = this.workspaceRoot.findMember(_path);
  }
  return _xblockexpression;
}
 
Example 11
Source File: AbstractFileSystemSupport.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected Path getPath(final URI absoluteURI, final URI baseURI, final Path basePath) {
  Path _xblockexpression = null;
  {
    URI _xifexpression = null;
    if ((baseURI.isPlatformResource() && absoluteURI.isPlatformResource())) {
      URI _xifexpression_1 = null;
      String _segment = baseURI.segment(1);
      String _segment_1 = absoluteURI.segment(1);
      boolean _notEquals = (!Objects.equal(_segment, _segment_1));
      if (_notEquals) {
        URI _xblockexpression_1 = null;
        {
          String _platformString = absoluteURI.toPlatformString(true);
          final org.eclipse.core.runtime.Path p = new org.eclipse.core.runtime.Path(_platformString);
          String _string = p.toString();
          String _plus = (".." + _string);
          _xblockexpression_1 = URI.createURI(_plus);
        }
        _xifexpression_1 = _xblockexpression_1;
      } else {
        _xifexpression_1 = absoluteURI.deresolve(baseURI);
      }
      _xifexpression = _xifexpression_1;
    } else {
      _xifexpression = absoluteURI.deresolve(baseURI);
    }
    final URI relativeURI = _xifexpression;
    if ((relativeURI.isEmpty() || Objects.equal(relativeURI, absoluteURI))) {
      return null;
    }
    _xblockexpression = basePath.getAbsolutePath(relativeURI.toString());
  }
  return _xblockexpression;
}
 
Example 12
Source File: EclipseResourceTypeDetector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the given resource is a test resource according to the Java or Maven standard.
 *
 * @param resource the resource to test.
 * @return {@link Boolean#TRUE} if the resource is a test resource. {@link Boolean#FALSE}
 *     if the resource is not a test resource. {@code null} if the detector cannot determine
 *     the type of the resource.
 */
@SuppressWarnings("checkstyle:nestedifdepth")
protected static Boolean isJavaOrMavenTestResource(Resource resource) {
	final URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		final String platformString = uri.toPlatformString(true);
		final IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
		if (iresource != null) {
			final IProject project = iresource.getProject();
			final IJavaProject javaProject = JavaCore.create(project);
			try {
				final IPackageFragment packageFragment = javaProject.findPackageFragment(iresource.getParent().getFullPath());
				final IPackageFragmentRoot root = (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
				if (root != null) {
					final IPath rootPath = root.getPath();
					String name = null;
					if (root.isExternal()) {
						name = rootPath.toOSString();
					} else if (javaProject.getElementName().equals(rootPath.segment(0))) {
					    if (rootPath.segmentCount() != 1) {
							name = rootPath.removeFirstSegments(1).makeRelative().toString();
					    }
					} else {
						name = rootPath.toString();
					}
					if (name != null && name.startsWith(SARLConfig.FOLDER_MAVEN_TEST_PREFIX)) {
						return Boolean.TRUE;
					}
				}
			} catch (JavaModelException e) {
				//
			}
		}
	}
	return null;
}
 
Example 13
Source File: GenerationFileNamesPage.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the file name from the given {@link URI}.
 * 
 * @param uri
 *            the {@link URI}
 * @return the file name from the given {@link URI}
 */
private String getFileName(URI uri) {
    final String res;

    if (uri.isPlatformResource()) {
        res = uri.toPlatformString(true);
    } else {
        res = "";
    }

    return res;
}
 
Example 14
Source File: AbstractLaunchConfigurationMainTab.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the "Resource to Run", using the workspace relative location retrieved via the attribute in
 * {@link RunConfiguration#USER_SELECTION} If attribute is not present, an empty string is returned. A concrete test
 * method are removed, use getTestMethod instead.
 */
public static String getResourceRunAsText(ILaunchConfiguration configuration) throws CoreException {
	String uriStr;
	uriStr = configuration.getAttribute(RunConfiguration.USER_SELECTION, "");
	final URI uri = uriStr.trim().length() > 0 ? URI.createURI(uriStr) : null;
	final String wsRelativePath = uri != null ? uri.toPlatformString(true) : null;
	return wsRelativePath != null ? wsRelativePath : "";
}
 
Example 15
Source File: ImportedResourceCache.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Refresh local file to avoid deadlock with scheduling rule XtextBuilder ->
 * Editing Domain runexclusive
 */
protected void refreshFile(final URI uri) {
	String platformString = uri.toPlatformString(true);
	if (platformString == null)
		return;
	IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));
	if (file.isAccessible() && !file.isSynchronized(IResource.DEPTH_INFINITE)) {
		try {
			file.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
 
Example 16
Source File: EMFHelper.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static IFile getIFileFromEMFUri(URI uri) {
	if (uri.isPlatformResource()) {
		String platformString = uri.toPlatformString(true);
		return (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
	} else if (uri.isFile()) {
		File file = new File(uri.toFileString());
		if (!file.exists())
			return null;
		IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI());
		if (files.length == 1) {
			return files[0];
		}
	}
	return null;
}
 
Example 17
Source File: EmfUriUtil.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static IFile toFile(URI emfUri) {
	if (emfUri.isPlatformResource()) {
		String platformString = emfUri.toPlatformString(true);
		return (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
	} else if (emfUri.isFile()) {
		File file = new File(emfUri.toFileString());
		if (!file.exists())
			return null;
		IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI());
		if (files.length == 1) {
			return files[0];
		}
	}
	return null;
}
 
Example 18
Source File: SCTFileEditorOpener.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public IFile toFile(URI uri) {
	if (uri.isPlatformResource()) {
		String platformString = uri.toPlatformString(true);
		return (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
	}
	return null;
}
 
Example 19
Source File: ResourceUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Finds the file corresponding to the specified URI, using a URI converter if necessary (and provided) to normalize
 * it.
 * 
 * @param uri
 *            a URI
 * @param converter
 *            an optional URI converter (may be <code>null</code>)
 * 
 * @return the file, if available in the workspace
 */
private static IFile getFile(URI uri, URIConverter converter, boolean considerArchives) {
	IFile result = null;

	if (considerArchives && uri.isArchive()) {
		class MyArchiveURLConnection extends ArchiveURLConnection {
			public MyArchiveURLConnection(String url) {
				super(url);
			}

			public String getNestedURI() {
				try {
					return getNestedURL();
				} catch (IOException exception) {
					return ""; //$NON-NLS-1$
				}
			}
		}
		MyArchiveURLConnection archiveURLConnection = new MyArchiveURLConnection(uri.toString());
		result = getFile(URI.createURI(archiveURLConnection.getNestedURI()), converter, considerArchives);
	} else if (uri.isPlatformResource()) {
		IPath path = new Path(uri.toPlatformString(true));
		result = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
	} else if (uri.isFile() && !uri.isRelative()) {
		result = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(uri.toFileString()));
	} else {
		// normalize, to see whether we can resolve it this time
		if (converter != null) {
			URI normalized = converter.normalize(uri);

			if (!uri.equals(normalized)) {
				// recurse on the new URI
				result = getFile(normalized, converter, considerArchives);
			}
		}
	}

	if ((result == null) && !uri.isRelative()) {
		try {
			IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(
					new java.net.URI(uri.toString()));
			if (files.length > 0) {
				// set the result to be the first file found
				result = files[0];
			}
		} catch (URISyntaxException e) {
			// won't get this because EMF provides a well-formed URI
		}
	}

	return result;
}
 
Example 20
Source File: ExternalPackagesPluginTest.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Checks if expected list of stringified file locations matches
 *
 * @param expected
 *            collection of entries
 * @param actual
 *            collection of entries
 */
public void assertResourceDescriptions(Collection<String> expected, Iterable<IResourceDescription> actual) {
	Set<String> extraDescriptions = new HashSet<>();
	Set<String> missingDescriptions = new HashSet<>(expected);

	for (IResourceDescription iResourceDescription : actual) {
		URI uri = iResourceDescription.getURI();
		String stringUri = uri.isPlatform() ? uri.toPlatformString(false) : uri.toFileString();

		String missingDescription = "";
		for (String missingDescr : missingDescriptions) {
			if (stringUri.endsWith(missingDescr)) {
				missingDescription = missingDescr;
				break;
			}
		}

		if (missingDescription.isEmpty()) {
			extraDescriptions.add(stringUri);
		} else {
			missingDescriptions.remove(missingDescription);
		}
	}

	if (missingDescriptions.isEmpty() && extraDescriptions.isEmpty()) {
		return;
	}

	StringBuilder msg = new StringBuilder("unexpected actual resources" + "\n");

	if (!extraDescriptions.isEmpty()) {
		msg.append("actual contains " + extraDescriptions.size() + " extra resources" + "\n");
	}

	if (!missingDescriptions.isEmpty()) {
		msg.append("actual is missing  " + missingDescriptions.size() + " expected resources" + "\n");
	}

	for (String extra : extraDescriptions) {
		msg.append("[extra] " + extra + "\n");
	}
	for (String missing : missingDescriptions) {
		msg.append("[missing] " + missing + "\n");
	}
	fail(msg.toString());
}