コード例 #1
0
  public EntryPoint acquire(@NotNull Target target, @NotNull Parameters configuration)
      throws Exception {
    ApplicationManagerEx.getApplicationEx().assertTimeConsuming();

    Ref<RunningInfo> ref = Ref.create(null);
    Pair<Target, Parameters> key = Pair.create(target, configuration);
    if (!getExistingInfo(ref, key)) {
      startProcess(target, configuration, key);
      if (ref.isNull()) {
        try {
          //noinspection SynchronizationOnLocalVariableOrMethodParameter
          synchronized (ref) {
            while (ref.isNull()) {
              ref.wait(1000);
              ProgressManager.checkCanceled();
            }
          }
        } catch (InterruptedException e) {
          ProgressManager.checkCanceled();
        }
      }
    }
    if (ref.isNull())
      throw new RuntimeException("Unable to acquire remote proxy for: " + getName(target));
    RunningInfo info = ref.get();
    if (info.handler == null) {
      String message = info.name;
      if (message != null && message.startsWith("ERROR: transport error 202:")) {
        message =
            "Unable to start java process in debug mode: -Xdebug parameters are already in use.";
      }
      throw new ExecutionException(message);
    }
    return acquire(info);
  }
コード例 #2
0
 public static boolean runVcsProcessWithProgress(
     final VcsRunnable runnable, String progressTitle, boolean canBeCanceled, Project project)
     throws VcsException {
   final Ref<VcsException> ex = new Ref<VcsException>();
   boolean result =
       ProgressManager.getInstance()
           .runProcessWithProgressSynchronously(
               new Runnable() {
                 @Override
                 public void run() {
                   try {
                     runnable.run();
                   } catch (VcsException e) {
                     ex.set(e);
                   }
                 }
               },
               progressTitle,
               canBeCanceled,
               project);
   if (!ex.isNull()) {
     throw ex.get();
   }
   return result;
 }
コード例 #3
0
  public static void deleteFile(Project project, final VirtualFile file) throws ExecutionException {
    final Ref<IOException> error = new Ref<IOException>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          if (file.isValid()) {
                            file.delete(this);
                          }
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };

    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }
    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
  }
コード例 #4
0
  static void invokeAndWait(
      @NotNull final Runnable runnable, @NotNull ModalityState modalityState) {
    LOG.assertTrue(!isDispatchThread());

    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    final Ref<Throwable> exception = Ref.create();
    Runnable runnable1 =
        new Runnable() {
          @Override
          public void run() {
            try {
              runnable.run();
            } catch (Throwable e) {
              exception.set(e);
            } finally {
              semaphore.up();
            }
          }

          @Override
          @NonNls
          public String toString() {
            return "InvokeAndWait[" + runnable + "]";
          }
        };
    invokeLater(runnable1, modalityState);
    semaphore.waitFor();
    if (!exception.isNull()) {
      throw new RuntimeException(exception.get());
    }
  }
コード例 #5
0
  @Nullable
  private FilePath unshelveBinaryFile(
      final ShelvedBinaryFile file, @NotNull final VirtualFile patchTarget) throws IOException {
    final Ref<FilePath> result = new Ref<FilePath>();
    final Ref<IOException> ex = new Ref<IOException>();
    final Ref<VirtualFile> patchedFileRef = new Ref<VirtualFile>();
    final File shelvedFile = file.SHELVED_PATH == null ? null : new File(file.SHELVED_PATH);

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                try {
                  result.set(new FilePathImpl(patchTarget));
                  if (shelvedFile == null) {
                    patchTarget.delete(this);
                  } else {
                    patchTarget.setBinaryContent(FileUtil.loadFileBytes(shelvedFile));
                    patchedFileRef.set(patchTarget);
                  }
                } catch (IOException e) {
                  ex.set(e);
                }
              }
            });
    if (!ex.isNull()) {
      throw ex.get();
    }
    return result.get();
  }
コード例 #6
0
  public boolean replaceUsage(
      @NotNull final Usage usage,
      @NotNull final FindModel findModel,
      @NotNull final Set<Usage> excludedSet,
      final boolean justCheck)
      throws FindManager.MalformedReplacementStringException {
    final Ref<FindManager.MalformedReplacementStringException> exceptionResult = Ref.create();
    final boolean result =
        ApplicationManager.getApplication()
            .runWriteAction(
                new Computable<Boolean>() {
                  @Override
                  public Boolean compute() {
                    if (excludedSet.contains(usage)) {
                      return false;
                    }

                    final Document document = ((UsageInfo2UsageAdapter) usage).getDocument();
                    if (!document.isWritable()) return false;

                    boolean result =
                        ((UsageInfo2UsageAdapter) usage)
                            .processRangeMarkers(
                                new Processor<Segment>() {
                                  @Override
                                  public boolean process(Segment segment) {
                                    final int textOffset = segment.getStartOffset();
                                    final int textEndOffset = segment.getEndOffset();
                                    final Ref<String> stringToReplace = Ref.create();
                                    try {
                                      if (!getStringToReplace(
                                          textOffset,
                                          textEndOffset,
                                          document,
                                          findModel,
                                          stringToReplace)) return true;
                                      if (!stringToReplace.isNull() && !justCheck) {
                                        document.replaceString(
                                            textOffset, textEndOffset, stringToReplace.get());
                                      }
                                    } catch (FindManager.MalformedReplacementStringException e) {
                                      exceptionResult.set(e);
                                      return false;
                                    }
                                    return true;
                                  }
                                });
                    return result;
                  }
                });

    if (!exceptionResult.isNull()) {
      throw exceptionResult.get();
    }
    return result;
  }
