public boolean commitTransaction(final Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document);
    if (documentChangeTransaction == null) return false;
    final PsiFile changeScope = documentChangeTransaction.myChangeScope;
    try {
      mySyncDocument = document;

      final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager());
      fakeEvent.setParent(changeScope);
      fakeEvent.setFile(changeScope);
      checkPsiModificationAllowed(fakeEvent);
      doSync(
          fakeEvent,
          true,
          new DocSyncAction() {
            @Override
            public void syncDocument(
                @NotNull Document document, @NotNull PsiTreeChangeEventImpl event) {
              doCommitTransaction(document, documentChangeTransaction);
            }
          });
      myBus
          .syncPublisher(PsiDocumentTransactionListener.TOPIC)
          .transactionCompleted(document, changeScope);
    } catch (Throwable e) {
      myPsiDocumentManager.forceReload(
          changeScope.getViewProvider().getVirtualFile(), changeScope.getViewProvider());
      ExceptionUtil.rethrowAllAsUnchecked(e);
    } finally {
      mySyncDocument = null;
    }
    return true;
  }
  public final void showError(@NotNull String message, @NotNull Throwable e) {
    if (getProject().isDisposed()) {
      return;
    }

    while (e instanceof InvocationTargetException) {
      if (e.getCause() == null) {
        break;
      }
      e = e.getCause();
    }

    ErrorInfo info = new ErrorInfo();
    info.myMessage = info.myDisplayMessage = message;
    info.myThrowable = e;
    configureError(info);

    if (info.myShowMessage) {
      showErrorPage(info);
    }
    if (info.myShowLog) {
      LOG.error(
          LogMessageEx.createEvent(
              info.myDisplayMessage,
              info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable),
              new Attachment(myFile)));
    } else {
      LOG.info(info.myDisplayMessage + "\n" + info.myMessage, info.myThrowable);
    }
  }
  // returns list of resolved files if updated successfully, or null if write action or dumb mode
  // started
  private int[] processFile(
      @NotNull final VirtualFile file, int fileId, @NotNull final ProgressIndicator indicator) {
    final TIntHashSet forward;
    try {
      forward = calcForwardRefs(file, indicator);
    } catch (IndexNotReadyException e) {
      return null;
    } catch (ApplicationUtil.CannotRunReadActionException e) {
      return null;
    } catch (ProcessCanceledException e) {
      throw e;
    } catch (Exception e) {
      log(ExceptionUtil.getThrowableText(e));
      flushLog();
      return null;
    }

    int[] forwardIds = forward.toArray();
    fileIsResolved.set(fileId);
    logf(
        "  ---- " + file.getPresentableUrl() + " processed. forwardIds: " + toVfString(forwardIds));
    for (Listener listener : myListeners) {
      listener.fileResolved(file);
    }
    return forwardIds;
  }
  private void startProcess(Target target, Parameters configuration, Pair<Target, Parameters> key) {
    ProgramRunner runner =
        new DefaultProgramRunner() {
          @NotNull
          public String getRunnerId() {
            return "MyRunner";
          }

          public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
            return true;
          }
        };
    Executor executor = DefaultRunExecutor.getRunExecutorInstance();
    ProcessHandler processHandler = null;
    try {
      RunProfileState state = getRunProfileState(target, configuration, executor);
      ExecutionResult result = state.execute(executor, runner);
      //noinspection ConstantConditions
      processHandler = result.getProcessHandler();
    } catch (Exception e) {
      dropProcessInfo(key, ExceptionUtil.getUserStackTrace(e, LOG), processHandler);
      return;
    }
    processHandler.addProcessListener(getProcessListener(key));
    processHandler.startNotify();
  }
  private static int bind(
      int firstPort,
      int portsCount,
      boolean tryAnyPort,
      @NotNull ServerBootstrap bootstrap,
      @NotNull ChannelRegistrar channelRegistrar)
      throws Exception {
    InetAddress address = NetUtils.getLoopbackAddress();

    for (int i = 0; i < portsCount; i++) {
      int port = firstPort + i;

      if (ArrayUtil.indexOf(FORBIDDEN_PORTS, i) >= 0) {
        continue;
      }

      ChannelFuture future = bootstrap.bind(address, port).awaitUninterruptibly();
      if (future.isSuccess()) {
        channelRegistrar.add(future.channel());
        return port;
      } else if (!tryAnyPort && i == (portsCount - 1)) {
        ExceptionUtil.rethrowAll(future.cause());
      }
    }

    LOG.info("We cannot bind to our default range, so, try to bind to any free port");
    ChannelFuture future = bootstrap.bind(address, 0).awaitUninterruptibly();
    if (future.isSuccess()) {
      channelRegistrar.add(future.channel());
      return ((InetSocketAddress) future.channel().localAddress()).getPort();
    } else {
      ExceptionUtil.rethrowAll(future.cause());
    }

    return -1; // unreachable
  }
 public static void error(
     @NotNull Logger logger,
     @NotNull String message,
     @NotNull Throwable cause,
     @NotNull String... attachmentText) {
   StringBuilder detailsBuffer = new StringBuilder();
   for (String detail : attachmentText) {
     detailsBuffer.append(detail).append(",");
   }
   if (attachmentText.length > 0 && detailsBuffer.length() > 0) {
     detailsBuffer.setLength(detailsBuffer.length() - 1);
   }
   Attachment attachment =
       detailsBuffer.length() > 0
           ? new Attachment("current-context.txt", detailsBuffer.toString())
           : null;
   logger.error(
       createEvent(message, ExceptionUtil.getThrowableText(cause), null, null, attachment));
 }
 // TODO this is to be removed when tags will be supported by the GitRepositoryReader
 private Collection<? extends VcsRef> readTags(@NotNull VirtualFile root) throws VcsException {
   GitSimpleHandler tagHandler = new GitSimpleHandler(myProject, root, GitCommand.LOG);
   tagHandler.setSilent(true);
   tagHandler.addParameters(
       "--tags", "--no-walk", "--format=%H%d" + GitLogParser.RECORD_START_GIT, "--decorate=full");
   String out = tagHandler.run();
   Collection<VcsRef> refs = new ArrayList<VcsRef>();
   try {
     for (String record : out.split(GitLogParser.RECORD_START)) {
       if (!StringUtil.isEmptyOrSpaces(record)) {
         refs.addAll(new RefParser(myVcsObjectsFactory).parseCommitRefs(record.trim(), root));
       }
     }
   } catch (Exception e) {
     LOG.error(
         "Error during tags parsing",
         new Attachment("stack_trace.txt", ExceptionUtil.getThrowableText(e)),
         new Attachment("git_output.txt", out));
   }
   return refs;
 }
  @NotNull
  public static CharSequence loadText(@NotNull final VirtualFile file) {
    if (file instanceof LightVirtualFile) {
      return ((LightVirtualFile) file).getContent();
    }

    if (file.isDirectory()) {
      throw new AssertionError("'" + file.getPresentableUrl() + "' is a directory");
    }

    FileType fileType = file.getFileType();
    if (fileType.isBinary()) {
      final BinaryFileDecompiler decompiler =
          BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType);
      if (decompiler != null) {
        CharSequence text;

        Application app = ApplicationManager.getApplication();
        if (app != null
            && app.isDispatchThread()
            && !app.isWriteAccessAllowed()
            && !ourDecompileProgressStarted) {
          final Ref<CharSequence> result = Ref.create(ArrayUtil.EMPTY_CHAR_SEQUENCE);
          final Ref<Throwable> error = Ref.create();

          ourDecompileProgressStarted = true;
          try {
            ProgressManager.getInstance()
                .run(
                    new Task.Modal(null, "Decompiling " + file.getName(), true) {
                      @Override
                      public void run(@NotNull ProgressIndicator indicator) {
                        indicator.setIndeterminate(true);
                        try {
                          result.set(
                              ApplicationUtil.runWithCheckCanceled(
                                  new Callable<CharSequence>() {
                                    @Override
                                    public CharSequence call() {
                                      return decompiler.decompile(file);
                                    }
                                  },
                                  indicator));
                        } catch (Throwable t) {
                          error.set(t);
                        }
                      }
                    });
          } finally {
            ourDecompileProgressStarted = false;
          }

          ExceptionUtil.rethrowUnchecked(error.get());
          text = result.get();
        } else {
          text = decompiler.decompile(file);
        }

        StringUtil.assertValidSeparators(text);
        return text;
      }

      throw new IllegalArgumentException(
          "Attempt to load text for binary file which doesn't have a decompiler plugged in: "
              + file.getPresentableUrl()
              + ". File type: "
              + fileType.getName());
    }

    try {
      byte[] bytes = file.contentsToByteArray();
      return getTextByBinaryPresentation(bytes, file);
    } catch (IOException e) {
      return ArrayUtil.EMPTY_CHAR_SEQUENCE;
    }
  }