org.eclipse.xtext.util.Tuples Java Examples

The following examples show how to use org.eclipse.xtext.util.Tuples. 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 Project: n4js   Author: eclipse   File: ProcessResult.java    License: Eclipse Public License 1.0 8 votes vote down vote up
/** @return a list of pairs where the first entry is a name and the second is a property. */
List<Pair<String, String>> getProperties() {
	List<Pair<String, String>> props = new ArrayList<>();
	props.add(Tuples.pair("workingDir", workingDir));
	props.add(Tuples.pair("command", command));
	props.add(Tuples.pair("exit code", (exitCode == NO_EXIT_CODE ? "-" : String.valueOf(exitCode))));
	props.add(Tuples.pair("duration", (duration == NO_DURATION ? "-" : duration + "ms")));
	props.add(Tuples.pair("exception", exception == null ? "" : exception.toString()));

	props.add(Tuples.pair("std out", ""));
	if (stdOut != null && !stdOut.isBlank()) {
		props.add(Tuples.pair(null, ">>>>\n" + stdOut + "\n<<<<"));
	}
	props.add(Tuples.pair("err out", ""));
	if (errOut != null && !errOut.isBlank()) {
		props.add(Tuples.pair(null, ">>>>\n" + errOut + "\n<<<<"));
	}

	return props;
}
 
Example #2
Source Project: n4js   Author: eclipse   File: ExternalProjectLoader.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** @return load project and description from given URI. Returns null if not available. */
public Pair<N4JSExternalProject, ProjectDescription> load(final FileURI rootLocation) {
	try {
		ProjectDescription projectDescription = packageManager.loadProjectDescriptionFromProjectRoot(rootLocation);

		if (null != projectDescription) {
			File projectRoot = URIUtils.toFile(rootLocation.toURI());
			ExternalProject p = new ExternalProject(projectRoot, NATURE_ID, BUILDER_ID);
			IN4JSProject pp = new N4JSEclipseProject(p, rootLocation, model);
			N4JSExternalProject ppp = new N4JSExternalProject(projectRoot, pp);

			return Tuples.create(ppp, projectDescription);
		}
	} catch (N4JSBrokenProjectException e) {
		LOGGER.error("Failed to obtain project description for external library.");
	}
	return null;
}
 
Example #3
Source Project: n4js   Author: eclipse   File: PackageJsonHyperlinkHelperExtension.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToMain(JSONStringLiteral mainModuleJsonLiteral) {
	String mainPath = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(mainPath)) {
		URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI();
		IN4JSProject project = model.findProject(packageJsonLoc).orNull();
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (project != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);
			SafeURI<?> mainResolvedPath = project.getLocation().resolve(mainPath);
			if (mainResolvedPath.exists()) {
				return Tuples.pair(mainResolvedPath, region);
			}
		}
	}

	return null;
}
 
Example #4
Source Project: n4js   Author: eclipse   File: PackageJsonHyperlinkHelperExtension.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToMainModule(JSONStringLiteral mainModuleJsonLiteral) {
	String mainModule = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(mainModule)) {
		URI packageJsonLoc = mainModuleJsonLiteral.eResource().getURI();
		IN4JSProject project = model.findProject(packageJsonLoc).orNull();
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (project != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);

			for (IN4JSSourceContainer sc : project.getSourceContainers()) {
				QualifiedName qualifiedName = QualifiedName.create(mainModule);
				SafeURI<?> mainModuleURI = sc.findArtifact(qualifiedName,
						Optional.of(N4JSGlobals.N4JS_FILE_EXTENSION));
				if (mainModuleURI == null) {
					mainModuleURI = sc.findArtifact(qualifiedName, Optional.of(N4JSGlobals.N4JSX_FILE_EXTENSION));
				}
				if (mainModuleURI != null) {
					return Tuples.pair(mainModuleURI, region);
				}
			}
		}
	}

	return null;
}
 
