Java Code Examples for org.eclipse.xtext.util.Pair#getSecond()

The following examples show how to use org.eclipse.xtext.util.Pair#getSecond() . 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: PackageJsonHyperlinkHelperExtension.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IHyperlink[] getHyperlinks(XtextResource resource, int offset) {
	EObject eObject = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
	Pair<SafeURI<?>, Region> linkedProjectWithRegion = getUriRegionPair(eObject);

	if (linkedProjectWithRegion != null) {
		URI uri = linkedProjectWithRegion.getFirst().toURI();
		IRegion region = linkedProjectWithRegion.getSecond();
		IN4JSProject uriProject = model.findProject(uri).orNull();

		String lnkName = uriProject == null ? ProjectDescriptionUtils.deriveN4JSProjectNameFromURI(uri)
				: uriProject.getProjectName().getRawName();

		XtextHyperlink hyperlink = hyperlinkProvider.get();
		hyperlink.setHyperlinkRegion(region);
		hyperlink.setURI(uri);
		hyperlink.setHyperlinkText(lnkName);

		return new IHyperlink[] { hyperlink };
	}

	return null;
}
 
Example 2
Source File: JavaSearchHelper.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void accept(IReferenceDescription referenceDescription) {
	URI sourceResourceURI = referenceDescription.getSourceEObjectUri().trimFragment();
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(sourceResourceURI);
	Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
	while (iterator.hasNext()) {
		Pair<IStorage, IProject> pair = iterator.next();
		IStorage storage = pair.getFirst();
		IProject project = pair.getSecond();
		if (project != null && !project.isHidden()) {
			ResourceSet resourceSet = getResourceSet(project);
			EObject sourceEObject = resourceSet.getEObject(referenceDescription.getSourceEObjectUri(), true);
			if (sourceEObject != null) {
				ITextRegion region = getLocation(
						sourceEObject, referenceDescription.getEReference(), 
						referenceDescription.getIndexInList());
				acceptMatch(storage, region);
			} else {
				acceptMatch(referenceDescription, null);
			}
		}
	}
}
 
Example 3
Source File: AssignmentQuantityAllocator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public String toString(Map<ISyntaxConstraint, Pair<Integer, Integer>> minmax) {
	Map<ISyntaxConstraint, String> postfix = Maps.newHashMap();
	for (Map.Entry<ISyntaxConstraint, Integer> e : assignmentQuants.entrySet()) {
		String s = ":" + e.getValue();
		if (minmax != null && minmax.containsKey(e.getKey())) {
			Pair<Integer, Integer> p = minmax.get(e.getKey());
			s += "<" + p.getFirst() + "," + (p.getSecond() == Integer.MAX_VALUE ? "*" : p.getSecond()) + ">";
		}
		postfix.put(e.getKey(), s);
	}
	Iterator<ISyntaxConstraint> i = assignmentQuants.keySet().iterator();
	if (!i.hasNext())
		return "";
	ISyntaxConstraint root = i.next();
	while (i.hasNext())
		root = root.findCommonContainer(i.next());
	return root.toString(postfix);
}
 
Example 4
Source File: RawTypeReferenceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public JvmTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference reference, Pair<Resource, Set<JvmType>> context) {
	JvmType type = reference.getType();
	if (type != null && !type.eIsProxy()) {
		if (type instanceof JvmTypeParameterDeclarator) {
			if (!((JvmTypeParameterDeclarator) type).getTypeParameters().isEmpty()) {
				JvmParameterizedTypeReference result = factory.createJvmParameterizedTypeReference();
				result.setType(type);
				return result;
			}
		} else if (type instanceof JvmTypeParameter) {
			Set<JvmType> recursionGuard = context.getSecond();
			if (recursionGuard.add(type)) {
				return getRawTypeFromConstraints(((JvmTypeParameter) type).getConstraints(), context);
			} else {
				return createObjectReference(context.getFirst());
			}
		}
	}
	return reference;
}
 
Example 5
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 6
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 7
Source File: AcfContentAssistProcessorTestBuilder.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell.
 */
@Override
public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, final int cursorPosition) throws Exception {
  Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() {
    @Override
    public Pair<ICompletionProposal[], BadLocationException> run() {
      final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
      final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
      return internalComputeCompletionProposals(cursorPosition, xtextDocument);
    }
  });
  if (result.getSecond() != null) {
    throw result.getSecond();
  }
  return result.getFirst();
}
 
Example 8
Source File: AcfContentAssistProcessorTestBuilder.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell.
 */
