Example usage for org.eclipse.jdt.core.compiler CharOperation splitOn

List of usage examples for org.eclipse.jdt.core.compiler CharOperation splitOn

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler CharOperation splitOn.

Prototype

public static final char[][] splitOn(char divider, char[] array) 

Source Link

Document

Return a new array which is the split of the given array using the given divider.

Usage

From source file:com.codenvy.ide.ext.java.DeltaProcessingTest.java

License:Open Source License

@Test
public void testRemoveClass() throws Exception {
    ResourceChangedEvent event = new ResourceChangedEvent(
            new File(BaseTest.class.getResource("/projects").getFile()),
            new DeleteEvent("projects", "/test/src/main/java/com/codenvy/test/MyClass.java", false));
    NameEnvironmentAnswer answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.MyClass".toCharArray()));

    assertThat(answer).isNotNull();//w w w  .j a v a 2  s .co m

    project.getJavaModelManager().deltaState.resourceChanged(event);
    project.creteNewNameEnvironment();

    answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.MyClass".toCharArray()));
    assertThat(answer).isNull();
}

From source file:com.codenvy.ide.ext.java.DeltaProcessingTest.java

License:Open Source License

@Test
public void testRemoveFolder() throws Exception {
    ResourceChangedEvent event = new ResourceChangedEvent(
            new File(BaseTest.class.getResource("/projects").getFile()),
            new DeleteEvent("projects", "/test/src/main/java/com/codenvy/test", true));
    NameEnvironmentAnswer answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.MyClass".toCharArray()));

    assertThat(answer).isNotNull();/*  w w  w.j  av a  2  s.c om*/
    project.getJavaModelManager().deltaState.resourceChanged(event);
    project.creteNewNameEnvironment();
    answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.MyClass".toCharArray()));
    assertThat(answer).isNull();
}

From source file:com.codenvy.ide.ext.java.DeltaProcessingTest.java

License:Open Source License

@Test
public void testAddClass() throws Exception {

    File workspace = new File(BaseTest.class.getResource("/projects").getFile());
    ResourceChangedEvent event = new ResourceChangedEvent(workspace,
            new CreateEvent("projects", "/test/src/main/java/com/codenvy/test/NewClass.java", false));

    NameEnvironmentAnswer answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.NewClass".toCharArray()));
    assertThat(answer).isNull();// w w w.  ja va  2s .c o m

    FileOutputStream outputStream = new FileOutputStream(
            new File(workspace, "/test/src/main/java/com/codenvy/test/NewClass.java"));
    outputStream.write("package com.codenvy.test;\n public class NewClass{}\n".getBytes());
    outputStream.close();

    project.getJavaModelManager().deltaState.resourceChanged(event);
    project.creteNewNameEnvironment();
    answer = project.getNameEnvironment()
            .findType(CharOperation.splitOn('.', "com.codenvy.test.NewClass".toCharArray()));
    assertThat(answer).isNotNull();
}

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

License:Open Source License

public ImportReference[] buildImports(ClassFileReader reader) {
    // add remaining references to the list of type names
    // (code extracted from BinaryIndexer#extractReferenceFromConstantPool(...))
    int[] constantPoolOffsets = reader.getConstantPoolOffsets();
    int constantPoolCount = constantPoolOffsets.length;
    for (int i = 0; i < constantPoolCount; i++) {
        int tag = reader.u1At(constantPoolOffsets[i]);
        char[] name = null;
        switch (tag) {
        case ClassFileConstants.MethodRefTag:
        case ClassFileConstants.InterfaceMethodRefTag:
            int constantPoolIndex = reader.u2At(constantPoolOffsets[i] + 3);
            int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 3)];
            name = reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
            break;
        case ClassFileConstants.ClassTag:
            utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[i] + 1)];
            name = reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
            break;
        }/*from  w  w  w . j  a v a2 s.  c om*/
        if (name == null || (name.length > 0 && name[0] == '['))
            break; // skip over array references
        this.typeNames.add(CharOperation.splitOn('/', name));
    }

    // convert type names into import references
    int typeNamesLength = this.typeNames.size();
    ImportReference[] imports = new ImportReference[typeNamesLength];
    char[][][] set = this.typeNames.set;
    int index = 0;
    for (int i = 0, length = set.length; i < length; i++) {
        char[][] typeName = set[i];
        if (typeName != null) {
            imports[index++] = new ImportReference(typeName, new long[typeName.length]/*dummy positions*/,
                    false/*not on demand*/, 0);
        }
    }
    return imports;
}

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

