public void insertOrUpdateTranslation(
      String key, String value, final PropertiesFile propertiesFile)
      throws IncorrectOperationException {
    final IProperty property = propertiesFile.findPropertyByKey(key);
    if (property != null) {
      final String oldValue = property.getValue();
      if (!Comparing.equal(oldValue, value)) {
        property.setValue(value);
        myCodeStyleManager.reformat(property.getPsiElement());
      }
      return;
    }

    if (myOrdered) {
      if (myAlphaSorted) {
        myCodeStyleManager.reformat(propertiesFile.addProperty(key, value).getPsiElement());
        return;
      }
      final Pair<IProperty, Integer> propertyAndPosition =
          findExistedPrevSiblingProperty(key, propertiesFile);
      myCodeStyleManager.reformat(
          propertiesFile
              .addPropertyAfter(
                  key,
                  value,
                  propertyAndPosition == null ? null : (Property) propertyAndPosition.getFirst())
              .getPsiElement());
    } else {
      insertPropertyLast(key, value, propertiesFile);
    }
  }
  @NotNull
  @Override
  public PsiCatchSection createCatchSection(
      @NotNull final PsiType exceptionType,
      @NotNull final String exceptionName,
      @Nullable final PsiElement context)
      throws IncorrectOperationException {
    if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) {
      throw new IncorrectOperationException("Unexpected type:" + exceptionType);
    }

    @NonNls
    final String text = "catch (" + exceptionType.getCanonicalText() + " " + exceptionName + ") {}";
    final DummyHolder holder =
        DummyHolderFactory.createHolder(
            myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context);
    final PsiElement element =
        SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode());
    if (!(element instanceof PsiCatchSection)) {
      throw new IncorrectOperationException(
          "Incorrect catch section '" + text + "'. Parsed element: " + element);
    }

    final Project project = myManager.getProject();
    final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project);
    helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection) element);
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    final PsiCatchSection catchSection = (PsiCatchSection) styleManager.reformat(element);

    GeneratedMarkerVisitor.markGenerated(catchSection);
    return catchSection;
  }
示例#3
0
 protected static void replaceExpressionWithNegatedExpression(
     @NotNull PsiExpression newExpression, @NotNull PsiExpression expression) {
   final Project project = expression.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   PsiExpression expressionToReplace = expression;
   final String newExpressionText = newExpression.getText();
   final String expString;
   if (BoolUtils.isNegated(expression)) {
     expressionToReplace = BoolUtils.findNegation(expression);
     expString = newExpressionText;
   } else if (ComparisonUtils.isComparison(newExpression)) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) newExpression;
     final String negatedComparison =
         ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
     final PsiExpression lhs = binaryExpression.getLOperand();
     final PsiExpression rhs = binaryExpression.getROperand();
     assert rhs != null;
     expString = lhs.getText() + negatedComparison + rhs.getText();
   } else {
     if (ParenthesesUtils.getPrecedence(newExpression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
       expString = "!(" + newExpressionText + ')';
     } else {
       expString = '!' + newExpressionText;
     }
   }
   final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
   assert expressionToReplace != null;
   final PsiElement insertedElement = expressionToReplace.replace(newCall);
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   codeStyleManager.reformat(insertedElement);
 }
 private void insertPropertyLast(String key, String value, PropertiesFile propertiesFile) {
   final List<IProperty> properties = propertiesFile.getProperties();
   final IProperty lastProperty =
       properties.isEmpty() ? null : properties.get(properties.size() - 1);
   myCodeStyleManager.reformat(
       propertiesFile.addPropertyAfter(key, value, lastProperty).getPsiElement());
 }