コード例 #7
0
  @Nullable
  public static PsiType rawSecondGeneric(PsiType type, Project project) {
    if (!(type instanceof PsiClassType)) return null;

    final PsiClassType.ClassResolveResult result = ((PsiClassType) type).resolveGenerics();
    final PsiClass element = result.getElement();
    if (element == null) return null;

    final PsiType[] parameters = ((PsiClassType) type).getParameters();

    boolean changed = false;
    for (int i = 0; i < parameters.length; i++) {
      PsiType parameter = parameters[i];
      if (parameter == null) continue;

      final Ref<PsiType> newParam = new Ref<PsiType>();
      parameter.accept(
          new PsiTypeVisitorEx<Object>() {
            @Nullable
            @Override
            public Object visitClassType(PsiClassType classType) {
              if (classType.getParameterCount() > 0) {
                newParam.set(classType.rawType());
              }
              return null;
            }

            @Nullable
            @Override
            public Object visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
              newParam.set(capturedWildcardType.getWildcard().getBound());
              return null;
            }

            @Nullable
            @Override
            public Object visitWildcardType(PsiWildcardType wildcardType) {
              newParam.set(wildcardType.getBound());
              return null;
            }
          });

      if (!newParam.isNull()) {
        changed = true;
        parameters[i] = newParam.get();
      }
    }
    if (!changed) return null;
    return JavaPsiFacade.getElementFactory(project).createType(element, parameters);
  }
コード例 #8
0
  /**
   * Sends signal to every child process of a tree root process
   *
   * @param process tree root process
   */
  public static boolean sendSignalToProcessTree(Process process, int signal) {
    checkCLib();

    final int our_pid = C_LIB.getpid();
    final int process_pid = getProcessPid(process);

    final Ref<Integer> foundPid = new Ref<Integer>();
    final ProcessInfo processInfo = new ProcessInfo();
    final List<Integer> childrenPids = new ArrayList<Integer>();

    processPSOutput(
        getPSCmd(false),
        new Processor<String>() {
          @Override
          public boolean process(String s) {
            StringTokenizer st = new StringTokenizer(s, " ");

            int parent_pid = Integer.parseInt(st.nextToken());
            int pid = Integer.parseInt(st.nextToken());

            processInfo.register(pid, parent_pid);

            if (parent_pid == process_pid) {
              childrenPids.add(pid);
            }

            if (pid == process_pid) {
              if (parent_pid == our_pid) {
                foundPid.set(pid);
              } else {
                throw new IllegalStateException("process is not our child");
              }
            }
            return false;
          }
        });

    boolean result;
    if (!foundPid.isNull()) {
      processInfo.killProcTree(foundPid.get(), signal, UNIX_KILLER);
      result = true;
    } else {
      for (Integer pid : childrenPids) {
        processInfo.killProcTree(pid, signal, UNIX_KILLER);
      }
      result = false;
    }
    return result;
  }
コード例 #9
0
 @NotNull
 private LocalFileSystem.WatchRequest watch(final File watchFile, final boolean recursive) {
   final Ref<LocalFileSystem.WatchRequest> request = Ref.create();
   getEvents(
       "events to add watch " + watchFile,
       new Runnable() {
         @Override
         public void run() {
           request.set(myFileSystem.addRootToWatch(watchFile.getAbsolutePath(), recursive));
         }
       });
   assertFalse(request.isNull());
   assertFalse(myWatcher.isSettingRoots());
   return request.get();
 }
コード例 #10
0
 @Nullable
 private Map<VirtualFile, String> getLastCommitMessages() throws VcsException {
   Map<VirtualFile, String> messagesForRoots = new HashMap<VirtualFile, String>();
   Collection<VirtualFile> roots =
       myCheckinPanel.getRoots(); // all committed vcs roots, not only selected
   final Ref<VcsException> exception = Ref.create();
   for (VirtualFile root : roots) {
     String message = getLastCommitMessage(root);
     messagesForRoots.put(root, message);
   }
   if (!exception.isNull()) {
     throw exception.get();
   }
   return messagesForRoots;
 }
