@NotNull private static PsiClass[] getSupersInner(@NotNull PsiClass psiClass) { PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes(); PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes(); if (psiClass.isInterface()) { return resolveClassReferenceList( extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), true); } if (psiClass instanceof PsiAnonymousClass) { PsiAnonymousClass psiAnonymousClass = (PsiAnonymousClass) psiClass; PsiClassType baseClassReference = psiAnonymousClass.getBaseClassType(); PsiClass baseClass = baseClassReference.resolve(); if (baseClass != null) { if (baseClass.isInterface()) { PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass, baseClass} : new PsiClass[] {baseClass}; } return new PsiClass[] {baseClass}; } PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY; } if (psiClass instanceof PsiTypeParameter) { if (extendsListTypes.length == 0) { final PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY; } return resolveClassReferenceList( extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false); } PsiClass[] interfaces = resolveClassReferenceList( implementsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false); PsiClass superClass = getSuperClass(psiClass); if (superClass == null) return interfaces; PsiClass[] types = new PsiClass[interfaces.length + 1]; types[0] = superClass; System.arraycopy(interfaces, 0, types, 1, interfaces.length); return types; }
private static String compoundLambdaOrMethodReference( PsiParameter parameter, PsiExpression expression, String samQualifiedName, PsiType[] samParamTypes) { String result = ""; final Project project = parameter.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass functionClass = psiFacade.findClass(samQualifiedName, GlobalSearchScope.allScope(project)); for (int i = 0; i < samParamTypes.length; i++) { if (samParamTypes[i] instanceof PsiPrimitiveType) { samParamTypes[i] = ((PsiPrimitiveType) samParamTypes[i]).getBoxedType(expression); } } final PsiClassType functionalInterfaceType = functionClass != null ? psiFacade.getElementFactory().createType(functionClass, samParamTypes) : null; final PsiParameter[] parameters = {parameter}; final String methodReferenceText = LambdaCanBeMethodReferenceInspection.convertToMethodReference( expression, parameters, functionalInterfaceType, null); if (methodReferenceText != null) { LOG.assertTrue(functionalInterfaceType != null); result += "(" + functionalInterfaceType.getCanonicalText() + ")" + methodReferenceText; } else { result += parameter.getName() + " -> " + expression.getText(); } return result; }
@Nullable private MoveDestination selectDestination() { final String packageName = getTargetPackage().trim(); if (packageName.length() > 0 && !JavaPsiFacade.getInstance(myManager.getProject()) .getNameHelper() .isQualifiedName(packageName)) { Messages.showErrorDialog( myProject, RefactoringBundle.message("please.enter.a.valid.target.package.name"), RefactoringBundle.message("move.title")); return null; } RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, packageName); PackageWrapper targetPackage = new PackageWrapper(myManager, packageName); if (!targetPackage.exists()) { final int ret = Messages.showYesNoDialog( myProject, RefactoringBundle.message("package.does.not.exist", packageName), RefactoringBundle.message("move.title"), Messages.getQuestionIcon()); if (ret != 0) return null; } return ((DestinationFolderComboBox) myDestinationFolderCB).selectDirectory(targetPackage, true); }
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { try { PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement(); IElementType opSign = binaryExpression.getOperationSign().getTokenType(); PsiExpression lExpr = binaryExpression.getLOperand(); PsiExpression rExpr = binaryExpression.getROperand(); if (rExpr == null) return; PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); PsiMethodCallExpression equalsCall = (PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null); equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr); equalsCall.getArgumentList().getExpressions()[0].replace(rExpr); PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall); if (opSign == JavaTokenType.NE) { PsiPrefixExpression negation = (PsiPrefixExpression) factory.createExpressionFromText("!a", null); negation.getOperand().replace(result); result.replace(negation); } } catch (IncorrectOperationException e) { LOG.error(e); } }
public void testAllInPackageForProject() throws IOException, ExecutionException { // module1 -> module2 -> module3 // module5 addModule("module5"); addDependency(getModule1(), getModule2()); addDependency(getModule2(), getModule3()); String[][] outputs = new String[4][]; for (int i = 0; i < 4; i++) { outputs[i] = addOutputs(getModule(i), i + 1); } PsiPackage defaultPackage = JavaPsiFacade.getInstance(myProject).findPackage(""); JUnitConfiguration configuration = createJUnitConfiguration( defaultPackage, AllInPackageConfigurationProducer.class, new MapDataContext()); configuration.getPersistentData().setScope(TestSearchScope.WHOLE_PROJECT); JavaParameters javaParameters = checkCanRun(configuration); String classPath = javaParameters.getClassPath().getPathsString(); assertEquals(-1, classPath.indexOf(JarFileSystem.PROTOCOL_PREFIX)); assertEquals(-1, classPath.indexOf(LocalFileSystem.PROTOCOL_PREFIX)); for (int i = 0; i < 4; i++) { checkContains(classPath, outputs[i][0]); checkContains(classPath, outputs[i][1]); } }
public void testCantCreateConfiguration() { PsiClass objectClass = JavaPsiFacade.getInstance(myProject) .findClass(CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(myProject)); assertNull(createConfiguration(objectClass)); assertNull(createConfiguration(JUnitUtil.getContainingPackage(objectClass))); }
@NotNull private static PsiClass[] resolveClassReferenceList( @NotNull PsiClassType[] listOfTypes, @NotNull PsiManager manager, @NotNull GlobalSearchScope resolveScope, boolean includeObject) { PsiClass objectClass = JavaPsiFacade.getInstance(manager.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); if (objectClass == null) includeObject = false; if (listOfTypes.length == 0) { if (includeObject) return new PsiClass[] {objectClass}; return PsiClass.EMPTY_ARRAY; } int referenceCount = listOfTypes.length; if (includeObject) referenceCount++; PsiClass[] resolved = new PsiClass[referenceCount]; int resolvedCount = 0; if (includeObject) resolved[resolvedCount++] = objectClass; for (PsiClassType reference : listOfTypes) { PsiClass refResolved = reference.resolve(); if (refResolved != null) resolved[resolvedCount++] = refResolved; } if (resolvedCount < referenceCount) { PsiClass[] shorter = new PsiClass[resolvedCount]; System.arraycopy(resolved, 0, shorter, 0, resolvedCount); resolved = shorter; } return resolved; }
private boolean isTrivial(PsiMethod method) { final PsiCodeBlock body = method.getBody(); if (body == null) { return true; } final PsiStatement[] statements = body.getStatements(); if (statements.length == 0) { return true; } final Project project = method.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiConstantEvaluationHelper evaluationHelper = psiFacade.getConstantEvaluationHelper(); for (PsiStatement statement : statements) { if (!(statement instanceof PsiIfStatement)) { return false; } final PsiIfStatement ifStatement = (PsiIfStatement) statement; final PsiExpression condition = ifStatement.getCondition(); final Object result = evaluationHelper.computeConstantExpression(condition); if (result == null || !result.equals(Boolean.FALSE)) { return false; } } return true; }
@Nullable public static PsiClass getSuperClass(@NotNull PsiClass psiClass) { PsiManager manager = psiClass.getManager(); GlobalSearchScope resolveScope = psiClass.getResolveScope(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); if (psiClass.isInterface()) { return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); } if (psiClass.isEnum()) { return facade.findClass(CommonClassNames.JAVA_LANG_ENUM, resolveScope); } if (psiClass instanceof PsiAnonymousClass) { PsiClassType baseClassReference = ((PsiAnonymousClass) psiClass).getBaseClassType(); PsiClass baseClass = baseClassReference.resolve(); if (baseClass == null || baseClass.isInterface()) return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); return baseClass; } if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) return null; final PsiClassType[] referenceElements = psiClass.getExtendsListTypes(); if (referenceElements.length == 0) return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); PsiClass psiResoved = referenceElements[0].resolve(); return psiResoved == null ? facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope) : psiResoved; }
@Nullable private LocalQuickFix[] createNPEFixes( PsiExpression qualifier, PsiExpression expression, boolean onTheFly) { if (qualifier == null || expression == null) return null; if (qualifier instanceof PsiMethodCallExpression) return null; if (qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression) qualifier).getValue() == null) return null; try { final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>(); if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) { final Project project = qualifier.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiBinaryExpression binary = (PsiBinaryExpression) elementFactory.createExpressionFromText("a != null", null); binary.getLOperand().replace(qualifier); fixes.add(new AddAssertStatementFix(binary)); } addSurroundWithIfFix(qualifier, fixes, onTheFly); if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) { fixes.add(new ReplaceWithTernaryOperatorFix(qualifier)); } return fixes.toArray(new LocalQuickFix[fixes.size()]); } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
public AddModuleDependencyFix( Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) { final PsiElement psiElement = reference.getElement(); final Project project = psiElement.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.add(classModule); } } myCurrentModule = currentModule; myClassVFile = classVFile; myClasses = classes; myReference = reference; }
private static PsiClassType createDefaultConsumerType(Project project, PsiParameter parameter) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass consumerClass = psiFacade.findClass("java.util.function.Consumer", GlobalSearchScope.allScope(project)); return consumerClass != null ? psiFacade.getElementFactory().createType(consumerClass, parameter.getType()) : null; }
@Nullable public PsiClass getContainingClassElement() { final PsiClassType containingClassType = JavaPsiFacade.getInstance(getProject()) .getElementFactory() .createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject())); return containingClassType.resolve(); }
@NotNull public static PsiClassType[] getExtendsListTypes(@NotNull PsiClass psiClass) { if (psiClass.isEnum()) { PsiClassType enumSuperType = getEnumSuperType( psiClass, JavaPsiFacade.getInstance(psiClass.getProject()).getElementFactory()); return enumSuperType == null ? PsiClassType.EMPTY_ARRAY : new PsiClassType[] {enumSuperType}; } if (psiClass.isAnnotationType()) { return new PsiClassType[] { getAnnotationSuperType( psiClass, JavaPsiFacade.getInstance(psiClass.getProject()).getElementFactory()) }; } final PsiReferenceList extendsList = psiClass.getExtendsList(); if (extendsList != null) { return extendsList.getReferencedTypes(); } return PsiClassType.EMPTY_ARRAY; }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (!(element instanceof PsiTypeElement)) { return; } final PsiTypeElement typeElement = (PsiTypeElement) element; final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiClassType type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION); final PsiTypeElement newTypeElement = factory.createTypeElement(type); typeElement.replace(newTypeElement); }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiType thrownType = myThrown.getType(); if (thrownType == null) { return; } final PsiElement typeElement = descriptor.getPsiElement(); if (typeElement == null) { return; } final PsiElement catchParameter = typeElement.getParent(); if (!(catchParameter instanceof PsiParameter)) { return; } final PsiElement catchBlock = ((PsiParameter) catchParameter).getDeclarationScope(); if (!(catchBlock instanceof PsiCatchSection)) { return; } final PsiCatchSection myBeforeCatchSection = (PsiCatchSection) catchBlock; final PsiTryStatement myTryStatement = myBeforeCatchSection.getTryStatement(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final String name = codeStyleManager.suggestUniqueVariableName("e", myTryStatement.getTryBlock(), false); final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiCatchSection section = factory.createCatchSection(thrownType, name, myTryStatement); final PsiCatchSection element = (PsiCatchSection) myTryStatement.addBefore(section, myBeforeCatchSection); codeStyleManager.shortenClassReferences(element); if (isOnTheFly()) { final PsiCodeBlock newBlock = element.getCatchBlock(); assert newBlock != null; final TextRange range = SurroundWithUtil.getRangeToSelect(newBlock); final PsiFile file = element.getContainingFile(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor == null) { return; } final Document document = PsiDocumentManager.getInstance(project).getDocument(file); if (editor.getDocument() != document) { return; } editor.getCaretModel().moveToOffset(range.getStartOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); } }
@Override protected void canRun() throws ConfigurationException { if (isMoveToPackage()) { String name = getTargetPackage().trim(); if (name.length() != 0 && !JavaPsiFacade.getInstance(myManager.getProject()) .getNameHelper() .isQualifiedName(name)) { throw new ConfigurationException("\'" + name + "\' is invalid destination package name"); } } else { if (findTargetClass() == null) throw new ConfigurationException("Destination class not found"); final String validationError = getValidationError(); if (validationError != null) throw new ConfigurationException(validationError); } }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement classNameIdentifier = descriptor.getPsiElement(); final PsiClass aClass = (PsiClass) classNameIdentifier.getParent(); if (aClass == null) { return; } final PsiManager psiManager = PsiManager.getInstance(project); final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); final PsiMethod constructor = factory.createConstructor(); final PsiModifierList modifierList = constructor.getModifierList(); modifierList.setModifierProperty(PsiModifier.PRIVATE, true); aClass.add(constructor); final CodeStyleManager styleManager = psiManager.getCodeStyleManager(); styleManager.reformat(constructor); }
private static List<LanguageDefinition> collectLanguageDefinitions(final ConvertContext context) { final Project project = context.getProject(); final Collection<PsiClass> allLanguages = CachedValuesManager.getManager(project) .getCachedValue( project, () -> { final PsiClass languageClass = JavaPsiFacade.getInstance(project) .findClass(Language.class.getName(), GlobalSearchScope.allScope(project)); if (languageClass == null) { return Result.create( Collections.emptyList(), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } final GlobalSearchScope projectProductionScope = GlobalSearchScopesCore.projectProductionScope(project); GlobalSearchScope allScope = projectProductionScope.union(ProjectScope.getLibrariesScope(project)); final Collection<PsiClass> allInheritors = ClassInheritorsSearch.search(languageClass, allScope, true).findAll(); return Result.create( allInheritors, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); if (allLanguages.isEmpty()) { return Collections.emptyList(); } final List<LanguageDefinition> libraryDefinitions = collectLibraryLanguages(context, allLanguages); final GlobalSearchScope projectProductionScope = GlobalSearchScopesCore.projectProductionScope(project); final Collection<PsiClass> projectLanguages = ContainerUtil.filter( allLanguages, aClass -> PsiSearchScopeUtil.isInScope(projectProductionScope, aClass)); final List<LanguageDefinition> projectDefinitions = collectProjectLanguages(projectLanguages, libraryDefinitions); final List<LanguageDefinition> all = ContainerUtil.newArrayList(libraryDefinitions); all.addAll(projectDefinitions); return all; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!FileModificationService.getInstance() .preparePsiElementForWrite(descriptor.getPsiElement())) return; final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement instanceof PsiInstanceOfExpression) { try { final PsiExpression compareToNull = JavaPsiFacade.getInstance(psiElement.getProject()) .getElementFactory() .createExpressionFromText( ((PsiInstanceOfExpression) psiElement).getOperand().getText() + " != null", psiElement.getParent()); psiElement.replace(compareToNull); } catch (IncorrectOperationException e) { LOG.error(e); } } }
@Override public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { PsiElement nameElement = getNameIdentifierGroovy(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(nameElement.getProject()); PsiElement newNameElement; if (JavaPsiFacade.getInstance(getProject()).getNameHelper().isIdentifier(name)) { try { GrMethod method = factory.createMethod(name, null); newNameElement = method.getNameIdentifierGroovy(); } catch (IncorrectOperationException e) { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } } else { newNameElement = factory.createLiteralFromValue(name).getFirstChild(); } nameElement.replace(newNameElement); return this; }
// todo: inline private static void generateBean( final PsiClass aClass, final String[] properties, final HashMap<String, String> property2fqClassName) throws MyException { final StringBuffer membersBuffer = new StringBuffer(); final StringBuffer methodsBuffer = new StringBuffer(); final CodeStyleManager formatter = CodeStyleManager.getInstance(aClass.getProject()); final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(aClass.getProject()); for (final String property : properties) { LOG.assertTrue(property != null); final String type = property2fqClassName.get(property); LOG.assertTrue(type != null); generateProperty(styler, property, type, membersBuffer, methodsBuffer); } final PsiClass fakeClass; try { fakeClass = JavaPsiFacade.getInstance(aClass.getProject()) .getElementFactory() .createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null); final PsiField[] fields = fakeClass.getFields(); for (final PsiField field : fields) { aClass.add(field); } final PsiMethod[] methods = fakeClass.getMethods(); for (final PsiMethod method : methods) { aClass.add(method); } styler.shortenClassReferences(aClass); formatter.reformat(aClass); } catch (IncorrectOperationException e) { throw new MyException(e.getMessage()); } }
public static boolean isMainOrPremainMethod(@NotNull PsiMethod method) { if (!PsiType.VOID.equals(method.getReturnType())) return false; String name = method.getName(); if (!("main".equals(name) || "premain".equals(name))) return false; PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY); try { MethodSignature main = createSignatureFromText(factory, "void main(String[] args);"); if (MethodSignatureUtil.areSignaturesEqual(signature, main)) return true; MethodSignature premain = createSignatureFromText( factory, "void premain(String args, java.lang.instrument.Instrumentation i);"); if (MethodSignatureUtil.areSignaturesEqual(signature, premain)) return true; } catch (IncorrectOperationException e) { LOG.error(e); } return false; }
@Nullable protected VirtualFile findCoreJar(@Nullable Module module) { if (module == null) return null; JavaPsiFacade javaFacade = JavaPsiFacade.getInstance(module.getProject()); for (PsiClass aClass : javaFacade.findClasses( getSomeFrameworkClass(), GlobalSearchScope.moduleWithLibrariesScope(module))) { VirtualFile virtualFile = aClass.getContainingFile().getVirtualFile(); if (virtualFile != null && virtualFile.getFileSystem() instanceof JarFileSystem) { VirtualFile localFile = PathUtil.getLocalFile(virtualFile); if (isCoreJar(localFile)) { return localFile; } } } return null; }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); final PsiElement parent = element.getParent(); if (!(parent instanceof PsiCatchSection)) { return; } final PsiCatchSection catchSection = (PsiCatchSection) parent; final PsiParameter parameter = catchSection.getParameter(); if (parameter == null) { return; } final PsiIdentifier identifier = parameter.getNameIdentifier(); if (identifier == null) { return; } final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiIdentifier newIdentifier = factory.createIdentifier("ignored"); identifier.replace(newIdentifier); }
@NotNull public static SearchScope getClassUseScope(@NotNull PsiClass aClass) { if (aClass instanceof PsiAnonymousClass) { return new LocalSearchScope(aClass); } final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(aClass); PsiFile file = aClass.getContainingFile(); if (PsiImplUtil.isInServerPage(file)) return maximalUseScope; final PsiClass containingClass = aClass.getContainingClass(); if (aClass.hasModifierProperty(PsiModifier.PUBLIC) || aClass.hasModifierProperty(PsiModifier.PROTECTED)) { return containingClass == null ? maximalUseScope : containingClass.getUseScope(); } else if (aClass.hasModifierProperty(PsiModifier.PRIVATE) || aClass instanceof PsiTypeParameter) { PsiClass topClass = PsiUtil.getTopLevelClass(aClass); return new LocalSearchScope(topClass == null ? aClass.getContainingFile() : topClass); } else { PsiPackage aPackage = null; if (file instanceof PsiJavaFile) { aPackage = JavaPsiFacade.getInstance(aClass.getProject()) .findPackage(((PsiJavaFile) file).getPackageName()); } if (aPackage == null) { PsiDirectory dir = file.getContainingDirectory(); if (dir != null) { aPackage = JavaDirectoryService.getInstance().getPackage(dir); } } if (aPackage != null) { SearchScope scope = PackageScope.packageScope(aPackage, false); scope = scope.intersectWith(maximalUseScope); return scope; } return new LocalSearchScope(file); } }
public void testAllInPackageForCommonAncestorModule() throws IOException, ExecutionException { disposeModule(getModule2()); addModule("module5", true); Module ancestor = getModule1(); Module child1 = getModule2(); Module child2 = getModule3(); addDependency(ancestor, child1); addDependency(ancestor, child2); PsiPackage psiPackage = JavaPsiFacade.getInstance(myProject).findPackage("test1"); JUnitConfiguration configuration = createJUnitConfiguration( psiPackage, AllInPackageConfigurationProducer.class, new MapDataContext()); configuration.getPersistentData().setScope(TestSearchScope.WHOLE_PROJECT); assertNotNull(configuration); checkPackage(psiPackage.getQualifiedName(), configuration); assertEmpty(configuration.getModules()); JavaParameters parameters = checkCanRun(configuration); List<String> tests = extractAllInPackageTests(parameters, psiPackage); String childTest1 = findClass(child1, "test1.TestB").getQualifiedName(); String childTest2 = findClass(child2, "test1.Test5").getQualifiedName(); String ancestorTest = findClass(ancestor, "test1.TestA").getQualifiedName(); CHECK.containsAll(tests, new Object[] {ancestorTest, childTest1, childTest2}); }
private static PsiClassType getEnumSuperType( @NotNull PsiClass psiClass, @NotNull PsiElementFactory factory) { PsiClassType superType; final PsiManager manager = psiClass.getManager(); final PsiClass enumClass = JavaPsiFacade.getInstance(manager.getProject()) .findClass("java.lang.Enum", psiClass.getResolveScope()); if (enumClass == null) { try { superType = (PsiClassType) factory.createTypeFromText("java.lang.Enum", null); } catch (IncorrectOperationException e) { superType = null; } } else { final PsiTypeParameter[] typeParameters = enumClass.getTypeParameters(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; if (typeParameters.length == 1) { substitutor = substitutor.put(typeParameters[0], factory.createType(psiClass)); } superType = new PsiImmediateClassType(enumClass, substitutor); } return superType; }
public static void addAvailableSystemScripts( final Collection<String> result, @NotNull Module module) { VirtualFile scriptRoot = null; GlobalSearchScope searchScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false); for (PsiClass aClass : JavaPsiFacade.getInstance(module.getProject()).findClasses("CreateApp_", searchScope)) { PsiClass superClass = aClass.getSuperClass(); if (superClass != null && GroovyCommonClassNames.GROOVY_LANG_SCRIPT.equals(superClass.getQualifiedName())) { PsiFile psiFile = aClass.getContainingFile(); if (psiFile != null) { VirtualFile file = psiFile.getVirtualFile(); if (file != null && file.getFileSystem() instanceof ArchiveFileSystem) { VirtualFile parent = file.getParent(); if (parent != null && parent.findChild("Console.class") != null) { scriptRoot = parent; break; } } } } } if (scriptRoot == null) return; Pattern scriptPattern = Pattern.compile("([A-Za-z0-9]+)_?\\.class"); for (VirtualFile file : scriptRoot.getChildren()) { Matcher matcher = scriptPattern.matcher(file.getName()); if (matcher.matches()) { result.add(GroovyNamesUtil.camelToSnake(matcher.group(1))); } } }
private static boolean areGroovyObjectMethodsOverridden(GrReferenceExpression ref) { PsiType qualifierType = GrReferenceResolveUtil.getQualifierType(ref); if (!(qualifierType instanceof PsiClassType)) return false; PsiClass resolved = ((PsiClassType) qualifierType).resolve(); if (resolved == null) return false; PsiClass groovyObject = JavaPsiFacade.getInstance(ref.getProject()) .findClass(GroovyCommonClassNames.GROOVY_OBJECT, ref.getResolveScope()); if (groovyObject == null) return false; String methodName; if (ref.getParent() instanceof GrCall) { methodName = "invokeMethod"; } else if (PsiUtil.isLValue(ref)) { methodName = "setProperty"; } else { methodName = "getProperty"; } PsiMethod[] patternMethods = groovyObject.findMethodsByName(methodName, false); if (patternMethods.length != 1) return false; PsiMethod patternMethod = patternMethods[0]; PsiMethod found = resolved.findMethodBySignature(patternMethod, true); if (found == null) return false; PsiClass aClass = found.getContainingClass(); if (aClass == null) return false; String qname = aClass.getQualifiedName(); if (GroovyCommonClassNames.GROOVY_OBJECT.equals(qname)) return false; if (GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(qname)) return false; return true; }