示例#5
0
  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;
  }
    @Nullable
    private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings)
        throws IncorrectOperationException {
      myDocument.insertString(myOffset, buffer);

      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      CodeStyleManager.getInstance(getProject())
          .adjustLineIndent(myFile, myOffset + buffer.length() - 2);

      PsiComment comment =
          PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);

      comment = createJavaDocStub(settings, comment, getProject());
      if (comment == null) {
        return null;
      }

      CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
      CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
      boolean old = codeStyleSettings.ENABLE_JAVADOC_FORMATTING;
      codeStyleSettings.ENABLE_JAVADOC_FORMATTING = false;

      try {
        comment = (PsiComment) codeStyleManager.reformat(comment);
      } finally {
        codeStyleSettings.ENABLE_JAVADOC_FORMATTING = old;
      }
      PsiElement next = comment.getNextSibling();
      if (next == null && comment.getParent().getClass() == comment.getClass()) {
        next =
            comment
                .getParent()
                .getNextSibling(); // expanding chameleon comment produces comment under comment
      }
      if (next != null) {
        next =
            myFile.findElementAt(
                next.getTextRange().getStartOffset()); // maybe switch to another tree
      }
      if (next != null
          && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode())
              || !next.getText().contains(LINE_SEPARATOR))) {
        int lineBreakOffset = comment.getTextRange().getEndOffset();
        myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
        comment =
            PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
      }
      return comment;
    }
 public void insertNewProperty(String key, String value) {
   if (ApplicationManager.getApplication().isUnitTestMode() && myKeysOrder != null) {
     LOG.assertTrue(!myKeysOrder.contains(key));
   }
   final PropertiesFile propertiesFile = myResourceBundle.getDefaultPropertiesFile();
   if (myAlphaSorted) {
     myCodeStyleManager.reformat(propertiesFile.addProperty(key, value).getPsiElement());
   } else {
     insertPropertyLast(key, value, propertiesFile);
     if (myOrdered) {
       myKeysOrder.add(key);
     }
   }
 }
 public static PsiReferenceExpression qualifyReference(
     PsiReferenceExpression referenceExpression,
     final PsiMember member,
     @Nullable final PsiClass qualifyingClass)
     throws IncorrectOperationException {
   PsiManager manager = referenceExpression.getManager();
   PsiMethodCallExpression methodCallExpression =
       PsiTreeUtil.getParentOfType(referenceExpression, PsiMethodCallExpression.class, true);
   while ((methodCallExpression) != null) {
     if (HighlightUtil.isSuperOrThisMethodCall(methodCallExpression)) {
       return referenceExpression;
     }
     methodCallExpression =
         PsiTreeUtil.getParentOfType(methodCallExpression, PsiMethodCallExpression.class, true);
   }
   PsiReferenceExpression expressionFromText;
   final PsiElementFactory factory =
       JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
   if (qualifyingClass == null) {
     PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
     final PsiClass containingClass = member.getContainingClass();
     if (parentClass != null
         && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
       while (parentClass != null
           && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
         parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
       }
       LOG.assertTrue(parentClass != null);
       expressionFromText =
           (PsiReferenceExpression)
               factory.createExpressionFromText("A.this." + member.getName(), null);
       ((PsiThisExpression) expressionFromText.getQualifierExpression())
           .getQualifier()
           .replace(factory.createClassReferenceElement(parentClass));
     } else {
       expressionFromText =
           (PsiReferenceExpression)
               factory.createExpressionFromText("this." + member.getName(), null);
     }
   } else {
     expressionFromText =
         (PsiReferenceExpression) factory.createExpressionFromText("A." + member.getName(), null);
     expressionFromText.setQualifierExpression(factory.createReferenceExpression(qualifyingClass));
   }
   CodeStyleManager codeStyleManager = manager.getCodeStyleManager();
   expressionFromText = (PsiReferenceExpression) codeStyleManager.reformat(expressionFromText);
   return (PsiReferenceExpression) referenceExpression.replace(expressionFromText);
 }
 @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 void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0) fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
      fieldBuffer.append("this");
    }

    fieldBuffer.append(");");
    try {
      final String fieldString = fieldBuffer.toString();
      final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
      final PsiElement newField = sourceClass.add(field);
      codeStyleManager.reformat(
          JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
      logger.error(e);
    }
  }
  @Override
  public TextRange surroundStatements(
      Project project, Editor editor, PsiElement container, PsiElement[] statements)
      throws IncorrectOperationException {
    PsiManager manager = PsiManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    statements = SurroundWithUtil.moveDeclarationsOut(container, statements, false);
    if (statements.length == 0) {
      return null;
    }

    @NonNls String text = "try{\n}finally{\n\n}";
    PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null);
    tryStatement = (PsiTryStatement) codeStyleManager.reformat(tryStatement);

    tryStatement =
        (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]);

    PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    if (tryBlock == null) {
      return null;
    }
    SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements);
    tryBlock.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);

    PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
    if (finallyBlock == null) {
      return null;
    }
    int offset = finallyBlock.getTextRange().getStartOffset() + 2;
    editor.getCaretModel().moveToOffset(offset);
    final Document document = editor.getDocument();
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    editor.getSelectionModel().removeSelection();
    final PsiStatement firstTryStmt = tryBlock.getStatements()[0];
    final int indent =
        firstTryStmt.getTextOffset()
            - document.getLineStartOffset(document.getLineNumber(firstTryStmt.getTextOffset()));
    EditorModificationUtil.insertStringAtCaret(editor, StringUtil.repeat(" ", indent), false, true);
    return new TextRange(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset());
  }
  protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory)
      throws IncorrectOperationException {
    if (!mySettings.isChangeSignature()) return;

    PsiElement element = usage.getElement();

    if (element instanceof PsiReferenceExpression) {
      PsiReferenceExpression newRef = null;

      if (mySettings.isMakeFieldParameters()) {
        PsiElement resolved = ((PsiReferenceExpression) element).resolve();
        if (resolved instanceof PsiField) {
          String name = mySettings.getNameForField((PsiField) resolved);
          if (name != null) {
            newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null);
          }
        }
      }

      if (newRef == null && mySettings.isMakeClassParameter()) {
        newRef =
            (PsiReferenceExpression)
                factory.createExpressionFromText(
                    mySettings.getClassParameterName() + "." + element.getText(), null);
      }

      if (newRef != null) {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        newRef = (PsiReferenceExpression) codeStyleManager.reformat(newRef);
        element.replace(newRef);
      }
    } else if (element instanceof PsiThisExpression && mySettings.isMakeClassParameter()) {
      element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
    } else if (element instanceof PsiSuperExpression && mySettings.isMakeClassParameter()) {
      element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
    } else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter()) {
      final PsiNewExpression newExpression = ((PsiNewExpression) element);
      LOG.assertTrue(newExpression.getQualifier() == null);
      final String newText = mySettings.getClassParameterName() + "." + newExpression.getText();
      final PsiExpression expr = factory.createExpressionFromText(newText, null);
      element.replace(expr);
    }
  }
  // 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());
    }
  }
  @Override
  public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr)
      throws IncorrectOperationException {
    PsiManager manager = expr.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    @NonNls String text = "if(a){\nst;\n}";
    PsiIfStatement ifStatement = (PsiIfStatement) factory.createStatementFromText(text, null);
    ifStatement = (PsiIfStatement) codeStyleManager.reformat(ifStatement);

    ifStatement.getCondition().replace(expr);

    PsiExpressionStatement statement = (PsiExpressionStatement) expr.getParent();
    ifStatement = (PsiIfStatement) statement.replace(ifStatement);

    PsiCodeBlock block = ((PsiBlockStatement) ifStatement.getThenBranch()).getCodeBlock();
    block = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(block);
    TextRange range = block.getStatements()[0].getTextRange();
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    return new TextRange(range.getStartOffset(), range.getStartOffset());
  }
 public static GrReferenceExpression qualifyReference(
     GrReferenceExpression referenceExpression,
     final PsiMember member,
     @Nullable final PsiClass qualifyingClass)
     throws IncorrectOperationException {
   PsiManager manager = referenceExpression.getManager();
   GrReferenceExpression expressionFromText;
   final GroovyPsiElementFactory factory =
       GroovyPsiElementFactory.getInstance(referenceExpression.getProject());
   if (qualifyingClass == null) {
     PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
     final PsiClass containingClass = member.getContainingClass();
     if (parentClass != null
         && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
       while (parentClass != null
           && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
         parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
       }
       LOG.assertTrue(parentClass != null);
       expressionFromText =
           factory.createReferenceExpressionFromText("A.this." + member.getName());
       //noinspection ConstantConditions
       ((GrReferenceExpression) expressionFromText.getQualifier())
           .getQualifier()
           .replace(factory.createReferenceElementForClass(parentClass));
     } else {
       expressionFromText =
           (GrReferenceExpression) factory.createExpressionFromText("this." + member.getName());
     }
   } else {
     expressionFromText =
         (GrReferenceExpression) factory.createExpressionFromText("A." + member.getName());
     expressionFromText.setQualifier(factory.createReferenceElementForClass(qualifyingClass));
   }
   CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
   expressionFromText = (GrReferenceExpression) codeStyleManager.reformat(expressionFromText);
   return (GrReferenceExpression) referenceExpression.replace(expressionFromText);
 }
