static String suggestUniqueParameterName(
     JavaCodeStyleManager codeStyleManager,
     PsiExpression expression,
     PsiType exprType,
     Set<String> existingNames) {
   SuggestedNameInfo nameInfo =
       codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, expression, exprType);
   @NonNls String[] names = nameInfo.names;
   if (expression instanceof PsiReferenceExpression) {
     final PsiElement resolve = ((PsiReferenceExpression) expression).resolve();
     if (resolve instanceof PsiVariable) {
       final VariableKind variableKind = codeStyleManager.getVariableKind((PsiVariable) resolve);
       final String propertyName =
           codeStyleManager.variableNameToPropertyName(
               ((PsiVariable) resolve).getName(), variableKind);
       final String parameterName =
           codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
       names = ArrayUtil.mergeArrays(new String[] {parameterName}, names);
     }
   }
   if (names.length == 0) names = new String[] {"param"};
   int suffix = 0;
   while (true) {
     for (String name : names) {
       String suggested = name + (suffix == 0 ? "" : String.valueOf(suffix));
       if (existingNames.add(suggested)) {
         return suggested;
       }
     }
     suffix++;
   }
 }
 private String createNewVariableName(
   @NotNull PsiForStatement scope, PsiType type,
   @Nullable String containerName) {
   final Project project = scope.getProject();
   final JavaCodeStyleManager codeStyleManager =
     JavaCodeStyleManager.getInstance(project);
   @NonNls String baseName;
   if (containerName != null) {
     baseName = StringUtils.createSingularFromName(containerName);
   }
   else {
     final SuggestedNameInfo suggestions =
       codeStyleManager.suggestVariableName(
         VariableKind.LOCAL_VARIABLE, null, null, type);
     final String[] names = suggestions.names;
     if (names != null && names.length > 0) {
       baseName = names[0];
     }
     else {
       baseName = "value";
     }
   }
   if (baseName == null || baseName.isEmpty()) {
     baseName = "value";
   }
   return codeStyleManager.suggestUniqueVariableName(baseName, scope,
                                                     true);
 }
  private static PsiMethod reformat(Project project, PsiMethod result)
      throws IncorrectOperationException {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    result = (PsiMethod) codeStyleManager.reformat(result);

    JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    result = (PsiMethod) javaCodeStyleManager.shortenClassReferences(result);
    return result;
  }