License:Open Source License

/**
 * Decode some element tag containing a sequence of patterns into IPath[]
 *//*w  w  w.j a  v  a2 s  .c  o m*/
private static IPath[] decodePatterns(NamedNodeMap nodeMap, String tag) {
    String sequence = removeAttribute(tag, nodeMap);
    if (!sequence.equals("")) { //$NON-NLS-1$
        char[][] patterns = CharOperation.splitOn('|', sequence.toCharArray());
        int patternCount;
        if ((patternCount = patterns.length) > 0) {
            IPath[] paths = new IPath[patternCount];
            int index = 0;
            for (int j = 0; j < patternCount; j++) {
                char[] pattern = patterns[j];
                if (pattern.length == 0)
                    continue; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=105581
                paths[index++] = new Path(new String(pattern));
            }
            if (index < patternCount)
                System.arraycopy(paths, 0, paths = new IPath[index], 0, index);
            return paths;
        }
    }
    return null;
}

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

License:Open Source License

private AccessRestriction getViolatedRestriction(String typeName, String packageName, IType type,
        AccessRestriction accessRestriction) {
    PackageFragmentRoot root = (PackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    ClasspathEntry entry = (ClasspathEntry) this.rootToResolvedEntries.get(root);
    if (entry != null) { // reverse map always contains resolved CP entry
        AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
        if (accessRuleSet != null) {
            // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
            char[][] packageChars = CharOperation.splitOn('.', packageName.toCharArray());
            char[] typeChars = typeName.toCharArray();
            accessRestriction = accessRuleSet
                    .getViolatedRestriction(CharOperation.concatWith(packageChars, typeChars, '/'));
        }//from   ww  w .  j a va  2s  . c  o  m
    }
    return accessRestriction;
}

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)./* w w  w.  j a  va 2s .  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.BasicSearchEngine.java

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope using  a case sensitive exact match
 * with the given qualified names and type names.
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], org.eclipse.jdt.core.search.IJavaSearchScope,
 * org.eclipse.jdt.core.search.TypeNameRequestor, int, org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment// ww w . j av  a 2 s .co m
 */
public void searchAllTypeNames(final char[][] qualifications, final char[][] typeNames, final int matchRule,
        int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor,
        int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException {

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (qualifications == null ? "null"
                : new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type name: "
                + (typeNames == null ? "null" : new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - match rule: " + getMatchRuleString(matchRule)); //$NON-NLS-1$
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }

    // Create pattern
    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 MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames,
            typeSuffix, matchRule);

    // 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
            QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) 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 qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0
                        : record.qualification.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[qualificationLength + nameLength];
                int pos = 0;
                if (qualificationLength > 0) {
                    System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[qualificationLength - 1] = '/';
                    pos += qualificationLength;
                }
                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);
                }
            }
            nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames,
                    documentPath, accessRestriction);
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 100);
        }
        // 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, 100));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0, length = copies.length; i < length; i++) {
                ICompilationUnit workingCopy = copies[i];
                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;
                        char[] qualification = packageDeclaration;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                            qualification = CharOperation.concat(qualification, parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        char suffix = IIndexConstants.TYPE_SUFFIX;
                        if (type.isClass()) {
                            suffix = IIndexConstants.CLASS_SUFFIX;
                        } else if (type.isInterface()) {
                            suffix = IIndexConstants.INTERFACE_SUFFIX;
                        } else if (type.isEnum()) {
                            suffix = IIndexConstants.ENUM_SUFFIX;
                        } else if (type.isAnnotation()) {
                            suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
                        }
                        if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification,
                                simpleName, suffix, matchRule))) {
                            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) {
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        packageDeclaration, typeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                            typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                // compute enclosing type names
                                char[] qualification = packageDeclaration;
                                TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                while (enclosing != null) {
                                    qualification = CharOperation.concat(qualification, enclosing.name, '.');
                                    enclosingTypeNames = CharOperation
                                            .arrayConcat(new char[][] { enclosing.name }, enclosingTypeNames);
                                    if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                        enclosing = enclosing.enclosingType;
                                    } else {
                                        enclosing = null;
                                    }
                                }
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        qualification, memberTypeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                            packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames,
                                            path, null);
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

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