コード例 #11
0
  @Nullable
  public static VirtualFile suggestManifestFileDirectory(
      @NotNull CompositePackagingElement<?> root,
      PackagingElementResolvingContext context,
      ArtifactType artifactType) {
    final VirtualFile metaInfDir =
        ArtifactUtil.findSourceFileByOutputPath(root, MANIFEST_DIR_NAME, context, artifactType);
    if (metaInfDir != null) {
      return metaInfDir;
    }

    final Ref<VirtualFile> sourceDir = Ref.create(null);
    final Ref<VirtualFile> sourceFile = Ref.create(null);
    ArtifactUtil.processElementsWithSubstitutions(
        root.getChildren(),
        context,
        artifactType,
        PackagingElementPath.EMPTY,
        new PackagingElementProcessor<PackagingElement<?>>() {
          @Override
          public boolean process(
              @NotNull PackagingElement<?> element, @NotNull PackagingElementPath path) {
            if (element instanceof FileCopyPackagingElement) {
              final VirtualFile file = ((FileCopyPackagingElement) element).findFile();
              if (file != null) {
                sourceFile.set(file);
              }
            } else if (element instanceof DirectoryCopyPackagingElement) {
              final VirtualFile file = ((DirectoryCopyPackagingElement) element).findFile();
              if (file != null) {
                sourceDir.set(file);
                return false;
              }
            }
            return true;
          }
        });

    if (!sourceDir.isNull()) {
      return sourceDir.get();
    }

    final Project project = context.getProject();
    return suggestBaseDir(project, sourceFile.get());
  }
コード例 #12
0
  protected void performRemoteGitTask(final GitLineHandler handler, String title)
      throws ServerRuntimeException {
    final GitTask task = new GitTask(myProject, handler, title);
    task.setProgressAnalyzer(new GitStandardProgressAnalyzer());

    final Semaphore semaphore = new Semaphore();
    semaphore.down();

    final Ref<ServerRuntimeException> errorRef = new Ref<ServerRuntimeException>();

    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {

              @Override
              public void run() {
                task.execute(
                    false,
                    false,
                    new GitTaskResultHandlerAdapter() {

                      @Override
                      protected void run(GitTaskResult result) {
                        super.run(result);
                        semaphore.up();
                      }

                      @Override
                      protected void onFailure() {
                        for (VcsException error : handler.errors()) {
                          myLoggingHandler.println(error.toString());
                          if (errorRef.isNull()) {
                            errorRef.set(new ServerRuntimeException(error));
                          }
                        }
                      }
                    });
              }
            });

    semaphore.waitFor();
    if (!errorRef.isNull()) {
      throw errorRef.get();
    }
  }
コード例 #13
0
  public static VirtualFile createFile(
      Project project, final VirtualFile directory, final String fileName, final String fileText)
      throws ExecutionException {
    LOG.assertTrue(directory != null);
    final Ref<IOException> error = new Ref<IOException>();
    final Ref<VirtualFile> launcherFile = new Ref<VirtualFile>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          VirtualFile file = directory.findChild(fileName);
                          if (file == null) {
                            file =
                                directory.createChildData(CfmlUnitRunConfiguration.class, fileName);
                          }
                          CfmlScriptNodeSuppressor.suppress(file);
                          VfsUtil.saveText(file, fileText);
                          launcherFile.set(file);
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };
    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }

    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
    return launcherFile.get();
  }
コード例 #14
0
  @NotNull
  public static PsiElement createYamlPsiFromText(
      Project p, final IElementType type, @NotNull String text) {
    final Ref<PsiElement> ret = new Ref<PsiElement>();
    PsiFile dummyFile = createDummyFile(p, text);
    dummyFile.accept(
        new PsiRecursiveElementWalkingVisitor() {
          @Override
          public void visitElement(PsiElement element) {
            if (element.getNode() == type) {
              ret.set(element);
            }

            super.visitElement(element);
          }
        });

    assert !ret.isNull() : "cannot create element from text:\n" + dummyFile.getText();

    return ret.get();
  }
コード例 #15
0
 public void openFiles() {
   if (mySplittersElement != null) {
     Ref<EditorWindow> currentWindow = new Ref<EditorWindow>();
     final JPanel comp = readExternalPanel(mySplittersElement, getTopPanel(), currentWindow);
     if (comp != null) {
       removeAll();
       add(comp, BorderLayout.CENTER);
       mySplittersElement = null;
     }
     // clear empty splitters
     for (EditorWindow window : getWindows()) {
       if (window.getEditors().length == 0) {
         for (EditorWindow sibling : window.findSiblings()) {
           sibling.unsplit(false);
         }
       }
     }
     if (!currentWindow.isNull()) {
       setCurrentWindow(currentWindow.get(), true);
     }
   }
 }
コード例 #16
0
  private void disposeConsole() throws InterruptedException {
    if (myCommunication != null) {
      UIUtil.invokeAndWaitIfNeeded(
          new Runnable() {
            @Override
            public void run() {
              try {
                myCommunication.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
              myCommunication = null;
            }
          });
    }

    disposeConsoleProcess();

    if (!myContentDescriptorRef.isNull()) {
      UIUtil.invokeAndWaitIfNeeded(
          new Runnable() {
            @Override
            public void run() {
              Disposer.dispose(myContentDescriptorRef.get());
            }
          });
    }

    if (myConsoleView != null) {
      new WriteAction() {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
          Disposer.dispose(myConsoleView);
          myConsoleView = null;
        }
      }.execute();
    }
  }
 private static void setupEditorForInjectedLanguage() {
   if (myEditor != null) {
     final Ref<EditorWindow> editorWindowRef = new Ref<EditorWindow>();
     myEditor
         .getCaretModel()
         .runForEachCaret(
             new CaretAction() {
               @Override
               public void perform(Caret caret) {
                 Editor editor =
                     InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myEditor, myFile);
                 if (caret == myEditor.getCaretModel().getPrimaryCaret()
                     && editor instanceof EditorWindow) {
                   editorWindowRef.set((EditorWindow) editor);
                 }
               }
             });
     if (!editorWindowRef.isNull()) {
       myEditor = editorWindowRef.get();
       myFile = editorWindowRef.get().getInjectedFile();
     }
   }
 }
