Example usage for org.eclipse.jdt.core.search TypeNameMatch getType

List of usage examples for org.eclipse.jdt.core.search TypeNameMatch getType

Introduction

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

Prototype

public abstract IType getType();

Source Link

Document

Returns a java model type handle.

Usage

From source file:com.curlap.orb.plugin.generator.impl.CurlDataClassGeneratorImpl.java

License:Open Source License

protected List<Field> getAllSuperclassFields(Set<String> importPackages, String superclass)
        throws JavaModelException {
    List<Field> fields = new ArrayList<Field>();
    TypeNameMatch typeNameMatch = new JavaElementSearcher(iCompilationUnit).searchClassInfo(superclass);
    if (typeNameMatch == null)
        return fields;
    IType iType = typeNameMatch.getType();
    for (IField iField : iType.getFields()) {
        // skip static field
        if (Flags.isStatic(iField.getFlags()))
            continue;
        String name = iField.getElementName();
        Field field = new Field();
        field.setName(name);/*from w  ww  . j a  va2  s. com*/
        field.setType(CurlSpecUtil.marshalCurlTypeWithSignature(
                addImportedPackageIfNecessaryWithSignature(importPackages, iField.getTypeSignature())));
        field.setDefaultValue(CurlSpecUtil.getDefaultValue(field.getType()));
        field.setIsTransient(Flags.isTransient(iField.getFlags()));
        String modifier = Flags.toString(iField.getFlags());
        if (modifier.length() == 0)
            modifier = "package";
        field.setGetterModifier(modifier + "-get");
        field.setSetterModifier(modifier + "-set");
        field.setComment("");
        fields.add(field);
    }
    // more superclasses
    if (iType.getSuperclassName() != null)
        fields.addAll(getAllSuperclassFields(importPackages, iType.getSuperclassName()));
    return fields;
}

From source file:com.curlap.orb.plugin.generator.impl.CurlServiceClassGenerator.java

License:Open Source License

protected List<Method> addMethodsOfSuperclass(ICompilationUnit source, String superclass,
        Set<String> importPackages, boolean returnTypeIsNullable) throws JavaModelException {
    TypeNameMatch typeNameMatch = new JavaElementSearcher(source).searchClassInfo(superclass);
    IType iType = typeNameMatch.getType();
    List<Method> methods = new ArrayList<Method>();
    methods.addAll(getMethodsFromIType(iType, importPackages, returnTypeIsNullable));
    addImportedPackageIfNecessary(importPackages, superclass);
    String superclassOfthis = iType.getSuperclassName();
    if (superclassOfthis != null) {
        methods.addAll(addMethodsOfSuperclass(iType.getCompilationUnit(), superclassOfthis, importPackages,
                returnTypeIsNullable));//ww  w.j a  v a  2s .  c om
    }
    return methods;
}

From source file:com.curlap.orb.plugin.generator.impl.CurlServiceClassGenerator.java

License:Open Source License

