public static void createProperty(
      @NotNull final Project project,
      @NotNull final PsiElement psiElement,
      @NotNull final Collection<PropertiesFile> selectedPropertiesFiles,
      @NotNull final String key,
      @NotNull final String value) {
    for (PropertiesFile selectedFile : selectedPropertiesFiles) {
      if (!FileModificationService.getInstance()
          .prepareFileForWrite(selectedFile.getContainingFile())) return;
    }
    UndoUtil.markPsiFileForUndo(psiElement.getContainingFile());

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                CommandProcessor.getInstance()
                    .executeCommand(
                        project,
                        new Runnable() {
                          public void run() {
                            try {
                              I18nUtil.createProperty(project, selectedPropertiesFiles, key, value);
                            } catch (IncorrectOperationException e) {
                              LOG.error(e);
                            }
                          }
                        },
                        CodeInsightBundle.message("quickfix.i18n.command.name"),
                        project);
              }
            });
  }
示例#2
0
    public PsiReturnStatement addReturnForMethod(final PsiFile file, final PsiMethod method) {
      final PsiModifierList modifiers = method.getModifierList();
      if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT) || method.getBody() == null) {
        return null;
      }

      try {
        final ConvertReturnStatementsVisitor visitor =
            new ConvertReturnStatementsVisitor(factory, method, myTargetType);

        ControlFlow controlFlow;
        try {
          controlFlow = HighlightControlFlowUtil.getControlFlowNoConstantEvaluate(method.getBody());
        } catch (AnalysisCanceledException e) {
          return null; // must be an error
        }
        PsiReturnStatement returnStatement;
        if (controlFlow != null && ControlFlowUtil.processReturns(controlFlow, visitor)) {
          // extra return statement not needed
          // get latest modified return statement and select...
          returnStatement = visitor.getLatestReturn();
        } else {
          returnStatement = visitor.createReturnInLastStatement();
        }
        if (method.getContainingFile() != file) {
          UndoUtil.markPsiFileForUndo(file);
        }
        return returnStatement;
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }

      return null;
    }
 private void annotateExternally(
     @NotNull PsiModifierListOwner listOwner,
     @NotNull String annotationFQName,
     @Nullable final XmlFile xmlFile,
     @NotNull PsiFile codeUsageFile,
     PsiNameValuePair[] values) {
   if (xmlFile == null) return;
   try {
     final XmlDocument document = xmlFile.getDocument();
     if (document != null) {
       final XmlTag rootTag = document.getRootTag();
       final String externalName = getExternalName(listOwner, false);
       if (rootTag != null) {
         for (XmlTag tag : rootTag.getSubTags()) {
           if (Comparing.strEqual(
               StringUtil.unescapeXml(tag.getAttributeValue("name")), externalName)) {
             for (XmlTag annTag : tag.getSubTags()) {
               if (Comparing.strEqual(annTag.getAttributeValue("name"), annotationFQName)) {
                 annTag.delete();
                 break;
               }
             }
             tag.add(
                 XmlElementFactory.getInstance(myPsiManager.getProject())
                     .createTagFromText(createAnnotationTag(annotationFQName, values)));
             return;
           }
         }
         @NonNls String text = "<item name=\'" + StringUtil.escapeXml(externalName) + "\'>\n";
         text += createAnnotationTag(annotationFQName, values);
         text += "</item>";
         rootTag.add(
             XmlElementFactory.getInstance(myPsiManager.getProject()).createTagFromText(text));
       }
     }
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   } finally {
     dropCache();
     if (codeUsageFile.getVirtualFile().isInLocalFileSystem()) {
       UndoUtil.markPsiFileForUndo(codeUsageFile);
     }
   }
 }
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      @Nullable("is null when called from inspection") Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiModifierListOwner myModifierListOwner = (PsiModifierListOwner) startElement;

    final ExternalAnnotationsManager annotationsManager =
        ExternalAnnotationsManager.getInstance(project);
    final PsiModifierList modifierList = myModifierListOwner.getModifierList();
    LOG.assertTrue(modifierList != null);
    if (modifierList.findAnnotation(myAnnotation) != null) return;
    final ExternalAnnotationsManager.AnnotationPlace annotationAnnotationPlace =
        annotationsManager.chooseAnnotationsPlace(myModifierListOwner);
    if (annotationAnnotationPlace == ExternalAnnotationsManager.AnnotationPlace.NOWHERE) return;
    if (annotationAnnotationPlace == ExternalAnnotationsManager.AnnotationPlace.EXTERNAL) {
      for (String fqn : myAnnotationsToRemove) {
        annotationsManager.deannotate(myModifierListOwner, fqn);
      }
      annotationsManager.annotateExternally(myModifierListOwner, myAnnotation, file, myPairs);
    } else {
      final PsiFile containingFile = myModifierListOwner.getContainingFile();
      if (!CodeInsightUtilBase.preparePsiElementForWrite(containingFile)) return;
      for (String fqn : myAnnotationsToRemove) {
        PsiAnnotation annotation = AnnotationUtil.findAnnotation(myModifierListOwner, fqn);
        if (annotation != null) {
          annotation.delete();
        }
      }

      PsiAnnotation inserted = modifierList.addAnnotation(myAnnotation);
      for (PsiNameValuePair pair : myPairs) {
        inserted.setDeclaredAttributeValue(pair.getName(), pair.getValue());
      }
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(inserted);
      if (containingFile != file) {
        UndoUtil.markPsiFileForUndo(file);
      }
    }
  }
  public static List<ParameterInfoImpl> performChange(
      final Project project,
      final Editor editor,
      final PsiFile file,
      final PsiMethod method,
      final int minUsagesNumber,
      final ParameterInfoImpl[] newParametersInfo,
      final boolean changeAllUsages,
      final boolean allowDelegation) {
    if (!FileModificationService.getInstance().prepareFileForWrite(method.getContainingFile()))
      return null;
    final FindUsagesManager findUsagesManager =
        ((FindManagerImpl) FindManager.getInstance(project)).getFindUsagesManager();
    final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(method, false);
    if (handler == null) return null; // on failure or cancel (e.g. cancel of super methods dialog)

    final JavaMethodFindUsagesOptions options = new JavaMethodFindUsagesOptions(project);
    options.isImplementingMethods = true;
    options.isOverridingMethods = true;
    options.isUsages = true;
    options.isSearchForTextOccurrences = false;
    final int[] usagesFound = new int[1];
    Runnable runnable =
        () -> {
          Processor<UsageInfo> processor = t -> ++usagesFound[0] < minUsagesNumber;

          handler.processElementUsages(method, processor, options);
        };
    String progressTitle = QuickFixBundle.message("searching.for.usages.progress.title");
    if (!ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(runnable, progressTitle, true, project)) return null;

    if (ApplicationManager.getApplication().isUnitTestMode() || usagesFound[0] < minUsagesNumber) {
      ChangeSignatureProcessor processor =
          new ChangeSignatureProcessor(
              project,
              method,
              false,
              null,
              method.getName(),
              method.getReturnType(),
              newParametersInfo) {
            @Override
            @NotNull
            protected UsageInfo[] findUsages() {
              return changeAllUsages ? super.findUsages() : UsageInfo.EMPTY_ARRAY;
            }

            @Override
            protected void performRefactoring(@NotNull UsageInfo[] usages) {
              CommandProcessor.getInstance().setCurrentCommandName(getCommandName());
              super.performRefactoring(usages);
            }
          };
      processor.run();
      ApplicationManager.getApplication().runWriteAction(() -> UndoUtil.markPsiFileForUndo(file));
      return Arrays.asList(newParametersInfo);
    } else {
      final List<ParameterInfoImpl> parameterInfos =
          newParametersInfo != null
              ? new ArrayList<ParameterInfoImpl>(Arrays.asList(newParametersInfo))
              : new ArrayList<ParameterInfoImpl>();
      final PsiReferenceExpression refExpr =
          JavaTargetElementEvaluator.findReferenceExpression(editor);
      JavaChangeSignatureDialog dialog =
          JavaChangeSignatureDialog.createAndPreselectNew(
              project, method, parameterInfos, allowDelegation, refExpr);
      dialog.setParameterInfos(parameterInfos);
      dialog.show();
      return dialog.isOK() ? dialog.getParameters() : null;
    }
  }