private Boolean doExecute(ReferencesSearch.SearchParameters queryParameters, final Processor<PsiReference> consumer) { final PsiElement element = queryParameters.getElementToSearch(); //was selector_identifier->redefined in DictionaryComponent dictionaryComponent = null; if (element instanceof DictionaryComponent) { dictionaryComponent = (DictionaryComponent) element; } if (dictionaryComponent == null) return true; final List<String> parts = dictionaryComponent.getNameIdentifiers(); if (parts.isEmpty()) return true; final String componentName = dictionaryComponent.getName(); //or just getName()... final PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(element.getProject()); String searchWord = parts.get(0); return searchWord.isEmpty() || helper.processElementsWithWord(new MyOccurrenceProcessor(dictionaryComponent, componentName, consumer), queryParameters.getScopeDeterminedByUser(), searchWord, UsageSearchContext.IN_CODE, true); }
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) { for (String key : keys) { final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>(); FileBasedIndexImpl.getInstance().getFilesWithKey(id, new HashSet<String>(Arrays.asList(key)), new Processor<VirtualFile>() { @Override public boolean process(VirtualFile virtualFile) { virtualFiles.add(virtualFile); return true; } }, GlobalSearchScope.allScope(getProject())); if(notCondition && virtualFiles.size() > 0) { fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key)); } else if(!notCondition && virtualFiles.size() == 0) { fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key)); } } }
@Override public boolean filterElements(@NotNull ChooseByNameBase base, @NotNull String pattern, boolean everywhere, @NotNull ProgressIndicator indicator, @NotNull Processor<Object> consumer) { Collection<SearchResultElement> elements = getAllFilterItems(); if (elements != null) { for (SearchResultElement element : elements) { String value = element.getValue(); if (value == null) { return false; } if (value.toLowerCase().contains(pattern.toLowerCase()) && !consumer.process(element)) { return false; } } } return false; }
@Override public boolean processPackageDirectories(@NotNull PsiPackage psiPackage, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiDirectory> consumer, boolean includeLibrarySources) { //System.out.println( "processDirectories() : " + psiPackage + " : " + scope ); final PsiManager psiManager = PsiManager.getInstance( _project ); return PackageIndex.getInstance( _project ) .getDirsByPackageName(psiPackage.getQualifiedName(), includeLibrarySources) .forEach(new ReadActionProcessor<VirtualFile>() { @Override public boolean processInReadAction(final VirtualFile dir) { if (!scope.contains(dir)) return true; PsiDirectory psiDir = psiManager.findDirectory(dir); return psiDir == null || consumer.process(psiDir); } }); }
private int findTagUsage(XmlTag element) { final FindUsagesHandler handler = FindUsageUtils.getFindUsagesHandler(element, element.getProject()); if (handler != null) { final FindUsagesOptions findUsagesOptions = handler.getFindUsagesOptions(); final PsiElement[] primaryElements = handler.getPrimaryElements(); final PsiElement[] secondaryElements = handler.getSecondaryElements(); Factory factory = new Factory() { public UsageSearcher create() { return FindUsageUtils.createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, (PsiFile) null); } }; UsageSearcher usageSearcher = (UsageSearcher)factory.create(); final AtomicInteger mCount = new AtomicInteger(0); usageSearcher.generate(new Processor<Usage>() { @Override public boolean process(Usage usage) { if (ResourceUsageCountUtils.isUsefulUsageToCount(usage)) { mCount.incrementAndGet(); } return true; } }); return mCount.get(); } return 0; }
@Override public boolean processTextOccurrence(@NotNull final PsiElement element, int offsetInElement, @NotNull Processor<PsiReference> consumer) { String alias = getAlias(element); if (alias == null) return true; final PsiReference reference = element.getReference(); if (reference == null) { return true; } if (!reference.isReferenceTo(myTarget instanceof GrAccessorMethod ? ((GrAccessorMethod)myTarget).getProperty() : myTarget)) { return true; } final SearchRequestCollector collector = new SearchRequestCollector(mySession); final SearchScope fileScope = new LocalSearchScope(element.getContainingFile()); collector.searchWord(alias, fileScope, UsageSearchContext.IN_CODE, true, myTarget); if (prefix != null) { collector.searchWord(prefix + GroovyPropertyUtils.capitalize(alias), fileScope, UsageSearchContext.IN_CODE, true, myTarget); } return PsiSearchHelper.SERVICE.getInstance(element.getProject()).processRequests(collector, consumer); }
@Override public boolean getBaseVersionContent(FilePath filePath, Processor<CharSequence> processor, final String beforeVersionId, List<String> warnings) throws VcsException { if (StringUtil.isEmptyOrSpaces(beforeVersionId) || filePath.getVirtualFile() == null) return false; // apply if base revision id matches revision final VirtualFile root = GitUtil.getGitRoot(filePath); if (root == null) return false; final SHAHash shaHash = GitChangeUtils.commitExists(myProject, root, beforeVersionId, null, "HEAD"); if (shaHash == null) { throw new VcsException("Can not apply patch to " + filePath.getPath() + ".\nCan not find revision '" + beforeVersionId + "'."); } final ContentRevision content = GitVcs.getInstance(myProject).getDiffProvider() .createFileContent(new GitRevisionNumber(shaHash.getValue()), filePath.getVirtualFile()); if (content == null) { throw new VcsException("Can not load content of '" + filePath.getPath() + "' for revision '" + shaHash.getValue() + "'"); } return ! processor.process(content.getContent()); }
@NotNull public static Set<MavenDomDependency> searchDependencyUsages(@NotNull final MavenDomProjectModel model, @NotNull final DependencyConflictId dependencyId, @NotNull final Set<MavenDomDependency> excludes) { Project project = model.getManager().getProject(); final Set<MavenDomDependency> usages = new HashSet<MavenDomDependency>(); Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() { public boolean process(MavenDomProjectModel mavenDomProjectModel) { for (MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) { if (excludes.contains(domDependency)) continue; if (dependencyId.equals(DependencyConflictId.create(domDependency))) { usages.add(domDependency); } } return false; } }; processChildrenRecursively(model, collectProcessor, project, new HashSet<MavenDomProjectModel>(), true); return usages; }
@NotNull protected final Object[] buildChildren(@NotNull final HierarchyNodeDescriptor descriptor) { final Object element = ((TypeHierarchyNodeDescriptor)descriptor).getPsiClass(); if (!(element instanceof PsiClass)) return ArrayUtil.EMPTY_OBJECT_ARRAY; final PsiClass psiClass = (PsiClass)element; if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) { return new Object[]{IdeBundle.message("node.hierarchy.java.lang.object")}; } if (psiClass instanceof PsiAnonymousClass) return ArrayUtil.EMPTY_OBJECT_ARRAY; if (psiClass.hasModifierProperty(PsiModifier.FINAL)) return ArrayUtil.EMPTY_OBJECT_ARRAY; final SearchScope searchScope = psiClass.getUseScope().intersectWith(getSearchScope(myCurrentScopeType, psiClass)); final List<PsiClass> classes = new ArrayList<PsiClass>(ClassInheritorsSearch.search(psiClass, searchScope, false).findAll()); final List<HierarchyNodeDescriptor> descriptors = new ArrayList<HierarchyNodeDescriptor>(classes.size()); for (PsiClass aClass : classes) { descriptors.add(new TypeHierarchyNodeDescriptor(myProject, descriptor, aClass, false)); } FunctionalExpressionSearch.search(psiClass, searchScope).forEach(new Processor<PsiFunctionalExpression>() { @Override public boolean process(PsiFunctionalExpression expression) { descriptors.add(new TypeHierarchyNodeDescriptor(myProject, descriptor, expression, false)); return true; } }); return descriptors.toArray(new HierarchyNodeDescriptor[descriptors.size()]); }
@NotNull private static Set<VirtualFile> getVirtualFilesByNameIgnoringCase(@NotNull final String name, @NotNull final GlobalSearchScope scope, @Nullable final IdFilter idFilter) { final Set<String> keys = new THashSet<String>(); final FileBasedIndex index = FileBasedIndex.getInstance(); index.processAllKeys(NAME, new Processor<String>() { @Override public boolean process(String value) { if (name.equalsIgnoreCase(value)) { keys.add(value); } return true; } }, scope, idFilter); // values accessed outside of provessAllKeys final Set<VirtualFile> files = new THashSet<VirtualFile>(); for (String each : keys) { files.addAll(index.getContainingFiles(NAME, each, scope)); } return files; }
@Override public <Key, Psi extends PsiElement> boolean processElements(@NotNull final StubIndexKey<Key, Psi> indexKey, @NotNull final Key key, @NotNull final Project project, @Nullable final GlobalSearchScope scope, @Nullable IdFilter idFilter, @NotNull final Class<Psi> requiredClass, @NotNull final Processor<? super Psi> processor) { return doProcessStubs(indexKey, key, project, scope, new StubIdListContainerAction(idFilter, project) { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); @Override protected boolean process(int id, StubIdList value) { final VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file == null || scope != null && !scope.contains(file)) { return true; } return myStubProcessingHelper.processStubsInFile(project, file, value, processor, requiredClass); } }); }
private static void copyUnversionedMembersOfDirectory(final File src, final File dst) throws SvnBindException { if (src.isDirectory()) { final SvnBindException[] exc = new SvnBindException[1]; FileUtil.processFilesRecursively(src, new Processor<File>() { @Override public boolean process(File file) { String relativePath = FileUtil.getRelativePath(src, file); File newFile = new File(dst, relativePath); if (!newFile.exists()) { try { FileUtil.copyFileOrDir(src, dst); } catch (IOException e) { exc[0] = new SvnBindException(e); return false; } } return true; } }); if (exc[0] != null) { throw exc[0]; } } }
public String fun(final PyFunction pyFunction) { final StringBuilder builder = new StringBuilder("<html>Is overridden in:"); final AtomicInteger count = new AtomicInteger(); PyClassInheritorsSearch.search(pyFunction.getContainingClass(), true).forEach(new Processor<PyClass>() { public boolean process(PyClass pyClass) { if (count.incrementAndGet() >= 10) { builder.setLength(0); builder.append("Has overridden methods"); return false; } if (pyClass.findMethodByName(pyFunction.getName(), false) != null) { builder.append("<br> ").append(pyClass.getName()); } return true; } }); return builder.toString(); }
/** * Process control flow graph in depth first order */ public static boolean process(final Instruction[] flow, final int start, final Processor<Instruction> processor){ final int length = flow.length; boolean[] visited = new boolean[length]; Arrays.fill(visited, false); final IntStack stack = new IntStack(length); stack.push(start); while (!stack.empty()) { ProgressManager.checkCanceled(); final int num = stack.pop(); final Instruction instruction = flow[num]; if (!processor.process(instruction)){ return false; } for (Instruction succ : instruction.allSucc()) { final int succNum = succ.num(); if (!visited[succNum]) { visited[succNum] = true; stack.push(succNum); } } } return true; }
@Override protected VirtualFile[] computeFiles(final PsiFile file, final boolean compileTimeOnly) { final Set<VirtualFile> files = new THashSet<VirtualFile>(); processIncludes(file, new Processor<FileIncludeInfo>() { @Override public boolean process(FileIncludeInfo info) { if (compileTimeOnly != info.runtimeOnly) { PsiFileSystemItem item = resolveFileInclude(info, file); if (item != null) { ContainerUtil.addIfNotNull(files, item.getVirtualFile()); } } return true; } }); return VfsUtilCore.toVirtualFileArray(files); }
@NotNull private List<InspectionContext> visitPriorityElementsAndInit(@NotNull Map<LocalInspectionToolWrapper, Set<String>> toolToSpecifiedLanguageIds, @NotNull final InspectionManager iManager, final boolean isOnTheFly, @NotNull final ProgressIndicator indicator, @NotNull final List<PsiElement> elements, @NotNull final LocalInspectionToolSession session, @NotNull List<LocalInspectionToolWrapper> wrappers, @NotNull final Set<String> elementDialectIds) { final List<InspectionContext> init = new ArrayList<InspectionContext>(); List<Map.Entry<LocalInspectionToolWrapper, Set<String>>> entries = new ArrayList<Map.Entry<LocalInspectionToolWrapper, Set<String>>>(toolToSpecifiedLanguageIds.entrySet()); Processor<Map.Entry<LocalInspectionToolWrapper, Set<String>>> processor = new Processor<Map.Entry<LocalInspectionToolWrapper, Set<String>>>() { @Override public boolean process(final Map.Entry<LocalInspectionToolWrapper, Set<String>> pair) { LocalInspectionToolWrapper toolWrapper = pair.getKey(); Set<String> dialectIdsSpecifiedForTool = pair.getValue(); return runToolOnElements(toolWrapper, dialectIdsSpecifiedForTool, iManager, isOnTheFly, indicator, elements, session, init, elementDialectIds); } }; boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(entries, indicator, myFailFastOnAcquireReadAction, processor); if (!result) throw new ProcessCanceledException(); inspectInjectedPsi(elements, isOnTheFly, indicator, iManager, true, wrappers); return init; }
private static boolean processStringLiteralsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope, PsiSearchHelper helper, final Processor<PsiElement> processor) { TextOccurenceProcessor occurenceProcessor = new TextOccurenceProcessor() { @Override public boolean execute(@NotNull PsiElement element, int offsetInElement) { final ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(element.getLanguage()); final ASTNode node = element.getNode(); if (definition != null && node != null && definition.getStringLiteralElements().contains(node.getElementType())) { return processor.process(element); } return true; } }; return helper.processElementsWithWord(occurenceProcessor, searchScope, identifier, UsageSearchContext.IN_STRINGS, true); }
public void testUnbalancedTaskJobUtilPerformance() { List<Integer> things = new ArrayList<Integer>(Collections.<Integer>nCopies(10000, null)); int sum = 0; for (int i = 0; i < things.size(); i++) { int v = i < 9950 ? 1 : 1000; things.set(i, v); sum += things.get(i); } assertEquals(59950, sum); long start = System.currentTimeMillis(); boolean b = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(things, new ProgressIndicatorBase(), false, false, new Processor<Integer>() { @Override public boolean process(Integer o) { busySleep(o); return true; } }); assertTrue(b); long elapsed = System.currentTimeMillis() - start; int expected = 2 * (9950 + 50 * 1000) / JobSchedulerImpl.CORES_COUNT; String message = "Elapsed: " + elapsed + "; expected: " + expected; System.out.println(message); assertTrue(message, elapsed < expected); }
@NotNull public static Collection<MavenDomPlugin> searchManagedPluginUsages(@NotNull final MavenDomProjectModel model, @Nullable final String groupId, @NotNull final String artifactId) { Project project = model.getManager().getProject(); final Set<MavenDomPlugin> usages = new HashSet<MavenDomPlugin>(); Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() { public boolean process(MavenDomProjectModel mavenDomProjectModel) { for (MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) { if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { usages.add(domPlugin); } } return false; } }; processChildrenRecursively(model, collectProcessor, project, new HashSet<MavenDomProjectModel>(), true); return usages; }
private static boolean processSameNamedClasses(Processor<PsiClass> consumer, List<PsiClass> sameNamedClasses, final VirtualFile jarFile) { // if there is a class from the same jar, prefer it boolean sameJarClassFound = false; if (jarFile != null && sameNamedClasses.size() > 1) { for (PsiClass sameNamedClass : sameNamedClasses) { ProgressManager.checkCanceled(); boolean fromSameJar = Comparing.equal(getJarFile(sameNamedClass), jarFile); if (fromSameJar) { sameJarClassFound = true; if (!consumer.process(sameNamedClass)) return false; } } } return sameJarClassFound || ContainerUtil.process(sameNamedClasses, consumer); }
@Override public void processQuery(@NotNull MethodReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) { final PsiMethod method = queryParameters.getMethod(); final String propertyName; if (GdkMethodUtil.isCategoryMethod(method, null, null, PsiSubstitutor.EMPTY)) { final GrGdkMethod cat = GrGdkMethodImpl.createGdkMethod(method, false, null); propertyName = GroovyPropertyUtils.getPropertyName((PsiMethod)cat); } else { propertyName = GroovyPropertyUtils.getPropertyName(method); } if (propertyName == null) return; final SearchScope onlyGroovyFiles = GroovyScopeUtil.restrictScopeToGroovyFiles(queryParameters.getEffectiveSearchScope(), GroovyScopeUtil.getEffectiveScope(method)); queryParameters.getOptimizer().searchWord(propertyName, onlyGroovyFiles, UsageSearchContext.IN_CODE, true, method); if (!GroovyPropertyUtils.isPropertyName(propertyName)) { queryParameters.getOptimizer().searchWord(StringUtil.decapitalize(propertyName), onlyGroovyFiles, UsageSearchContext.IN_CODE, true, method); } }
@Override public void clear() { l.writeLock().lock(); process(new Processor<T>() { @Override public boolean process(T t) { beforeRemove(t, "Clear all"); return true; } }); try { super.clear(); keySize = 0; } finally { l.writeLock().unlock(); } }
private boolean processAbbreviations(final String pattern, Processor<MatchedValue> consumer, DataContext context) { List<String> actions = AbbreviationManager.getInstance().findActions(pattern); if (actions.isEmpty()) return true; List<ActionWrapper> wrappers = ContainerUtil.newArrayListWithCapacity(actions.size()); for (String actionId : actions) { AnAction action = myActionManager.getAction(actionId); wrappers.add(new ActionWrapper(action, myModel.myActionGroups.get(action), MatchMode.NAME, context)); } return ContainerUtil.process(ContainerUtil.map(wrappers, new Function<ActionWrapper, MatchedValue>() { @Override public MatchedValue fun(@NotNull ActionWrapper w) { return new MatchedValue(w, pattern) { @Nullable @Override public String getValueText() { return pattern; } }; } }), consumer); }
private HighlightInfo findInfo(Project project, Editor editor, final int caretOffset, HighlightSeverity minSeverity) { final Document document = editor.getDocument(); final HighlightInfo[][] infoToGo = new HighlightInfo[2][2]; //HighlightInfo[luck-noluck][skip-noskip] final int caretOffsetIfNoLuck = myGoForward ? -1 : document.getTextLength(); DaemonCodeAnalyzerEx.processHighlights(document, project, minSeverity, 0, document.getTextLength(), new Processor<HighlightInfo>() { @Override public boolean process(HighlightInfo info) { int startOffset = getNavigationPositionFor(info, document); if (SeverityRegistrar.isGotoBySeverityEnabled(info.getSeverity())) { infoToGo[0][0] = getBetterInfoThan(infoToGo[0][0], caretOffset, startOffset, info); infoToGo[1][0] = getBetterInfoThan(infoToGo[1][0], caretOffsetIfNoLuck, startOffset, info); } infoToGo[0][1] = getBetterInfoThan(infoToGo[0][1], caretOffset, startOffset, info); infoToGo[1][1] = getBetterInfoThan(infoToGo[1][1], caretOffsetIfNoLuck, startOffset, info); return true; } }); if (infoToGo[0][0] == null) infoToGo[0][0] = infoToGo[1][0]; if (infoToGo[0][1] == null) infoToGo[0][1] = infoToGo[1][1]; if (infoToGo[0][0] == null) infoToGo[0][0] = infoToGo[0][1]; return infoToGo[0][0]; }
@Override public void processQuery(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final Processor<PsiReference> consumer) { new ReadAction() { @Override protected void run(@NotNull final Result result) throws Throwable { final PsiElement refElement = queryParameters.getElementToSearch(); if (PyMagicLiteralTools.isMagicLiteral(refElement)) { final String refText = ((StringLiteralExpression)refElement).getStringValue(); if (!StringUtil.isEmpty(refText)) { final SearchScope searchScope = queryParameters.getEffectiveSearchScope(); queryParameters.getOptimizer().searchWord(refText, searchScope, true, refElement); } } } }.execute(); }
@NotNull private static MultiMap<DependencyConflictId, MavenDomDependency> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) { final MultiMap<DependencyConflictId, MavenDomDependency> allDependencies = MultiMap.createSet(); Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() { public boolean process(MavenDomProjectModel model) { collect(allDependencies, model.getDependencies()); return false; } }; MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true); MavenDomProjectProcessorUtils.processParentProjects(projectModel, collectProcessor); return allDependencies; }
public static void processWsdlSchemas(final XmlTag rootTag, Processor<XmlTag> processor) { if ("definitions".equals(rootTag.getLocalName())) { final String nsPrefix = rootTag.getNamespacePrefix(); final String types = nsPrefix.isEmpty() ? "types" : nsPrefix + ":types"; final XmlTag subTag = rootTag.findFirstSubTag(types); if (subTag != null) { for (int i = 0; i < XmlUtil.SCHEMA_URIS.length; i++) { final XmlTag[] tags = subTag.findSubTags("schema", XmlUtil.SCHEMA_URIS[i]); for (XmlTag t : tags) { if (!processor.process(t)) return; } } } } }
private static boolean processFilesContainingAllKeys(@NotNull Project project, @NotNull final GlobalSearchScope scope, @Nullable final Condition<Integer> checker, @NotNull final Collection<IdIndexEntry> keys, @NotNull final Processor<VirtualFile> processor) { final FileIndexFacade index = FileIndexFacade.getInstance(project); return DumbService.getInstance(project).runReadActionInSmartMode(new Computable<Boolean>() { @Override public Boolean compute() { return FileBasedIndex.getInstance().processFilesContainingAllKeys(IdIndex.NAME, keys, scope, checker, new Processor<VirtualFile>() { @Override public boolean process(VirtualFile file) { return !index.shouldBeFound(scope, file) || processor.process(file); } }); } }); }
@Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { // here we only detect package movement and update relative names of components in manifest, don't change the current element if (!(element instanceof PsiPackage) || !(myElement instanceof XmlAttributeValue)) { throw new IncorrectOperationException("Cannot bind to " + element); } final String newPackageName = ((PsiPackage)element).getQualifiedName(); final String basePackage = ((XmlAttributeValue)myElement).getValue(); final String oldPackageName = myElement.getText().substring(myReferenceSet.myStartInElement, myTextRange.getEndOffset()); final PsiFile file = myElement.getContainingFile(); if (basePackage.length() > 0 && file instanceof XmlFile) { AndroidApplicationPackageRenameProcessor.processAllAttributesToUpdate( (XmlFile)file, basePackage, oldPackageName, newPackageName, new Processor<Pair<GenericAttributeValue, String>>() { @Override public boolean process(Pair<GenericAttributeValue, String> pair) { pair.getFirst().setStringValue(pair.getSecond()); return true; } }); } return myElement; }
@Override public void prepareRenaming(PsiElement element, final String newName, final Map<PsiElement, String> allRenames, SearchScope scope) { final PsiMethod method = (PsiMethod) element; OverridingMethodsSearch.search(method, scope, true).forEach(new Processor<PsiMethod>() { public boolean process(PsiMethod overrider) { if (overrider instanceof PsiMirrorElement) { final PsiElement prototype = ((PsiMirrorElement)overrider).getPrototype(); if (prototype instanceof PsiMethod) { overrider = (PsiMethod)prototype; } } if (overrider instanceof SyntheticElement) return true; final String overriderName = overrider.getName(); final String baseName = method.getName(); final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName); if (newOverriderName != null) { RenameProcessor.assertNonCompileElement(overrider); allRenames.put(overrider, newOverriderName); } return true; } }); }
public PsiMethodPattern definedInClass(final ElementPattern<? extends PsiClass> pattern) { return with(new PatternConditionPlus<PsiMethod, PsiClass>("definedInClass", pattern) { @Override public boolean processValues(PsiMethod t, final ProcessingContext context, final PairProcessor<PsiClass, ProcessingContext> processor) { if (!processor.process(t.getContainingClass(), context)) return false; final Ref<Boolean> result = Ref.create(Boolean.TRUE); SuperMethodsSearch.search(t, null, true, false).forEach(new Processor<MethodSignatureBackedByPsiMethod>() { @Override public boolean process(final MethodSignatureBackedByPsiMethod signature) { if (!processor.process(signature.getMethod().getContainingClass(), context)) { result.set(Boolean.FALSE); return false; } return true; } }); return result.get(); } }); }
private static void reportHierarchyInconsistency(@NotNull PsiClass superClass, @NotNull PsiClass derivedClass, @NotNull Set<PsiClass> visited) { final StringBuilder msg = new StringBuilder("Super: " + classInfo(superClass)); msg.append("visited:\n"); for (PsiClass aClass : visited) { msg.append(" each: " + classInfo(aClass)); } msg.append("isInheritor: " + InheritanceUtil.isInheritorOrSelf(derivedClass, superClass, true) + " " + derivedClass.isInheritor(superClass, true)); msg.append("\nhierarchy:\n"); InheritanceUtil.processSupers(derivedClass, true, new Processor<PsiClass>() { @Override public boolean process(PsiClass psiClass) { msg.append("each: " + classInfo(psiClass)); return true; } }); LOG.error(msg.toString()); }
@NotNull @Override public Object[] getVariants() { final String name = getContainingFile().getName(); final PsiClass superProvider = JavaPsiFacade.getInstance(getProject()).findClass(name, getResolveScope()); if (superProvider != null) { final List<Object> result = new ArrayList<Object>(); ClassInheritorsSearch.search(superProvider).forEach(new Processor<PsiClass>() { @Override public boolean process(PsiClass psiClass) { if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { final String jvmClassName = ClassUtil.getJVMClassName(psiClass); if (jvmClassName != null) { result.add(LookupElementBuilder.create(psiClass, jvmClassName)); } } return true; } }); return ArrayUtil.toObjectArray(result); } return ArrayUtil.EMPTY_OBJECT_ARRAY; }
private static Processor<PsiLanguageInjectionHost> getAnnotationFixer(@NotNull final Project project, @NotNull final String languageId) { return new Processor<PsiLanguageInjectionHost>() { @Override public boolean process(@Nullable PsiLanguageInjectionHost host) { if (host == null) return false; final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); boolean allowed = configuration.isSourceModificationAllowed(); configuration.setSourceModificationAllowed(true); try { return doInject(languageId, host, host); } finally { configuration.setSourceModificationAllowed(allowed); } } }; }
private static boolean processConstructors(final PsiMethod searchedConstructor, final Processor<PsiReference> consumer, final PsiClass clazz, final boolean processThisRefs) { final PsiMethod[] constructors = clazz.getConstructors(); if (constructors.length == 0) { processImplicitConstructorCall(clazz, consumer, searchedConstructor); } for (PsiMethod constructor : constructors) { if (!(constructor instanceof GrMethod)) continue; final GrOpenBlock block = ((GrMethod)constructor).getBlock(); if (block != null) { final GrStatement[] statements = block.getStatements(); if (statements.length > 0 && statements[0] instanceof GrConstructorInvocation) { final GrConstructorInvocation invocation = (GrConstructorInvocation)statements[0]; if (invocation.isThisCall() == processThisRefs && invocation.getManager().areElementsEquivalent(invocation.resolveMethod(), searchedConstructor) && !consumer.process(invocation.getInvokedExpression())) { return false; } } else { processImplicitConstructorCall(constructor, consumer, searchedConstructor); } } } return true; }
@NotNull @Override public Object[] getVariants() { final PsiClass viewClass = JavaPsiFacade.getInstance(myElement.getProject()) .findClass(AndroidUtils.VIEW_CLASS_NAME, myFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false)); if (viewClass == null) { return EMPTY_ARRAY; } final Set<Object> shortNames = new HashSet<Object>(); ClassInheritorsSearch.search(viewClass, myFacet.getModule().getModuleWithDependenciesScope(), true). forEach(new Processor<PsiClass>() { @Override public boolean process(PsiClass aClass) { final String name = aClass.getName(); if (name != null) { shortNames.add(JavaLookupElementBuilder.forClass(aClass, name, true)); } return true; } }); return shortNames.toArray(); }
private static boolean processReferencesInFiles(List<PsiFile> files, PsiManager psiManager, String baseName, PsiElement element, LocalSearchScope filterScope, Processor<PsiReference> processor) { psiManager.startBatchFilesProcessingMode(); try { for (PsiFile file : files) { ProgressManager.checkCanceled(); if (file.getFileType() != StdFileTypes.GUI_DESIGNER_FORM) continue; if (!processReferences(processor, file, baseName, element, filterScope)) return false; } } finally { psiManager.finishBatchFilesProcessingMode(); } return true; }
private static boolean processChildren(Module module, Processor<Object> processor) { final PsiManager psiManager = PsiManager.getInstance(module.getProject()); ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); VirtualFile[] roots = moduleRootManager.getContentRoots(); for (final VirtualFile root : roots) { final PsiDirectory psiDirectory = ApplicationManager.getApplication().runReadAction( new Computable<PsiDirectory>() { @Override public PsiDirectory compute() { return psiManager.findDirectory(root); } } ); if (psiDirectory != null) { if (!processor.process(psiDirectory)) return false; } } return true; }
@Override public boolean execute(@NotNull final ReferencesSearch.SearchParameters queryParameters, @NotNull final Processor<PsiReference> consumer) { return new ReadAction<Boolean>() { protected void run(@NotNull final Result<Boolean> result) { result.setResult(doExecute(queryParameters, consumer)); } }.execute().getResultObject(); }