コード例 #1
0
  @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);
  }
コード例 #2
0
  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];
  }
コード例 #3
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);
  }
コード例 #4
0
 @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);
 }
コード例 #5
0
 @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);
 }
コード例 #6
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];
 }
コード例 #7
0
 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;
 }
コード例 #8
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);
 }
コード例 #9
0
 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;
 }
コード例 #10
0
  @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());
  }
コード例 #11
0
  @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();
          }
        });
  }
コード例 #12
0
ファイル: Converter.java プロジェクト: rlnbpr/kotlin
 @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));
 }
コード例 #13
0
  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;
  }
コード例 #14
0
ファイル: ImportHelper.java プロジェクト: jexp/idea2
 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;
 }
コード例 #15
0
  @Nullable
  public ProblemDescriptor[] checkFile(
      @NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    // does not work in tests since CodeInsightTestCase copies file into temporary location
    if (ApplicationManager.getApplication().isUnitTestMode()) return null;
    if (file instanceof PsiJavaFile) {
      if (JspPsiUtil.isInJspFile(file)) return null;
      PsiJavaFile javaFile = (PsiJavaFile) file;

      PsiDirectory directory = javaFile.getContainingDirectory();
      if (directory == null) return null;
      PsiPackage dirPackage = JavaDirectoryService.getInstance().getPackage(directory);
      if (dirPackage == null) return null;
      PsiPackageStatement packageStatement = javaFile.getPackageStatement();

      // highlight the first class in the file only
      PsiClass[] classes = javaFile.getClasses();
      if (classes.length == 0 && packageStatement == null) return null;

      String packageName = dirPackage.getQualifiedName();
      if (!Comparing.strEqual(packageName, "", true) && packageStatement == null) {
        String description = JavaErrorMessages.message("missing.package.statement", packageName);

        return new ProblemDescriptor[] {
          manager.createProblemDescriptor(
              classes[0].getNameIdentifier(),
              description,
              new AdjustPackageNameFix(javaFile, null, dirPackage),
              ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
              isOnTheFly)
        };
      }
      if (packageStatement != null) {
        final PsiJavaCodeReferenceElement packageReference = packageStatement.getPackageReference();
        PsiPackage classPackage = (PsiPackage) packageReference.resolve();
        List<LocalQuickFix> availableFixes = new ArrayList<LocalQuickFix>();
        if (classPackage == null) {
          availableFixes.add(new AdjustPackageNameFix(javaFile, packageStatement, dirPackage));
        } else if (!Comparing.equal(
            dirPackage.getQualifiedName(), packageReference.getText(), true)) {
          availableFixes.add(new AdjustPackageNameFix(javaFile, packageStatement, dirPackage));
          MoveToPackageFix moveToPackageFix = new MoveToPackageFix(file, classPackage);
          if (moveToPackageFix.isAvailable()) {
            availableFixes.add(moveToPackageFix);
          }
        }
        if (!availableFixes.isEmpty()) {
          String description =
              JavaErrorMessages.message(
                  "package.name.file.path.mismatch",
                  packageReference.getText(),
                  dirPackage.getQualifiedName());
          return new ProblemDescriptor[] {
            manager.createProblemDescriptor(
                packageStatement.getPackageReference(),
                description,
                isOnTheFly,
                availableFixes.toArray(new LocalQuickFix[availableFixes.size()]),
                ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
          };
        }
      }
    }
    return null;
  }
コード例 #16
0
  private PsiClass buildClass() {
    final PsiManager manager = sourceClass.getManager();
    final Project project = sourceClass.getProject();
    final ExtractedClassBuilder extractedClassBuilder = new ExtractedClassBuilder();
    extractedClassBuilder.setProject(myProject);
    extractedClassBuilder.setClassName(newClassName);
    extractedClassBuilder.setPackageName(newPackageName);
    extractedClassBuilder.setOriginalClassName(sourceClass.getQualifiedName());
    extractedClassBuilder.setRequiresBackPointer(requiresBackpointer);
    extractedClassBuilder.setExtractAsEnum(enumConstants);
    for (PsiField field : fields) {
      extractedClassBuilder.addField(field);
    }
    for (PsiMethod method : methods) {
      extractedClassBuilder.addMethod(method);
    }
    for (PsiClass innerClass : innerClasses) {
      extractedClassBuilder.addInnerClass(
          innerClass, innerClassesToMakePublic.contains(innerClass));
    }
    extractedClassBuilder.setTypeArguments(typeParams);
    final List<PsiClass> interfaces = calculateInterfacesSupported();
    extractedClassBuilder.setInterfaces(interfaces);

    if (myGenerateAccessors) {
      final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
      sourceClass.accept(visitor);
      extractedClassBuilder.setFieldsNeedingGetters(visitor.getFieldsNeedingGetter());
      extractedClassBuilder.setFieldsNeedingSetters(visitor.getFieldsNeedingSetter());
    }

    final String classString = extractedClassBuilder.buildBeanClass();
    if (extractInnerClass) {
      final PsiFileFactory factory = PsiFileFactory.getInstance(project);
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(
                  newClassName + ".java", JavaFileType.INSTANCE, classString);
      final PsiClass psiClass = newFile.getClasses()[0];
      if (!psiClass.isEnum()) {
        final PsiModifierList modifierList = psiClass.getModifierList();
        assert modifierList != null;
        modifierList.setModifierProperty(PsiModifier.STATIC, true);
      }
      final PsiElement addedClass = sourceClass.add(psiClass);
      return (PsiClass)
          CodeStyleManager.getInstance(manager)
              .reformat(
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClass));
    }

    try {
      final PsiFile containingFile = sourceClass.getContainingFile();
      final PsiDirectory directory;
      final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
      if (myMoveDestination != null) {
        directory = myMoveDestination.getTargetDirectory(containingDirectory);
      } else {
        final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
        assert module != null;
        directory =
            PackageUtil.findOrCreateDirectoryForPackage(
                module, newPackageName, containingDirectory, false, true);
      }
      if (directory != null) {
        final PsiFileFactory factory = PsiFileFactory.getInstance(project);
        final PsiFile newFile =
            factory.createFileFromText(newClassName + ".java", JavaFileType.INSTANCE, classString);
        final PsiElement addedFile = directory.add(newFile);
        final CodeStyleManager codeStyleManager =
            CodeStyleManager.getInstance(manager.getProject());
        final PsiElement shortenedFile =
            JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedFile);
        return ((PsiJavaFile) codeStyleManager.reformat(shortenedFile)).getClasses()[0];
      } else {
        return null;
      }
    } catch (IncorrectOperationException e) {
      return null;
    }
  }
