Example usage for org.eclipse.jdt.internal.core JavaModelManager getJavaModelManager

List of usage examples for org.eclipse.jdt.internal.core JavaModelManager getJavaModelManager

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaModelManager getJavaModelManager.

Prototype

public final static JavaModelManager getJavaModelManager() 

Source Link

Document

Returns the singleton JavaModelManager

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

private void findAllTypes(char[] prefix) {
    try {/*w w w.  j  a v  a 2  s . co m*/
        IProgressMonitor progressMonitor = new IProgressMonitor() {
            boolean isCanceled = false;

            public void beginTask(String name, int totalWork) {
                // implements interface method
            }

            public void done() {
                // implements interface method
            }

            public void internalWorked(double work) {
                // implements interface method
            }

            public boolean isCanceled() {
                return this.isCanceled;
            }

            public void setCanceled(boolean value) {
                this.isCanceled = value;
            }

            public void setTaskName(String name) {
                // implements interface method
            }

            public void subTask(String name) {
                // implements interface method
            }

            public void worked(int work) {
                // implements interface method
            }
        };

        TypeNameMatchRequestor typeNameMatchRequestor = new TypeNameMatchRequestor() {
            public void acceptTypeNameMatch(TypeNameMatch match) {
                if (SelectionEngine.this.requestor instanceof SelectionRequestor) {
                    SelectionEngine.this.noProposal = false;
                    ((SelectionRequestor) SelectionEngine.this.requestor).acceptType(match.getType());
                }
            }
        };

        IJavaSearchScope scope = BasicSearchEngine.createWorkspaceScope();

        SelectionTypeNameMatchRequestorWrapper requestorWrapper = new SelectionTypeNameMatchRequestorWrapper(
                typeNameMatchRequestor, scope,
                this.unitScope == null ? null : this.unitScope.referenceContext.imports);

        org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.owner == null ? null
                : JavaModelManager.getJavaModelManager().getWorkingCopies(this.owner, true/*add primary WCs*/);

        try {
            new BasicSearchEngine(indexManager, javaProject).searchAllTypeNames(null,
                    SearchPattern.R_EXACT_MATCH, prefix,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE,
                    scope, requestorWrapper, IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH,
                    progressMonitor);
        } catch (OperationCanceledException e) {
            // do nothing
        }
        requestorWrapper.acceptNotImported();
    } catch (JavaModelException e) {
        // do nothing
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java

License:Open Source License

/**
 * Creates a class path entry of the specified kind with the given path.
 *///from w w w . j  ava 2s  .com
public ClasspathEntry(int contentKind, int entryKind, IPath path, IPath[] inclusionPatterns,
        IPath[] exclusionPatterns, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath,
        IPath specificOutputLocation, IClasspathEntry referencingEntry, boolean isExported,
        IAccessRule[] accessRules, boolean combineAccessRules, IClasspathAttribute[] extraAttributes) {

    this.contentKind = contentKind;
    this.entryKind = entryKind;
    this.path = path;
    this.inclusionPatterns = inclusionPatterns;
    this.exclusionPatterns = exclusionPatterns;
    this.referencingEntry = referencingEntry;

    int length;
    if (accessRules != null && (length = accessRules.length) > 0) {
        AccessRule[] rules = new AccessRule[length];
        System.arraycopy(accessRules, 0, rules, 0, length);
        byte classpathEntryType;
        String classpathEntryName;
        JavaModelManager manager = JavaModelManager.getJavaModelManager();
        if (this.entryKind == CPE_PROJECT || this.entryKind == CPE_SOURCE) { // can be remote source entry when reconciling
            classpathEntryType = AccessRestriction.PROJECT;
            classpathEntryName = manager.intern(getPath().segment(0));
        } else {
            classpathEntryType = AccessRestriction.LIBRARY;
            Object target = JavaModel.getWorkspaceTarget(path);
            if (target == null) {
                classpathEntryName = manager.intern(path.toOSString());
            } else {
                classpathEntryName = manager.intern(path.makeRelative().toString());
            }
        }
        this.accessRuleSet = new AccessRuleSet(rules, classpathEntryType, classpathEntryName);
    }
    //      else { -- implicit!
    //         this.accessRuleSet = null;
    //      }

    this.combineAccessRules = combineAccessRules;
    this.extraAttributes = extraAttributes;

    if (inclusionPatterns != INCLUDE_ALL && inclusionPatterns.length > 0) {
        this.fullInclusionPatternChars = UNINIT_PATTERNS;
    }
    if (exclusionPatterns.length > 0) {
        this.fullExclusionPatternChars = UNINIT_PATTERNS;
    }
    this.sourceAttachmentPath = sourceAttachmentPath;
    this.sourceAttachmentRootPath = sourceAttachmentRootPath;
    this.specificOutputLocation = specificOutputLocation;
    this.isExported = isExported;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java

License:Open Source License

private static void resolvedChainedLibraries(IPath jarPath, HashSet visited, ArrayList result) {
    if (visited.contains(jarPath))
        return;//from  w  w w .ja va2s  .  co  m
    visited.add(jarPath);
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    if (manager.isNonChainingJar(jarPath))
        return;
    List calledFileNames = getCalledFileNames(jarPath);
    if (calledFileNames == null) {
        manager.addNonChainingJar(jarPath);
    } else {
        Iterator calledFilesIterator = calledFileNames.iterator();
        IPath directoryPath = jarPath.removeLastSegments(1);
        while (calledFilesIterator.hasNext()) {
            String calledFileName = (String) calledFilesIterator.next();
            if (!directoryPath.isValidPath(calledFileName)) {
                if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                    Util.verbose("Invalid Class-Path entry " + calledFileName + " in manifest of jar file: " //$NON-NLS-1$//$NON-NLS-2$
                            + jarPath.toOSString());
                }
            } else {
                IPath calledJar = directoryPath.append(new Path(calledFileName));
                // Ignore if segment count is Zero (https://bugs.eclipse.org/bugs/show_bug.cgi?id=308150)
                if (calledJar.segmentCount() == 0) {
                    if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                        Util.verbose("Invalid Class-Path entry " + calledFileName + " in manifest of jar file: " //$NON-NLS-1$//$NON-NLS-2$
                                + jarPath.toOSString());
                    }
                    continue;
                }
                resolvedChainedLibraries(calledJar, visited, result);
                result.add(calledJar);
            }
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java

License:Open Source License

private static List getCalledFileNames(IPath jarPath) {
    Object target = JavaModel.getTarget(jarPath,
            true/*check existence, otherwise the manifest cannot be read*/);
    if (!(target instanceof IFile || target instanceof File))
        return null;
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    ZipFile zip = null;//from   ww  w.ja v  a  2s  .co m
    InputStream inputStream = null;
    List calledFileNames = null;
    try {
        zip = manager.getZipFile(jarPath);
        ZipEntry manifest = zip.getEntry("META-INF/MANIFEST.MF"); //$NON-NLS-1$
        if (manifest == null)
            return null;
        // non-null implies regular file
        ManifestAnalyzer analyzer = new ManifestAnalyzer();
        inputStream = zip.getInputStream(manifest);
        boolean success = analyzer.analyzeManifestContents(inputStream);
        calledFileNames = analyzer.getCalledFileNames();
        if (!success || analyzer.getClasspathSectionsCount() == 1 && calledFileNames == null) {
            if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                Util.verbose("Invalid Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            }
            return null;
        } else if (analyzer.getClasspathSectionsCount() > 1) {
            if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                Util.verbose("Multiple Class-Path headers in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            }
            return null;
        }
    } catch (CoreException e) {
        // not a zip file
        if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
            Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    } catch (IOException e) {
        // not a zip file
        if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
            Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // best effort
            }
        }
        manager.closeZipFile(zip);
    }
    return calledFileNames;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClasspathEntry.java

License:Open Source License

private static IJavaModelStatus validateLibraryContents(IPath path, IJavaProject project, String entryPathMsg) {
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    try {/*  w ww  .  jav a  2  s.c  o  m*/
        manager.verifyArchiveContent(path);
    } catch (CoreException e) {
        if (e.getStatus().getMessage() == Messages.status_IOException) {
            return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH,
                    Messages.bind(Messages.classpath_archiveReadError,
                            new String[] { entryPathMsg, project.getElementName() }));
        }
    }
    return JavaModelStatus.VERIFIED_OK;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.HierarchyScope.java

License:Open Source License

private IPath[] computeProjectsAndJars(IType type) throws JavaModelException {
    HashSet set = new HashSet();
    IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
    if (root.isArchive()) {
        // add the root
        set.add(root.getPath());/*  www. jav a2  s  .  c  o m*/
        // add all projects that reference this archive and their dependents
        IPath rootPath = root.getPath();
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject[] projects = model.getJavaProjects();
        HashSet visited = new HashSet();
        for (int i = 0; i < projects.length; i++) {
            JavaProject project = (JavaProject) projects[i];
            IClasspathEntry entry = project.getClasspathEntryFor(rootPath);
            if (entry != null) {
                // add the project and its binary pkg fragment roots
                IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
                set.add(project.getPath());
                for (int k = 0; k < roots.length; k++) {
                    IPackageFragmentRoot pkgFragmentRoot = roots[k];
                    if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
                        set.add(pkgFragmentRoot.getPath());
                    }
                }
                // add the dependent projects
                computeDependents(project, set, visited);
            }
        }
    } else {
        // add all the project's pkg fragment roots
        IJavaProject project = (IJavaProject) root.getParent();
        IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            IPackageFragmentRoot pkgFragmentRoot = roots[i];
            if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
                set.add(pkgFragmentRoot.getPath());
            } else {
                set.add(pkgFragmentRoot.getParent().getPath());
            }
        }
        // add the dependent projects
        computeDependents(project, set, new HashSet());
    }
    IPath[] result = new IPath[set.size()];
    set.toArray(result);
    return result;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.AbstractIndexer.java

License:Open Source License

protected void addTypeDeclaration(int modifiers, char[] packageName, char[] name, char[][] enclosingTypeNames,
        boolean secondary) {
    char[] indexKey = TypeDeclarationPattern.createIndexKey(modifiers, name, packageName, enclosingTypeNames,
            secondary);//from  w  ww.  java  2s. c  o  m
    if (secondary)
        JavaModelManager.getJavaModelManager().secondaryTypeAdding(this.document.getPath(),
                name == null ? CharOperation.NO_CHAR : name,
                packageName == null ? CharOperation.NO_CHAR : packageName);

    addIndexEntry(TYPE_DECL, indexKey);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.SourceIndexer.java

License:Open Source License

public void indexDocument() {
    // Create a new Parser
    SourceIndexerRequestor requestor = new SourceIndexerRequestor(this);
    String documentPath = this.document.getPath();
    SourceElementParser parser = this.document.getParser();
    if (parser == null) {
        //todo change this code
        IPath path = new Path(documentPath);
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
        parser = JavaModelManager.getJavaModelManager().indexManager
                .getSourceElementParser(JavaCore.create(project), requestor);
    } else {//w w  w.  j  a v a2s.c o m
        parser.setRequestor(requestor);
    }

    // Launch the parser
    char[] source = null;
    char[] name = null;
    try {
        source = this.document.getCharContents();
        name = documentPath.toCharArray();
    } catch (Exception e) {
        // ignore
    }
    if (source == null || name == null)
        return; // could not retrieve document info (e.g. resource was discarded)
    CompilationUnit compilationUnit = new CompilationUnit(source, name);
    try {
        parser.parseCompilationUnit(compilationUnit, true/*full parse*/, null/*no progress*/);
    } catch (Exception e) {
        if (JobManager.VERBOSE) {
            e.printStackTrace();
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

/**
 * Returns whether elements of the given project or jar can see the given focus (an IJavaProject or
 * a JarPackageFragmentRot) either because the focus is part of the project or the jar, or because it is
 * accessible throught the project's classpath
 *//*from   w w  w . j av  a  2  s . c  om*/
public static boolean canSeeFocus(SearchPattern pattern, IPath projectOrJarPath) {
    try {
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject project = getJavaProject(projectOrJarPath, model);
        IJavaElement[] focuses = getFocusedElementsAndTypes(pattern, project, null);
        if (focuses.length == 0)
            return false;
        if (project != null) {
            return canSeeFocus(focuses, (JavaProject) project, null);
        }

        // projectOrJarPath is a jar
        // it can see the focus only if it is on the classpath of a project that can see the focus
        IJavaProject[] allProjects = model.getJavaProjects();
        for (int i = 0, length = allProjects.length; i < length; i++) {
            JavaProject otherProject = (JavaProject) allProjects[i];
            IClasspathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
            if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                if (canSeeFocus(focuses, otherProject, null)) {
                    return true;
                }
            }
        }
        return false;
    } catch (JavaModelException e) {
        return false;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

private static boolean canSeeFocus(IJavaElement focus, JavaProject javaProject,
        char[][][] focusQualifiedNames) {
    try {/*  w w  w  .j a v  a 2s. c  om*/
        if (focus == null)
            return false;
        if (focus.equals(javaProject))
            return true;

        if (focus instanceof JarPackageFragmentRoot) {
            // focus is part of a jar
            IPath focusPath = focus.getPath();
            IClasspathEntry[] entries = javaProject.getExpandedClasspath();
            for (int i = 0, length = entries.length; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(focusPath))
                    return true;
            }
            return false;
        }
        // look for dependent projects
        IPath focusPath = ((JavaProject) focus).getProject().getFullPath();
        IClasspathEntry[] entries = javaProject.getExpandedClasspath();
        for (int i = 0, length = entries.length; i < length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && entry.getPath().equals(focusPath)) {
                if (focusQualifiedNames != null) { // builder state is usable, hence use it to try to reduce project which can see the focus...
                    State projectState = (State) JavaModelManager.getJavaModelManager()
                            .getLastBuiltState(javaProject.getProject(), null);
                    if (projectState != null) {
                        Object[] values = projectState.getReferences().valueTable;
                        int vLength = values.length;
                        for (int j = 0; j < vLength; j++) {
                            if (values[j] == null)
                                continue;
                            ReferenceCollection references = (ReferenceCollection) values[j];
                            if (references.includes(focusQualifiedNames, null, null)) {
                                return true;
                            }
                        }
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    } catch (JavaModelException e) {
        return false;
    }
}