Beispiel #4
0
  public static PsiMethod generateSetterPrototype(
      PsiField field, final PsiClass containingClass, boolean returnSelf) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();

    String name = field.getName();
    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
    VariableKind kind = codeStyleManager.getVariableKind(field);
    String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
    String setName = suggestSetterName(project, field);
    try {
      PsiMethod setMethod =
          factory.createMethod(
              setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID);
      String parameterName =
          codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
      PsiParameter param = factory.createParameter(parameterName, field.getType());

      annotateWithNullableStuff(field, factory, param);

      setMethod.getParameterList().add(param);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);

      @NonNls StringBuffer buffer = new StringBuffer();
      buffer.append("{\n");
      if (name.equals(parameterName)) {
        if (!isStatic) {
          buffer.append("this.");
        } else {
          String className = containingClass.getName();
          if (className != null) {
            buffer.append(className);
            buffer.append(".");
          }
        }
      }
      buffer.append(name);
      buffer.append("=");
      buffer.append(parameterName);
      buffer.append(";\n");
      if (returnSelf) {
        buffer.append("return this;\n");
      }
      buffer.append("}");
      PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null);
      setMethod.getBody().replace(body);
      setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod);
      return setMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
 @Override
 public void postProcess(PsiElement affectedElement, ReplaceOptions options) {
   if (!affectedElement.isValid()) {
     return;
   }
   if (options.isToUseStaticImport()) {
     shortenWithStaticImports(affectedElement, 0, affectedElement.getTextLength());
   }
   if (options.isToShortenFQN()) {
     final JavaCodeStyleManager codeStyleManager =
         JavaCodeStyleManager.getInstance(affectedElement.getProject());
     codeStyleManager.shortenClassReferences(affectedElement, 0, affectedElement.getTextLength());
   }
 }
 @Nullable
 private static String getLookupObjectName(Object o) {
   if (o instanceof PsiVariable) {
     final PsiVariable variable = (PsiVariable) o;
     JavaCodeStyleManager codeStyleManager =
         JavaCodeStyleManager.getInstance(variable.getProject());
     VariableKind variableKind = codeStyleManager.getVariableKind(variable);
     return codeStyleManager.variableNameToPropertyName(variable.getName(), variableKind);
   }
   if (o instanceof PsiMethod) {
     return ((PsiMethod) o).getName();
   }
   return null;
 }
 @Override
 protected final void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement element = descriptor.getPsiElement();
   final PsiTypeElement castTypeElement;
   final PsiReferenceExpression reference;
   if (element instanceof PsiTypeCastExpression) {
     final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) element;
     castTypeElement = typeCastExpression.getCastType();
     final PsiExpression operand = typeCastExpression.getOperand();
     if (!(operand instanceof PsiReferenceExpression)) {
       return;
     }
     reference = (PsiReferenceExpression) operand;
   } else if (element instanceof PsiMethodCallExpression) {
     final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) element;
     final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
     final PsiExpression qualifier = methodExpression.getQualifierExpression();
     if (!(qualifier instanceof PsiClassObjectAccessExpression)) {
       return;
     }
     final PsiClassObjectAccessExpression classObjectAccessExpression =
         (PsiClassObjectAccessExpression) qualifier;
     castTypeElement = classObjectAccessExpression.getOperand();
     final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
     final PsiExpression[] arguments = argumentList.getExpressions();
     if (arguments.length != 1) {
       return;
     }
     final PsiExpression argument = arguments[0];
     if (!(argument instanceof PsiReferenceExpression)) {
       return;
     }
     reference = (PsiReferenceExpression) argument;
   } else {
     return;
   }
   if (castTypeElement == null) {
     return;
   }
   final PsiInstanceOfExpression conflictingInstanceof =
       InstanceOfUtils.getConflictingInstanceof(castTypeElement.getType(), reference, element);
   final PsiTypeElement instanceofTypeElement = conflictingInstanceof.getCheckType();
   if (instanceofTypeElement == null) {
     return;
   }
   final PsiElement newElement = replace(castTypeElement, instanceofTypeElement);
   final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
   codeStyleManager.shortenClassReferences(newElement);
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   PsiElement element = descriptor.getStartElement();
   if (!(element instanceof PsiLoopStatement)) return;
   PsiLoopStatement loop = (PsiLoopStatement) element;
   IteratorDeclaration declaration;
   declaration = IteratorDeclaration.fromLoop(loop);
   if (declaration == null) return;
   PsiStatement body = loop.getBody();
   if (!(body instanceof PsiBlockStatement)) return;
   PsiStatement[] statements = ((PsiBlockStatement) body).getCodeBlock().getStatements();
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   String replacement = null;
   CommentTracker ct = new CommentTracker();
   if (statements.length == 2 && statements[1] instanceof PsiIfStatement) {
     PsiVariable variable = declaration.getNextElementVariable(statements[0]);
     if (variable == null) return;
     PsiExpression condition = ((PsiIfStatement) statements[1]).getCondition();
     if (condition == null) return;
     replacement = generateRemoveIf(declaration, ct, condition, variable.getName());
   } else if (statements.length == 1 && statements[0] instanceof PsiIfStatement) {
     PsiExpression condition = ((PsiIfStatement) statements[0]).getCondition();
     if (condition == null) return;
     PsiElement ref = declaration.findOnlyIteratorRef(condition);
     if (ref != null) {
       PsiElement call = ref.getParent().getParent();
       if (!declaration.isIteratorMethodCall(call, "next")) return;
       PsiType type = ((PsiExpression) call).getType();
       JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
       SuggestedNameInfo info =
           javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type);
       if (info.names.length == 0) {
         info =
             javaCodeStyleManager.suggestVariableName(
                 VariableKind.PARAMETER, "value", null, type);
       }
       String paramName =
           javaCodeStyleManager.suggestUniqueVariableName(info, condition, true).names[0];
       ct.replace(call, factory.createIdentifier(paramName));
       replacement = generateRemoveIf(declaration, ct, condition, paramName);
     }
   }
   if (replacement == null) return;
   ct.delete(declaration.getIterator());
   PsiElement result = ct.replaceAndRestoreComments(loop, replacement);
   LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result);
   CodeStyleManager.getInstance(project).reformat(result);
 }
    @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 String[] suggestNames(PsiType defaultType, String propName) {
   return IntroduceConstantDialog.createNameSuggestionGenerator(
           propName, myExpr, JavaCodeStyleManager.getInstance(myProject), null, myParentClass)
       .getSuggestedNameInfo(defaultType)
       .names;
 }
  public void setType(@Nullable PsiType type) {
    final GrTypeElement typeElement = getTypeElementGroovy();
    if (type == null) {
      if (typeElement == null) return;
      if (getModifierList().getModifiers().length == 0) {
        getModifierList().setModifierProperty(GrModifier.DEF, true);
      }
      typeElement.delete();
      return;
    }

    type = TypesUtil.unboxPrimitiveTypeWrapper(type);
    GrTypeElement newTypeElement;
    try {
      newTypeElement = GroovyPsiElementFactory.getInstance(getProject()).createTypeElement(type);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return;
    }

    if (typeElement == null) {
      getModifierList().setModifierProperty(GrModifier.DEF, false);
      final GrVariable[] variables = getVariables();
      if (variables.length == 0) return;
      newTypeElement = (GrTypeElement) addBefore(newTypeElement, variables[0]);
    } else {
      newTypeElement = (GrTypeElement) typeElement.replace(newTypeElement);
    }

    JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(newTypeElement);
  }
  @Override
  public void run() throws Throwable {
    if (mCreateHolder) {
      generateAdapter();
    } else {
      generateFields();
      generateFindViewById();
    }

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(mFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false)
        .runWithoutProgress();
  }
  @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);
  }
  @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);
  }
  protected void doTest(final String extension) throws Exception {
    CommandProcessor.getInstance()
        .executeCommand(
            getProject(),
            () ->
                WriteCommandAction.runWriteCommandAction(
                    null,
                    () -> {
                      String fileName = getTestName(false) + extension;
                      try {
                        String text = loadFile(fileName);
                        PsiFile file = createFile(fileName, text);

                        JavaCodeStyleManager.getInstance(myProject).optimizeImports(file);
                        PostprocessReformattingAspect.getInstance(getProject())
                            .doPostponedFormatting();
                        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
                        String textAfter = loadFile(getTestName(false) + "_after" + extension);
                        String fileText = file.getText();
                        assertEquals(textAfter, fileText);
                      } catch (Exception e) {
                        LOG.error(e);
                      }
                    }),
            "",
            "");
  }
  private void fixReferencesToStatic(GroovyPsiElement classMember, Set<PsiMember> movedMembers)
      throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector(movedMembers);
    classMember.accept(collector);
    ArrayList<GrReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);

    for (int i = 0; i < refs.size(); i++) {
      GrReferenceElement ref = refs.get(i);
      PsiElement namedElement = members.get(i);
      PsiClass aClass = classes.get(i);

      if (namedElement instanceof PsiNamedElement) {
        GrReferenceExpression newRef =
            (GrReferenceExpression)
                factory.createExpressionFromText(
                    "a." + ((PsiNamedElement) namedElement).getName(), null);
        GrExpression qualifier = newRef.getQualifierExpression();
        assert qualifier != null;
        qualifier =
            (GrExpression)
                qualifier.replace(
                    factory.createReferenceExpressionFromText(aClass.getQualifiedName()));
        qualifier.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
        PsiElement replaced = ref.replace(newRef);
        JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(replaced);
      }
    }
  }
  private static PsiElement fixCatchBlock(GrTryCatchStatement tryCatch, PsiClassType[] exceptions) {
    if (exceptions.length == 0) return tryCatch;
    final GroovyPsiElementFactory factory =
        GroovyPsiElementFactory.getInstance(tryCatch.getProject());

    final GrCatchClause[] clauses = tryCatch.getCatchClauses();
    List<String> restricted =
        ContainerUtil.map(
            clauses,
            new Function<GrCatchClause, String>() {
              @Override
              @Nullable
              public String fun(GrCatchClause grCatchClause) {
                final GrParameter grParameter = grCatchClause.getParameter();
                return grParameter != null ? grParameter.getName() : null;
              }
            });

    restricted = ContainerUtil.skipNulls(restricted);
    final DefaultGroovyVariableNameValidator nameValidator =
        new DefaultGroovyVariableNameValidator(tryCatch, restricted);

    GrCatchClause anchor = clauses.length == 0 ? null : clauses[clauses.length - 1];
    for (PsiClassType type : exceptions) {
      final String[] names =
          GroovyNameSuggestionUtil.suggestVariableNameByType(type, nameValidator);
      final GrCatchClause catchClause = factory.createCatchClause(type, names[0]);
      final GrStatement printStackTrace =
          factory.createStatementFromText(names[0] + ".printStackTrace()");
      catchClause.getBody().addStatementBefore(printStackTrace, null);
      anchor = tryCatch.addCatchClause(catchClause, anchor);
      JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor);
    }
    return tryCatch;
  }
  private static void qualify(PsiMember member, PsiElement renamed, String name) {
    if (!(renamed instanceof GrReferenceExpression)) return;

    final PsiClass clazz = member.getContainingClass();
    if (clazz == null) return;

    final GrReferenceExpression refExpr = (GrReferenceExpression) renamed;
    if (refExpr.getQualifierExpression() != null) return;

    final PsiElement replaced;
    if (member.hasModifierProperty(PsiModifier.STATIC)) {
      final GrReferenceExpression newRefExpr =
          GroovyPsiElementFactory.getInstance(member.getProject())
              .createReferenceExpressionFromText(clazz.getQualifiedName() + "." + name);
      replaced = refExpr.replace(newRefExpr);
    } else {
      final PsiClass containingClass = PsiTreeUtil.getParentOfType(renamed, PsiClass.class);
      if (member.getManager().areElementsEquivalent(containingClass, clazz)) {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText("this." + name);
        replaced = refExpr.replace(newRefExpr);
      } else {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText(clazz.getQualifiedName() + ".this." + name);
        replaced = refExpr.replace(newRefExpr);
      }
    }
    JavaCodeStyleManager.getInstance(replaced.getProject()).shortenClassReferences(replaced);
  }
  private void addNewClause(
      Collection<String> elements,
      Collection<String> additional,
      Project project,
      boolean isExtends)
      throws IncorrectOperationException {
    if (elements.isEmpty() && additional.isEmpty()) return;

    StringBuilder classText = new StringBuilder();
    classText.append("class A ");
    classText.append(isExtends ? "extends " : "implements ");

    for (String str : elements) {
      classText.append(str);
      classText.append(", ");
    }

    for (String str : additional) {
      classText.append(str);
      classText.append(", ");
    }

    classText.delete(classText.length() - 2, classText.length());

    classText.append(" {}");

    final GrTypeDefinition definition =
        GroovyPsiElementFactory.getInstance(project).createTypeDefinition(classText.toString());
    GroovyPsiElement clause =
        isExtends ? definition.getExtendsClause() : definition.getImplementsClause();
    assert clause != null;

    PsiElement addedClause = myClass.addBefore(clause, myClass.getBody());
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClause);
  }
  private static void addExceptions(PsiClassType[] exceptionsToAdd, PsiTryStatement tryStatement)
      throws IncorrectOperationException {
    for (PsiClassType type : exceptionsToAdd) {
      final JavaCodeStyleManager styleManager =
          JavaCodeStyleManager.getInstance(tryStatement.getProject());
      String name =
          styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type).names[0];
      name = styleManager.suggestUniqueVariableName(name, tryStatement, false);

      PsiCatchSection catchSection =
          JavaPsiFacade.getInstance(tryStatement.getProject())
              .getElementFactory()
              .createCatchSection(type, name, tryStatement);
      tryStatement.add(catchSection);
    }
  }
  private PsiMethod generateMethodPrototype(PsiField field) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    String propertyName =
        codeStyleManager.variableNameToPropertyName(
            field.getName(), codeStyleManager.getVariableKind(field));
    String methodName = methodNameGenerator.generateMethodNameFor(propertyName);
    String parameterName =
        codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);

    PsiMethod withMethod = generateMethodFor(field, methodName, parameterName, elementFactory);
    generateMethodBodyFor(withMethod, propertyName, parameterName, elementFactory);

    return withMethod;
  }
 private static boolean shouldRenameSetterParameter(
     JavaCodeStyleManager manager, String propertyName, PsiMethod setter) {
   boolean shouldRenameSetterParameter;
   String parameterName = manager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
   PsiParameter setterParameter = setter.getParameterList().getParameters()[0];
   shouldRenameSetterParameter = parameterName.equals(setterParameter.getName());
   return shouldRenameSetterParameter;
 }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
  private static void generateProperty(
      final JavaCodeStyleManager codeStyleManager,
      final String property,
      final String type,
      @NonNls final StringBuffer membersBuffer,
      @NonNls final StringBuffer methodsBuffer) {
    final String field =
        codeStyleManager.suggestVariableName(VariableKind.FIELD, property, null, null).names[0];

    membersBuffer.append("private ");
    membersBuffer.append(type);
    membersBuffer.append(" ");
    membersBuffer.append(field);
    membersBuffer.append(";\n");

    // getter
    methodsBuffer.append("public ");
    methodsBuffer.append(type);
    methodsBuffer.append(" ");
    methodsBuffer.append(suggestGetterName(property, type));
    methodsBuffer.append("(){\n");
    methodsBuffer.append("return ");
    methodsBuffer.append(field);
    methodsBuffer.append(";}\n");

    // setter
    final String parameterName =
        codeStyleManager.suggestVariableName(VariableKind.PARAMETER, property, null, null).names[0];
    methodsBuffer.append("public void ");
    methodsBuffer.append(PropertyUtil.suggestSetterName(property));
    methodsBuffer.append("(final ");
    methodsBuffer.append(type);
    methodsBuffer.append(" ");
    methodsBuffer.append(parameterName);
    methodsBuffer.append("){\n");
    if (parameterName.equals(field)) {
      methodsBuffer.append("this.");
    }
    methodsBuffer.append(field);
    methodsBuffer.append("=");
    methodsBuffer.append(parameterName);
    methodsBuffer.append(";}\n");
  }
  // 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());
    }
  }
 private static String getUniqueParameterName(
     PsiParameter[] parameters, PsiVariable variable, HashMap<PsiField, String> usedNames) {
   final JavaCodeStyleManager styleManager =
       JavaCodeStyleManager.getInstance(variable.getProject());
   final SuggestedNameInfo nameInfo =
       styleManager.suggestVariableName(
           VariableKind.PARAMETER,
           styleManager.variableNameToPropertyName(variable.getName(), VariableKind.FIELD),
           null,
           variable.getType());
   String newName = nameInfo.names[0];
   int n = 1;
   while (true) {
     if (isUnique(parameters, newName, usedNames)) {
       break;
     }
     newName = nameInfo.names[0] + n++;
   }
   return newName;
 }
 private static String suggestNewName(Project project, PsiVariable variable) {
   // new name should not conflict with another variable at the variable declaration level and
   // usage level
   String name = variable.getName();
   // trim last digit to suggest variable names like i1,i2, i3...
   if (name.length() > 1 && Character.isDigit(name.charAt(name.length() - 1))) {
     name = name.substring(0, name.length() - 1);
   }
   name = "final" + StringUtil.capitalize(StringUtil.trimStart(name, "final"));
   return JavaCodeStyleManager.getInstance(project)
       .suggestUniqueVariableName(name, variable, true);
 }