コード例 #17
0
 @Override
 public void visitJavaFile(PsiJavaFile file) {
   for (PsiClass psiClass : file.getClasses()) {
     visitClass(psiClass);
   }
 }
  private PsiClass buildClass() {
    if (existingClass != null) {
      return existingClass;
    }
    final ParameterObjectBuilder beanClassBuilder = new ParameterObjectBuilder();
    beanClassBuilder.setVisibility(myCreateInnerClass ? PsiModifier.PRIVATE : PsiModifier.PUBLIC);
    beanClassBuilder.setProject(myProject);
    beanClassBuilder.setTypeArguments(typeParams);
    beanClassBuilder.setClassName(className);
    beanClassBuilder.setPackageName(packageName);
    for (ParameterChunk parameterChunk : parameters) {
      final VariableData parameter = parameterChunk.parameter;
      final boolean setterRequired = paramsNeedingSetters.contains(parameter.variable);
      beanClassBuilder.addField(
          (PsiParameter) parameter.variable, parameter.name, parameter.type, setterRequired);
    }
    final String classString = beanClassBuilder.buildBeanClass();

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(method.getProject());
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, classString);
      if (myCreateInnerClass) {
        final PsiClass containingClass = method.getContainingClass();
        final PsiClass[] classes = newFile.getClasses();
        assert classes.length > 0 : classString;
        final PsiClass innerClass = (PsiClass) containingClass.add(classes[0]);
        PsiUtil.setModifierProperty(innerClass, PsiModifier.STATIC, true);
        return (PsiClass)
            JavaCodeStyleManager.getInstance(newFile.getProject())
                .shortenClassReferences(innerClass);
      } else {
        final PsiFile containingFile = method.getContainingFile();
        final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
        final PsiDirectory directory;
        if (myMoveDestination != null) {
          directory = myMoveDestination.getTargetDirectory(containingDirectory);
        } else {
          final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
          directory =
              PackageUtil.findOrCreateDirectoryForPackage(
                  module, packageName, containingDirectory, true, true);
        }

        if (directory != null) {

          final CodeStyleManager codeStyleManager =
              CodeStyleManager.getInstance(method.getManager().getProject());
          final PsiElement shortenedFile =
              JavaCodeStyleManager.getInstance(newFile.getProject())
                  .shortenClassReferences(newFile);
          final PsiElement reformattedFile = codeStyleManager.reformat(shortenedFile);
          return ((PsiJavaFile) directory.add(reformattedFile)).getClasses()[0];
        }
      }
    } catch (IncorrectOperationException e) {
      logger.info(e);
    }
    return null;
  }