示例#16
0
 protected static void replaceExpressionWithNegatedExpressionString(
     @NotNull String newExpression, @NotNull PsiExpression expression) {
   final Project project = expression.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiElementFactory factory = psiFacade.getElementFactory();
   PsiExpression expressionToReplace = expression;
   final String expString;
   if (BoolUtils.isNegated(expression)) {
     expressionToReplace = BoolUtils.findNegation(expressionToReplace);
     expString = newExpression;
   } else {
     PsiElement parent = expressionToReplace.getParent();
     while (parent instanceof PsiParenthesizedExpression) {
       expressionToReplace = (PsiExpression) parent;
       parent = parent.getParent();
     }
     expString = "!(" + newExpression + ')';
   }
   final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
   assert expressionToReplace != null;
   final PsiElement insertedElement = expressionToReplace.replace(newCall);
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   codeStyleManager.reformat(insertedElement);
 }
示例#17
0
  @Override
  public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr)
      throws IncorrectOperationException {
    PsiManager manager = expr.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    @NonNls String text = "if(a != null){\nst;\n}";
    PsiIfStatement ifStatement = (PsiIfStatement) factory.createStatementFromText(text, null);
    ifStatement = (PsiIfStatement) codeStyleManager.reformat(ifStatement);

    ((PsiBinaryExpression) ifStatement.getCondition()).getLOperand().replace(expr);

    PsiExpressionStatement statement =
        PsiTreeUtil.getParentOfType(expr, PsiExpressionStatement.class);
    String oldText = statement.getText();
    ifStatement = (PsiIfStatement) statement.replace(ifStatement);
    PsiCodeBlock block = ((PsiBlockStatement) ifStatement.getThenBranch()).getCodeBlock();
    block = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(block);
    PsiElement replace =
        block.getStatements()[0].replace(factory.createStatementFromText(oldText, block));
    int offset = replace.getTextRange().getEndOffset();
    return new TextRange(offset, offset);
  }
  @NotNull
  @Override
  public PsiParameter createParameter(@NotNull final String name, @NotNull final PsiType type)
      throws IncorrectOperationException {
    PsiUtil.checkIsIdentifier(myManager, name);
    if (PsiType.NULL.equals(type)) {
      throw new IncorrectOperationException("Cannot create parameter with type \"null\".");
    }

    final String text = type.getCanonicalText() + " " + name;
    PsiParameter parameter = createParameterFromText(text, null);
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myManager.getProject());
    PsiUtil.setModifierProperty(
        parameter,
        PsiModifier.FINAL,
        JavaCodeStyleSettingsFacade.getInstance(myManager.getProject())
            .isGenerateFinalParameters());
    GeneratedMarkerVisitor.markGenerated(parameter);
    parameter =
        (PsiParameter)
            JavaCodeStyleManager.getInstance(myManager.getProject())
                .shortenClassReferences(parameter);
    return (PsiParameter) codeStyleManager.reformat(parameter);
  }
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiReferenceExpression parameterReference =
       (PsiReferenceExpression) descriptor.getPsiElement();
   final PsiElement target = parameterReference.resolve();
   if (!(target instanceof PsiParameter)) {
     return;
   }
   final PsiParameter parameter = (PsiParameter) target;
   final PsiElement declarationScope = parameter.getDeclarationScope();
   final PsiElement body;
   if (declarationScope instanceof PsiMethod) {
     final PsiMethod method = (PsiMethod) declarationScope;
     body = method.getBody();
   } else if (declarationScope instanceof PsiCatchSection) {
     final PsiCatchSection catchSection = (PsiCatchSection) declarationScope;
     body = catchSection.getCatchBlock();
   } else if (declarationScope instanceof PsiLoopStatement) {
     final PsiLoopStatement forStatement = (PsiLoopStatement) declarationScope;
     final PsiStatement forBody = forStatement.getBody();
     if (forBody instanceof PsiBlockStatement) {
       final PsiBlockStatement blockStatement = (PsiBlockStatement) forBody;
       body = blockStatement.getCodeBlock();
     } else {
       body = forBody;
     }
   } else {
     return;
   }
   if (body == null) {
     return;
   }
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   final String parameterName = parameterReference.getText();
   final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
   final String variableName =
       javaCodeStyleManager.suggestUniqueVariableName(parameterName, parameterReference, true);
   final SearchScope scope = parameter.getUseScope();
   final Query<PsiReference> search = ReferencesSearch.search(parameter, scope);
   final PsiReference reference = search.findFirst();
   if (reference == null) {
     return;
   }
   final PsiElement element = reference.getElement();
   if (!(element instanceof PsiReferenceExpression)) {
     return;
   }
   final PsiReferenceExpression firstReference = (PsiReferenceExpression) element;
   final PsiElement[] children = body.getChildren();
   final int startIndex;
   final int endIndex;
   if (body instanceof PsiCodeBlock) {
     startIndex = 1;
     endIndex = children.length - 1;
   } else {
     startIndex = 0;
     endIndex = children.length;
   }
   boolean newDeclarationCreated = false;
   final StringBuilder buffer = new StringBuilder();
   for (int i = startIndex; i < endIndex; i++) {
     final PsiElement child = children[i];
     newDeclarationCreated |=
         replaceVariableName(child, firstReference, variableName, parameterName, buffer);
   }
   final String replacementText;
   if (newDeclarationCreated) {
     replacementText = "{" + buffer + '}';
   } else {
     final PsiType type = parameterReference.getType();
     if (type == null) {
       return;
     }
     final String className = type.getCanonicalText();
     replacementText =
         '{' + className + ' ' + variableName + " = " + parameterName + ';' + buffer + '}';
   }
   final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
   final PsiCodeBlock block = elementFactory.createCodeBlockFromText(replacementText, null);
   body.replace(block);
   codeStyleManager.reformat(declarationScope);
 }
  /** Should be invoked in command and write action */
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static void generateDataBindingMethods(final WizardData data) throws MyException {
    if (data.myBindToNewBean) {
      data.myBeanClass = createBeanClass(data);
    } else {
      if (!CommonRefactoringUtil.checkReadOnlyStatus(
          data.myBeanClass.getProject(), data.myBeanClass)) {
        return;
      }
    }

    final HashMap<String, String> binding2beanGetter = new HashMap<String, String>();
    final HashMap<String, String> binding2beanSetter = new HashMap<String, String>();

    final FormProperty2BeanProperty[] bindings = data.myBindings;
    for (final FormProperty2BeanProperty form2bean : bindings) {
      if (form2bean == null || form2bean.myBeanProperty == null) {
        continue;
      }

      // check that bean contains the property, and if not, try to add the property to the bean
      {
        final String setterName = PropertyUtil.suggestSetterName(form2bean.myBeanProperty.myName);
        final PsiMethod[] methodsByName = data.myBeanClass.findMethodsByName(setterName, true);
        if (methodsByName.length < 1) {
          // bean does not contain this property
          // try to add...

          LOG.assertTrue(
              !data.myBindToNewBean); // just generated bean class should contain all necessary
                                      // properties

          if (!data.myBeanClass.isWritable()) {
            throw new MyException(
                "Cannot add property to non writable class " + data.myBeanClass.getQualifiedName());
          }

          final StringBuffer membersBuffer = new StringBuffer();
          final StringBuffer methodsBuffer = new StringBuffer();

          final Project project = data.myBeanClass.getProject();
          final CodeStyleManager formatter = CodeStyleManager.getInstance(project);
          final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(project);

          generateProperty(
              styler,
              form2bean.myBeanProperty.myName,
              form2bean.myBeanProperty.myType,
              membersBuffer,
              methodsBuffer);

          final PsiClass fakeClass;
          try {
            fakeClass =
                JavaPsiFacade.getInstance(data.myBeanClass.getProject())
                    .getElementFactory()
                    .createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null);

            final PsiField[] fields = fakeClass.getFields();
            {
              final PsiElement result = data.myBeanClass.add(fields[0]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }

            final PsiMethod[] methods = fakeClass.getMethods();
            {
              final PsiElement result = data.myBeanClass.add(methods[0]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }
            {
              final PsiElement result = data.myBeanClass.add(methods[1]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }
          } catch (IncorrectOperationException e) {
            throw new MyException(e.getMessage());
          }
        }
      }

      final PsiMethod propertySetter =
          PropertyUtil.findPropertySetter(
              data.myBeanClass, form2bean.myBeanProperty.myName, false, true);
      final PsiMethod propertyGetter =
          PropertyUtil.findPropertyGetter(
              data.myBeanClass, form2bean.myBeanProperty.myName, false, true);

      if (propertyGetter == null) {
        // todo
        continue;
      }
      if (propertySetter == null) {
        // todo
        continue;
      }

      final String binding = form2bean.myFormProperty.getLwComponent().getBinding();
      binding2beanGetter.put(binding, propertyGetter.getName());
      binding2beanSetter.put(binding, propertySetter.getName());
    }

    final String dataBeanClassName = data.myBeanClass.getQualifiedName();

    final LwRootContainer[] rootContainer = new LwRootContainer[1];
    final FormProperty[] formProperties =
        exposeForm(data.myProject, data.myFormFile, rootContainer);

    final StringBuffer getDataBody = new StringBuffer();
    final StringBuffer setDataBody = new StringBuffer();
    final StringBuffer isModifiedBody = new StringBuffer();

    // iterate exposed formproperties

    for (final FormProperty formProperty : formProperties) {
      final String binding = formProperty.getLwComponent().getBinding();
      if (!binding2beanGetter.containsKey(binding)) {
        continue;
      }

      getDataBody.append("data.");
      getDataBody.append(binding2beanSetter.get(binding));
      getDataBody.append("(");
      getDataBody.append(binding);
      getDataBody.append(".");
      getDataBody.append(formProperty.getComponentPropertyGetterName());
      getDataBody.append("());\n");

      setDataBody.append(binding);
      setDataBody.append(".");
      setDataBody.append(formProperty.getComponentPropertySetterName());
      setDataBody.append("(data.");
      setDataBody.append(binding2beanGetter.get(binding));
      setDataBody.append("());\n");

      final String propertyClassName = formProperty.getComponentPropertyClassName();
      if ("boolean".equals(propertyClassName)) {
        isModifiedBody.append("if (");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append("!= ");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        //
        isModifiedBody.append(") return true;\n");
      } else {
        isModifiedBody.append("if (");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append("!= null ? ");
        //
        isModifiedBody.append("!");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append(".equals(");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        isModifiedBody.append(") : ");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        isModifiedBody.append("!= null");
        //
        isModifiedBody.append(") return true;\n");
      }
    }
    isModifiedBody.append("return false;\n");

    final String textOfMethods =
        "public void setData("
            + dataBeanClassName
            + " data){\n"
            + setDataBody.toString()
            + "}\n"
            + "\n"
            + "public void getData("
            + dataBeanClassName
            + " data){\n"
            + getDataBody.toString()
            + "}\n"
            + "\n"
            + "public boolean isModified("
            + dataBeanClassName
            + " data){\n"
            + isModifiedBody.toString()
            + "}\n";

    // put them to the bound class

    final Module module = ModuleUtil.findModuleForFile(data.myFormFile, data.myProject);
    LOG.assertTrue(module != null);
    final PsiClass boundClass =
        FormEditingUtil.findClassToBind(module, rootContainer[0].getClassToBind());
    LOG.assertTrue(boundClass != null);

    if (!CommonRefactoringUtil.checkReadOnlyStatus(module.getProject(), boundClass)) {
      return;
    }

    // todo: check that this method does not exist yet

    final PsiClass fakeClass;
    try {
      fakeClass =
          JavaPsiFacade.getInstance(data.myProject)
              .getElementFactory()
              .createClassFromText(textOfMethods, null);

      final PsiMethod methodSetData = fakeClass.getMethods()[0];
      final PsiMethod methodGetData = fakeClass.getMethods()[1];
      final PsiMethod methodIsModified = fakeClass.getMethods()[2];

      final PsiMethod existing1 = boundClass.findMethodBySignature(methodSetData, false);
      final PsiMethod existing2 = boundClass.findMethodBySignature(methodGetData, false);
      final PsiMethod existing3 = boundClass.findMethodBySignature(methodIsModified, false);

      // warning already shown
      if (existing1 != null) {
        existing1.delete();
      }
      if (existing2 != null) {
        existing2.delete();
      }
      if (existing3 != null) {
        existing3.delete();
      }

      final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject());
      final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject());

      final PsiElement setData = boundClass.add(methodSetData);
      styler.shortenClassReferences(setData);
      formatter.reformat(setData);

      final PsiElement getData = boundClass.add(methodGetData);
      styler.shortenClassReferences(getData);
      formatter.reformat(getData);

      if (data.myGenerateIsModified) {
        final PsiElement isModified = boundClass.add(methodIsModified);
        styler.shortenClassReferences(isModified);
        formatter.reformat(isModified);
      }

      final OpenFileDescriptor descriptor =
          new OpenFileDescriptor(
              setData.getProject(),
              setData.getContainingFile().getVirtualFile(),
              setData.getTextOffset());
      FileEditorManager.getInstance(data.myProject).openTextEditor(descriptor, true);
    } catch (IncorrectOperationException e) {
      throw new MyException(e.getMessage());
    }
  }
  public static PsiMethod generateConstructorPrototype(
      PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields)
      throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    JVMElementFactory factory =
        JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());

    PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
    String modifier = PsiUtil.getMaximumModifierForMember(aClass, false);

    if (modifier != null) {
      PsiUtil.setModifierProperty(constructor, modifier, true);
    }

    if (baseConstructor != null) {
      PsiJavaCodeReferenceElement[] throwRefs =
          baseConstructor.getThrowsList().getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : throwRefs) {
        constructor.getThrowsList().add(ref);
      }

      if (copyJavaDoc) {
        final PsiDocComment docComment =
            ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
        if (docComment != null) {
          constructor.addAfter(docComment, null);
        }
      }
    }

    boolean isNotEnum = false;
    if (baseConstructor != null) {
      PsiClass superClass = aClass.getSuperClass();
      LOG.assertTrue(superClass != null);
      if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
        isNotEnum = true;
        if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
          PsiClass dummyClass =
              JVMElementFactories.requireFactory(
                      baseConstructor.getLanguage(), baseConstructor.getProject())
                  .createClass("Dummy");
          baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
        }
        PsiParameter[] params = baseConstructor.getParameterList().getParameters();
        for (PsiParameter param : params) {
          PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
          GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
          constructor.getParameterList().add(newParam);
        }
      }
    }

    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());

    final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
    for (PsiField field : fields) {
      String fieldName = field.getName();
      String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
      String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
      parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
      PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);

      final NullableNotNullManager nullableManager =
          NullableNotNullManager.getInstance(field.getProject());
      final String notNull = nullableManager.getNotNull(field);
      if (notNull != null) {
        parm.getModifierList()
            .addAfter(factory.createAnnotationFromText("@" + notNull, field), null);
      }

      constructor.getParameterList().add(parm);
      dummyConstructor.getParameterList().add(parm.copy());
      fieldParams.add(parm);
    }

    ConstructorBodyGenerator generator =
        ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
      @NonNls StringBuilder buffer = new StringBuilder();
      generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
      if (isNotEnum) {
        generator.generateSuperCallIfNeeded(
            buffer, baseConstructor.getParameterList().getParameters());
      }
      generator.generateFieldInitialization(
          buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
      generator.finish(buffer);
      PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
      constructor.getBody().replace(stub.getBody());
    }

    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
  }
