Example usage for org.eclipse.jdt.core IType getType

List of usage examples for org.eclipse.jdt.core IType getType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType getType.

Prototype

IType getType(String name);

Source Link

Document

Returns the member type declared in this type with the given simple name.

Usage

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

License:Open Source License

private IType getMemberType(IType type, String name, int dot) {
    while (dot != -1) {
        int start = dot + 1;
        dot = name.indexOf('.', start);
        String typeName = name.substring(start, dot == -1 ? name.length() : dot);
        type = type.getType(typeName);
    }//from w  w  w .  j  a  va  2  s.c om
    return type;
}

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

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope.
 * The search can be selecting specific types (given a package or a type name
 * prefix and match modes)./*from   w  w  w. j  a v  a2s  .  c o  m*/
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int,
 * org.eclipse.jdt.core.search.IJavaSearchScope, org.eclipse.jdt.core.search.TypeNameRequestor, int,
 * org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment
 */
public void searchAllTypeNames(final char[] packageName, final int packageMatchRule, final char[] typeName,
        final int typeMatchRule, int searchFor, IJavaSearchScope scope,
        final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor)
        throws JavaModelException {

    // Validate match rule first
    final int validatedTypeMatchRule = SearchPattern
            .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule);

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, "
                        + "int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - package match rule: " + getMatchRuleString(packageMatchRule)); //$NON-NLS-1$
        Util.verbose("   - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
        if (validatedTypeMatchRule != typeMatchRule) {
            Util.verbose("   - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
        }
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    final char typeSuffix;
    switch (searchFor) {
    case IJavaSearchConstants.CLASS:
        typeSuffix = IIndexConstants.CLASS_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_INTERFACE:
        typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_ENUM:
        typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE:
        typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
        typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
        break;
    case IJavaSearchConstants.ENUM:
        typeSuffix = IIndexConstants.ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.ANNOTATION_TYPE:
        typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
        break;
    default:
        typeSuffix = IIndexConstants.TYPE_SUFFIX;
        break;
    }
    final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH
            ? new TypeDeclarationPattern(packageName, null, typeName, typeSuffix, validatedTypeMatchRule)
            : new QualifiedTypeDeclarationPattern(packageName, packageMatchRule, typeName, typeSuffix,
                    validatedTypeMatchRule);

    // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
    final HashSet workingCopyPaths = new HashSet();
    String workingCopyPath = null;
    ICompilationUnit[] copies = getWorkingCopies();
    final int copiesLength = copies == null ? 0 : copies.length;
    if (copies != null) {
        if (copiesLength == 1) {
            workingCopyPath = copies[0].getPath().toString();
        } else {
            for (int i = 0; i < copiesLength; i++) {
                ICompilationUnit workingCopy = copies[i];
                workingCopyPaths.add(workingCopy.getPath().toString());
            }
        }
    }
    final String singleWkcpPath = workingCopyPath;

    // Index requestor
    IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {
        public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord,
                SearchParticipant participant, AccessRuleSet access) {
            // Filter unexpected types
            TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord;
            if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
                return true; // filter out local and anonymous classes
            }
            switch (copiesLength) {
            case 0:
                break;
            case 1:
                if (singleWkcpPath.equals(documentPath)) {
                    return true; // filter out *the* working copy
                }
                break;
            default:
                if (workingCopyPaths.contains(documentPath)) {
                    return true; // filter out working copies
                }
                break;
            }

            // Accept document path
            AccessRestriction accessRestriction = null;
            if (access != null) {
                // Compute document relative path
                int pkgLength = (record.pkg == null || record.pkg.length == 0) ? 0 : record.pkg.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.pkg, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.simpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            if (match(record.typeSuffix, record.modifiers)) {
                nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName,
                        record.enclosingTypeNames, documentPath, accessRestriction);
            }
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 1000);
        }
        // add type names from indexes
        indexManager.performConcurrentJob(
                new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only
                        scope, searchRequestor, indexManager),
                waitingPolicy,
                progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0; i < copiesLength; i++) {
                final ICompilationUnit workingCopy = copies[i];
                if (scope instanceof HierarchyScope) {
                    if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor))
                        continue;
                } else {
                    if (!scope.encloses(workingCopy))
                        continue;
                }
                final String path = workingCopy.getPath().toString();
                if (workingCopy.isConsistent()) {
                    IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
                    char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR
                            : packageDeclarations[0].getElementName().toCharArray();
                    IType[] allTypes = workingCopy.getAllTypes();
                    for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
                        IType type = allTypes[j];
                        IJavaElement parent = type.getParent();
                        char[][] enclosingTypeNames;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        int kind;
                        if (type.isEnum()) {
                            kind = TypeDeclaration.ENUM_DECL;
                        } else if (type.isAnnotation()) {
                            kind = TypeDeclaration.ANNOTATION_TYPE_DECL;
                        } else if (type.isClass()) {
                            kind = TypeDeclaration.CLASS_DECL;
                        } else /*if (type.isInterface())*/ {
                            kind = TypeDeclaration.INTERFACE_DECL;
                        }
                        if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule,
                                kind, packageDeclaration, simpleName)) {
                            if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                ((TypeNameMatchRequestorWrapper) nameRequestor).requestor.acceptTypeNameMatch(
                                        new JavaSearchTypeNameMatch(type, type.getFlags()));
                            } else {
                                nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName,
                                        enclosingTypeNames, path, null);
                            }
                        }
                    }
                } else {
                    Parser basicParser = getParser();
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
                    CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0,
                            this.compilerOptions.maxProblemsPerUnit);
                    CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
                    if (parsedUnit != null) {
                        final char[] packageDeclaration = parsedUnit.currentPackage == null
                                ? CharOperation.NO_CHAR
                                : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
                        class AllTypeDeclarationsVisitor extends ASTVisitor {
                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false; // no local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration,
                                    CompilationUnitScope compilationUnitScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers),
                                        packageDeclaration, typeDeclaration.name)) {
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(typeName));
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type,
                                                        typeDeclaration.modifiers));
                                    } else {
                                        nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                                typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                    }
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule,
                                        TypeDeclaration.kind(memberTypeDeclaration.modifiers),
                                        packageDeclaration, memberTypeDeclaration.name)) {
                                    // compute enclosing type names
                                    TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                    char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                    while (enclosing != null) {
                                        enclosingTypeNames = CharOperation.arrayConcat(
                                                new char[][] { enclosing.name }, enclosingTypeNames);
                                        if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                            enclosing = enclosing.enclosingType;
                                        } else {
                                            enclosing = null;
                                        }
                                    }
                                    // report
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(enclosingTypeNames[0]));
                                        for (int j = 1, l = enclosingTypeNames.length; j < l; j++) {
                                            type = type.getType(new String(enclosingTypeNames[j]));
                                        }
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
                                    } else {
                                        nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                                packageDeclaration, memberTypeDeclaration.name,
                                                enclosingTypeNames, path, null);
                                    }
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled())
                        throw new OperationCanceledException();
                    progressMonitor.worked(1);
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

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