Beispiel #28
0
  @Override
  protected void run() throws Throwable {
    int fieldCount = 0;
    PsiMethod initViewMethod = getInitView();
    StringBuilder methodBuild = new StringBuilder("private void initView() {");
    for (ViewPart viewPart : viewPartList) {
      if (!viewPart.isSelected() || fieldExist(viewPart)) {
        continue;
      }
      mClass.add(mFactory.createFieldFromText(viewPart.getDeclareString(false, false), mClass));
      if (initViewMethod != null) {
        initViewMethod
            .getBody()
            .add(mFactory.createStatementFromText(viewPart.getFindViewString(), mClass));
      } else {
        if (isViewHolder) {
          methodBuild.append(viewPart.getFindViewStringForViewHolder("convertView"));
        } else if (isAddRootView && !TextUtils.isEmpty(rootViewStr)) {
          methodBuild.append(viewPart.getFindViewStringWithRootView(rootViewStr));
        } else {
          methodBuild.append(viewPart.getFindViewString());
        }
        fieldCount++;
      }
    }
    methodBuild.append("}");
    if (fieldCount > 0) {
      mClass.add(mFactory.createMethodFromText(methodBuild.toString(), mClass));
    }
    addInitViewAfterOnCreate();

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(psiFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false)
        .runWithoutProgress();
  }
    @Override
    public void handleInsert(InsertionContext context) {
      context
          .getDocument()
          .replaceString(context.getStartOffset(), context.getTailOffset(), getInsertString());
      context.commitDocument();

      PsiMethodCallExpression call =
          PsiTreeUtil.findElementOfClassAtOffset(
              context.getFile(), context.getStartOffset(), PsiMethodCallExpression.class, false);
      if (call == null) return;

      PsiExpression[] args = call.getArgumentList().getExpressions();
      if (args.length != 1 || !(args[0] instanceof PsiMethodCallExpression)) return;

      JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(args[0]);
    }
 private static void resolveParameterVsFieldsConflicts(
     final PsiParameter[] newParms,
     final PsiMethod method,
     final PsiParameterList list,
     boolean[] toRemoveParm)
     throws IncorrectOperationException {
   List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>();
   for (PsiParameter parameter : newParms) {
     conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody()));
   }
   ChangeSignatureUtil.synchronizeList(
       list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm);
   JavaCodeStyleManager.getInstance(list.getProject()).shortenClassReferences(list);
   for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) {
     fieldConflictsResolver.fix();
   }
 }