コード例 #18
0
  private void showUsageView(
      @NotNull final UsageViewDescriptor viewDescriptor,
      final Factory<UsageSearcher> factory,
      @NotNull final UsageInfo[] usageInfos) {
    UsageViewManager viewManager = UsageViewManager.getInstance(myProject);

    final PsiElement[] initialElements = viewDescriptor.getElements();
    final UsageTarget[] targets = PsiElement2UsageTargetAdapter.convert(initialElements);
    final Ref<Usage[]> convertUsagesRef = new Ref<>();
    if (!ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .runReadAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos));
                          }
                        });
              }
            },
            "Preprocess usages",
            true,
            myProject)) return;

    if (convertUsagesRef.isNull()) return;

    final Usage[] usages = convertUsagesRef.get();

    final UsageViewPresentation presentation = createPresentation(viewDescriptor, usages);

    final UsageView usageView = viewManager.showUsages(targets, usages, presentation, factory);
    customizeUsagesView(viewDescriptor, usageView);
  }
コード例 #19
0
  public void inlineElement(
      final Project project, final Editor editor, final PsiElement psiElement) {
    final PsiParameter psiParameter = (PsiParameter) psiElement;
    final PsiParameterList parameterList = (PsiParameterList) psiParameter.getParent();
    if (!(parameterList.getParent() instanceof PsiMethod)) {
      return;
    }
    final int index = parameterList.getParameterIndex(psiParameter);
    final PsiMethod method = (PsiMethod) parameterList.getParent();

    String errorMessage = getCannotInlineMessage(psiParameter, method);
    if (errorMessage != null) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          errorMessage,
          RefactoringBundle.message("inline.parameter.refactoring"),
          null);
      return;
    }

    final Ref<PsiExpression> refInitializer = new Ref<PsiExpression>();
    final Ref<PsiExpression> refConstantInitializer = new Ref<PsiExpression>();
    final Ref<PsiCallExpression> refMethodCall = new Ref<PsiCallExpression>();
    final List<PsiReference> occurrences =
        Collections.synchronizedList(new ArrayList<PsiReference>());
    final Collection<PsiFile> containingFiles = Collections.synchronizedSet(new HashSet<PsiFile>());
    containingFiles.add(psiParameter.getContainingFile());
    boolean result =
        ReferencesSearch.search(method)
            .forEach(
                new Processor<PsiReference>() {
                  public boolean process(final PsiReference psiReference) {
                    PsiElement element = psiReference.getElement();
                    final PsiElement parent = element.getParent();
                    if (parent instanceof PsiCallExpression) {
                      final PsiCallExpression methodCall = (PsiCallExpression) parent;
                      occurrences.add(psiReference);
                      containingFiles.add(element.getContainingFile());
                      final PsiExpression[] expressions =
                          methodCall.getArgumentList().getExpressions();
                      if (expressions.length <= index) return false;
                      PsiExpression argument = expressions[index];
                      if (!refInitializer.isNull()) {
                        return argument != null
                            && PsiEquivalenceUtil.areElementsEquivalent(
                                refInitializer.get(), argument)
                            && PsiEquivalenceUtil.areElementsEquivalent(
                                refMethodCall.get(), methodCall);
                      }
                      if (InlineToAnonymousConstructorProcessor.isConstant(argument)
                          || getReferencedFinalField(argument) != null) {
                        if (refConstantInitializer.isNull()) {
                          refConstantInitializer.set(argument);
                        } else if (!isSameConstant(argument, refConstantInitializer.get())) {
                          return false;
                        }
                      } else if (!isRecursiveReferencedParameter(argument, psiParameter)) {
                        if (!refConstantInitializer.isNull()) return false;
                        refInitializer.set(argument);
                        refMethodCall.set(methodCall);
                      }
                    }
                    return true;
                  }
                });
    final int offset = editor.getCaretModel().getOffset();
    final PsiElement refExpr = psiElement.getContainingFile().findElementAt(offset);
    final PsiCodeBlock codeBlock = PsiTreeUtil.getParentOfType(refExpr, PsiCodeBlock.class);
    if (codeBlock != null) {
      final PsiElement[] defs = DefUseUtil.getDefs(codeBlock, psiParameter, refExpr);
      if (defs.length == 1) {
        final PsiElement def = defs[0];
        if (def instanceof PsiReferenceExpression
            && PsiUtil.isOnAssignmentLeftHand((PsiExpression) def)) {
          final PsiExpression rExpr = ((PsiAssignmentExpression) def.getParent()).getRExpression();
          if (rExpr != null) {
            final PsiElement[] refs = DefUseUtil.getRefs(codeBlock, psiParameter, refExpr);

            if (InlineLocalHandler.checkRefsInAugmentedAssignmentOrUnaryModified(refs, def)
                == null) {
              new WriteCommandAction(project) {
                @Override
                protected void run(Result result) throws Throwable {
                  for (final PsiElement ref : refs) {
                    InlineUtil.inlineVariable(
                        psiParameter, rExpr, (PsiJavaCodeReferenceElement) ref);
                  }
                  def.getParent().delete();
                }
              }.execute();
              return;
            }
          }
        }
      }
    }
    if (occurrences.isEmpty()) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          "Method has no usages",
          RefactoringBundle.message("inline.parameter.refactoring"),
          null);
      return;
    }
    if (!result) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          "Cannot find constant initializer for parameter",
          RefactoringBundle.message("inline.parameter.refactoring"),
          null);
      return;
    }
    if (!refInitializer.isNull()) {
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        final InlineParameterExpressionProcessor processor =
            new InlineParameterExpressionProcessor(
                refMethodCall.get(),
                method,
                psiParameter,
                refInitializer.get(),
                method
                    .getProject()
                    .getUserData(InlineParameterExpressionProcessor.CREATE_LOCAL_FOR_TESTS));
        processor.run();
      } else {
        final boolean createLocal = ReferencesSearch.search(psiParameter).findAll().size() > 1;
        InlineParameterDialog dlg =
            new InlineParameterDialog(
                refMethodCall.get(), method, psiParameter, refInitializer.get(), createLocal);
        dlg.show();
      }
      return;
    }
    if (refConstantInitializer.isNull()) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          "Cannot find constant initializer for parameter",
          RefactoringBundle.message("inline.parameter.refactoring"),
          null);
      return;
    }

    final Ref<Boolean> isNotConstantAccessible = new Ref<Boolean>();
    final PsiExpression constantExpression = refConstantInitializer.get();
    constantExpression.accept(
        new JavaRecursiveElementVisitor() {
          @Override
          public void visitReferenceExpression(PsiReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            final PsiElement resolved = expression.resolve();
            if (resolved instanceof PsiMember
                && !PsiUtil.isAccessible((PsiMember) resolved, method, null)) {
              isNotConstantAccessible.set(Boolean.TRUE);
            }
          }
        });
    if (!isNotConstantAccessible.isNull() && isNotConstantAccessible.get()) {
      CommonRefactoringUtil.showErrorHint(
          project,
          editor,
          "Constant initializer is not accessible in method body",
          RefactoringBundle.message("inline.parameter.refactoring"),
          null);
      return;
    }

    for (PsiReference psiReference : ReferencesSearch.search(psiParameter)) {
      final PsiElement element = psiReference.getElement();
      if (element instanceof PsiExpression
          && PsiUtil.isAccessedForWriting((PsiExpression) element)) {
        CommonRefactoringUtil.showErrorHint(
            project,
            editor,
            "Inline parameter which has write usages is not supported",
            RefactoringBundle.message("inline.parameter.refactoring"),
            null);
        return;
      }
    }

    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      String occurencesString = RefactoringBundle.message("occurences.string", occurrences.size());
      String question =
          RefactoringBundle.message(
                  "inline.parameter.confirmation",
                  psiParameter.getName(),
                  constantExpression.getText())
              + " "
              + occurencesString;
      RefactoringMessageDialog dialog =
          new RefactoringMessageDialog(
              REFACTORING_NAME,
              question,
              HelpID.INLINE_VARIABLE,
              "OptionPane.questionIcon",
              true,
              project);
      dialog.show();
      if (!dialog.isOK()) {
        return;
      }
    }

    final RefactoringEventData data = new RefactoringEventData();
    data.addElement(psiElement.copy());
    project
        .getMessageBus()
        .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
        .refactoringStarted(REFACTORING_ID, data);

    SameParameterValueInspection.InlineParameterValueFix.inlineSameParameterValue(
        method, psiParameter, constantExpression);

    project
        .getMessageBus()
        .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
        .refactoringDone(REFACTORING_ID, null);
  }