Example #5
Source Project: n4js   Author: eclipse   File: PackageJsonHyperlinkHelperExtension.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToProjectProperty(NameValuePair nvpDependency) {
	String projectName = nvpDependency.getName();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
	if (pdu != null) {
		List<INode> node = NodeModelUtils.findNodesForFeature(nvpDependency,
				JSONPackage.Literals.NAME_VALUE_PAIR__NAME);

		if (!node.isEmpty()) {
			INode nameNode = node.get(0);
			Region region = new Region(nameNode.getOffset() + 1, nameNode.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example #6
Source Project: xtext-core   Author: eclipse   File: FormattableDocument.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void addReplacer(ITextReplacer replacer) {
	if (!this.getRegion().contains(replacer.getRegion())) {
		String frameTitle = getClass().getSimpleName();
		ITextSegment frameRegion = getRegion();
		String replacerTitle = replacer.getClass().getSimpleName();
		ITextSegment replacerRegion = replacer.getRegion();
		RegionsOutsideFrameException exception = new RegionsOutsideFrameException(frameTitle, frameRegion,
				Tuples.create(replacerTitle, replacerRegion));
		getRequest().getExceptionHandler().accept(exception);
		return;
	}
	try {
		getReplacers().add(replacer, getFormatter().createTextReplacerMerger());
	} catch (ConflictingRegionsException e) {
		getRequest().getExceptionHandler().accept(e);
	}
}
 
Example #7
Source Project: xtext-extras   Author: eclipse   File: EcoreQualifiedNameProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
	return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {

		@Override
		public QualifiedName get() {
			EObject temp = obj;
			String name = nameDispatcher.invoke(temp);
			if (Strings.isEmpty(name))
				return null;
			QualifiedName qualifiedName = QualifiedName.create(name);
			if(!isRecurseParent(obj))
				return qualifiedName;
			QualifiedName parentsQualifiedName = getFullyQualifiedName(obj.eContainer());
			if (parentsQualifiedName == null)
				return null;
			else 
				return parentsQualifiedName.append(qualifiedName);
		}

	});
}
 
Example #8
Source Project: xtext-extras   Author: eclipse   File: SerializerTester.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected List<Pair<EObject, ICompositeNode>> detachNodeModel(EObject eObject) {
	EcoreUtil.resolveAll(eObject);
	List<Pair<EObject, ICompositeNode>> result = Lists.newArrayList();
	Iterator<Object> iterator = EcoreUtil.getAllContents(eObject.eResource(), false);
	while (iterator.hasNext()) {
		EObject object = (EObject) iterator.next();
		Iterator<Adapter> adapters = object.eAdapters().iterator();
		while (adapters.hasNext()) {
			Adapter adapter = adapters.next();
			if (adapter instanceof ICompositeNode) {
				adapters.remove();
				result.add(Tuples.create(object, (ICompositeNode) adapter));
				break;
			}
		}
	}
	return result;
}
 
Example #9
Source Project: xtext-eclipse   Author: eclipse   File: Storage2UriMapperImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Iterable<Pair<IStorage, IProject>> getStorages(/* @NonNull */ URI uri, IFile file) {
	if (file == null || !file.isAccessible()) {
		Iterable<Pair<IStorage, IProject>> result = contribution.getStorages(uri);
		if (result == null || !result.iterator().hasNext()) {
			 // Handle files external to the workspace. But check contribution first to be backwards compatible.
			if (uri.isFile()) {
				Path filePath = new Path(uri.toFileString());
				IFileStore fileStore = EFS.getLocalFileSystem().getStore(filePath);
				IFileInfo fileInfo = fileStore.fetchInfo();
				if (fileInfo.exists() && !fileInfo.isDirectory()) {
					return Collections.singletonList(
							Tuples.<IStorage, IProject> create(new FileStoreStorage(fileStore, fileInfo, filePath), (IProject) null));
				}
			}
		}
		return result;
	}
	return Collections.singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
}
 
Example #10
Source Project: xtext-eclipse   Author: eclipse   File: AstSelectionProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected Pair<EObject, EObject> internalGetSelectedAstElements(EObject eObject, ITextRegion currentSelection) {
	ITextRegion textRegion = getTextRegion(eObject);
	while (textRegion.getOffset() == currentSelection.getOffset()) {
		EObject container = eObject.eContainer();
		if (container != null) {
			for (EObject obj : container.eContents()) {
				ITextRegion region = getTextRegion(obj);
				if (getEndOffset(region) == getEndOffset(currentSelection)) {
					Pair<EObject, EObject> parentMatch = internalGetSelectedAstElements(eObject.eContainer(), currentSelection);
					if (parentMatch != null)
						return parentMatch;
					return Tuples.create(eObject, obj);
				}
			}
		} else {
			if (textRegion.equals(currentSelection))
				return Tuples.create(eObject, eObject);
			return null;
		}
		eObject = container;
		textRegion = getTextRegion(eObject);
	}
	return null;
}
 
Example #11
Source Project: dsl-devkit   Author: dsldevkit   File: ParallelResourceLoader.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Load the {@link Resource} with the given {@link URI} and publish the load result.
 *
 * @param uri
 *          the {@link URI} of the {@link Resource} to be loaded
 */
protected void loadResource(final URI uri) {
  Throwable exception = null;
  Resource resource = null;
  currentlyProcessedUris.add(uri);

  if (parallelLoadingSupported(uri)) {
    try {
      resource = doLoadResource(uri);
      // CHECKSTYLE:OFF
    } catch (Throwable t) {
      // CHECKSTYLE:ON
      exception = t;
    }
  }

  currentlyProcessedUris.remove(uri);
  publishLoadResult(Tuples.create(uri, resource, exception));
}
 
Example #12
Source Project: xtext-eclipse   Author: eclipse   File: DefaultFoldingStructureProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.17
 */
protected Collection<FoldedPosition> filterFoldedPositions(Collection<FoldedPosition> foldedPositions) {
	Map<Pair<Integer, Integer>, FoldedPosition> acceptedPositions = new HashMap<>();
	
	for (FoldedPosition foldedPosition : foldedPositions) {
		int startLineNumber = getLineNumber(foldedPosition.getOffset());
		int endLineNumber = getLineNumber(foldedPosition.getOffset() + foldedPosition.getLength());
		Pair<Integer, Integer> startAndEndLineNumbers = Tuples.create(startLineNumber, endLineNumber);
		
		if (!acceptedPositions.containsKey(startAndEndLineNumbers)) {
			acceptedPositions.put(startAndEndLineNumbers, foldedPosition);
		} else {
			// if the folded position has already been accepted, keep the one with the smaller region
			FoldedPosition alreadyAcceptedPosition = acceptedPositions.get(startAndEndLineNumbers);
			if(foldedPosition.getLength() < alreadyAcceptedPosition.getLength()) {
				acceptedPositions.put(startAndEndLineNumbers, foldedPosition);
			}
		}
	}
	
	return acceptedPositions.values();
}
 
Example #13
Source Project: xtext-eclipse   Author: eclipse   File: SerializerTester.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected List<Pair<EObject, ICompositeNode>> detachNodeModel(EObject eObject) {
	EcoreUtil.resolveAll(eObject);
	List<Pair<EObject, ICompositeNode>> result = Lists.newArrayList();
	Iterator<Object> iterator = EcoreUtil.getAllContents(eObject.eResource(), false);
	while (iterator.hasNext()) {
		EObject object = (EObject) iterator.next();
		Iterator<Adapter> adapters = object.eAdapters().iterator();
		while (adapters.hasNext()) {
			Adapter adapter = adapters.next();
			if (adapter instanceof ICompositeNode) {
				adapters.remove();
				result.add(Tuples.create(object, (ICompositeNode) adapter));
				break;
			}
		}
	}
	return result;
}
 
Example #14
Source Project: xtext-eclipse   Author: eclipse   File: ParallelResourceLoader.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	Throwable exception = null;
	Resource resource = null;

	// load resource
	try {
		ResourceSet localResourceSet = resourceSetProvider.get();
		resource = loadResource(uri, localResourceSet, parent);
		localResourceSet.getResources().clear();
	} catch (Throwable t) {
		exception = t;
	}

	// push resource to the queue, wait if queue is full
	try {
		resourceQueue.put(Tuples.create(uri, resource, exception));
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
	}
}
 
Example #15
Source Project: xtext-core   Author: eclipse   File: NfaToProduction.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected <T> Pair<Integer, StateAlias<T>> findSplitState(StateAlias<T> state, Integer depth,
		Set<StateAlias<T>> visited) {
	if (!visited.add(state))
		return null;
	Pair<Integer, StateAlias<T>> result;
	if (state.getOutgoing().size() > 0 && state.getIncoming().size() > 0
			&& state.getOutgoing().size() + state.getIncoming().size() > 2)
		result = Tuples.create(depth, state);
	else
		result = null;
	for (StateAlias<T> out : state.getOutgoing()) {
		Pair<Integer, StateAlias<T>> cand = findSplitState(out, depth + 1, visited);
		if (cand != null && (result == null || isPreferredSplitState(cand, result)))
			result = cand;
	}
	return result;
}
 
Example #16
Source Project: gef   Author: eclipse   File: DotEObjectHover.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Out of the box, Xtext supports hovers only for identifying features of
 * model artifacts, i.e. the name of an object or crosslinks to other
 * objects (see locationInFileProvider.getSignificantTextRegion). That's why
 * this customization is needed to be able to also hover on the current dot
 * attribute values.
 */
@Override
protected Pair<EObject, IRegion> getXtextElementAt(XtextResource resource,
		int offset) {

	Pair<EObject, IRegion> result = super.getXtextElementAt(resource,
			offset);

	if (result == null) {
		EObject o = eObjectAtOffsetHelper.resolveElementAt(resource,
				offset);
		if (o != null) {
			// use fullTextRegion instead of the significantTtextRegion
			ITextRegion region = locationInFileProvider
					.getFullTextRegion(o);
			final IRegion region2 = new Region(region.getOffset(),
					region.getLength());
			if (TextUtilities.overlaps(region2, new Region(offset, 0)))
				return Tuples.create(o, region2);
		}
	}
	return result;
}
 
Example #17
Source Project: dsl-devkit   Author: dsldevkit   File: AcfContentAssistProcessorTestBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Internally compute completion proposals.
 *
 * @param cursorPosition
 *          the position of the cursor in the {@link IXtextDocument}
 * @param xtextDocument
 *          the {@link IXtextDocument}
 * @return a pair of {@link ICompletionProposal}[] and {@link BadLocationException}. If the tail argument is not {@code null}, an exception occurred in the UI
 *         thread.
 */
private Pair<ICompletionProposal[], BadLocationException> internalComputeCompletionProposals(final int cursorPosition, final IXtextDocument xtextDocument) {
  XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
  Shell shell = new Shell();
  try {
    ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
    IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
    String contentType = xtextDocument.getContentType(cursorPosition);
    IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType);
    if (processor != null) {
      return Tuples.create(processor.computeCompletionProposals(sourceViewer, cursorPosition), null);
    }
    return Tuples.create(new ICompletionProposal[0], null);
  } catch (BadLocationException e) {
    return Tuples.create(new ICompletionProposal[0], e);
  } finally {
    shell.dispose();
  }
}
 
