List of usage examples for org.eclipse.jdt.core.search SearchMatch getOffset
public final int getOffset()
From source file:com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.java
License:Open Source License
/** * Returns the activity associated with the given layout file. * <p>/*from www. j av a 2 s .com*/ * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas * guessActivity simply looks for references to "R.layout.foo", this method searches * for all usages of Activity#setContentView(int), and for each match it looks up the * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses * a regexp to pull out "foo" from this, and stores the association that layout "foo" * is associated with the activity class that contained the setContentView call. * <p> * This has two potential advantages: * <ol> * <li>It can be faster. We do the reference search -once-, and we've built a map of * all the layout-to-activity mappings which we can then immediately look up other * layouts for, which is particularly useful at startup when we have to compute the * layout activity associations to populate the theme choosers. * <li>It can be more accurate. Just because an activity references an "R.layout.foo" * field doesn't mean it's setting it as a content view. * </ol> * However, this second advantage is also its chief problem. There are some common * code constructs which means that the associated layout is not explicitly referenced * in a direct setContentView call; on a couple of sample projects I tested I found * patterns like for example "setContentView(v)" where "v" had been computed earlier. * Therefore, for now we're going to stick with the more general approach of just * looking up each field when needed. We're keeping the code around, though statically * compiled out with the "if (false)" construct below in case we revisit this. * * @param layoutFile the layout whose activity we want to look up * @return the activity name */ @SuppressWarnings("all") @Nullable public String guessActivityBySetContentView(String layoutName) { if (false) { // These should be fields final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$ Map<String, String> mUsages = null; sync(); if (mUsages == null) { final Map<String, String> usages = new HashMap<String, String>(); mUsages = usages; SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IMethod) { IMethod method = (IMethod) element; IType declaringType = method.getDeclaringType(); String fqcn = declaringType.getFullyQualifiedName(); IDocumentProvider provider = new TextFileDocumentProvider(); IResource resource = match.getResource(); try { provider.connect(resource); IDocument document = provider.getDocument(resource); if (document != null) { String matchText = document.get(match.getOffset(), match.getLength()); Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText); if (matcher.find()) { usages.put(matcher.group(1), fqcn); } } } catch (Exception e) { AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName()); } finally { provider.disconnect(resource); } } } }; try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject); if (javaProject == null) { return null; } // Search for which java classes call setContentView(R.layout.layoutname); String typeFqcn = "R.layout"; //$NON-NLS-1$ if (mPackage != null) { typeFqcn = mPackage + '.' + typeFqcn; } IType activityType = javaProject.findType(CLASS_ACTIVITY); if (activityType != null) { IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$ if (method.exists()) { SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES); search(requestor, javaProject, pattern); } } } catch (CoreException e) { AdtPlugin.log(e, null); } } return mUsages.get(layoutName); } return null; }
From source file:com.android.ide.eclipse.auidt.internal.editors.manifest.ManifestInfo.java
License:Open Source License
/** * Returns the activity associated with the given layout file. * <p>//from w ww .j a v a 2 s . c o m * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas * guessActivity simply looks for references to "R.layout.foo", this method searches * for all usages of Activity#setContentView(int), and for each match it looks up the * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses * a regexp to pull out "foo" from this, and stores the association that layout "foo" * is associated with the activity class that contained the setContentView call. * <p> * This has two potential advantages: * <ol> * <li>It can be faster. We do the reference search -once-, and we've built a map of * all the layout-to-activity mappings which we can then immediately look up other * layouts for, which is particularly useful at startup when we have to compute the * layout activity associations to populate the theme choosers. * <li>It can be more accurate. Just because an activity references an "R.layout.foo" * field doesn't mean it's setting it as a content view. * </ol> * However, this second advantage is also its chief problem. There are some common * code constructs which means that the associated layout is not explicitly referenced * in a direct setContentView call; on a couple of sample projects I tested I found * patterns like for example "setContentView(v)" where "v" had been computed earlier. * Therefore, for now we're going to stick with the more general approach of just * looking up each field when needed. We're keeping the code around, though statically * compiled out with the "if (false)" construct below in case we revisit this. * * @param layoutFile the layout whose activity we want to look up * @return the activity name */ @SuppressWarnings("all") @Nullable public String guessActivityBySetContentView(String layoutName) { if (false) { // These should be fields final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$ Map<String, String> mUsages = null; sync(); if (mUsages == null) { final Map<String, String> usages = new HashMap<String, String>(); mUsages = usages; SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IMethod) { IMethod method = (IMethod) element; IType declaringType = method.getDeclaringType(); String fqcn = declaringType.getFullyQualifiedName(); IDocumentProvider provider = new TextFileDocumentProvider(); IResource resource = match.getResource(); try { provider.connect(resource); IDocument document = provider.getDocument(resource); if (document != null) { String matchText = document.get(match.getOffset(), match.getLength()); Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText); if (matcher.find()) { usages.put(matcher.group(1), fqcn); } } } catch (Exception e) { AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName()); } finally { provider.disconnect(resource); } } } }; try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject); if (javaProject == null) { return null; } // Search for which java classes call setContentView(R.layout.layoutname); String typeFqcn = "R.layout"; //$NON-NLS-1$ if (mPackage != null) { typeFqcn = mPackage + '.' + typeFqcn; } IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY); if (activityType != null) { IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$ if (method.exists()) { SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES); search(requestor, javaProject, pattern); } } } catch (CoreException e) { AdtPlugin.log(e, null); } } return mUsages.get(layoutName); } return null; }
From source file:edu.brown.cs.bubbles.bedrock.BedrockUtil.java
License:Open Source License
/********************************************************************************/ static void outputSearchMatch(SearchMatch mat, IvyXmlWriter xw) { xw.begin("MATCH"); xw.field("OFFSET", mat.getOffset()); xw.field("LENGTH", mat.getLength()); xw.field("STARTOFFSET", mat.getOffset()); xw.field("ENDOFFSET", mat.getOffset() + mat.getLength()); IResource irc = mat.getResource();/*from w w w . j a v a 2 s .c om*/ if (irc != null) { File f = mat.getResource().getLocation().toFile(); switch (irc.getType()) { case IResource.FILE: xw.field("FILE", f.toString()); break; case IResource.PROJECT: xw.field("PROJECT", f.toString()); break; case IResource.FOLDER: xw.field("FOLDER", f.toString()); break; case IResource.ROOT: xw.field("ROOT", f.toString()); break; } } xw.field("ACCURACY", mat.getAccuracy()); xw.field("EQUIV", mat.isEquivalent()); xw.field("ERASURE", mat.isErasure()); xw.field("EXACT", mat.isExact()); xw.field("IMPLICIT", mat.isImplicit()); xw.field("INDOCCMMT", mat.isInsideDocComment()); xw.field("RAW", mat.isRaw()); Object o = mat.getElement(); BedrockPlugin.logD("MATCH ELEMENT " + o); if (o instanceof IJavaElement) { IJavaElement nelt = (IJavaElement) o; outputJavaElement(nelt, false, xw); } xw.end("MATCH"); }
From source file:edu.illinois.compositerefactorings.refactorings.usesupertypeininstanceof.UseSuperTypeInInstanceOfRefactoring.java
License:Open Source License
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus result = new RefactoringStatus(); fChangeManager = new TextChangeManager(); for (Iterator<CompilationUnitRewrite> iter = fRewrites.values().iterator(); iter.hasNext();) { iter.next().clearASTAndImportRewrites(); }// www. ja v a2 s. c o m SearchPattern pattern = RefactoringSearchEngine.createOrPattern(new IJavaElement[] { fSubType }, IJavaSearchConstants.REFERENCES); IJavaSearchScope scope = RefactoringScopeFactory.create(fSubType, false); SearchResultGroup[] allReferences = RefactoringSearchEngine.search(pattern, scope, pm, result); SearchResultGroup[] references = Checks.excludeCompilationUnits(allReferences, result); if (result.hasFatalError()) { return result; } result.merge(Checks.checkCompileErrorsInAffectedFiles(references)); if (result.hasFatalError()) { return result; } for (int i = 0; i < references.length; ++i) { SearchResultGroup group = references[i]; SearchMatch[] searchResults = group.getSearchResults(); CompilationUnitRewrite currentCURewrite = getCachedCURewrite(group.getCompilationUnit()); for (int j = 0; j < searchResults.length; j++) { SearchMatch match = searchResults[j]; if (match.isInsideDocComment()) continue; ASTNode target = getSelectedNode(group.getCompilationUnit(), currentCURewrite.getRoot(), match.getOffset(), match.getLength()); if (target != null) { currentCURewrite.getImportRewrite().addImport(getSuperType().getFullyQualifiedName()); SimpleName superTypeName = currentCURewrite.getASTRewrite().getAST() .newSimpleName(getSuperType().getElementName()); SimpleType superTypeNode = currentCURewrite.getASTRewrite().getAST() .newSimpleType(superTypeName); currentCURewrite.getASTRewrite().replace(target, superTypeNode, null); } } createChangeAndDiscardRewrite(group.getCompilationUnit()); } result.merge(Checks.validateModifiesFiles(getAllFilesToModify(), getValidationContext())); return result; }
From source file:nz.ac.massey.cs.care.refactoring.executers.IntroduceFactoryRefactoring.java
License:Open Source License
/** * Use the given <code>ASTRewrite</code> to replace direct calls to the constructor * with calls to the newly-created factory method. * @param rg the <code>SearchResultGroup</code> indicating all of the constructor references * @param unit the <code>CompilationUnit</code> to be rewritten * @param unitRewriter the rewriter//from w ww . j a v a2 s .c o m * @param unitChange the compilation unit change * @throws CoreException * @return true iff at least one constructor call site was rewritten. */ private boolean replaceConstructorCalls(SearchResultGroup rg, CompilationUnit unit, ASTRewrite unitRewriter, CompilationUnitChange unitChange) throws CoreException { Assert.isTrue(ASTCreator.getCu(unit).equals(rg.getCompilationUnit())); SearchMatch[] hits = rg.getSearchResults(); Arrays.sort(hits, new Comparator<SearchMatch>() { /** * Sort by descending offset, such that nested constructor calls are processed first. * This is necessary, since they can only be moved into the factory method invocation * after they have been rewritten. */ public int compare(SearchMatch m1, SearchMatch m2) { return m2.getOffset() - m1.getOffset(); } }); boolean someCallPatched = false; for (int i = 0; i < hits.length; i++) { ASTNode ctrCall = getCtorCallAt(hits[i].getOffset(), hits[i].getLength(), unit); if (ctrCall instanceof ClassInstanceCreation) { TextEditGroup gd = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_replaceCalls); rewriteFactoryMethodCall((ClassInstanceCreation) ctrCall, unitRewriter, gd); unitChange.addTextEditGroup(gd); someCallPatched = true; } else if (ctrCall instanceof MethodRef) { TextEditGroup gd = new TextEditGroup( RefactoringCoreMessages.IntroduceFactoryRefactoring_replaceJavadocReference); rewriteJavadocReference((MethodRef) ctrCall, unitRewriter, gd); unitChange.addTextEditGroup(gd); someCallPatched = true; } } return someCallPatched; }
From source file:org.codehaus.groovy.eclipse.core.search.SyntheticMemberSearchTests.java
License:Apache License
/** * asserts that the given match exists at least once in the list * * @param matchName//from w w w . j a va 2s . c o m * @param contents * @param matches */ private void assertMatch(String enclosingName, String matchName, String contents, List<SearchMatch> matches) { int matchStart = 0; int matchIndex = 0; boolean matchFound = false; for (SearchMatch match : matches) { if (((IJavaElement) match.getElement()).getElementName().equals(enclosingName) && contents.indexOf(matchName, matchStart) == match.getOffset() && matchName.length() == match.getLength()) { matchFound = true; break; } matchIndex++; } if (!matchFound) { fail("Match name " + matchName + " not found in\n" + printMatches(matches)); } SearchMatch match = matches.remove(matchIndex); assertTrue("Match enclosing element does not exist", ((IJavaElement) match.getElement()).exists()); }
From source file:org.codehaus.groovy.eclipse.core.search.SyntheticMemberSearchTests.java
License:Apache License
private void assertNoMatch(String enclosingName, String matchName, String contents, List<SearchMatch> matches) { boolean matchFound = false; for (SearchMatch match : matches) { if (((IJavaElement) match.getElement()).getElementName().equals(enclosingName) && contents.indexOf(matchName) == match.getOffset() && matchName.length() == match.getLength()) { matchFound = true;//from ww w . j a v a2 s.com break; } } if (matchFound) { fail("Match name " + matchName + " was found, but should not have been.\n" + printMatches(matches)); } }
From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java
License:Open Source License
/** * Creates a Position from the supplied SearchMatch. * * @param project The project searching from. * @param match The SearchMatch.//from www .j a v a 2 s .c o m * @return The Position. */ protected Position createPosition(IProject project, SearchMatch match) throws Exception { IJavaElement element = (IJavaElement) match.getElement(); IJavaElement parent = JavaUtils.getPrimaryElement(element); String file = null; String elementName = JavaUtils.getFullyQualifiedName(parent); if (parent.getElementType() == IJavaElement.CLASS_FILE) { IResource resource = parent.getResource(); // occurs with a referenced project as a lib with no source and class // files that are not archived in that project if (resource != null && resource.getType() == IResource.FILE && !isJarArchive(resource.getLocation())) { file = resource.getLocation().toOSString(); } else { IPath path = null; IPackageFragmentRoot root = (IPackageFragmentRoot) parent.getParent().getParent(); resource = root.getResource(); if (resource != null) { if (resource.getType() == IResource.PROJECT) { path = ProjectUtils.getIPath((IProject) resource); } else { path = resource.getLocation(); } } else { path = root.getPath(); } String classFile = elementName.replace('.', File.separatorChar); if (isJarArchive(path)) { file = "jar:file://" + path.toOSString() + '!' + classFile + ".class"; } else { file = path.toOSString() + '/' + classFile + ".class"; } // android injects its jdk classes, so filter those out if the project // doesn't have the android nature. if (ANDROID_JDK_URL.matcher(file).matches() && project != null && !project.hasNature(ANDROID_NATURE)) { return null; } // if a source path attachment exists, use it. IPath srcPath = root.getSourceAttachmentPath(); if (srcPath != null) { String rootPath; IProject elementProject = root.getJavaProject().getProject(); // determine if src path is project relative or file system absolute. if (srcPath.isAbsolute() && elementProject.getName().equals(srcPath.segment(0))) { rootPath = ProjectUtils.getFilePath(elementProject, srcPath.toString()); } else { rootPath = srcPath.toOSString(); } String srcFile = FileUtils.toUrl(rootPath + File.separator + classFile + ".java"); // see if source file exists at source path. FileSystemManager fsManager = VFS.getManager(); FileObject fileObject = fsManager.resolveFile(srcFile.replace("%", "%25")); if (fileObject.exists()) { file = srcFile; // jdk sources on osx are under a "src/" dir in the jar } else if (Os.isFamily(Os.FAMILY_MAC)) { srcFile = FileUtils .toUrl(rootPath + File.separator + "src" + File.separator + classFile + ".java"); fileObject = fsManager.resolveFile(srcFile.replace("%", "%25")); if (fileObject.exists()) { file = srcFile; } } } } } else { IPath location = match.getResource().getLocation(); file = location != null ? location.toOSString() : null; } elementName = JavaUtils.getFullyQualifiedName(element); return Position.fromOffset(file.replace('\\', '/'), elementName, match.getOffset(), match.getLength()); }
From source file:org.eclipse.ajdt.core.tests.search.AbstractITDSearchTest.java
License:Open Source License
protected void assertMatch(String matchName, String contents, List<SearchMatch> matches) { // remove matches from inside import statements int matchStart = 0; if (matches.size() > 1) { SearchMatch match = matches.get(0); if (match.getElement() instanceof IImportDeclaration) { matches.remove(match);//from w ww .j a va 2s . c o m matchStart = match.getOffset() + match.getLength(); } } assertEquals("Should have found exactly 1 match, but instead found " + printMatches(matches), 1, matches.size()); SearchMatch match = matches.get(0); assertEquals("Wrong match location", contents.indexOf(matchName, matchStart), match.getOffset()); assertEquals("Wrong match length", matchName.length(), match.getLength()); assertTrue("Match enclosing element does not exist", ((IJavaElement) match.getElement()).exists()); // disabled because we can't get this right right now. // assertEquals("Expected exact match, but was potential", SearchMatch.A_ACCURATE, match.getAccuracy()); }
From source file:org.eclipse.ajdt.core.tests.search.AbstractITDSearchTest.java
License:Open Source License
protected void assertTwoMatches(String matchName, String contents, List<SearchMatch> matches) { assertEquals("Should have found exactly 2 matches, but instead found " + printMatches(matches), 2, matches.size());/* ww w. j av a 2 s . c o m*/ SearchMatch match = matches.get(0); assertEquals("Wrong match location", contents.indexOf(matchName), match.getOffset()); assertEquals("Wrong match length", matchName.length(), match.getLength()); match = (SearchMatch) matches.get(1); assertEquals("Wrong match location", contents.lastIndexOf(matchName), match.getOffset()); assertEquals("Wrong match length", matchName.length(), match.getLength()); // disabled because we can't get this right right now. // assertEquals("Expected exact match, but was potential", SearchMatch.A_ACCURATE, match.getAccuracy()); }