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

The following examples show how to use org.eclipse.emf.common.util.URI#isFile() . 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: GamlSyntacticConverter.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static String getAbsoluteContainerFolderPathOf(final Resource r) {
	URI uri = r.getURI();
	if (uri.isFile()) {
		uri = uri.trimSegments(1);
		return uri.toFileString();
	} else if (uri.isPlatform()) {
		final IPath path = GamlResourceServices.getPathOf(r);
		final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		final IContainer folder = file.getParent();
		return folder.getLocation().toString();
	}
	return URI.decode(uri.toString());

	// final IPath fullPath = file.getLocation();
	// path = fullPath; // toOSString ?
	// if (path == null) { return null; }
	// return path.uptoSegment(path.segmentCount() - 1);
}
 
Example 2
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 3
Source File: GamlResourceServices.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static String getProjectPathOf(final Resource r) {
	if (r == null) { return ""; }
	final URI uri = r.getURI();
	if (uri == null) { return ""; }
	// Cf. #2983 -- we are likely in a headless scenario
	if (uri.isFile()) {
		File project = new File(uri.toFileString());
		while (project != null && !isProject(project)) {
			project = project.getParentFile();
		}
		return project == null ? "" : project.getAbsolutePath();
	} else {
		final IPath path = getPathOf(r);
		final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		final IPath fullPath = file.getProject().getLocation();
		return fullPath == null ? "" : fullPath.toOSString();
	}
}
 
Example 4
Source File: N4JSResourceLinkHelper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IStructuredSelection findSelection(IEditorInput input) {

	final IStructuredSelection selection = super.findSelection(input);
	if (null == selection || selection.isEmpty() && input instanceof XtextReadonlyEditorInput) {
		try {
			final IStorage storage = ((XtextReadonlyEditorInput) input).getStorage();
			if (storage instanceof IURIBasedStorage) {
				final URI uri = ((IURIBasedStorage) storage).getURI();
				if (uri.isFile()) {
					final File file = URIUtils.toFile(uri);
					if (file.isFile()) {
						final Node node = getResourceNode(file);
						if (null != node) {
							return new StructuredSelection(node);
						}
					}
				}
			}
		} catch (final CoreException e) {
			LOGGER.error("Error while extracting storage from read-only Xtext editor input.", e);
			return EMPTY;
		}
	}
	return selection;
}
 
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: N4JSEclipseModel.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IN4JSEclipseProject findProjectWith(URI nestedLocation) {
	// FIXME: mm
	if (nestedLocation.isPlatformResource()) {
		SafeURI<?> location = fromURI(getInternalWorkspace(), nestedLocation);
		if (location != null) {
			return getN4JSProject(location, false);
		}
	}

	// FIXME: Does this actually work for the LSP case?
	if (nestedLocation.isFile()) {
		SafeURI<?> externalLocation = fromURI(externalLibraryWorkspace, nestedLocation);
		if (null != externalLocation) {
			return getN4JSProject(externalLocation, true);
		}
	}
	return null;
}
 
Example 7
Source File: URIUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Converts any emf file URI to an accessible platform local URI. Otherwise returns given URI. */
public static URI tryToPlatformUri(URI fileUri) {
	if (fileUri.isFile()) {
		java.net.URI jnUri = java.net.URI.create(fileUri.toString());
		IFile[] platformFiles = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(jnUri);
		if (platformFiles.length > 0 && platformFiles[0].isAccessible()) {
			IFile localTargetFile = platformFiles[0];
			URI uri = URIUtils.convert(localTargetFile);
			if (fileUri.hasFragment()) {
				uri = uri.appendFragment(fileUri.fragment());
			}
			return uri;
		}
	}
	return fileUri;
}
 
Example 8
Source File: N4JSStorage2UriMapper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * GH-1190: disable a new behavior of Xtext, which adds pairs <code>FileStoreStorage -> null</code> for file URIs
 * (see private method <code>#getStorages(URI, IFile)</code> of super class), because these pairs will lead to a
 * NullPointerException in Xtext's {@code ToBeBuiltComputer#doRemoveProject(IProject, IProgressMonitor)} when
 * applied to a project located in the external library workspace.
 */
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	Iterable<Pair<IStorage, IProject>> storages = super.getStorages(uri);
	if (!uri.isPlatformResource() && uri.isFile()) {
		storages = super.getContribution().getStorages(uri);
	} else {
		storages = super.getStorages(uri);
	}
	return Iterables.filter(storages,
			pair -> !(pair != null && pair.getFirst() instanceof FileStoreStorage));
}
 
