Search in sources :

Example 1 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class HandleFactory method getJarPkgFragmentRoot.

/**
	 * Returns the package fragment root that corresponds to the given jar path.
	 * See createOpenable(...) for the format of the jar path string.
	 * If not null, uses the given scope as a hint for getting Java project handles.
	 */
private PackageFragmentRoot getJarPkgFragmentRoot(String resourcePathString, int jarSeparatorIndex, String jarPathString, IJavaSearchScope scope) {
    IPath jarPath = new Path(jarPathString);
    Object target = JavaModel.getTarget(jarPath, false);
    if (target instanceof IFile) {
        // internal jar: is it on the classpath of its project?
        //  e.g. org.eclipse.swt.win32/ws/win32/swt.jar
        //        is NOT on the classpath of org.eclipse.swt.win32
        IFile jarFile = (IFile) target;
        JavaProject javaProject = (JavaProject) this.javaModel.getJavaProject(jarFile);
        try {
            IClasspathEntry entry = javaProject.getClasspathEntryFor(jarPath);
            if (entry != null) {
                return (PackageFragmentRoot) javaProject.getPackageFragmentRoot(jarFile);
            }
        } catch (JavaModelException e) {
        // ignore and try to find another project
        }
    }
    // walk projects in the scope and find the first one that has the given jar path in its classpath
    IJavaProject[] projects;
    if (scope != null) {
        if (scope instanceof AbstractJavaSearchScope) {
            PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) scope).packageFragmentRoot(resourcePathString, jarSeparatorIndex, jarPathString);
            if (root != null)
                return root;
        } else {
            IPath[] enclosingProjectsAndJars = scope.enclosingProjectsAndJars();
            int length = enclosingProjectsAndJars.length;
            projects = new IJavaProject[length];
            int index = 0;
            for (int i = 0; i < length; i++) {
                IPath path = enclosingProjectsAndJars[i];
                if (path.segmentCount() == 1) {
                    projects[index++] = this.javaModel.getJavaProject(path.segment(0));
                }
            }
            if (index < length) {
                System.arraycopy(projects, 0, projects = new IJavaProject[index], 0, index);
            }
            PackageFragmentRoot root = getJarPkgFragmentRoot(jarPath, target, projects);
            if (root != null) {
                return root;
            }
        }
    }
    // not found in the scope, walk all projects
    try {
        projects = this.javaModel.getJavaProjects();
    } catch (JavaModelException e) {
        // java model is not accessible
        return null;
    }
    return getJarPkgFragmentRoot(jarPath, target, projects);
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) JavaProject(org.eclipse.jdt.internal.core.JavaProject) IJavaProject(org.eclipse.jdt.core.IJavaProject) PackageFragmentRoot(org.eclipse.jdt.internal.core.PackageFragmentRoot) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) JavaModelException(org.eclipse.jdt.core.JavaModelException) IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) AbstractJavaSearchScope(org.eclipse.jdt.internal.core.search.AbstractJavaSearchScope) IJavaProject(org.eclipse.jdt.core.IJavaProject)

Example 2 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class OrganizeImportsOperation method collectReferences.

// find type references in a compilation unit
private boolean collectReferences(CompilationUnit astRoot, List<SimpleName> typeReferences, List<SimpleName> staticReferences, Set<String> oldSingleImports, Set<String> oldDemandImports) {
    if (!fAllowSyntaxErrors) {
        IProblem[] problems = astRoot.getProblems();
        for (int i = 0; i < problems.length; i++) {
            IProblem curr = problems[i];
            if (curr.isError() && (curr.getID() & IProblem.Syntax) != 0) {
                fParsingError = problems[i];
                return false;
            }
        }
    }
    List<ImportDeclaration> imports = astRoot.imports();
    for (int i = 0; i < imports.size(); i++) {
        ImportDeclaration curr = imports.get(i);
        String id = ASTResolving.getFullName(curr.getName());
        if (curr.isOnDemand()) {
            oldDemandImports.add(id);
        } else {
            oldSingleImports.add(id);
        }
    }
    IJavaProject project = fCompilationUnit.getJavaProject();
    ImportReferencesCollector.collect(astRoot, project, null, typeReferences, staticReferences);
    return true;
}
Also used : IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Example 3 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class StubUtility method getLineDelimiterUsed.

/**
	 * @param elem a Java element (doesn't have to exist)
	 * @return the existing or default line delimiter for the element
	 */
public static String getLineDelimiterUsed(IJavaElement elem) {
    IOpenable openable = elem.getOpenable();
    if (openable instanceof ITypeRoot) {
        try {
            return openable.findRecommendedLineSeparator();
        } catch (JavaModelException exception) {
        // Use project setting
        }
    }
    IJavaProject project = elem.getJavaProject();
    return getProjectLineDelimiter(project.exists() ? project : null);
}
Also used : IOpenable(org.eclipse.jdt.core.IOpenable) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) ITypeRoot(org.eclipse.jdt.core.ITypeRoot)

Example 4 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class AddImportsOperation method evaluateEdits.