License:Open Source License

protected IType lookupType(ReferenceBinding typeBinding) {
    if (typeBinding == null || !typeBinding.isValidBinding())
        return null;

    char[] packageName = typeBinding.qualifiedPackageName();
    IPackageFragment[] pkgs = this.nameLookup.findPackageFragments(
            (packageName == null || packageName.length == 0) ? IPackageFragment.DEFAULT_PACKAGE_NAME
                    : new String(packageName),
            false);/*from   w  ww .ja  va 2 s. c  o  m*/

    // iterate type lookup in each package fragment
    char[] sourceName = typeBinding.qualifiedSourceName();
    String typeName = new String(sourceName);
    int acceptFlag = 0;
    if (typeBinding.isAnnotationType()) {
        acceptFlag = NameLookup.ACCEPT_ANNOTATIONS;
    } else if (typeBinding.isEnum()) {
        acceptFlag = NameLookup.ACCEPT_ENUMS;
    } else if (typeBinding.isInterface()) {
        acceptFlag = NameLookup.ACCEPT_INTERFACES;
    } else if (typeBinding.isClass()) {
        acceptFlag = NameLookup.ACCEPT_CLASSES;
    }
    if (pkgs != null) {
        for (int i = 0, length = pkgs.length; i < length; i++) {
            IType type = this.nameLookup.findType(typeName, pkgs[i], false, acceptFlag,
                    true/*consider secondary types*/);
            if (type != null)
                return type;
        }
    }

    // search inside enclosing element
    char[][] qualifiedName = CharOperation.splitOn('.', sourceName);
    int length = qualifiedName.length;
    if (length == 0)
        return null;

    IType type = createTypeHandle(new String(qualifiedName[0])); // find the top-level type
    if (type == null)
        return null;

    for (int i = 1; i < length; i++) {
        type = type.getType(new String(qualifiedName[i]));
        if (type == null)
            return null;
    }
    if (type.exists())
        return type;
    return null;
}

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