License:Open Source License

/**
 * Extract all type, method, field and interface method references from the constant pool
 *//*from  w  ww .  j  a  v a2s  .  c o m*/
private void extractReferenceFromConstantPool(byte[] contents, ClassFileReader reader)
        throws ClassFormatException {
    int[] constantPoolOffsets = reader.getConstantPoolOffsets();
    int constantPoolCount = constantPoolOffsets.length;
    for (int i = 1; i < constantPoolCount; i++) {
        int tag = reader.u1At(constantPoolOffsets[i]);
        /**
         * u1 tag
         * u2 class_index
         * u2 name_and_type_index
         */
        char[] name = null;
        char[] type = null;
        switch (tag) {
        case ClassFileConstants.FieldRefTag:
            // add reference to the class/interface and field name and type
            name = extractName(constantPoolOffsets, reader, i);
            addFieldReference(name);
            break;
        case ClassFileConstants.MethodRefTag:
            // add reference to the class and method name and type
        case ClassFileConstants.InterfaceMethodRefTag:
            // add reference to the interface and method name and type
            name = extractName(constantPoolOffsets, reader, i);
            type = extractType(constantPoolOffsets, reader, i);
            if (CharOperation.equals(INIT, name)) {
                // get class name and see if it's a local type or not
                char[] className = extractClassName(constantPoolOffsets, reader, i);
                boolean localType = false;
                if (className != null) {
                    for (int c = 0, max = className.length; c < max; c++) {
                        switch (className[c]) {
                        case '/':
                            className[c] = '.';
                            break;
                        case '$':
                            localType = true;
                            break;
                        }
                    }
                }
                // add a constructor reference, use class name to extract arg count if it's a local type to remove synthetic parameter
                addConstructorReference(className, extractArgCount(type, localType ? className : null));
            } else {
                // add a method reference
                addMethodReference(name, extractArgCount(type, null));
            }
            break;
        case ClassFileConstants.ClassTag:
            // add a type reference
            name = extractClassReference(constantPoolOffsets, reader, i);
            if (name.length > 0 && name[0] == '[')
                break; // skip over array references
            name = replace('/', '.', name); // so that it looks like java.lang.String
            addTypeReference(name);

            // also add a simple reference on each segment of the qualification (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24741)
            char[][] qualification = CharOperation.splitOn('.', name);
            for (int j = 0, length = qualification.length; j < length; j++) {
                addNameReference(qualification[j]);
            }
            break;
        }
    }
}

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

License:Open Source License

private char[][] readJavaLikeNamesFile() {
    try {/*from  ww  w  . j  a va2 s.c  om*/
        String pathName = getJavaPluginWorkingLocation().toOSString();
        File javaLikeNamesFile = new File(pathName, "javaLikeNames.txt"); //$NON-NLS-1$
        if (!javaLikeNamesFile.exists())
            return null;
        char[] javaLikeNames = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(javaLikeNamesFile,
                null);
        if (javaLikeNames.length > 0) {
            char[][] names = CharOperation.splitOn('\n', javaLikeNames);
            return names;
        }
    } catch (IOException ignored) {
        if (VERBOSE)
            Util.verbose("Failed to read javaLikeNames file"); //$NON-NLS-1$
    }
    return null;
}