@NotNull @Override public PsiMethod createMethod(@NotNull final String name, final PsiType returnType) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(returnType)) { throw new IncorrectOperationException("Cannot create method with type \"null\"."); } final String canonicalText = returnType.getCanonicalText(); final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { public " + canonicalText + " " + name + "() {} }"); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException( "Class was not created. Method name: " + name + "; return type: " + canonicalText); } final PsiMethod[] methods = classes[0].getMethods(); if (methods.length < 1) { throw new IncorrectOperationException( "Method was not created. Method name: " + name + "; return type: " + canonicalText); } PsiMethod method = methods[0]; method = (PsiMethod) JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(method); return (PsiMethod) CodeStyleManager.getInstance(myManager.getProject()).reformat(method); }
@Override @Nullable public Collection<PsiImportStatementBase> findRedundantImports(final PsiJavaFile file) { final PsiImportList importList = file.getImportList(); if (importList == null) return null; final PsiImportStatementBase[] imports = importList.getAllImportStatements(); if (imports.length == 0) return null; Set<PsiImportStatementBase> allImports = new THashSet<PsiImportStatementBase>(Arrays.asList(imports)); final Collection<PsiImportStatementBase> redundant; if (FileTypeUtils.isInServerPageFile(file)) { // remove only duplicate imports redundant = ContainerUtil.newIdentityTroveSet(); ContainerUtil.addAll(redundant, imports); redundant.removeAll(allImports); for (PsiImportStatementBase importStatement : imports) { if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) { redundant.remove(importStatement); } } } else { redundant = allImports; final List<PsiFile> roots = file.getViewProvider().getAllFiles(); for (PsiElement root : roots) { root.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { if (!reference.isQualified()) { final JavaResolveResult resolveResult = reference.advancedResolve(false); if (!inTheSamePackage(file, resolveResult.getElement())) { final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase) { final PsiImportStatementBase importStatementBase = (PsiImportStatementBase) resolveScope; redundant.remove(importStatementBase); } } } super.visitReferenceElement(reference); } private boolean inTheSamePackage(PsiJavaFile file, PsiElement element) { if (element instanceof PsiClass && ((PsiClass) element).getContainingClass() == null) { final PsiFile containingFile = element.getContainingFile(); if (containingFile instanceof PsiJavaFile) { return Comparing.strEqual( file.getPackageName(), ((PsiJavaFile) containingFile).getPackageName()); } } return false; } }); } } return redundant; }
private static PsiClass createClassFromTemplate( @NotNull PsiDirectory dir, String name, String templateName, boolean askToDefineVariables) throws IncorrectOperationException { // checkCreateClassOrInterface(dir, name); FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName); Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(); Properties properties = new Properties(defaultProperties); properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name); String ext = StdFileTypes.JAVA.getDefaultExtension(); String fileName = name + "." + ext; PsiElement element; try { element = askToDefineVariables ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties) .create() : FileTemplateUtil.createFromTemplate(template, fileName, properties, dir); } catch (IncorrectOperationException e) { throw e; } catch (Exception e) { LOG.error(e); return null; } if (element == null) return null; final PsiJavaFile file = (PsiJavaFile) element.getContainingFile(); PsiClass[] classes = file.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName)); } return classes[0]; }
@NotNull @Override public PsiField createField(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(type)) { throw new IncorrectOperationException("Cannot create field with type \"null\"."); } @NonNls final String text = "class _Dummy_ { private " + type.getCanonicalText() + " " + name + "; }"; final PsiJavaFile aFile = createDummyJavaFile(text); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException("Class was not created " + text); } final PsiClass psiClass = classes[0]; final PsiField[] fields = psiClass.getFields(); if (fields.length < 1) { throw new IncorrectOperationException("Field was not created " + text); } PsiField field = fields[0]; field = (PsiField) JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(field); return (PsiField) CodeStyleManager.getInstance(myManager.getProject()).reformat(field); }
public SNode resolveClass(PsiClassType t) { PsiClass cls = t.resolve(); // TODO q: handle this case? create dynamic reference? if (cls == null) { return null; } System.out.println("Class resolved: " + cls.getQualifiedName()); PsiElement e = cls; do { e = e.getParent(); if (!(e instanceof PsiClass) && !(e instanceof PsiJavaFile)) { return null; } } while (!(e instanceof PsiJavaFile)); PsiJavaFile file = (PsiJavaFile) e; String packageName = file.getPackageName(); SModelReference modelRef = SModelReference.fromString(packageName); SNode clsType = SConceptOperations.createNewNode( "jetbrains.mps.baseLanguage.structure.ClassifierType", null); clsType.setReference( "classifier", new DynamicReference("classifier", clsType, modelRef, t.getClassName())); System.out.println("Class type: " + t.getClassName()); return clsType; }
@NotNull @Override public PsiClassInitializer createClassInitializer() throws IncorrectOperationException { final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { {} }"); final PsiClassInitializer classInitializer = aFile.getClasses()[0].getInitializers()[0]; return (PsiClassInitializer) CodeStyleManager.getInstance(myManager.getProject()).reformat(classInitializer); }
@NotNull @Override public PsiMethod createConstructor(@NotNull @NonNls final String name) { final PsiJavaFile aFile = createDummyJavaFile("class " + name + " { public " + name + "() {} }"); final PsiMethod method = aFile.getClasses()[0].getMethods()[0]; return (PsiMethod) CodeStyleManager.getInstance(myManager.getProject()).reformat(method); }
private static PsiImportStatementBase extractImport( final PsiJavaFile aFile, final boolean isStatic) { final PsiImportList importList = aFile.getImportList(); assert importList != null : aFile; final PsiImportStatementBase[] statements = isStatic ? importList.getImportStaticStatements() : importList.getImportStatements(); assert statements.length == 1 : aFile.getText(); return statements[0]; }
private PsiClass createClassInner(@NonNls final String type, @NonNls String name) { PsiUtil.checkIsIdentifier(myManager, name); final PsiJavaFile aFile = createDummyJavaFile("public " + type + " " + name + " { }"); final PsiClass[] classes = aFile.getClasses(); if (classes.length != 1) { throw new IncorrectOperationException("Incorrect " + type + " name \"" + name + "\"."); } return classes[0]; }
public void deleteChildInternal(@NotNull ASTNode child) { if (child.getElementType() == JavaElementType.CLASS) { PsiJavaFile file = SourceTreeToPsiMap.treeToPsiNotNull(this); if (file.getClasses().length == 1) { file.delete(); return; } } super.deleteChildInternal(child); }
public static boolean addStaticImport( @NotNull String qualifierClass, @NonNls @NotNull String memberName, @NotNull PsiElement context) { if (!nameCanBeStaticallyImported(qualifierClass, memberName, context)) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritor(containingClass, qualifierClass)) { return true; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement != null) { return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, qualifierClass); if (onDemandImportStatement != null && !hasOnDemandImportStaticConflict(qualifierClass, memberName, context)) { return true; } final Project project = context.getProject(); final GlobalSearchScope scope = context.getResolveScope(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass aClass = psiFacade.findClass(qualifierClass, scope); if (aClass == null) { return false; } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return false; } final List<PsiImportStaticStatement> imports = getMatchingImports(importList, qualifiedName); final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); if (imports.size() < codeStyleSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND) { importList.add(elementFactory.createImportStaticStatement(aClass, memberName)); } else { for (PsiImportStaticStatement importStatement : imports) { importStatement.delete(); } importList.add(elementFactory.createImportStaticStatement(aClass, "*")); } return true; }
@Override public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException { PsiElement mirrorElement = SourceTreeToPsiMap.treeToPsiNotNull(element); if (!(mirrorElement instanceof PsiJavaFile)) { throw new InvalidMirrorException("Unexpected mirror file: " + mirrorElement); } PsiJavaFile mirrorFile = (PsiJavaFile) mirrorElement; setMirrorIfPresent(getPackageStatement(), mirrorFile.getPackageStatement()); setMirrors(getClasses(), mirrorFile.getClasses()); }
@NotNull @Override public PsiPackageStatement createPackageStatement(@NotNull final String name) throws IncorrectOperationException { final PsiJavaFile aFile = createDummyJavaFile("package " + name + ";"); final PsiPackageStatement stmt = aFile.getPackageStatement(); if (stmt == null) { throw new IncorrectOperationException("Incorrect package name: " + name); } return stmt; }
private static void collectNamesToImport( @NotNull final Set<String> names, @NotNull final PsiJavaFile file, @NotNull final Set<String> namesToImportStaticly, PsiFile context) { String packageName = file.getPackageName(); final PsiElement[] roots = file.getPsiRoots(); for (PsiElement root : roots) { addNamesToImport(names, root, packageName, namesToImportStaticly, context); } }
@Override public void create( @NotNull Project project, @NotNull BuildSystem buildSystem, @NotNull ProgressIndicator indicator) { Util.runWriteTask( () -> { try { indicator.setText("Writing main class"); VirtualFile file = buildSystem.getSourceDirectories().get(0); final String[] files = this.mainClass.split("\\."); final String className = files[files.length - 1]; final String packageName = this.mainClass.substring(0, this.mainClass.length() - className.length() - 1); file = getMainClassDirectory(files, file); final VirtualFile mainClassFile = file.findOrCreateChildData(this, className + ".java"); SpongeTemplate.applyMainClassTemplate( project, mainClassFile, packageName, className, hasDependencies(), generateDocumentedListeners); final PsiJavaFile mainClassPsi = (PsiJavaFile) PsiManager.getInstance(project).findFile(mainClassFile); if (mainClassPsi == null) { return; } final PsiClass psiClass = mainClassPsi.getClasses()[0]; writeMainSpongeClass( project, mainClassPsi, psiClass, buildSystem, pluginName, description, website, hasAuthors(), authors, hasDependencies(), dependencies); EditorHelper.openInEditor(mainClassPsi); } catch (IOException e) { e.printStackTrace(); } }); }
@NotNull private File fileToFile(PsiJavaFile javaFile, List<String> additionalImports) { PsiImportList importList = javaFile.getImportList(); List<Import> imports = importList == null ? Collections.<Import>emptyList() : importsToImportList(importList.getAllImportStatements()); for (String i : additionalImports) imports.add(new Import(i)); return new File( quoteKeywords(javaFile.getPackageName()), imports, classesToClassList(javaFile.getClasses()), createMainFunction(javaFile)); }
public static boolean hasDefaultImportConflict(String fqName, PsiJavaFile file) { final String shortName = ClassUtil.extractClassName(fqName); final String packageName = ClassUtil.extractPackageName(fqName); final String filePackageName = file.getPackageName(); if (filePackageName.equals(packageName)) { return false; } final Project project = file.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiPackage filePackage = psiFacade.findPackage(filePackageName); if (filePackage == null) { return false; } return filePackage.containsClassNamed(shortName); }
private void chooseDirectoryAndMove(Project project, PsiFile myFile) { try { PsiDirectory directory = MoveClassesOrPackagesUtil.chooseDestinationPackage(project, myTargetPackage, null); if (directory == null) { return; } String error = RefactoringMessageUtil.checkCanCreateFile(directory, myFile.getName()); if (error != null) { Messages.showMessageDialog( project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return; } new MoveClassesOrPackagesProcessor( project, new PsiElement[] {((PsiJavaFile) myFile).getClasses()[0]}, new SingleSourceRootMoveDestination( PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(directory)), directory), false, false, null) .run(); } catch (IncorrectOperationException e) { LOG.error(e); } }
public static boolean isImplicitlyImported(@NotNull String className, @NotNull PsiJavaFile file) { String[] packageNames = file.getImplicitlyImportedPackages(); for (String packageName : packageNames) { if (hasPackage(className, packageName)) return true; } return false; }
@NotNull private static List<PsiJavaCodeReferenceElement> getImportsFromPackage( @NotNull PsiJavaFile file, @NotNull String packageName) { PsiClass[] refs = file.getSingleClassImports(true); List<PsiJavaCodeReferenceElement> array = new ArrayList<PsiJavaCodeReferenceElement>(); for (PsiClass ref1 : refs) { String className = ref1.getQualifiedName(); if (getPackageOrClassName(className).equals(packageName)) { final PsiJavaCodeReferenceElement ref = file.findImportReferenceTo(ref1); if (ref != null) { array.add(ref); } } } return array; }
public static boolean isInside(PsiElement place, PsiElement ancestor) { if (SafeDeleteProcessor.isInside(place, ancestor)) return true; if (PsiTreeUtil.getParentOfType(place, PsiComment.class, false) != null && ancestor instanceof PsiClass) { final PsiClass aClass = (PsiClass) ancestor; if (aClass.getParent() instanceof PsiJavaFile) { final PsiJavaFile file = (PsiJavaFile) aClass.getParent(); if (PsiTreeUtil.isAncestor(file, place, false)) { if (file.getClasses().length == 1) { // file will be deleted on class deletion return true; } } } } return false; }
private static PsiClass findSingleImportByShortName( @NotNull PsiJavaFile file, @NotNull String shortClassName) { PsiClass[] refs = file.getSingleClassImports(true); for (PsiClass ref : refs) { String className = ref.getQualifiedName(); if (className != null && PsiNameHelper.getShortClassName(className).equals(shortClassName)) { return ref; } } for (PsiClass aClass : file.getClasses()) { String className = aClass.getQualifiedName(); if (className != null && PsiNameHelper.getShortClassName(className).equals(shortClassName)) { return aClass; } } return null; }
public static boolean isStaticallyImported( @NotNull PsiMember member, @NotNull PsiElement context) { final PsiClass memberClass = member.getContainingClass(); if (memberClass == null) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritorOrSelf(containingClass, memberClass, true)) { return false; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final String memberName = member.getName(); if (memberName == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement instanceof PsiImportStaticStatement) { final PsiClass importClass = ((PsiImportStaticStatement) existingImportStatement).resolveTargetClass(); if (InheritanceUtil.isInheritorOrSelf(importClass, memberClass, true)) { return true; } } final String memberClassName = memberClass.getQualifiedName(); if (memberClassName == null) { return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, memberClassName); if (onDemandImportStatement != null) { if (!hasOnDemandImportStaticConflict(memberClassName, memberName, context)) { return true; } } return false; }
@Test public void testJavaFileIsEmpty() throws Exception { final PsiJavaFile psiJavaFile = mock(PsiJavaFile.class); final PsiClass toImport = mock(PsiClass.class); final PsiImportStatement psiImportStatement = mock(PsiImportStatement.class); final PsiImportList psiImportList = mock(PsiImportList.class); final RunnableHolder writeActionHolder = getWriteActionHolder(); when(psiJavaFile.getProject()).thenReturn(project); when(psiImportStatement.getParent()).thenReturn(psiImportList); when(psiElementFactory.createImportStatement(toImport)).thenReturn(psiImportStatement); addImportService.addImportStatement(psiJavaFile, toImport); assertNotNull(writeActionHolder.getRunnable()); verify(psiJavaFile, never()).add(any()); writeActionHolder.getRunnable().run(); verify(psiJavaFile).add(psiImportList); }
private static boolean containsConflictingClass(String fqName, PsiJavaFile file) { final PsiClass[] classes = file.getClasses(); for (PsiClass aClass : classes) { if (containsConflictingInnerClass(fqName, aClass)) { return true; } } return false; }
private static PsiPackage findImportOnDemand( @NotNull PsiJavaFile file, @NotNull String packageName) { PsiElement[] refs = file.getOnDemandImports(false, true); for (PsiElement ref : refs) { if (ref instanceof PsiPackage && ((PsiPackage) ref).getQualifiedName().equals(packageName)) { return (PsiPackage) ref; } } return null; }
private static void assertOrder(PsiJavaFile file, @NonNls String... expectedOrder) { PsiImportStatementBase[] statements = file.getImportList().getAllImportStatements(); assertEquals(expectedOrder.length, statements.length); for (int i = 0; i < statements.length; i++) { PsiImportStatementBase statement = statements[i]; String text = StringUtil.trimEnd(StringUtil.trimStart(statement.getText(), "import "), ";"); assertEquals(expectedOrder[i], text); } }
public static void addImportIfNeeded(@NotNull PsiClass aClass, @NotNull PsiElement context) { final PsiFile file = context.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } final PsiJavaFile javaFile = (PsiJavaFile) file; final PsiClass outerClass = aClass.getContainingClass(); if (outerClass == null) { if (PsiTreeUtil.isAncestor(javaFile, aClass, true)) { return; } } else if (PsiTreeUtil.isAncestor(outerClass, context, true)) { final PsiElement brace = outerClass.getLBrace(); if (brace != null && brace.getTextOffset() < context.getTextOffset()) { return; } } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return; } final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return; } final String containingPackageName = javaFile.getPackageName(); @NonNls final String packageName = ClassUtil.extractPackageName(qualifiedName); if (containingPackageName.equals(packageName) || importList.findSingleClassImportStatement(qualifiedName) != null) { return; } if (importList.findOnDemandImportStatement(packageName) != null && !hasDefaultImportConflict(qualifiedName, javaFile) && !hasOnDemandImportConflict(qualifiedName, javaFile)) { return; } final Project project = importList.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); final PsiImportStatement importStatement = elementFactory.createImportStatement(aClass); importList.add(importStatement); }
private static boolean containsConflictingClassName(String fqName, PsiJavaFile file) { final int lastDotIndex = fqName.lastIndexOf((int) '.'); final String shortName = fqName.substring(lastDotIndex + 1); final PsiClass[] classes = file.getClasses(); for (PsiClass aClass : classes) { if (shortName.equals(aClass.getName())) { return true; } } return false; }
/** * @param strict if strict is true this method checks if the conflicting class which is imported * is actually used in the file. If it isn't the on demand import can be overridden with an * exact import for the fqName without breaking stuff. */ private static boolean hasOnDemandImportConflict( @NotNull String fqName, @NotNull PsiJavaFile file, boolean strict) { final PsiImportList imports = file.getImportList(); if (imports == null) { return false; } final PsiImportStatement[] importStatements = imports.getImportStatements(); final String shortName = ClassUtil.extractClassName(fqName); final String packageName = ClassUtil.extractPackageName(fqName); for (final PsiImportStatement importStatement : importStatements) { if (!importStatement.isOnDemand()) { continue; } final PsiJavaCodeReferenceElement importReference = importStatement.getImportReference(); if (importReference == null) { continue; } final String packageText = importReference.getText(); if (packageText.equals(packageName)) { continue; } final PsiElement element = importReference.resolve(); if (!(element instanceof PsiPackage)) { continue; } final PsiPackage aPackage = (PsiPackage) element; if (!strict && aPackage.containsClassNamed(shortName)) { return true; } else { final PsiClass[] classes = aPackage.findClassByShortName(shortName, file.getResolveScope()); for (final PsiClass aClass : classes) { final String qualifiedClassName = aClass.getQualifiedName(); if (qualifiedClassName == null || fqName.equals(qualifiedClassName)) { continue; } return containsConflictingReference(file, qualifiedClassName); } } } return hasJavaLangImportConflict(fqName, file); }