Example #18
Source Project: xtext-core   Author: eclipse   File: IReferableElementsUnloader.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void unloadRoot(EObject root) {
	// Content adapters should be removed the same way as they are added: top-down. 
	// Fragments are recursive, so we need them to be calculated before proxifying the container.
	// OTOH, some model elements resolve their children when being proxified (e.g. EPackageImpl).
	// => first calculate all fragments, then proxify elements starting form root.
	List<Pair<EObject, URI>> elementsToUnload = newArrayList();
	elementsToUnload.add(Tuples.create(root, EcoreUtil.getURI(root)));
	root.eAdapters().clear();
	for (Iterator<EObject> i = EcoreUtil.getAllProperContents(root, false); i.hasNext();) {
		EObject element = i.next();
		elementsToUnload.add(Tuples.create(element, EcoreUtil.getURI(element)));
		element.eAdapters().clear();
	}
	for (Pair<EObject,URI> elementToUnload : elementsToUnload) {
		((InternalEObject) elementToUnload.getFirst()).eSetProxyURI(elementToUnload.getSecond());
	}
}
 
Example #19
Source Project: xtext-core   Author: eclipse   File: EcoreQualifiedNameProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
	return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {

		@Override
		public QualifiedName get() {
			EObject temp = obj;
			String name = nameDispatcher.invoke(temp);
			if (Strings.isEmpty(name))
				return null;
			QualifiedName qualifiedName = QualifiedName.create(name);
			if(!isRecurseParent(obj))
				return qualifiedName;
			QualifiedName parentsQualifiedName = getFullyQualifiedName(obj.eContainer());
			if (parentsQualifiedName == null)
				return null;
			else 
				return parentsQualifiedName.append(qualifiedName);
		}

	});
}
 