License:Open Source License

public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames,
        String path, AccessRestriction access) {

    // Get type/*from  w  w  w.  ja v  a 2 s  . c o m*/
    try {
        IType type = null;
        if (this.handleFactory != null) {
            //todo openable
            Openable openable = null;//this.handleFactory.createOpenable(path, this.scope);
            if (openable == null)
                return;
            switch (openable.getElementType()) {
            case IJavaElement.COMPILATION_UNIT:
                ICompilationUnit cu = (ICompilationUnit) openable;
                if (enclosingTypeNames != null && enclosingTypeNames.length > 0) {
                    type = cu.getType(new String(enclosingTypeNames[0]));
                    for (int j = 1, l = enclosingTypeNames.length; j < l; j++) {
                        type = type.getType(new String(enclosingTypeNames[j]));
                    }
                    type = type.getType(new String(simpleTypeName));
                } else {
                    type = cu.getType(new String(simpleTypeName));
                }
                break;
            case IJavaElement.CLASS_FILE:
                type = ((IClassFile) openable).getType();
                break;
            }
        } else {
            int separatorIndex = path.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR);
            type = separatorIndex == -1
                    ? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames)
                    : createTypeFromJar(path, separatorIndex);
        }

        // Accept match if the type has been found
        if (type != null) {
            // hierarchy scopes require one more check:
            if (!(this.scope instanceof org.eclipse.jdt.internal.core.search.HierarchyScope)
                    || ((HierarchyScope) this.scope).enclosesFineGrained(type)) {

                // Create the match
                final JavaSearchTypeNameMatch match = new JavaSearchTypeNameMatch(type, modifiers);

                // Update match accessibility
                if (access != null) {
                    switch (access.getProblemId()) {
                    case IProblem.ForbiddenReference:
                        match.setAccessibility(IAccessRule.K_NON_ACCESSIBLE);
                        break;
                    case IProblem.DiscouragedReference:
                        match.setAccessibility(IAccessRule.K_DISCOURAGED);
                        break;
                    }
                }

                // Accept match
                this.requestor.acceptTypeNameMatch(match);
            }
        }
    } catch (JavaModelException e) {
        // skip
    }
}

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

License:Open Source License