public ICompletionProposal[] computeCompletionProposals(final XtextTestSource testSource, final int cursorPosition) {
  Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() {
    @Override
    public Pair<ICompletionProposal[], BadLocationException> run() {
      final IXtextDocument xtextDocument = getDocument(testSource.getXtextResource(), testSource.getContent());
      return internalComputeCompletionProposals(cursorPosition, xtextDocument);
    }
  });
  if (result.getSecond() != null) {
    throw new WrappedException("Error computing completion proposals.", result.getSecond());
  }
  return result.getFirst();
}
 
Example 9
Source File: ExternalProjectMappings.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ProjectDescription getProjectDescription(
		Map<FileURI, Pair<N4JSExternalProject, ProjectDescription>> projectUriMappingTmp,
		SafeURI<?> loc) {

	ProjectDescription pd = loc instanceof PlatformResourceURI
			? userWorkspace.getProjectDescription((PlatformResourceURI) loc)
			: null;
	if (pd == null) {
		Pair<N4JSExternalProject, ProjectDescription> pair = projectUriMappingTmp.get(loc);
		if (pair != null) {
			pd = pair.getSecond();
		}
	}
	return pd;
}
 
Example 10
Source File: AstSelectionProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ITextRegion selectNext(XtextResource resource, ITextRegion currentEditorSelection) {
	Pair<EObject, EObject> currentlySelected = getSelectedAstElements(resource, currentEditorSelection);
	if (currentlySelected == null) {
		return selectEnclosing(resource, currentEditorSelection);
	}
	EObject second = currentlySelected.getSecond();
	EObject nextSibling = EcoreUtil2.getNextSibling(second);
	if (nextSibling != null) {
		return register(getRegion(Tuples.create(currentlySelected.getFirst(), nextSibling)));
	} else {
		if (second.eContainer() == null)
			return ITextRegion.EMPTY_REGION;
		return register(getRegion(Tuples.create(second.eContainer(), second.eContainer())));
	}
}
 
Example 11
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Set<EClass> getSemanticTypeByParent(Set<ISyntaxConstraint> exclude) {
	if (type == ConstraintType.ALTERNATIVE) {
		exclude.addAll(getContents());
		if (semanticType != null)
			return Sets.newHashSet(semanticType);
	} else {
		Pair<Set<EClass>, Set<EClass>> types = getAllSemanticTypesPairs(exclude);
		if (!types.getFirst().isEmpty())
			return types.getFirst();
		if (isRoot())
			return types.getSecond();
	}
	return ((SyntaxConstraintNode) getContainer()).getSemanticTypeByParent(exclude);
}
 
Example 12
Source File: EclipseGeneratorConfigProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public GeneratorConfig get(EObject context) {
	GeneratorConfig result = new GeneratorConfig();
	IProject project = null;
	if (context.eResource() != null) {
		Pair<IStorage, IProject> pair = Iterables.getFirst(storage2UriMapper.getStorages(context.eResource().getURI()), null);
		if (pair != null) {
			project = pair.getSecond();
		}
	}
	xbaseBuilderPreferenceAccess.loadBuilderPreferences(result, project);
	return result;
}
 
Example 13
Source File: XbaseReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createTextChange(ITextRegion referenceTextRegion, String newReferenceText, EObject referringElement,
		EObject newTargetElement, EReference reference, URI referringResourceURI,
		IRefactoringUpdateAcceptor updateAcceptor) {
	if (newReferenceText != null && updateAcceptor instanceof ImportAwareUpdateAcceptor && isReferenceToJvmType(newTargetElement, reference)) {
		JvmType newTargetType = (JvmType) newTargetElement;
		ImportAwareUpdateAcceptor importAwareUpdateAcceptor = (ImportAwareUpdateAcceptor) updateAcceptor;
		
		Pair<JvmDeclaredType, QualifiedName> importedTypeAndRelativeName = getImportedTypeAndRelativeName(newTargetType, importAwareUpdateAcceptor.getImportSection());
		if(importedTypeAndRelativeName != null) {
			JvmDeclaredType importedType = importedTypeAndRelativeName.getFirst();
			QualifiedName importRelativeName = importedTypeAndRelativeName.getSecond();
			
			importAwareUpdateAcceptor.removeImport(importedType, false, false, null);
			if (isReferencedByQualifiedName(referringElement, newTargetType, importRelativeName)) {
				QualifiedName newTypeQualifiedName = qualifiedNameProvider.getFullyQualifiedName(newTargetElement);
				newReferenceText = getLinkText(newTypeQualifiedName, newReferenceText);
			} else {
				if(!isEmpty(importedType.getPackageName())) { 
					importAwareUpdateAcceptor.acceptImport(importedType, false, false, null);
				}
				newReferenceText = getLinkText(importRelativeName, newReferenceText);
			}
		}
	}
	super.createTextChange(referenceTextRegion, newReferenceText, referringElement, newTargetElement, reference,
			referringResourceURI, updateAcceptor);
}
 