Example #20
Source Project: xtext-core   Author: eclipse   File: AbstractElementFinder.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public List<Pair<Keyword, Keyword>> findKeywordPairs(String leftKw, String rightKw) {
	ArrayList<Pair<Keyword, Keyword>> pairs = new ArrayList<Pair<Keyword, Keyword>>();
	for (AbstractRule ar : getRules())
		if (ar instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) ar)) {
			Stack<Keyword> openings = new Stack<Keyword>();
			TreeIterator<EObject> i = ar.eAllContents();
			while (i.hasNext()) {
				EObject o = i.next();
				if (o instanceof Keyword) {
					Keyword k = (Keyword) o;
					if (leftKw.equals(k.getValue()))
						openings.push(k);
					else if (rightKw.equals(k.getValue())) {
						if (openings.size() > 0)
							pairs.add(Tuples.create(openings.pop(), k));
					}
				}
			}
		}
	return pairs;
}
 
Example #21
Source Project: n4js   Author: eclipse   File: CliCompileResult.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
List<Pair<String, String>> getProperties() {
	List<Pair<String, String>> props = super.getProperties();

	List<String> fileNameList = getTranspiledFiles().stream().map(f -> f.toString()).collect(toList());
	props.add(Tuples.pair("transpiled (" + getTranspiledFilesCount() + ")", ""));
	if (getTranspiledFilesCount() > 0) {
		props.add(Tuples.pair(null, IDENT2 + String.join("\n" + IDENT2, fileNameList) + "\n"));
	}

	if (n4jscVariant == N4jscVariant.exprocess) {
		return props;
	}

	List<String> projectNameList = getProjects().entrySet().stream().map(e -> e.getKey() + " at " + e.getValue())
			.collect(toList());

	props.add(Tuples.pair("variant", n4jscVariant.toString()));
	props.add(Tuples.pair("projects (" + getProjects().size() + ")", ""));
	if (getProjects().size() > 0) {
		props.add(Tuples.pair(null, IDENT2 + String.join("\n" + IDENT2, projectNameList)));
	}

	props.add(Tuples.pair("warnings (" + getWrns() + ")", ""));
	if (getWrns() > 0) {
		props.add(Tuples.pair(null, IDENT1 + String.join("\n" + IDENT1, getWrnMsgs())));
	}
	props.add(Tuples.pair("errors (" + getErrs() + ")", ""));
	if (getErrs() > 0) {
		props.add(Tuples.pair(null, IDENT1 + String.join("\n" + IDENT1, getErrMsgs())));
	}

	return props;
}
 