@Override
public VelocityContext generateClass() throws CurlGenerateException {
    ICompilationUnit source = iCompilationUnit;
    Set<String> importPackages = new HashSet<String>();
    List<Method> methods = new ArrayList<Method>();

    String packageName = null;/* www .j a v  a 2  s  .c o  m*/
    String targetInterface = null;
    JavadocContent classJavadoc = null;
    String className = null;
    boolean returnTypeIsNullable = true;
    boolean generateTestTemplate = false;
    boolean generateAsyncMethod = true;
    importPackages.add("COM.CURLAP.ORB");
    try {
        for (IType iType : source.getAllTypes()) {
            // package
            IPackageFragment iPackageFragment = iType.getPackageFragment();
            packageName = (iPackageFragment != null ? iPackageFragment.getElementName().toUpperCase() : "");

            // javadoc
            classJavadoc = JavaElementAnalyzer.getJavaDoc(iType);

            // class name
            className = iType.getElementName();
            if (className == null)
                throw new CurlGenerateException("There is no class name.");

            // superclass
            String superclass = iType.getSuperclassName();
            if (superclass != null) {
                methods.addAll(
                        addMethodsOfSuperclass(source, superclass, importPackages, returnTypeIsNullable));
                // NOTE: the following code would be not necessary 
                // superclassBuf.append(", ");
                // superclassBuf.append(superclass);
                // addImportedPackageIfNecessary(importPackages, superclass);
            }

            // annotation
            for (IAnnotation iAnnotation : iType.getAnnotations()) {
                if (iAnnotation.getElementName().equals("AutoGenerateCurlServiceClient")) {
                    for (IMemberValuePair pair : iAnnotation.getMemberValuePairs()) {
                        String memberName = pair.getMemberName();
                        if (memberName.equals("generateTestTemplate"))
                            generateTestTemplate = ((Boolean) pair.getValue()).booleanValue();
                        if (memberName.equals("generateAsyncMethod"))
                            generateAsyncMethod = ((Boolean) pair.getValue()).booleanValue();
                        if (memberName.equals("targetInterface"))
                            targetInterface = (String) pair.getValue();
                    }
                }
                if (iAnnotation.getElementName().equals("DefaultNotNull"))
                    returnTypeIsNullable = false;
            }

            // interface
            String[] interfaceNames = iType.getSuperInterfaceNames();
            if (interfaceNames.length > 0) {
                if (interfaceNames.length == 1)
                    targetInterface = interfaceNames[0]; // In the case of only one interface 
                else {
                    boolean hasSuchInterface = false;
                    for (String interfaceName : interfaceNames)
                        if (interfaceName.equals(targetInterface))
                            hasSuchInterface = true;
                    if (!hasSuchInterface)
                        throw new CurlGenerateException("'targetInterface' is wrong interface.");
                }
            }
            if (targetInterface != null) {
                // Add interfaces' methods
                TypeNameMatch typeNameMatch = new JavaElementSearcher(source).searchClassInfo(targetInterface);
                IType interfaceIType = typeNameMatch.getType();
                className = targetInterface;
                fileName = className + ".scurl";
                methods.addAll(getMethodsFromIType(interfaceIType, importPackages, returnTypeIsNullable));
                addImportedPackageIfNecessary(importPackages, targetInterface);

                // Add interfaces' methods of interface.
                for (String interfaceNamesOfInterface : interfaceIType.getSuperInterfaceNames()) {
                    TypeNameMatch typeNameMatchOfInterface = new JavaElementSearcher(
                            interfaceIType.getCompilationUnit()).searchClassInfo(interfaceNamesOfInterface);
                    methods.addAll(getMethodsFromIType(typeNameMatchOfInterface.getType(), importPackages,
                            returnTypeIsNullable));
                }
            } else {
                // methods 
                methods.addAll(getMethodsFromIType(iType, importPackages, returnTypeIsNullable));
            }
        }
    } catch (JavaModelException e) {
        throw new CurlGenerateException(e);
    }

    // merge to velocity.
    VelocityContext context = new VelocityContext();
    context.put("is_template", generateTestTemplate);
    context.put("has_async_method", generateAsyncMethod);
    context.put("package_name", packageName);
    context.put("import_packages", importPackages);
    context.put("javadocContent", classJavadoc);
    context.put("class_name", className);
    context.put("methods", methods);
    return context;
}

From source file:com.technophobia.substeps.junit.action.OpenEditorAction.java

License:Open Source License