コード例 #20
0
  public static void executeScript(
      final CfmlUnitRunnerParameters params,
      final ProcessHandler processHandler /*final String webPath,
                                   final String componentFilePath,
                                   final String methodName,
                                   final ProcessHandler processHandler*/,
      final Project project)
      throws ExecutionException {
    final Ref<ExecutionException> ref = new Ref<ExecutionException>();

    ApplicationManager.getApplication().assertIsDispatchThread();

    ApplicationManager.getApplication()
        .executeOnPooledThread(
            new Runnable() {
              public void run() {
                try {
                  final VirtualFile componentFile =
                      LocalFileSystem.getInstance().refreshAndFindFileByPath(params.getPath());
                  if (componentFile == null) {
                    throw new ExecutionException("File " + params.getPath() + " not found");
                  }

                  // creating script files
                  final VirtualFile directory = componentFile.getParent();
                  final String launcherFileName =
                      "mxunit-launcher.cfc"; // generateUniqueName("mxunit-launcher", project);
                  LOG.debug(
                      "Copying script file"
                          + launcherFileName
                          + " to component folder: "
                          + directory);
                  createFile(
                      project,
                      directory,
                      launcherFileName,
                      getLauncherText("/scripts/mxunit-launcher.cfc"));

                  final String resultsFileName =
                      "mxunit-result-capture.cfc"; // generateUniqueName("mxunit-result-capture",
                                                   // project);
                  LOG.debug(
                      "Copying results capture file "
                          + resultsFileName
                          + " to component folder: "
                          + directory);
                  createFile(
                      project,
                      directory,
                      resultsFileName,
                      getLauncherText("/scripts/mxunit-result-capture.cfc"));

                  // retrieving data through URL
                  String webPath = params.getWebPath();
                  if (webPath.endsWith("/") || webPath.endsWith("\\")) {
                    webPath = webPath.substring(0, webPath.length() - 1);
                  }
                  String agentPath =
                      webPath.substring(0, webPath.lastIndexOf('/')) + "/" + launcherFileName;
                  LOG.debug("Retrieving data from coldfusion server by " + agentPath + " URL");
                  BufferedReader reader = null;
                  String agentUrl;
                  if (params.getScope() == CfmlUnitRunnerParameters.Scope.Directory) {
                    agentUrl =
                        agentPath
                            + "?method=executeDirectory&directoryName="
                            + componentFile.getName();
                  } else {
                    agentUrl =
                        agentPath
                            + "?method=executeTestCase&componentName="
                            + componentFile.getNameWithoutExtension();
                    if (params.getScope() == CfmlUnitRunnerParameters.Scope.Method) {
                      agentUrl += "&methodName=" + params.getMethod();
                    }
                  }
                  HttpMethod method = null;
                  try {
                    LOG.debug("Retrieving test results from: " + agentUrl);
                    /*
                    final FileObject httpFile = getManager().resolveFile(agentUrl);

                    reader = new BufferedReader(new InputStreamReader(httpFile.getContent().getInputStream()));
                    */
                    HttpClient client = new HttpClient();
                    method = new GetMethod(agentUrl);
                    int statusCode = client.executeMethod(method);
                    if (statusCode != HttpStatus.SC_OK) {
                      LOG.debug("Http request failed: " + method.getStatusLine());
                      processHandler.notifyTextAvailable(
                          "Http request failed: " + method.getStatusLine(),
                          ProcessOutputTypes.SYSTEM);
                    }
                    final InputStream responseStream = method.getResponseBodyAsStream();
                    reader = new BufferedReader(new InputStreamReader(responseStream));
                    String line;
                    while (!processHandler.isProcessTerminating()
                        && !processHandler.isProcessTerminated()
                        && (line = reader.readLine()) != null) {
                      if (!StringUtil.isEmptyOrSpaces(line)) {
                        LOG.debug("MXUnit: " + line);
                        processHandler.notifyTextAvailable(line + "\n", ProcessOutputTypes.SYSTEM);
                      }
                    }
                  } catch (IOException e) {
                    LOG.warn(e);
                    processHandler.notifyTextAvailable(
                        "Failed to retrieve test results from the server at " + agentUrl + "\n",
                        ProcessOutputTypes.SYSTEM);
                  } finally {
                    if (method != null) {
                      method.releaseConnection();
                    }
                    if (reader != null) {
                      try {
                        reader.close();
                      } catch (IOException e) {
                        // ignore
                      }
                    }
                  }
                  LOG.debug("Cleaning temporary files");
                  deleteFile(project, directory.findChild(launcherFileName));
                  deleteFile(project, directory.findChild(resultsFileName));
                  if (!processHandler.isProcessTerminated()
                      && !processHandler.isProcessTerminating()) {
                    processHandler.destroyProcess();
                  }
                } catch (ExecutionException e) {
                  ref.set(e);
                }
              }
            });
    if (!ref.isNull()) {
      throw ref.get();
    }
  }