Example #22
Source Project: xtext-core   Author: eclipse   File: FormattingConfigBasedStream.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public Pair<AbstractRule, String> getSpaces(LineEntry entry, boolean isLineStart) {
	String space = getSpacesStr(entry, isLineStart);
	if (space == null)
		return null;
	AbstractRule rule = hiddenTokenHelper.getWhitespaceRuleFor(entry.hiddenTokenDefinition, space);
	if (rule == null)
		return null;
	return Tuples.create(rule, space);
}
 
Example #23
Source Project: n4js   Author: eclipse   File: PackageJsonHyperlinkHelperExtension.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToRequiredRTLibs(JSONStringLiteral mainModuleJsonLiteral) {
	String projectName = mainModuleJsonLiteral.getValue();
	if (!Strings.isNullOrEmpty(projectName)) {
		SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));
		INode node = NodeModelUtils.getNode(mainModuleJsonLiteral);

		if (pdu != null && node != null) {
			Region region = new Region(node.getOffset() + 1, node.getLength() - 2);

			return Tuples.pair(pdu, region);
		}
	}

	return null;
}
 
Example #24
Source Project: n4js   Author: eclipse   File: PackageJsonHyperlinkHelperExtension.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Pair<SafeURI<?>, Region> hyperlinkToDependencySection(NameValuePair projectNameInValue) {
	JSONStringLiteral jsonValue = (JSONStringLiteral) projectNameInValue.getValue();
	String projectName = jsonValue.getValue();
	SafeURI<?> pdu = getProjectDescriptionLocationForName(new N4JSProjectName(projectName));

	if (pdu != null) {
		INode valueNode = NodeModelUtils.getNode(jsonValue);
		Region region = new Region(valueNode.getOffset() + 1, valueNode.getLength() - 2);

		return Tuples.pair(pdu, region);
	}
	return null;
}
 