protected final IType findType(final IJavaProject project, final String testClassName) {
    final IType[] result = { null };
    final String dottedName = testClassName.replace('$', '.'); // for nested
    // classes...
    try {//from  w ww .  j a v a  2  s .  c  o m
        PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
            @Override
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                try {
                    if (project != null) {
                        result[0] = internalFindType(project, dottedName, new HashSet<IJavaProject>(), monitor);
                    }
                    if (result[0] == null) {
                        final int lastDot = dottedName.lastIndexOf('.');
                        final TypeNameMatchRequestor nameMatchRequestor = new TypeNameMatchRequestor() {
                            @Override
                            public void acceptTypeNameMatch(final TypeNameMatch match) {
                                result[0] = match.getType();
                            }
                        };
                        new SearchEngine().searchAllTypeNames(
                                lastDot >= 0 ? dottedName.substring(0, lastDot).toCharArray() : null,
                                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
                                (lastDot >= 0 ? dottedName.substring(lastDot + 1) : dottedName).toCharArray(),
                                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
                                IJavaSearchConstants.TYPE, SearchEngine.createWorkspaceScope(),
                                nameMatchRequestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
                    }
                } catch (final JavaModelException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (final InvocationTargetException e) {
        FeatureRunnerPlugin.log(e);
    } catch (final InterruptedException e) {
        // user cancelled
    }
    return result[0];
}

From source file:de.jcup.egradle.eclipse.gradleeditor.jdt.JDTDataAccess.java

License:Apache License

/**
 * Find type/* www.ja  v  a 2  s .  c  om*/
 * 
 * @param className
 * @param monitor
 * @return type or <code>null</code>
 */
public IType findType(String className, IProgressMonitor monitor) {
    final IType[] result = { null };
    TypeNameMatchRequestor nameMatchRequestor = new TypeNameMatchRequestor() {
        @Override
        public void acceptTypeNameMatch(TypeNameMatch match) {
            result[0] = match.getType();
        }
    };
    int lastDot = className.lastIndexOf('.');
    char[] packageName = lastDot >= 0 ? className.substring(0, lastDot).toCharArray() : null;
    char[] typeName = (lastDot >= 0 ? className.substring(lastDot + 1) : className).toCharArray();
    SearchEngine engine = new SearchEngine();
    int packageMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    try {
        engine.searchAllTypeNames(packageName, packageMatchRule, typeName, packageMatchRule,
                IJavaSearchConstants.TYPE, SearchEngine.createWorkspaceScope(), nameMatchRequestor,
                IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
    } catch (JavaModelException e) {
        EGradleUtil.log(e);
    }
    return result[0];
}

From source file:io.sarl.eclipse.wizards.elements.AbstractSuperTypeSelectionDialog.java

License:Apache License

/** Adds selected interfaces to the list.
 */// w  w w.j a v a2 s  .  c o m
private void fillWizardPageWithSelectedTypes() {
    final StructuredSelection selection = getSelectedItems();
    if (selection == null) {
        return;
    }
    for (final Iterator<?> iter = selection.iterator(); iter.hasNext();) {
        final Object obj = iter.next();
        if (obj instanceof TypeNameMatch) {
            accessedHistoryItem(obj);
            final TypeNameMatch type = (TypeNameMatch) obj;
            final String qualifiedName = Utilities.getNameWithTypeParameters(type.getType());
            final String message;

            if (addTypeToWizardPage(this.typeWizardPage, qualifiedName)) {
                message = MessageFormat.format(Messages.AbstractSuperTypeSelectionDialog_2,
                        BasicElementLabels.getJavaElementName(qualifiedName));
            } else {
                message = MessageFormat.format(Messages.AbstractSuperTypeSelectionDialog_3,
                        BasicElementLabels.getJavaElementName(qualifiedName));
            }
            updateStatus(new StatusInfo(IStatus.INFO, message));
        }
    }
}

From source file:org.autorefactor.refactoring.rules.ReplaceQualifiedNamesBySimpleNamesRefactoring.java

License:Open Source License

private void importTypesFromPackage(final String pkgName, ASTNode node) {
    final TypeNameMatchRequestor importTypeCollector = new TypeNameMatchRequestor() {
        @Override/*from ww w  .  j a v a2  s. c  o m*/
        public void acceptTypeNameMatch(TypeNameMatch typeNameMatch) {
            final boolean isTopLevelType = typeNameMatch.getType().getDeclaringType() == null;
            if (isTopLevelType) {
                if (!pkgName.equals(typeNameMatch.getPackageName())) {
                    // sanity check failed
                    throw new IllegalStateException("Expected package '" + typeNameMatch.getPackageName()
                            + "' to be equal to '" + pkgName + "'");
                }
                QName qname = QName.valueOf(typeNameMatch.getFullyQualifiedName());
                types.addName(FQN.fromImport(qname, true));
            }
        }
    };

    SubMonitor monitor = SubMonitor.convert(ctx.getProgressMonitor(), 1);
    final SubMonitor childMonitor = monitor.newChild(1);
    try {
        final SearchEngine searchEngine = new SearchEngine();
        searchEngine.searchAllTypeNames(pkgName.toCharArray(), R_EXACT_MATCH, // search in this package
                null, R_EXACT_MATCH, // do not filter by type name
                TYPE, // look for all java types (class, interfaces, enums, etc.)
                createWorkspaceScope(), // search everywhere
                importTypeCollector, WAIT_UNTIL_READY_TO_SEARCH, // wait in case the indexer is indexing
                childMonitor);
    } catch (JavaModelException e) {
        throw new UnhandledException(node, e);
    } finally {
        childMonitor.done();
    }
}

From source file:org.autorefactor.refactoring.rules.SimpleNameRatherThanQualifiedNameRefactoring.java

License:Open Source License

private void importTypesFromPackage(final String pkgName, ASTNode node) {
    final TypeNameMatchRequestor importTypeCollector = new TypeNameMatchRequestor() {
        @Override/*from   ww  w.  j  a v  a2 s .  co m*/
        public void acceptTypeNameMatch(TypeNameMatch typeNameMatch) {
            final boolean isTopLevelType = typeNameMatch.getType().getDeclaringType() == null;
            if (isTopLevelType) {
                if (!pkgName.equals(typeNameMatch.getPackageName())) {
                    // sanity check failed
                    throw new IllegalStateException("Expected package '" + typeNameMatch.getPackageName()
                            + "' to be equal to '" + pkgName + "'");
                }
                QName qname = QName.valueOf(typeNameMatch.getFullyQualifiedName());
                types.addName(FQN.fromImport(qname, true));
            }
        }
    };

    try {
        final SearchEngine searchEngine = new SearchEngine();
        searchEngine.searchAllTypeNames(pkgName.toCharArray(), R_EXACT_MATCH, // search in this package
                null, R_EXACT_MATCH, // do not filter by type name
                TYPE, // look for all java types (class, interfaces, enums, etc.)
                createWorkspaceScope(), // search everywhere
                importTypeCollector, WAIT_UNTIL_READY_TO_SEARCH, // wait in case the indexer is indexing
                ctx.getProgressMonitor());
    } catch (JavaModelException e) {
        throw new UnhandledException(node, e);
    }
}

From source file:org.codehaus.groovy.eclipse.quickfix.proposals.AddMissingGroovyImportsResolver.java

License:Apache License

/**
 * Return the type suggestions that may resolve the unresolved type problem.
 * /*from w  ww  .j  av  a  2  s .  co m*/
 * @return list of type suggestions for the unresolved type, or null if
 *         nothing is found
 */
protected List<IType> getImportTypeSuggestions() {
    int offset = getQuickFixProblem().getOffset();
    try {

        String simpleTypeName = getUnresolvedSimpleName();
        if (simpleTypeName != null) {
            Map<String, OrganizeGroovyImports.UnresolvedTypeData> unresolvedTypes = new HashMap<String, OrganizeGroovyImports.UnresolvedTypeData>();
            unresolvedTypes.put(simpleTypeName, new UnresolvedTypeData(simpleTypeName, false,
                    new SourceRange(offset, simpleTypeName.length())));

            new TypeSearch().searchForTypes(getGroovyCompilationUnit(), unresolvedTypes);

            UnresolvedTypeData foundData = unresolvedTypes.get(simpleTypeName);

            List<TypeNameMatch> matches = foundData.getFoundInfos();
            if (matches != null) {
                List<IType> suggestions = new ArrayList<IType>();
                for (TypeNameMatch match : matches) {
                    suggestions.add(match.getType());
                }
                return suggestions;
            }
        }

    } catch (JavaModelException e) {
        GroovyQuickFixPlugin.log(e);
    }
    return null;

}

From source file:org.codehaus.groovy.eclipse.refactoring.actions.OrganizeGroovyImports.java

License:Apache License

private IType[] resolveMissingTypes() throws JavaModelException {

    // fill in all the potential matches
    new TypeSearch().searchForTypes(unit, missingTypes);
    List<TypeNameMatch> missingTypesNoChoiceRequired = new ArrayList<TypeNameMatch>();
    List<TypeNameMatch[]> missingTypesChoiceRequired = new ArrayList<TypeNameMatch[]>();
    List<ISourceRange> ranges = new ArrayList<ISourceRange>();

    // go through all the resovled matches and look for ambiguous matches
    for (UnresolvedTypeData data : missingTypes.values()) {
        if (data.foundInfos.size() > 1) {
            missingTypesChoiceRequired.add(data.foundInfos.toArray(new TypeNameMatch[0]));
            ranges.add(data.range);/*  ww w  .j av  a2  s . c  o m*/
        } else if (data.foundInfos.size() == 1) {
            missingTypesNoChoiceRequired.add(data.foundInfos.get(0));
        }
    }

    TypeNameMatch[][] missingTypesArr = missingTypesChoiceRequired.toArray(new TypeNameMatch[0][]);
    TypeNameMatch[] chosen;
    if (missingTypesArr.length > 0) {
        chosen = query.chooseImports(missingTypesArr, ranges.toArray(new ISourceRange[0]));
    } else {
        chosen = new TypeNameMatch[0];
    }

    if (chosen != null) {
        IType[] typeMatches = new IType[missingTypesNoChoiceRequired.size() + chosen.length];
        int cnt = 0;
        for (TypeNameMatch typeNameMatch : missingTypesNoChoiceRequired) {
            typeMatches[cnt++] = typeNameMatch.getType();
        }
        for (int i = 0; i < chosen.length; i++) {
            typeMatches[cnt++] = ((JavaSearchTypeNameMatch) chosen[i]).getType();
        }

        return typeMatches;
    } else {
        // dialog was canceled.  do nothing
        return new IType[0];
    }
}