Example 14
Source File: AbstractParseTreeConstructor.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void assignNodesByMatching(Map<EObject, AbstractToken> eObject2Token, ICompositeNode rootNode,
		Map<ILeafNode, EObject> comments) throws IOException {
	NodeIterator contents = new NodeIterator(rootNode);
	while (contents.hasNext()) {
		INode containedNode = contents.next();
		AbstractRule rule = containedNode.getGrammarElement() instanceof AbstractRule ? (AbstractRule) containedNode
				.getGrammarElement() : null;
		if (hiddenTokenHelper.isWhitespace(rule))
			continue;
		else if (containedNode instanceof ILeafNode && hiddenTokenHelper.isComment(rule))
			assignComment((ILeafNode) containedNode, eObject2Token, comments);
		else if (tokenUtil.isToken(containedNode)) {
			Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil
					.getLeadingAndTrailingHiddenTokens(containedNode);
			for (ILeafNode leadingHiddenNode : leadingAndTrailingHiddenTokens.getFirst()) {
				if (tokenUtil.isCommentNode(leadingHiddenNode)) {
					assignComment(leadingHiddenNode, eObject2Token, comments);
				}
			}
			assignTokenByMatcher(containedNode, eObject2Token);
			for (ILeafNode trailingHiddenNode : leadingAndTrailingHiddenTokens.getSecond()) {
				if (tokenUtil.isCommentNode(trailingHiddenNode)) {
					assignComment(trailingHiddenNode, eObject2Token, comments);
				}
			}
			contents.prune();
			ICompositeNode parentNode = containedNode.getParent();
			while (parentNode != null && assignTokenDirect(parentNode, eObject2Token))
				parentNode = parentNode.getParent();
			if (containedNode.getOffset() > rootNode.getEndOffset()) {
				break;
			}
		}
	}
}
 
Example 15
Source File: CheckEclipseGeneratorConfigProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CheckGeneratorConfig get(final URI uri) {
  CheckGeneratorConfig result = new CheckGeneratorConfig();
  IProject project = null;
  if (uri != null) {
    Pair<IStorage, IProject> pair = Iterables.getFirst(storage2UriMapper.getStorages(uri), null);
    if (pair != null) {
      project = pair.getSecond();
    }
  }
  xbaseBuilderPreferenceAccess.loadBuilderPreferences(result, project);
  return result;
}
 
Example 16
Source File: ConcreteSyntaxConstraintProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Set<EClass> getSemanticTypes() {
	Pair<Set<EClass>, Set<EClass>> types = getAllSemanticTypesPairs(null);
	return !types.getFirst().isEmpty() ? types.getFirst() : types.getSecond();
}
 
Example 17
Source File: JavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@SuppressWarnings("restriction")
protected boolean createConstructorProposals(final JvmDeclaredType contextType, final Issue issue, String typeName,
		IJavaSearchScope searchScope, final IssueResolutionAcceptor acceptor) throws JavaModelException {
	final boolean[] result = new boolean[] { false };
	if(contextType != null) {
		final IVisibilityHelper visibilityHelper = getVisibilityHelper(contextType);
		final Pair<String, String> packageAndType = typeNameGuesser.guessPackageAndTypeName(contextType, typeName);
		final String wantedPackageName = packageAndType.getFirst();
		final String wantedTypeName = packageAndType.getSecond();
		if (typeName.endsWith(wantedTypeName)) {
			return false;
		}
		org.eclipse.jdt.internal.core.search.BasicSearchEngine searchEngine = new org.eclipse.jdt.internal.core.search.BasicSearchEngine();
		final char[] wantedPackageChars = (isEmpty(wantedPackageName)) ? null : wantedPackageName.toCharArray();
		searchEngine.searchAllTypeNames(wantedPackageChars, SearchPattern.R_EXACT_MATCH, wantedTypeName.toCharArray(),
				SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, searchScope, new org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor() {
					
					@Override
					public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames,
							String path, org.eclipse.jdt.internal.compiler.env.AccessRestriction access) {
						final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames,
								simpleTypeName);
						if(access == null || (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter())){
							JvmType importType = services.getTypeReferences().findDeclaredType(qualifiedTypeName, contextType);
							if(importType instanceof JvmDeclaredType
									&& visibilityHelper.isVisible((JvmDeclaredType)importType)) {
								result[0] = true;
								StringBuilder label = new StringBuilder("Change to constructor call 'new ");
								label.append(simpleTypeName);
								label.append("()'");
								if(!equal(wantedPackageName, new String(packageName))) {
									label.append(" (");
									label.append(packageName);
									if(enclosingTypeNames.length > 0) {
										for(char[] enclosingTypeName: enclosingTypeNames) {
											label.append(".");
											label.append(enclosingTypeName);
										}
									}
									label.append(")");
								}
								acceptor.accept(issue, label.toString(), label.toString(), "impc_obj.gif", new ISemanticModification() {
									@Override
									public void apply(EObject element, IModificationContext context) throws Exception {
										IXtextDocument document = context.getXtextDocument();
										DocumentRewriter rewriter = rewriterFactory.create(document,
												(XtextResource) element.eResource());
										final int typeEndOffset = document.get().indexOf(wantedTypeName, 
												issue.getOffset() + wantedPackageName.length()) + wantedTypeName.length();
										final Section section = rewriter.newSection(issue.getOffset(), typeEndOffset - issue.getOffset());
										section.append(services.getTypeReferences().findDeclaredType(qualifiedTypeName, element));
										section.append("()");
										final TextEdit textEdit = replaceConverter.convertToTextEdit(rewriter.getChanges());
										textEdit.apply(document);
									}
								}, jdtTypeRelevance.getRelevance(qualifiedTypeName, wantedTypeName) + 100);
							}
						}
					}
				}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
	}
	return result[0];
}
 