Example #25
Source Project: n4js   Author: eclipse   File: ProjectDescriptionLoader.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Loads the project description of the N4JS project at the given {@code location} and returns the version string or
 * <code>null</code> if undefined or in case of error.
 */
public Pair<String, Boolean> loadVersionAndN4JSNatureFromProjectDescriptionAtLocation(SafeURI<?> location) {
	JSONDocument packageJSON = loadPackageJSONAtLocation(location);
	JSONValue versionValue = null;
	boolean hasN4JSNature = false;
	if (packageJSON != null) {
		versionValue = JSONModelUtils.getProperty(packageJSON, VERSION.name).orElse(null);
		hasN4JSNature = JSONModelUtils.getProperty(packageJSON, N4JS.name).isPresent();
	}
	Pair<String, Boolean> result = Tuples.create(asNonEmptyStringOrNull(versionValue), hasN4JSNature);
	return result;
}
 
Example #26
Source Project: n4js   Author: eclipse   File: ContainerTypesHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private TMemberEntry getOrCreateEntry(TMember member) {
	Pair<String, Boolean> p = Tuples.pair(member.getName(), member.isStatic());
	TMemberEntry entry = memberEntries.get(p);
	if (entry == null) {
		entry = new TMemberEntry(member.getName(), member.isStatic());
		memberEntries.put(p, entry);
	}
	return entry;
}
 
Example #27
Source Project: dsl-devkit   Author: dsldevkit   File: MonitoredClusteringBuilderState.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Iterable<IResourceDescription> findAllReferencingResources(final Set<IResourceDescription> targetResources, final ReferenceMatchPolicy matchPolicy) {
  Pair<Set<IResourceDescription>, ReferenceMatchPolicy> key = Tuples.create(targetResources, matchPolicy);
  Iterable<IResourceDescription> result = findAllReferencingResourcesCache.get(key);
  if (result == null) {
    result = Lists.newArrayList(delegate().findAllReferencingResources(targetResources, matchPolicy));
    findAllReferencingResourcesCache.put(key, result);
  }
  return result;
}
 
Example #28
Source Project: dsl-devkit   Author: dsldevkit   File: GenModelQualifiedNameProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
  return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {
    @Override
    public QualifiedName get() {
      if (obj instanceof GenPackage) {
        String nsUri = ((GenPackage) obj).getNSURI();
        return nsUri != null ? QualifiedName.create(nsUri) : null;
      }
      return null;
    }
  });
}
 
Example #29
Source Project: xtext-core   Author: eclipse   File: TestErrorAcceptor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void acceptError(TransformationErrorCode errorCode, String message, EObject element) {
	Triple<TransformationErrorCode, String, EObject> create = Tuples.create(errorCode, message, element);
	//		System.out.println((write ? "Write>" : "Read>") + " errorCode: " + (errorCode != null ? errorCode : "")
	//				+ ", message: " + (message != null ? message : "") + ", element: " + (element != null ? element : ""));
	if (write) {
		flugschreiber.push(create);
	} else {
		Triple<TransformationErrorCode, String, EObject> pop = flugschreiber.removeLast();
		assertNotNull("Queue is empty", pop);
		boolean equals = compareTriple(pop, create);
		assertTrue("Verified", equals);
	}
}
 
Example #30
Source Project: xtext-core   Author: eclipse   File: LazyURIEncoder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * decodes the uriFragment
 * 
 * @param res the resource that contains the feature holder
 * @param uriFragment the fragment that should be decoded
 * @return the decoded information
 * @see LazyURIEncoder#encode(EObject, EReference, INode)
 */
public Triple<EObject, EReference, INode> decode(Resource res, String uriFragment) {
	if (isUseIndexFragment(res)) {
		return getLazyProxyInformation(res, uriFragment);
	}
	List<String> split = Strings.split(uriFragment, SEP);
	EObject source = resolveShortFragment(res, split.get(1));
	EReference ref = fromShortExternalForm(source.eClass(), split.get(2));
	INode compositeNode = NodeModelUtils.getNode(source);
	if (compositeNode==null)
		throw new IllegalStateException("Couldn't resolve lazy link, because no node model is attached.");
	INode textNode = getNode(compositeNode, split.get(3));
	return Tuples.create(source, ref, textNode);
}