private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames)
        throws JavaModelException {
    // path to a file in a directory
    // Optimization: cache package fragment root handle and package handles
    int rootPathLength = -1;
    if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
            && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0
            && resourcePath.charAt(rootPathLength) == '/')) {
        PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) this.scope)
                .packageFragmentRoot(resourcePath, -1/*not a jar*/, null/*no jar path*/);
        if (root == null)
            return null;
        this.lastPkgFragmentRoot = root;
        this.lastPkgFragmentRootPath = root.internalPath().toString();
        this.packageHandles = new HashtableOfArrayToObject(5);
    }//from   w  w  w  .j a v  a  2 s.c o  m
    // create handle
    resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
    String[] simpleNames = new Path(resourcePath).segments();
    String[] pkgName;
    int length = simpleNames.length - 1;
    if (length > 0) {
        pkgName = new String[length];
        System.arraycopy(simpleNames, 0, pkgName, 0, length);
    } else {
        pkgName = CharOperation.NO_STRINGS;
    }
    IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
    if (pkgFragment == null) {
        pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
        this.packageHandles.put(pkgName, pkgFragment);
    }
    String simpleName = simpleNames[length];
    if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) {
        ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName);
        int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length;
        IType type = (etnLength == 0) ? unit.getType(simpleTypeName)
                : unit.getType(new String(enclosingTypeNames[0]));
        if (etnLength > 0) {
            for (int i = 1; i < etnLength; i++) {
                type = type.getType(new String(enclosingTypeNames[i]));
            }
            type = type.getType(simpleTypeName);
        }
        return type;
    } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) {
        IClassFile classFile = pkgFragment.getClassFile(simpleName);
        return classFile.getType();
    }
    return null;
}

From source file:com.google.gwt.eclipse.core.refactoring.GWTTypeRefactoringSupportTest.java

License:Open Source License

public void testCreateEditForInnerClass() {
    GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

    // Change the name of the inner class B to BBB
    IType r = rClass.getCompilationUnit().getType("R");
    IType oldType = r.getType("B");
    support.setOldElement(oldType);//from   w w  w  .  j a va 2s  . c om
    IType newType = r.getType("BBB");
    support.setNewElement(newType);

    String rawRef = "@com.hello.client.R.B::getNumber()";
    IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

    ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
    assertEquals(1, edit.getOffset());
    assertEquals(20, edit.getLength());
    assertEquals("com.hello.client.R.BBB", edit.getText());
}

From source file:com.google.gwt.eclipse.core.refactoring.GWTTypeRefactoringSupportTest.java

License:Open Source License

public void testCreateEditPreserveDollarClassSeparator() {
    GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

    // Change the name of the inner class B to BBB
    IType r = rClass.getCompilationUnit().getType("R");
    IType oldType = r.getType("B");
    support.setOldElement(oldType);/*  w ww .java  2s  . c o  m*/
    IType newType = r.getType("BBB");
    support.setNewElement(newType);

    String rawRef = "@com.hello.client.R$B::getNumber()";
    IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

    ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
    assertEquals(1, edit.getOffset());
    assertEquals(20, edit.getLength());
    assertEquals("com.hello.client.R$BBB", edit.getText());
}

From source file:com.google.gwt.eclipse.core.search.JavaQueryParticipantTest.java

License:Open Source License

public void testElementSearch() throws CoreException {
    IType cu1Type = getTestType1();
    IJavaElement element;/*from  w  ww  .  ja  v  a 2  s.c  o  m*/

    // Search for type references
    element = cu1Type;
    Match[] expected = new Match[] { createWindowsTestMatch(665, 41), createWindowsTestMatch(735, 41),
            createWindowsTestMatch(840, 41), createWindowsTestMatch(947, 41), createWindowsTestMatch(1125, 41),
            createWindowsTestMatch(1207, 41), createWindowsTestMatch(1297, 41),
            createWindowsTestMatch(1419, 41), createWindowsTestMatch(1545, 41),
            createWindowsTestMatch(1619, 41) };
    assertSearchMatches(expected, createQuery(element));

    // Search for field references
    element = cu1Type.getField("keith");
    assertSearchMatch(createWindowsTestMatch(990, 5), createQuery(element));

    // Search for method references
    element = cu1Type.getMethod("getNumber", NO_PARAMS);
    assertSearchMatch(createWindowsTestMatch(1588, 9), createQuery(element));

    // Search for constructor references
    element = cu1Type.getType("InnerSub").getMethod("InnerSub", new String[] { "QString;" });
    assertSearchMatch(createWindowsTestMatch(892, 3), createQuery(element));

    // Search for package references (unsupported)
    element = cu1Type.getPackageFragment();
    assertSearchMatches(NO_MATCHES, createQuery(element));
}

From source file:com.intel.ide.eclipse.mpt.ast.UnresolvedElementsSubProcessor.java

License:Open Source License