Example 18
Source File: NpmCLI.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Installs npm package with given name at the given path. Updates dependencies in the package.json of that
 * location. If there is no package.json at that location npm errors will be logged to the error log. In that case
 * npm/yarn usual still installs requested dependency (if possible).
 *
 * @param packageNamesAndVersions
 *            to be installed
 * @param installPath
 *            path where package is supposed to be installed
 */
private IStatus install(List<Pair<N4JSProjectName, String>> packageNamesAndVersions, File installPath) {
	List<String> packageNamesAndVersionsMerged = new ArrayList<>(packageNamesAndVersions.size());
	for (Pair<N4JSProjectName, String> pair : packageNamesAndVersions) {
		N4JSProjectName packageName = pair.getFirst();
		String packageVersion = pair.getSecond();

		// FIXME better error reporting (show all invalid names/versions, not just the first)
		if (invalidPackageName(packageName)) {
			return statusHelper.createError("Malformed npm package name: '" + packageName + "'.");
		}
		if (invalidPackageVersion(packageVersion)) {
			return statusHelper.createError("Malformed npm package version: '" + packageVersion + "'.");
		}

		String nameAndVersion = packageVersion.isEmpty() ? packageName.getRawName()
				: packageName.getRawName() + packageVersion;
		packageNamesAndVersionsMerged.add(nameAndVersion);
	}

	IStatus status = executor.execute(
			() -> commandFactory.createInstallPackageCommand(installPath, packageNamesAndVersionsMerged, true),
			"Error while installing npm package.");

	// TODO IDE-3136 / GH-1011 workaround for a problem in node related to URL/GitHub version requirements
	// In case of a dependency like "JSONSelect@dbo/JSONSelect" (wherein "dbo/JSONSelect" is a GitHub version
	// requirement), the first installation works fine, but subsequent installations of additional npm packages may
	// uninstall(!) the earlier package that used a URL/GitHub version requirement. This is supposed to be fixed
	// in npm version 5.7.1. As a work-around we run a plain "npm install" after every installation of new packages,
	// which should re-install the package with a URL/GitHub version requirement.
	boolean isNpmUsed = !isYarnUsed(installPath);
	if (isNpmUsed) {
		VersionNumber currNpmVersion = getNpmVersion();
		VersionNumber fixedNpmVersion = SemverUtils.createVersionNumber(5, 7, 1);
		if (currNpmVersion != null && SemverMatcher.compareLoose(currNpmVersion, fixedNpmVersion) < 0) {
			IStatus workaroundStatus = executor.execute(
					() -> commandFactory.createInstallPackageCommand(installPath, Collections.emptyList(), false),
					"Error while running \"npm install\" after installing npm packages.");
			MultiStatus combinedStatus = statusHelper
					.createMultiStatus("Installing npm packages with additional \"npm install\" afterwards.");
			combinedStatus.merge(status);
			combinedStatus.merge(workaroundStatus);
			status = combinedStatus;
		}
	}

	return status;
}
 
Example 19
Source File: EclipseExternalLibraryWorkspace.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public ProjectDescription getProjectDescription(FileURI location) {
	Pair<N4JSExternalProject, ProjectDescription> pair = projectProvider.getProjectWithDescription(location);
	return null == pair ? null : pair.getSecond();
}
 
Example 20
Source File: XbaseSeverityConverter.java    From xtext-extras with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * 
 * @param pair
 *            holds first=delegationKey, second=defaultValue. delegationKey starts with {@link XbaseConfigurableIssueCodes#JDT_CORE_PLUGIN_ID}
 * @return resolved delegated value
 */
protected String delegatedValue(Pair<String, String> pair) {
	return pair.getSecond();
}