List of usage examples for org.eclipse.jdt.core IType isClass
boolean isClass() throws JavaModelException;
From source file:cfgrecognition.loader.SootClassLoader.java
License:Open Source License
protected void dfsDomTree(IJavaElement element) throws Exception { // if (monitor.isCanceled()) { // return; // }/*www. ja v a 2s . co m*/ if (element.isReadOnly()) return; int elementType = element.getElementType(); if (elementType == IJavaElement.COMPILATION_UNIT) { ICompilationUnit cu = (ICompilationUnit) element; IType[] allTypes = cu.getTypes(); for (IType aType : allTypes) { dfsDomTree(aType); } } else if (elementType == IJavaElement.TYPE) { IType aType = (IType) element; if (aType.isClass()) { // Load a type in Soot load(aType.getFullyQualifiedName()); } // Go inside the methods to look for Anonymous Inner Class for (IMethod m : aType.getMethods()) { IJavaElement[] elems = m.getChildren(); for (IJavaElement elem : elems) { if (elem.getElementType() == IJavaElement.TYPE) { dfsDomTree(elem); } } } // For inner classes IType[] allTypes = aType.getTypes(); for (IType childType : allTypes) { dfsDomTree(childType); } } }
From source file:ch.mlutz.plugins.t4e.tapestry.editor.hyperlink.OgnlHyperlinkDetectorDelegate.java
License:Open Source License
@Override public List<SourceRangeHyperlink> detectHyperlinks(IDocument document, String content, IRegion region) { List<SourceRangeHyperlink> result = new ArrayList<SourceRangeHyperlink>(); // go back until whitespace is found and int charIndex = region.getOffset(); while (charIndex >= 0 && content.charAt(charIndex) != '"') { charIndex--;//from w w w . j a va 2s .c om } // charIndex might be -1, but that's ok String prefix = content.substring(charIndex + 1); final String expectedPrefix = "ognl:"; if (!prefix.startsWith(expectedPrefix)) { return null; } int ognlExpressionStart = charIndex + 1 + expectedPrefix.length(); charIndex = region.getOffset(); while (charIndex < content.length() && content.charAt(charIndex) != '"' && content.charAt(charIndex) != '.') { charIndex++; } final int hyperLinkOffset = ognlExpressionStart; final int hyperLinkLength = charIndex - hyperLinkOffset; if (hyperLinkLength < 0) { // caret might rest on the first quote log.warn("OGNL hyperLinkLength: " + hyperLinkLength + "; charIndex: " + charIndex + "; hyperLinkOffset: " + hyperLinkOffset); return null; } final String hyperlinkText = content.substring(ognlExpressionStart, ognlExpressionStart + hyperLinkLength); TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex(); IFile documentFile = tapestryIndex.getDocumentToFileMapping(document); if (documentFile == null) { return null; } ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile); if (javaCompilationUnit == null) { return null; } /* TapestryModule module= tapestryIndex.getModuleForResource(documentFile); TapestryHtmlElement linkedComponent= null; for (TapestryHtmlElement component: module.getComponents()) { if (hyperlinkText.equals(component.getPath())) { linkedComponent= component; } } final TapestryHtmlElement finalLinkedComponent= linkedComponent; */ IType[] types = new IType[0]; try { types = javaCompilationUnit.getTypes(); } catch (JavaModelException e) { log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e); } IMethod methodMatch = null; outer: for (IType type : types) { try { if (type.isClass() && Flags.isPublic(type.getFlags())) { IMethod[] methods = type.getMethods(); for (IMethod method : methods) { String ognlMethodName = method.getElementName() + "()"; if (ognlMethodName.equals(hyperlinkText)) { methodMatch = method; break outer; } ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1"); // TODO: check this match! if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) { methodMatch = method; break outer; } } } } catch (JavaModelException e) { log.warn("Could not get information for type " + type.getElementName(), e); } } IFile javaFile = null; try { javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class); } catch (JavaModelException e) { log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e); } final IFile finalJavaFile = javaFile; ISourceRange sourceRange = null; if (methodMatch != null) { try { sourceRange = methodMatch.getSourceRange(); } catch (JavaModelException e) { log.warn("Could not get source range for method " + methodMatch.getElementName(), e); } } if (finalJavaFile != null) { SourceRangeHyperlink hyperlink = new SourceRangeHyperlink(new Region(hyperLinkOffset, hyperLinkLength), "Open method", javaFile, sourceRange, Constants.TAPESTRY_EDITOR_ID); result.add(hyperlink); } if (result.size() > 0) { return result; } else { return null; } }
From source file:ch.mlutz.plugins.t4e.tapestry.editor.OgnlHyperlinkDetector.java
License:Open Source License
@Override public IHyperlink[] detectHyperlinks(ITextViewer viewer, IRegion region, boolean canHandleMultipleLinks) { IDocument document = viewer.getDocument(); String contentBefore;/*www. j a va 2 s . c o m*/ ITypedRegion partition; try { partition = document.getPartition(region.getOffset()); if (!partition.getType().equals(TapestryPartitionScanner.XML_TAG)) { return null; } contentBefore = document.get(partition.getOffset(), partition.getLength()); } catch (BadLocationException e) { log.warn("Could not detect hyperlinks: ", e); return null; } List<IHyperlink> result = new ArrayList<IHyperlink>(); // go back until whitespace is found and int charIndex = region.getOffset() - partition.getOffset(); while (charIndex >= 0 && contentBefore.charAt(charIndex) != '"') { charIndex--; } // charIndex might be -1, but that's ok String prefix = contentBefore.substring(charIndex + 1); final String expectedPrefix = "ognl:"; if (!prefix.startsWith(expectedPrefix)) { return null; } int ognlExpressionStart = charIndex + 1 + expectedPrefix.length(); charIndex = region.getOffset() - partition.getOffset(); while (charIndex < contentBefore.length() && contentBefore.charAt(charIndex) != '"' && contentBefore.charAt(charIndex) != '.') { charIndex++; } final int hyperLinkOffset = partition.getOffset() + ognlExpressionStart; final int hyperLinkLength = partition.getOffset() + charIndex - hyperLinkOffset; if (hyperLinkLength < 0) { // caret might rest on the first quote log.warn( "OGNL hyperLinkLength: " + hyperLinkLength + "; partition.getOffset(): " + partition.getOffset() + "; charIndex: " + charIndex + "; hyperLinkOffset: " + hyperLinkOffset); return null; } final String hyperlinkText = contentBefore.substring(ognlExpressionStart, ognlExpressionStart + hyperLinkLength); TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex(); IFile documentFile = tapestryIndex.getDocumentToFileMapping(document); if (documentFile == null) { return null; } ICompilationUnit javaCompilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile); if (javaCompilationUnit == null) { return null; } /* TapestryModule module= tapestryIndex.getModuleForResource(documentFile); TapestryHtmlElement linkedComponent= null; for (TapestryHtmlElement component: module.getComponents()) { if (hyperlinkText.equals(component.getPath())) { linkedComponent= component; } } final TapestryHtmlElement finalLinkedComponent= linkedComponent; */ IType[] types = new IType[0]; try { types = javaCompilationUnit.getTypes(); } catch (JavaModelException e) { log.warn("Could not get types of compilation unit " + javaCompilationUnit.getElementName(), e); } IMethod methodMatch = null; outer: for (IType type : types) { try { if (type.isClass() && Flags.isPublic(type.getFlags())) { IMethod[] methods = type.getMethods(); for (IMethod method : methods) { String ognlMethodName = method.getElementName() + "()"; if (ognlMethodName.equals(hyperlinkText)) { methodMatch = method; break outer; } ognlMethodName = ognlMethodName.replaceAll("^(?:get|is)(.+)\\(\\)$", "$1"); // TODO: check this match! if (ognlMethodName.equalsIgnoreCase(hyperlinkText)) { methodMatch = method; break outer; } } } } catch (JavaModelException e) { log.warn("Could not get information for type " + type.getElementName(), e); } } IFile javaFile = null; try { javaFile = (IFile) javaCompilationUnit.getCorrespondingResource().getAdapter(IFile.class); } catch (JavaModelException e) { log.warn("Could not get corresponding resource for " + javaCompilationUnit.getElementName(), e); } final IFile finalJavaFile = javaFile; ISourceRange sourceRange = null; if (methodMatch != null) { try { sourceRange = methodMatch.getSourceRange(); } catch (JavaModelException e) { log.warn("Could not get source range for method " + methodMatch.getElementName(), e); } } final ISourceRange finalSourceRange = sourceRange; if (finalJavaFile != null) { result.add(new IHyperlink() { @Override public void open() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = win.getActivePage(); IEditorPart editorPart = EclipseTools.openFileInEditor(finalJavaFile, page); if (!(editorPart instanceof ITextEditor)) { log.info("editorPart !instanceof ITextEditor"); } if (finalSourceRange == null) { log.info("finalSourceRange == null"); } if (editorPart instanceof ITextEditor && finalSourceRange != null) { log.info("Opening source range: " + finalSourceRange); ((ITextEditor) editorPart).selectAndReveal(finalSourceRange.getOffset(), finalSourceRange.getLength()); } } @Override public String getTypeLabel() { return null; } @Override public String getHyperlinkText() { return "Open method"; } @Override public IRegion getHyperlinkRegion() { return new Region(hyperLinkOffset, hyperLinkLength); } }); } /* log.info("detectHyperlinks called: " + hyperLinkOffset + " / " + hyperLinkLength + ", size: " + result.size()); */ if (result.size() > 0) { return result.toArray(new IHyperlink[result.size()]); } else { return null; } }
From source file:ch.mlutz.plugins.t4e.tapestry.editor.TagContentAssistProcessor.java
License:Open Source License
protected ICompletionProposal[] computeOgnlCompletionProposals(int offset, String ognlPrefix, IDocument document, IFile documentFile) { List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); int ognlPrefixLength = ognlPrefix.length(); TapestryIndex tapestryIndex = Activator.getDefault().getTapestryIndex(); ICompilationUnit compilationUnit = tapestryIndex.getRelatedCompilationUnit(documentFile); if (compilationUnit != null) { Map<ICompletionProposal, Integer> proposalScoreMap = new HashMap<ICompletionProposal, Integer>(); // TODO: improve this suffix computation as in computeAttributeCompletionProposals String suffix = "\""; int additionalCursorOffset = 1; try {/*from ww w.j a v a 2 s .c om*/ if (offset < document.getLength() - 1 && document.get(offset, 1).equals("\"")) { suffix = ""; } } catch (BadLocationException e) { log.warn("Could not compute suffix of completion proposals: ", e); } try { IType[] types = compilationUnit.getTypes(); for (IType type : types) { if (type.isClass() && Flags.isPublic(type.getFlags())) { IMethod[] methods = type.getMethods(); for (IMethod method : methods) { String completionProposalString = method.getElementName() + "()"; String ognlProposalString = completionProposalString.replaceAll("^get(.+)\\(\\)?$", "$1"); if (!ognlProposalString.equals(completionProposalString)) { // ognlProposalString is different from // original proposal => make sure first // character is lower case ognlProposalString = Character.toLowerCase(ognlProposalString.charAt(0)) + ognlProposalString.substring(1); completionProposalString = ognlProposalString; } if (completionProposalString.startsWith(ognlPrefix)) { String displayName = completionProposalString; String translatedSignature = translateSignatureToType(method.getReturnType()); if (translatedSignature != null) { displayName += " - " + translatedSignature; } ICompletionProposal completionProposal = new CompletionProposal( completionProposalString + suffix, offset - ognlPrefixLength, ognlPrefixLength, completionProposalString.length() + additionalCursorOffset, Activator.getImage("icons/t4e.png"), displayName, getContextInformation("", ""), completionProposalString); // compute score for this proposal int proposalScore = getProposalScoreForMethod(method, ParameterType.STRING); proposalScoreMap.put(completionProposal, proposalScore); result.add(completionProposal); } } } } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } Collections.sort(result, new ScoreComparator<Integer>(proposalScoreMap)); } return result.toArray(new ICompletionProposal[result.size()]); }
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).// ww w.j a va2 s .co 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 .jav a2s . c o 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.SourcesFromBytecodeGenerator.java
License:Open Source License
private String getJavaType(IType type) throws JavaModelException { if (type.isAnnotation()) { return "@interface"; }//from w w w . jav a2 s . c o m if (type.isClass()) { return "class"; } if (type.isInterface()) { return "interface"; } if (type.isEnum()) { return "enum"; } return "can't determine type"; }
From source file:com.ebmwebsourcing.petals.common.internal.provisional.utils.JaxWsUtils.java
License:Open Source License
/** * Searches all the Java types from a Java project that are annotated with @WebService. * * @param jp the containing Java project * @param monitor the progress monitor/*from w w w . ja v a 2s . c o m*/ * @param includeClasses true to include classes in the search results * @param includeInterfaces true to include the interfaces in the search results * @return a Map * <p> * Key = the qualified name of the annotated type<br /> * Value = the associated service name (in the target WSDL) * </p> * * @throws CoreException if the search could not be launched */ public static Map<String, String> getJaxAnnotatedJavaTypes(IJavaProject jp, IProgressMonitor monitor, final boolean includeClasses, final boolean includeInterfaces) throws CoreException { jp.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor); jp.getProject().build(IncrementalProjectBuilder.FULL_BUILD, monitor); final Map<String, String> classNameToServiceName = new HashMap<String, String>(); SearchPattern pattern = SearchPattern.createPattern(WEB_WS_ANNOTATION, IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); // This is what we do when we find a match SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { // We get the Java type that is annotated with @WebService if (match.getElement() instanceof IType) { // Find the annotation IType type = (IType) match.getElement(); if (type.isInterface() && includeInterfaces || type.isClass() && includeClasses) { IAnnotation ann = type.getAnnotation(WEB_WS_ANNOTATION); if (!ann.exists()) ann = type.getAnnotation(SHORT_WEB_WS_ANNOTATION); // Get the service name and store it if (ann.exists()) { String serviceName = null; for (IMemberValuePair pair : ann.getMemberValuePairs()) { if ("serviceName".equalsIgnoreCase(pair.getMemberName())) { serviceName = (String) pair.getValue(); break; } } if (serviceName == null) serviceName = type.getElementName() + "Service"; classNameToServiceName.put(type.getFullyQualifiedName(), serviceName); } } } } }; new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createJavaSearchScope(new IJavaElement[] { jp }, false), requestor, monitor); return classNameToServiceName; }
From source file:com.ecfeed.ui.common.EclipseClassImplementHelper.java
License:Open Source License
private boolean isClass(final IType type) { try {/* w w w .ja va 2 s.c o m*/ if (type.isClass()) { return true; } } catch (JavaModelException e) { return false; } return true; }
From source file:com.ecfeed.ui.common.EclipseImplementationStatusResolver.java
License:Open Source License
@Override protected boolean classDefinitionImplemented(String qualifiedName) { IType type = JavaModelAnalyser.getIType(qualifiedName); try {//from w w w . j a v a 2 s . c o m return type != null && type.isClass(); } catch (JavaModelException e) { SystemLogger.logCatch(e.getMessage()); } return false; }