private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
    SimpleName nameNode = null;
    if (root != null) {
        // got an AST
        ASTNode node = NodeFinder.perform(root, offset, length);
        if (node instanceof MarkerAnnotation) {
            node = ((Annotation) node).getTypeName();
        }
        if (node instanceof QualifiedName) {
            nameNode = ((QualifiedName) node).getName();
        } else if (node instanceof SimpleName) {
            nameNode = (SimpleName) node;
        }
    }
    String name, simpleName, containerName;
    int qualifierStart;
    int simpleNameStart;
    if (nameNode != null) {
        simpleName = nameNode.getIdentifier();
        simpleNameStart = nameNode.getStartPosition();
        if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
            Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
        } else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
            NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
            Name qualifier = nameQualifiedType.getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
            List<Annotation> annotations = nameQualifiedType.annotations();
            if (!annotations.isEmpty()) {
                // don't remove annotations
                simpleNameStart = annotations.get(0).getStartPosition();
            }
        } else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
            ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
            if (qualifier instanceof Name) {
                containerName = ASTNodes.asString(qualifier);
                name = JavaModelUtil.concatenateName(containerName, simpleName);
                qualifierStart = qualifier.getStartPosition();
            } else {
                return null;
            }
        } else {
            //$NON-NLS-1$
            containerName = "";
            name = simpleName;
            qualifierStart = simpleNameStart;
        }
        IBinding binding = nameNode.resolveBinding();
        if (binding != null && !binding.isRecovered()) {
            if (binding instanceof ITypeBinding) {
                ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
                String qualifiedBindingName = typeBinding.getQualifiedName();
                if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
                    return null;
                }
                ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
                String res = importRewrite.addImport(typeBinding, context);
                if (containerName.length() > 0 && !res.equals(simpleName)) {
                    // adding import failed
                    fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
                    return null;
                }
                if (containerName.length() == 0 && res.equals(simpleName)) {
                    // no change necessary
                    return null;
                }
                return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
            } else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
                boolean isField = binding instanceof IVariableBinding;
                ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
                if (declaringClass == null) {
                    // variableBinding.getDeclaringClass() is null for array.length
                    return null;
                }
                if (Modifier.isStatic(binding.getModifiers())) {
                    if (containerName.length() > 0) {
                        if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
                            ASTNode node = nameNode.getParent();
                            boolean isDirectlyAccessible = false;
                            while (node != null) {
                                if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
                                    isDirectlyAccessible = true;
                                    break;
                                }
                                node = node.getParent();
                            }
                            if (!isDirectlyAccessible) {
                                if (Modifier.isPrivate(declaringClass.getModifiers())) {
                                    fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
                                    return null;
                                }
                                String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
                                if (!res.equals(simpleName)) {
                                    // adding import failed
                                    return null;
                                }
                            }
                            //$NON-NLS-1$
                            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
                        }
                    }
                }
                // no static imports for packages
                return null;
            } else {
                return null;
            }
        }
        if (binding != null && binding.getKind() != IBinding.TYPE) {
            // recovered binding
            return null;
        }
    } else {
        IBuffer buffer = fCompilationUnit.getBuffer();
        qualifierStart = getNameStart(buffer, offset);
        int nameEnd = getNameEnd(buffer, offset + length);
        int len = nameEnd - qualifierStart;
        name = buffer.getText(qualifierStart, len).trim();
        if (name.length() == 0) {
            return null;
        }
        simpleName = Signature.getSimpleName(name);
        containerName = Signature.getQualifier(name);
        IJavaProject javaProject = fCompilationUnit.getJavaProject();
        if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
            return null;
        }
        simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
        int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
        if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
            return null;
        } else if (res == ImportRewriteContext.RES_NAME_FOUND) {
            //$NON-NLS-1$
            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
        }
    }
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
    TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
    if (types.length == 0) {
        fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
        return null;
    }
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    TypeNameMatch chosen;
    if (types.length > 1 && fQuery != null) {
        chosen = fQuery.chooseImport(types, containerName);
        if (chosen == null) {
            throw new OperationCanceledException();
        }
    } else {
        chosen = types[0];
    }
    ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
    importRewrite.addImport(chosen.getFullyQualifiedName(), context);
    //$NON-NLS-1$
    return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IBinding(org.eclipse.jdt.core.dom.IBinding) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) IBuffer(org.eclipse.jdt.core.IBuffer) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) List(java.util.List) ArrayList(java.util.ArrayList) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 5 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class ContextSensitiveImportRewriteContext method getImportedNames.

private Name[] getImportedNames() {
    if (fImportedNames == null) {
        IJavaProject project = null;
        IJavaElement javaElement = fCompilationUnit.getJavaElement();
        if (javaElement != null)
            project = javaElement.getJavaProject();
        List<SimpleName> imports = new ArrayList<SimpleName>();
        ImportReferencesCollector.collect(fCompilationUnit, project, null, imports, null);
        fImportedNames = imports.toArray(new Name[imports.size()]);
    }
    return fImportedNames;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) IJavaProject(org.eclipse.jdt.core.IJavaProject) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

IJavaProject (org.eclipse.jdt.core.IJavaProject)743 IProject (org.eclipse.core.resources.IProject)178 IFile (org.eclipse.core.resources.IFile)149 Test (org.junit.Test)146 CoreException (org.eclipse.core.runtime.CoreException)127 JavaModelException (org.eclipse.jdt.core.JavaModelException)124 IClasspathEntry (org.eclipse.jdt.core.IClasspathEntry)123 IPath (org.eclipse.core.runtime.IPath)110 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)103 ArrayList (java.util.ArrayList)87 IFolder (org.eclipse.core.resources.IFolder)78 IResource (org.eclipse.core.resources.IResource)75 IJavaElement (org.eclipse.jdt.core.IJavaElement)63 IType (org.eclipse.jdt.core.IType)63 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)62 Path (org.eclipse.core.runtime.Path)57 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)56 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)47 StringInputStream (org.eclipse.xtext.util.StringInputStream)39 HashMap (java.util.HashMap)38