public static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance,
        Map<String, LinkedCorrectionProposal> proposals) throws CoreException {
    Name node = refNode;/*from   w ww . j  av a 2  s.c  om*/
    //      do {
    String typeName = ASTNodes.getSimpleNameIdentifier(node);
    Name qualifier = null;
    // only propose to create types for qualifiers when the name starts with upper case
    boolean isPossibleName = isLikelyTypeName(typeName) || node == refNode;
    if (isPossibleName) {
        IPackageFragment enclosingPackage = null;
        IType enclosingType = null;
        if (node.isSimpleName()) {
            enclosingPackage = (IPackageFragment) cu.getParent();
            return;
            // don't suggest member type, user can select it in wizard
        } else {
            Name qualifierName = ((QualifiedName) node).getQualifier();
            IBinding binding = qualifierName.resolveBinding();
            if (binding != null && binding.isRecovered()) {
                binding = null;
            }
            if (binding instanceof ITypeBinding) {
                enclosingType = (IType) binding.getJavaElement();
            } else if (binding instanceof IPackageBinding) {
                qualifier = qualifierName;
                enclosingPackage = (IPackageFragment) binding.getJavaElement();
            } else {
                IJavaElement[] res = cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
                if (res != null && res.length > 0 && res[0] instanceof IType) {
                    enclosingType = (IType) res[0];
                } else {
                    qualifier = qualifierName;
                    enclosingPackage = JavaModelUtil.getPackageFragmentRoot(cu)
                            .getPackageFragment(ASTResolving.getFullName(qualifierName));
                }
            }
        }
        int rel = relevance;
        if (enclosingPackage != null && isLikelyPackageName(enclosingPackage.getElementName())) {
            rel += 3;
        }

        if (enclosingPackage != null
                && !enclosingPackage.getCompilationUnit(typeName + JavaModelUtil.DEFAULT_CU_SUFFIX).exists()
                || enclosingType != null && !enclosingType.isReadOnly()
                        && !enclosingType.getType(typeName).exists()) { // new member type
            IJavaElement enclosing = enclosingPackage != null ? (IJavaElement) enclosingPackage : enclosingType;

            String name = node.getFullyQualifiedName();

            if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_CLASS, enclosing, rel + 3));
            } else if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_INTERFACE, enclosing, rel + 2));
            } else if ((kind & SimilarElementsRequestor.ENUMS) != 0) {
                proposals.put(name, new NewCUProposal(cu, node, NewCUProposal.K_ENUM, enclosing, rel));
            }
        }
    }
    node = qualifier;
    //      } while (node != null);
}

From source file:com.sun.codemodel.ClassGenerator.java

License:Apache License

public void generateDummy(ServiceCoreElement element, String orchClassName, IProgressMonitor pm)
        throws JavaModelException {
    // IPackageFragmentRoot root =
    // project.getPackageFragmentRoot(generated);
    String packName = getPackageName(element);
    IPackageFragment pack = pfr.getPackageFragment(packName);
    if (pack == null || !pack.exists()) {
        pack = pfr.createPackageFragment(packName, true, pm);
    }//from ww w  .  ja  v  a 2s  .co  m
    String classname = getDummyClassName(element, orchClassName);
    ICompilationUnit cu = pack.getCompilationUnit(classname + ".java");
    if (cu == null || !cu.exists()) {
        cu = pack.createCompilationUnit(classname + ".java", "", true, pm);
    }
    cu.createPackageDeclaration(packName, pm);
    IType staticType = null;
    IType type = cu.getType(classname);
    if (type == null || !type.exists()) {
        type = cu.createType(generateDummyClassContent(classname), null, true, pm);
        staticType = type.createType(generateDummyStaticContent(), null, true, pm);
    } else {
        staticType = type.getType("Static");
        if (staticType == null || !staticType.exists()) {
            staticType = type.createType(generateDummyStaticContent(), null, true, pm);
        }
    }
    String methodContent = generateMethodContent(element);
    type.createMethod("public " + methodContent, null, true, pm);
    staticType.createMethod("public static " + methodContent, null, true, pm);

}