コード例 #21
0
  protected void doRun() {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    final Ref<UsageInfo[]> refUsages = new Ref<>();
    final Ref<Language> refErrorLanguage = new Ref<>();
    final Ref<Boolean> refProcessCanceled = new Ref<>();
    final Ref<Boolean> anyException = new Ref<>();

    final Runnable findUsagesRunnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              refUsages.set(
                  DumbService.getInstance(myProject)
                      .runReadActionInSmartMode(
                          new Computable<UsageInfo[]>() {
                            @Override
                            public UsageInfo[] compute() {
                              return findUsages();
                            }
                          }));
            } catch (UnknownReferenceTypeException e) {
              refErrorLanguage.set(e.getElementLanguage());
            } catch (ProcessCanceledException e) {
              refProcessCanceled.set(Boolean.TRUE);
            } catch (Throwable e) {
              anyException.set(Boolean.TRUE);
              LOG.error(e);
            }
          }
        };

    if (!ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            findUsagesRunnable, RefactoringBundle.message("progress.text"), true, myProject)) {
      return;
    }

    if (!refErrorLanguage.isNull()) {
      Messages.showErrorDialog(
          myProject,
          RefactoringBundle.message(
              "unsupported.refs.found", refErrorLanguage.get().getDisplayName()),
          RefactoringBundle.message("error.title"));
      return;
    }
    if (DumbService.isDumb(myProject)) {
      DumbService.getInstance(myProject)
          .showDumbModeNotification("Refactoring is not available until indices are ready");
      return;
    }
    if (!refProcessCanceled.isNull()) {
      Messages.showErrorDialog(
          myProject,
          "Index corruption detected. Please retry the refactoring - indexes will be rebuilt automatically",
          RefactoringBundle.message("error.title"));
      return;
    }

    if (!anyException.isNull()) {
      // do not proceed if find usages fails
      return;
    }
    assert !refUsages.isNull() : "Null usages from processor " + this;
    if (!preprocessUsages(refUsages)) return;
    final UsageInfo[] usages = refUsages.get();
    assert usages != null;
    UsageViewDescriptor descriptor = createUsageViewDescriptor(usages);

    boolean isPreview = isPreviewUsages(usages);
    if (!isPreview) {
      isPreview =
          !ensureElementsWritable(usages, descriptor) || UsageViewUtil.hasReadOnlyUsages(usages);
      if (isPreview) {
        StatusBarUtil.setStatusBarInfo(
            myProject, RefactoringBundle.message("readonly.occurences.found"));
      }
    }
    if (isPreview) {
      for (UsageInfo usage : usages) {
        LOG.assertTrue(usage != null, getClass());
      }
      previewRefactoring(usages);
    } else {
      execute(usages);
    }
  }