Example 9
Source File: ExternalLibraryUriHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check if the {@link URI URI} argument represents an external library location or not.
 *
 * @param uri
 *            to check whether external location or not.
 * @return {@code true} if the argument points to an external library location, otherwise {@code false}.
 */
public boolean isExternalLocation(final URI uri) {
	if (null != uri && uri.isFile()) {
		final IN4JSProject project = core.findProject(uri).orNull();
		return null != project && project.exists() && project.isExternal();
	}
	return false;
}
 
Example 10
Source File: UriExtensions.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Converts the file URIs with an absent (null) authority to one with an empty ("") authority
 */
public URI withEmptyAuthority(URI uri) {
	if (uri.isFile() && uri.authority() == null) {
		return URI.createHierarchicalURI(uri.scheme(), "", uri.device(), uri.segments(), uri.query(),
				uri.fragment());
	}
	return uri;
}
 
Example 11
Source File: N4JSMarkerUpdater.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void updateMarkersForExternalLibraries(Delta delta, ResourceSet resourceSet, IProgressMonitor monitor) {
	URI uri = delta.getUri();
	if (n4jsCore.isNoValidate(uri)) {
		return;
	}

	Resource resource = resourceSet.getResource(uri, true);
	IResourceValidator validator = getValidator(resource);
	IN4JSProject prj = n4jsCore.findProject(uri).orNull();
	CancelIndicator cancelIndicator = getCancelIndicator(monitor);

	if (prj != null && prj.isExternal() && prj.exists() && prj instanceof N4JSEclipseProject && uri.isFile()) {
		// transform file uri in workspace iResource
		IFile file = URIUtils.convertFileUriToPlatformFile(uri);

		if (file != null && resource != null) {
			List<Issue> list = validator.validate(resource, CheckMode.NORMAL_AND_FAST, cancelIndicator);

			if (SHOW_ONLY_EXTERNAL_ERRORS) {
				for (Iterator<Issue> iter = list.iterator(); iter.hasNext();) {
					if (iter.next().getSeverity() != Severity.ERROR) {
						iter.remove();
					}
				}
			}

			try {
				validatorExtension.createMarkers(file, resource, list);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 12
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 13
Source File: ImportHelper.java    From fixflow with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an absolute canonical representation of the given URI.
 * 
 * A relative uri is interpreted as relative to the working directory and made absolute. Furthermore,
 * redundant segments ("./") from the path are removed.
 * @param uri A relative or absolute URI.
 * @return <code>uri</code> in absolute and canonical form, obtained by creating a {@linkplain File file} 
 * from it and taking its {@linkplain File#getCanonicalPath() canonical path}.
 */
public static URI makeURICanonical(URI uri) {
    if (uri.isFile()) {
        File tmpFile = new File(uri.toFileString());
        try {
            return URI.createFileURI(tmpFile.getCanonicalPath());
        } catch (IOException e) {
            return URI.createFileURI(tmpFile.getAbsolutePath());
        }
    } else
        return uri;
}
 
Example 14
Source File: DefaultGenArtifactConfigurations.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected String relative(URI uri) {
	if (uri.isFile()) {
		return uri.toFileString();
	} else if (uri.isPlatform()) {
		return uri.toPlatformString(true);
	}
	throw new IllegalArgumentException("Unknown URI " + uri);
}
 
Example 15
Source File: URIUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Converts any emf URI to a file URI */
public static URI toFileUri(URI rUri) {
	URI fileUri = rUri;
	if (!rUri.isFile()) {
		fileUri = CommonPlugin.resolve(rUri);
	}
	return addEmptyAuthority(fileUri);
}
 
Example 16
Source File: AutoDiscoveryFileBasedWorkspace.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public FileURI fromURI(URI unsafe) {
	if (!unsafe.isFile() || unsafe.isRelative()) {
		unsafe = URIUtils.normalize(unsafe);
		if (unsafe.isRelative()) {
			return null;
		}
	}
	return super.fromURI(unsafe);
}
 
Example 17
Source File: N4JSRuntimeCore.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Optional<? extends IN4JSSourceContainer> findN4JSSourceContainer(URI nestedLocation) {
	if (nestedLocation == null || (nestedLocation.isFile() && nestedLocation.isRelative())) {
		return Optional.absent();
	} else {
		return model.findN4JSSourceContainer(nestedLocation);
	}
}
 
Example 18
Source File: HyperlinkXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private String getTargetDescription(XtextResource resource, IHyperlink hyperlink) {
	final StringBuffer sb = new StringBuffer();
	// append hyperlink text. Only consider the element name and ignore the qualified part.
	String hyperlinkText = hyperlink.getHyperlinkText();
	hyperlinkText = hyperlinkText.substring(
			hyperlinkText.lastIndexOf(N4JSHierarchicalNameComputerHelper.DELIMITER) + 1);
	final EObject target = getTarget(resource, hyperlink);

	if (target != null) {
		if (hyperlinkText != null)
			sb.append(hyperlinkText);
		else
			sb.append("<no hyperlink text>");
		// append description of target element (path from the element to the root of the AST)
		// build chain of ancestor AST elements
		sb.append(": ");
		final int startLen = sb.length();
		EObject currTarget = target;
		while (currTarget != null) {
			if (currTarget instanceof NamedElement || currTarget instanceof IdentifiableElement) {
				if (sb.length() > startLen)
					sb.append(" in ");
				String name = currTarget instanceof NamedElement ? ((NamedElement) currTarget).getName()
						: ((IdentifiableElement) currTarget).getName();
				if (name == null || name.trim().length() == 0)
					name = "<unnamed>";
				else
					name = "\"" + name + "\"";
				sb.append(name + "(" + currTarget.eClass().getName() + ")");
			}
			currTarget = currTarget.eContainer();
		}
		// add URI of resource
		final URI targetResURI = target.eResource() != null ? target.eResource().getURI() : null;
		final String fname = targetResURI != null ? targetResURI.lastSegment() : null;
		if (fname != null && fname.trim().length() > 0) {
			sb.append(" in file ");
			sb.append(fname);
		}

	} else {
		URI uri = getURI(hyperlink);
		if (uri != null) {
			if (uri.isFile()) {
				sb.append("file:/...");
				for (int i = Math.max(0, uri.segmentCount() - 2); i < uri.segmentCount(); i++) {
					sb.append("/");
					sb.append(uri.segment(i));
				}
			} else {
				sb.append(uri);
			}
		}
	}
	return sb.toString();
}
 
Example 19
Source File: TraceRegionSerializer.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public <Location, Region> Region doReadFrom(DataInput dataStream, Strategy<Region, Location> reader, Region parent, int version)
		throws IOException {
	int offset = dataStream.readInt();
	int length = dataStream.readInt();
	int lineNumber = dataStream.readInt();
	int endLineNumber = dataStream.readInt();
	boolean useForDebugging = version < VERSION_5 || dataStream.readBoolean();
	int locationSize = dataStream.readInt();
	List<Location> allLocations = Lists.newArrayListWithCapacity(locationSize);
	while(locationSize != 0) {
		int locationOffset = dataStream.readInt();
		int locationLength = dataStream.readInt();
		int locationLineNumber = dataStream.readInt();
		int locationEndLineNumber = dataStream.readInt();
		final SourceRelativeURI path;
		if (dataStream.readBoolean()) {
			if (version < VERSION_5) {
				URI uri = URI.createURI(dataStream.readUTF());
				if (version == VERSION_3 && !uri.isRelative()) {
					if (uri.isPlatform()) {
						String platformString = uri.toPlatformString(false);
						path = new SourceRelativeURI(platformString.substring(platformString.indexOf('/') + 1));
					} else if (uri.isFile()) {
						path = new SourceRelativeURI(uri.lastSegment());
					} else {
						path = SourceRelativeURI.fromAbsolute(uri);
					}
				} else {
					path = new SourceRelativeURI(uri);
				}
			} else {
				path = new SourceRelativeURI(dataStream.readUTF());
			}
		} else {
			path = null;
		}
		if(version == VERSION_3) {
			if (dataStream.readBoolean()) // true, if a project is specified
				dataStream.readUTF(); // read and skip the project name
		}
		allLocations.add(reader.createLocation(locationOffset, locationLength, locationLineNumber, locationEndLineNumber, path));
		locationSize--;
	}
	Region result = reader.createRegion(offset, length, lineNumber, endLineNumber, useForDebugging, allLocations, parent);
	int childrenSize = dataStream.readInt();
	while(childrenSize != 0) {
		doReadFrom(dataStream, reader, result, version);
		childrenSize--;
	}
	return result;
}
 
Example 20
Source File: GenerationPropertyTester.java    From M2Doc with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns <code>true</code> when the generation has a local URI (platform or file).
 * 
 * @param generation
 *            the tested generation.
 * @return <code>true</code> for local objects.
 */
private boolean isLocal(Generation generation) {
    URI uri = generation.eResource().getURI();
    return uri.isFile() || uri.isPlatform();
}