示例#22
0
  public PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(file.getProject());

    final Set<String> namesToImportStaticly = new THashSet<String>();
    String[] names =
        collectNamesToImport(
            file,
            namesToImportStaticly); // Note: this array may contain "<packageOrClassName>.*" for
                                    // unresolved imports!
    Arrays.sort(names);

    ArrayList<String> namesList = new ArrayList<String>();
    ImportLayoutTable table = mySettings.IMPORT_LAYOUT_TABLE;
    if (table != null) {
      int[] entriesForName = ArrayUtil.newIntArray(names.length);
      for (int i = 0; i < names.length; i++) {
        entriesForName[i] = findEntryIndex(names[i]);
      }

      Entry[] entries = table.getEntries();
      for (int i = 0; i < entries.length; i++) {
        Entry entry = entries[i];
        if (entry instanceof PackageEntry) {
          for (int j = 0; j < names.length; j++) {
            if (entriesForName[j] == i) {
              namesList.add(names[j]);
              names[j] = null;
            }
          }
        }
      }
    }
    for (String name : names) {
      if (name != null) namesList.add(name);
    }
    names = ArrayUtil.toStringArray(namesList);

    TObjectIntHashMap<String> packageToCountMap = new TObjectIntHashMap<String>();
    TObjectIntHashMap<String> classToCountMap = new TObjectIntHashMap<String>();
    for (String name : names) {
      String packageOrClassName = getPackageOrClassName(name);
      if (packageOrClassName.length() == 0) continue;
      if (namesToImportStaticly.contains(name)) {
        int count = classToCountMap.get(packageOrClassName);
        classToCountMap.put(packageOrClassName, count + 1);
      } else {
        int count = packageToCountMap.get(packageOrClassName);
        packageToCountMap.put(packageOrClassName, count + 1);
      }
    }

    final Set<String> classesOrPackagesToImportOnDemand = new THashSet<String>();
    class MyVisitorProcedure implements TObjectIntProcedure<String> {
      private final boolean myIsVisitingPackages;

      MyVisitorProcedure(boolean isVisitingPackages) {
        myIsVisitingPackages = isVisitingPackages;
      }

      public boolean execute(final String packageOrClassName, final int count) {
        if (isToUseImportOnDemand(packageOrClassName, count, !myIsVisitingPackages)) {
          classesOrPackagesToImportOnDemand.add(packageOrClassName);
        }
        return true;
      }
    }
    classToCountMap.forEachEntry(new MyVisitorProcedure(false));
    packageToCountMap.forEachEntry(new MyVisitorProcedure(true));

    Set<String> classesToUseSingle =
        findSingleImports(file, names, classesOrPackagesToImportOnDemand, namesToImportStaticly);

    try {
      final String text =
          buildImportListText(
              names, classesOrPackagesToImportOnDemand, classesToUseSingle, namesToImportStaticly);
      String ext = StdFileTypes.JAVA.getDefaultExtension();
      final PsiJavaFile dummyFile =
          (PsiJavaFile)
              PsiFileFactory.getInstance(file.getProject())
                  .createFileFromText("_Dummy_." + ext, StdFileTypes.JAVA, text);
      codeStyleManager.reformat(dummyFile);

      PsiImportList resultList = dummyFile.getImportList();
      PsiImportList oldList = file.getImportList();
      if (oldList.isReplaceEquivalent(resultList)) return null;
      return resultList;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  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;
  }
  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;
    }
  }
 private static void replaceConditionalWithIf(PsiConditionalExpression expression)
     throws IncorrectOperationException {
   final PsiStatement statement = PsiTreeUtil.getParentOfType(expression, PsiStatement.class);
   if (statement == null) {
     return;
   }
   final PsiVariable variable;
   if (statement instanceof PsiDeclarationStatement) {
     variable = PsiTreeUtil.getParentOfType(expression, PsiVariable.class);
   } else {
     variable = null;
   }
   final PsiExpression thenExpression = expression.getThenExpression();
   final PsiExpression elseExpression = expression.getElseExpression();
   final PsiExpression condition = expression.getCondition();
   final PsiExpression strippedCondition = ParenthesesUtils.stripParentheses(condition);
   final StringBuilder newStatement = new StringBuilder();
   newStatement.append("if(");
   if (strippedCondition != null) {
     newStatement.append(strippedCondition.getText());
   }
   newStatement.append(')');
   if (variable != null) {
     final String name = variable.getName();
     newStatement.append(name);
     newStatement.append('=');
     final PsiExpression initializer = variable.getInitializer();
     if (initializer == null) {
       return;
     }
     appendElementTextWithoutParentheses(initializer, expression, thenExpression, newStatement);
     newStatement.append("; else ");
     newStatement.append(name);
     newStatement.append('=');
     appendElementTextWithoutParentheses(initializer, expression, elseExpression, newStatement);
     newStatement.append(';');
     initializer.delete();
     final PsiManager manager = statement.getManager();
     final Project project = manager.getProject();
     final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
     final PsiElementFactory factory = facade.getElementFactory();
     final PsiStatement ifStatement =
         factory.createStatementFromText(newStatement.toString(), statement);
     final PsiElement parent = statement.getParent();
     final PsiElement addedElement = parent.addAfter(ifStatement, statement);
     final CodeStyleManager styleManager = CodeStyleManager.getInstance(manager.getProject());
     styleManager.reformat(addedElement);
   } else {
     final boolean addBraces =
         PsiTreeUtil.getParentOfType(expression, PsiIfStatement.class, true, PsiStatement.class)
             != null;
     if (addBraces || thenExpression == null) {
       newStatement.append('{');
     }
     appendElementTextWithoutParentheses(statement, expression, thenExpression, newStatement);
     if (addBraces) {
       newStatement.append("} else {");
     } else {
       if (thenExpression == null) {
         newStatement.append('}');
       }
       newStatement.append(" else ");
       if (elseExpression == null) {
         newStatement.append('{');
       }
     }
     appendElementTextWithoutParentheses(statement, expression, elseExpression, newStatement);
     if (addBraces || elseExpression == null) {
       newStatement.append('}');
     }
     replaceStatement(newStatement.toString(), statement);
   }
 }