コード例 #22
0
  public void apply() throws ConfigurationException {
    // validate content and source roots
    final Map<VirtualFile, String> contentRootToModuleNameMap = new HashMap<VirtualFile, String>();
    final Map<VirtualFile, VirtualFile> srcRootsToContentRootMap =
        new HashMap<VirtualFile, VirtualFile>();
    for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
      final ModifiableRootModel rootModel = moduleEditor.getModifiableRootModel();
      final ContentEntry[] contents = rootModel.getContentEntries();
      for (ContentEntry contentEntry : contents) {
        final VirtualFile contentRoot = contentEntry.getFile();
        if (contentRoot == null) {
          continue;
        }
        final String moduleName = moduleEditor.getName();
        final String previousName = contentRootToModuleNameMap.put(contentRoot, moduleName);
        if (previousName != null && !previousName.equals(moduleName)) {
          throw new ConfigurationException(
              ProjectBundle.message(
                  "module.paths.validation.duplicate.content.error",
                  contentRoot.getPresentableUrl(),
                  previousName,
                  moduleName));
        }
        for (VirtualFile srcRoot : contentEntry.getSourceFolderFiles()) {
          final VirtualFile anotherContentRoot = srcRootsToContentRootMap.put(srcRoot, contentRoot);
          if (anotherContentRoot != null) {
            final String problematicModule;
            final String correctModule;
            if (VfsUtilCore.isAncestor(anotherContentRoot, contentRoot, true)) {
              problematicModule = contentRootToModuleNameMap.get(anotherContentRoot);
              correctModule = contentRootToModuleNameMap.get(contentRoot);
            } else {
              problematicModule = contentRootToModuleNameMap.get(contentRoot);
              correctModule = contentRootToModuleNameMap.get(anotherContentRoot);
            }
            throw new ConfigurationException(
                ProjectBundle.message(
                    "module.paths.validation.duplicate.source.root.error",
                    problematicModule,
                    srcRoot.getPresentableUrl(),
                    correctModule));
          }
        }
      }
    }
    // additional validation: directories marked as src roots must belong to the same module as
    // their corresponding content root
    for (Map.Entry<VirtualFile, VirtualFile> entry : srcRootsToContentRootMap.entrySet()) {
      final VirtualFile srcRoot = entry.getKey();
      final VirtualFile correspondingContent = entry.getValue();
      final String expectedModuleName = contentRootToModuleNameMap.get(correspondingContent);

      for (VirtualFile candidateContent = srcRoot;
          candidateContent != null && !candidateContent.equals(correspondingContent);
          candidateContent = candidateContent.getParent()) {
        final String moduleName = contentRootToModuleNameMap.get(candidateContent);
        if (moduleName != null && !moduleName.equals(expectedModuleName)) {
          throw new ConfigurationException(
              ProjectBundle.message(
                  "module.paths.validation.source.root.belongs.to.another.module.error",
                  srcRoot.getPresentableUrl(),
                  expectedModuleName,
                  moduleName));
        }
      }
    }

    final List<ModifiableRootModel> models =
        new ArrayList<ModifiableRootModel>(myModuleEditors.size());
    for (ModuleEditor moduleEditor : myModuleEditors.values()) {
      moduleEditor.canApply();
    }

    final Map<Sdk, Sdk> modifiedToOriginalMap = new HashMap<Sdk, Sdk>();
    final ProjectSdksModel projectJdksModel =
        ProjectStructureConfigurable.getInstance(myProject).getProjectJdksModel();
    for (Map.Entry<Sdk, Sdk> entry : projectJdksModel.getProjectSdks().entrySet()) {
      modifiedToOriginalMap.put(entry.getValue(), entry.getKey());
    }

    final Ref<ConfigurationException> exceptionRef = Ref.create();
    DumbService.getInstance(myProject)
        .allowStartingDumbModeInside(
            DumbModePermission.MAY_START_BACKGROUND,
            new Runnable() {
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            try {
                              for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
                                final ModifiableRootModel model = moduleEditor.apply();
                                if (model != null) {
                                  if (!model.isSdkInherited()) {
                                    // make sure the sdk is set to original SDK stored in the JDK
                                    // Table
                                    final Sdk modelSdk = model.getSdk();
                                    if (modelSdk != null) {
                                      final Sdk original = modifiedToOriginalMap.get(modelSdk);
                                      if (original != null) {
                                        model.setSdk(original);
                                      }
                                    }
                                  }
                                  models.add(model);
                                }
                              }
                              myFacetsConfigurator.applyEditors();
                            } catch (ConfigurationException e) {
                              exceptionRef.set(e);
                              return;
                            }

                            try {
                              final ModifiableRootModel[] rootModels =
                                  models.toArray(new ModifiableRootModel[models.size()]);
                              ModifiableModelCommitter.multiCommit(rootModels, myModuleModel);
                              myModuleModelCommitted = true;
                              myFacetsConfigurator.commitFacets();

                            } finally {
                              ModuleStructureConfigurable.getInstance(myProject)
                                  .getFacetEditorFacade()
                                  .clearMaps(false);

                              myFacetsConfigurator = createFacetsConfigurator();
                              myModuleModel =
                                  ModuleManager.getInstance(myProject).getModifiableModel();
                              myModuleModelCommitted = false;
                            }
                          }
                        });
              }
            });

    if (!exceptionRef.isNull()) {
      throw exceptionRef.get();
    }

    myModified = false;
  }
コード例 #23
0
  /**
   * Invokes {@link com.intellij.openapi.diff.DiffManager#getDiffTool()} to show difference between
   * the given revisions of the given file.
   *
   * @param project project under vcs control.
   * @param filePath file which revisions are compared.
   * @param revision1 first revision - 'before', to the left.
   * @param revision2 second revision - 'after', to the right.
   * @throws com.intellij.openapi.vcs.VcsException
   * @throws java.io.IOException
   */
  public static void showDiff(
      @NotNull final Project project,
      @NotNull FilePath filePath,
      @NotNull VcsFileRevision revision1,
      @NotNull VcsFileRevision revision2,
      @NotNull String title1,
      @NotNull String title2)
      throws VcsException, IOException {
    final byte[] content1 = loadRevisionContent(revision1);
    final byte[] content2 = loadRevisionContent(revision2);

    final SimpleDiffRequest diffData = new SimpleDiffRequest(project, filePath.getPresentableUrl());
    diffData.addHint(DiffTool.HINT_SHOW_FRAME);
    final Document doc = filePath.getDocument();
    final Charset charset = filePath.getCharset();
    final FileType fileType = filePath.getFileType();
    diffData.setContentTitles(title1, title2);
    final Ref<VirtualFile> f1 = new Ref<VirtualFile>(null);
    final Ref<VirtualFile> f2 = new Ref<VirtualFile>(null);

    if (fileType.isBinary()) {
      final File file1 =
          FileUtil.createTempFile(revision1.getRevisionNumber().asString(), filePath.getName());
      final File file2 =
          FileUtil.createTempFile(revision2.getRevisionNumber().asString(), filePath.getName());
      try {
        final FileOutputStream fos1 = new FileOutputStream(file1);
        fos1.write(content1);
        final FileOutputStream fos2 = new FileOutputStream(file2);
        fos2.write(content2);
        fos1.close();
        fos2.close();
        f1.set(LocalFileSystem.getInstance().findFileByIoFile(file1));
        f2.set(LocalFileSystem.getInstance().findFileByIoFile(file2));
      } catch (Exception e) { //
      }
    }
    if (f1.isNull() || f2.isNull()) {
      diffData.setContents(
          createContent(project, content1, revision1, doc, charset, fileType, filePath.getPath()),
          createContent(project, content2, revision2, doc, charset, fileType, filePath.getPath()));
    } else {
      diffData.setContents(
          createFileContent(project, f1.get(), revision1),
          createFileContent(project, f2.get(), revision2));
    }
    WaitForProgressToShow.runOrInvokeLaterAboveProgress(
        new Runnable() {
          public void run() {
            DiffManager.getInstance().getDiffTool().show(diffData);
            if (!f1.isNull() || !f2.isNull()) {
              Disposer.register(
                  project,
                  new Disposable() {
                    @Override
                    public void dispose() {
                      ApplicationManager.getApplication()
                          .runWriteAction(
                              new Runnable() {
                                public void run() {
                                  try {
                                    if (!f1.isNull()) {
                                      f1.get().delete(this);
                                    }
                                    if (!f2.isNull()) {
                                      f2.get().delete(this);
                                    }
                                  } catch (IOException e) { //
                                  }
                                }
                              });
                    }
                  });
            }
          }
        },
        null,
        project);
  }