Java源码示例:com.intellij.openapi.util.ThrowableComputable

示例1
@Override
public void fetchChildren(@Nonnull Function<T, TreeNode<T>> nodeFactory, @Nullable T parentValue) {
  ThrowableComputable<Object[],RuntimeException> action = () -> myStructure.getChildElements(parentValue);
  for (Object o : AccessRule.read(action)) {
    T element = (T)o;
    TreeNode<T> apply = nodeFactory.apply(element);

    apply.setLeaf(o instanceof AbstractTreeNode && !((AbstractTreeNode)o).isAlwaysShowPlus());


    apply.setRender((fileElement, itemPresentation) -> {
      NodeDescriptor descriptor = myStructure.createDescriptor(element, null);

      descriptor.update();

      itemPresentation.append(descriptor.toString());
      try {
        AccessRule.read(() -> itemPresentation.setIcon(descriptor.getIcon()));
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    });
  }
}
 
示例2
private static void applyAdditionalInfoImpl(final Project project,
                                            @javax.annotation.Nullable ThrowableComputable<Map<String, Map<String, CharSequence>>, PatchSyntaxException> additionalInfo,
                                            CommitContext commitContext, final Consumer<InfoGroup> worker) {
  final PatchEP[] extensions = Extensions.getExtensions(PatchEP.EP_NAME, project);
  if (extensions.length == 0) return;
  if (additionalInfo != null) {
    try {
      for (Map.Entry<String, Map<String, CharSequence>> entry : additionalInfo.compute().entrySet()) {
        final String path = entry.getKey();
        final Map<String, CharSequence> innerMap = entry.getValue();

        for (PatchEP extension : extensions) {
          final CharSequence charSequence = innerMap.get(extension.getName());
          if (charSequence != null) {
            worker.consume(new InfoGroup(extension, path, charSequence, commitContext));
          }
        }
      }
    }
    catch (PatchSyntaxException e) {
      VcsBalloonProblemNotifier
              .showOverChangesView(project, "Can not apply additional patch info: " + e.getMessage(), MessageType.ERROR);
    }
  }
}
 
示例3
private void testPath(final DatabaseVendor databaseVendor) {
    ProcessOutput processOutput;
    try {
        processOutput = ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<ProcessOutput, Exception>() {
            @Override
            public ProcessOutput compute() throws Exception {
                return checkShellPath(databaseVendor, getShellPath());
            }
        }, "Testing " + databaseVendor.name + " CLI Executable...", true, NoSqlConfigurable.this.project);
    } catch (ProcessCanceledException pce) {
        return;
    } catch (Exception e) {
        Messages.showErrorDialog(mainPanel, e.getMessage(), "Something wrong happened");
        return;
    }
    if (processOutput != null && processOutput.getExitCode() == 0) {
        Messages.showInfoMessage(mainPanel, processOutput.getStdout(), databaseVendor.name + " CLI Path Checked");
    }
}
 
示例4
@Nullable
private static Document createPsiDocument(@Nonnull Project project,
                                          @Nonnull String content,
                                          @Nonnull FileType fileType,
                                          @Nonnull String fileName,
                                          boolean readOnly) {
  ThrowableComputable<Document,RuntimeException> action = () -> {
    LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
    file.setWritable(!readOnly);

    file.putUserData(DiffPsiFileSupport.KEY, true);

    Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return null;

    PsiDocumentManager.getInstance(project).getPsiFile(document);

    return document;
  };
  return AccessRule.read(action);
}
 
示例5
private void doCollectUsages(final ProjectStructureElement element) {
  ThrowableComputable<List<ProjectStructureElementUsage>,RuntimeException> action = () -> {
    if (myStopped.get()) return null;

    if (LOG.isDebugEnabled()) {
      LOG.debug("collecting usages in " + element);
    }
    return getUsagesInElement(element);
  };
  final List<ProjectStructureElementUsage> usages = AccessRule.read(action);

  invokeLater(new Runnable() {
    @Override
    public void run() {
      if (myStopped.get() || usages == null) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("updating usages for " + element);
      }
      updateUsages(element, usages);
    }
  });
}
 
示例6
@Nonnull
public static <T> AsyncResult<T> readAsync(@RequiredReadAction @Nonnull ThrowableComputable<T, Throwable> action) {
  AsyncResult<T> result = AsyncResult.undefined();
  Application application = Application.get();
  AppExecutorUtil.getAppExecutorService().execute(() -> {
    try {
      result.setDone(application.runReadAction(action));
    }
    catch (Throwable throwable) {
      LOG.error(throwable);

      result.rejectWithThrowable(throwable);
    }
  });
  return result;
}
 
示例7
private static <T> void createAndRun(final Project project, @javax.annotation.Nullable final VcsBackgroundableActions actionKey,
                               @javax.annotation.Nullable final Object actionParameter,
                               final String title,
                               final String errorTitle,
                               final ThrowableComputable<T, VcsException> backgroundable,
                               @javax.annotation.Nullable final Consumer<T> awtSuccessContinuation,
                               @Nullable final Runnable awtErrorContinuation, final boolean silent) {
  final ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(project);
  final BackgroundableActionEnabledHandler handler;
  if (actionKey != null) {
    handler = vcsManager.getBackgroundableActionHandler(actionKey);
    // fo not start same action twice
    if (handler.isInProgress(actionParameter)) return;
  } else {
    handler = null;
  }

  final VcsBackgroundableComputable<T> backgroundableComputable =
    new VcsBackgroundableComputable<T>(project, title, errorTitle, backgroundable, awtSuccessContinuation, awtErrorContinuation,
                                handler, actionParameter);
  backgroundableComputable.setSilent(silent);
  if (handler != null) {
    handler.register(actionParameter);
  }
  ProgressManager.getInstance().run(backgroundableComputable);
}
 
示例8
@Nonnull
public ThrowableComputable<Map<String, Map<String, CharSequence>>, PatchSyntaxException> getAdditionalInfo(@Nullable Set<String> paths) {
  ThrowableComputable<Map<String, Map<String, CharSequence>>, PatchSyntaxException> result;
  PatchSyntaxException e = myAdditionalInfoParser.getSyntaxException();

  if (e != null) {
    result = () -> {
      throw e;
    };
  }
  else {
    Map<String, Map<String, CharSequence>> additionalInfo = ContainerUtil.filter(myAdditionalInfoParser.getResultMap(), path -> paths == null || paths
            .contains(path));
    result = () -> additionalInfo;
  }

  return result;
}
 
示例9
/**
 * Finds duplicates of the code fragment specified in the finder in given scopes.
 * Note that in contrast to {@link #processDuplicates} the search is performed synchronously because normally you need the results in
 * order to complete the refactoring. If user cancels it, empty list will be returned.
 *
 * @param finder          finder object to seek for duplicates
 * @param searchScopes    scopes where to look them in
 * @param generatedMethod new method that should be excluded from the search
 * @return list of discovered duplicate code fragments or empty list if user interrupted the search
 * @see #replaceDuplicates(PsiElement, Editor, Consumer, List)
 */
@Nonnull
public static List<SimpleMatch> collectDuplicates(@Nonnull SimpleDuplicatesFinder finder,
                                                  @Nonnull List<PsiElement> searchScopes,
                                                  @Nonnull PsiElement generatedMethod) {
  final Project project = generatedMethod.getProject();
  try {
    //noinspection RedundantCast
    return ProgressManager.getInstance().runProcessWithProgressSynchronously(
            (ThrowableComputable<List<SimpleMatch>, RuntimeException>)() -> {
              ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true);
              ThrowableComputable<List<SimpleMatch>, RuntimeException> action = () -> finder.findDuplicates(searchScopes, generatedMethod);
              return AccessRule.read(action);
            }, RefactoringBundle.message("searching.for.duplicates"), true, project);
  }
  catch (ProcessCanceledException e) {
    return Collections.emptyList();
  }
}
 
示例10
private void loadMessagesInModalTask(@Nonnull Project project) {
  try {
    myMessagesForRoots =
      ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<Map<VirtualFile,String>, VcsException>() {
        @Override
        public Map<VirtualFile, String> compute() throws VcsException {
          return getLastCommitMessages();
        }
      }, "Reading commit message...", false, project);
  }
  catch (VcsException e) {
    Messages.showErrorDialog(getComponent(), "Couldn't load commit message of the commit to amend.\n" + e.getMessage(),
                             "Commit Message not Loaded");
    log.info(e);
  }
}
 
示例11
public static FilePath getLocalPath(@Nonnull Project project, FilePath filePath) {
  // check if the file has just been renamed (IDEADEV-15494)
  ThrowableComputable<Change, RuntimeException> action = () -> {
    if (project.isDisposed()) throw new ProcessCanceledException();
    return ChangeListManager.getInstance(project).getChange(filePath);
  };
  Change change = AccessRule.read(action);
  if (change != null) {
    ContentRevision beforeRevision = change.getBeforeRevision();
    ContentRevision afterRevision = change.getAfterRevision();
    if (beforeRevision != null && afterRevision != null && !beforeRevision.getFile().equals(afterRevision.getFile()) &&
        beforeRevision.getFile().equals(filePath)) {
      return afterRevision.getFile();
    }
  }
  return filePath;
}
 
示例12
private static <T> T readAndHandleErrors(@Nonnull ThrowableComputable<T, ?> action) {
  assert lock.getReadHoldCount() == 0; // otherwise DbConnection.handleError(e) (requires write lock) could fail
  try {
    r.lock();
    try {
      return action.compute();
    }
    finally {
      r.unlock();
    }
  }
  catch (Throwable e) {
    DbConnection.handleError(e);
    throw new RuntimeException(e);
  }
}
 
示例13
static void saveIn(@Nonnull final Document document, final Editor editor, @Nonnull final VirtualFile virtualFile, @Nonnull final Charset charset) {
  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  documentManager.saveDocument(document);
  final Project project = ProjectLocator.getInstance().guessProjectForFile(virtualFile);
  boolean writable = project == null ? virtualFile.isWritable() : ReadonlyStatusHandler.ensureFilesWritable(project, virtualFile);
  if (!writable) {
    CommonRefactoringUtil.showErrorHint(project, editor, "Cannot save the file " + virtualFile.getPresentableUrl(), "Unable to Save", null);
    return;
  }

  EncodingProjectManagerImpl.suppressReloadDuring(() -> {
    EncodingManager.getInstance().setEncoding(virtualFile, charset);
    try {
      ApplicationManager.getApplication().runWriteAction((ThrowableComputable<Object, IOException>)() -> {
        virtualFile.setCharset(charset);
        LoadTextUtil.write(project, virtualFile, virtualFile, document.getText(), document.getModificationStamp());
        return null;
      });
    }
    catch (IOException io) {
      Messages.showErrorDialog(project, io.getMessage(), "Error Writing File");
    }
  });
}
 
示例14
public static void awaitWithCheckCanceled(@Nonnull ThrowableComputable<Boolean, ? extends Exception> waiter) {
  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  boolean success = false;
  while (!success) {
    checkCancelledEvenWithPCEDisabled(indicator);
    try {
      success = waiter.compute();
    }
    catch (Exception e) {
      //noinspection InstanceofCatchParameter
      if (!(e instanceof InterruptedException)) {
        LOG.warn(e);
      }
      throw new ProcessCanceledException(e);
    }
  }
}
 
示例15
private VcsBackgroundableComputable(final Project project, final String title,
                                final String errorTitle,
                                final ThrowableComputable<T, VcsException> backgroundable,
                                final Consumer<T> awtSuccessContinuation,
                                final Runnable awtErrorContinuation,
                                final BackgroundableActionEnabledHandler handler,
                                final Object actionParameter) {
  super(project, title, true, BackgroundFromStartOption.getInstance());
  myErrorTitle = errorTitle;
  myBackgroundable = backgroundable;
  myAwtSuccessContinuation = awtSuccessContinuation;
  myAwtErrorContinuation = awtErrorContinuation;
  myProject = project;
  myHandler = handler;
  myActionParameter = actionParameter;
}
 
示例16
@Nonnull
private static ThrowableComputable<PersistentHashMap<String, Record>, IOException> getComputable(final File file) {
  return () -> new PersistentHashMap<>(file, EnumeratorStringDescriptor.INSTANCE, new DataExternalizer<Record>() {
    @Override
    public void save(@Nonnull DataOutput out, Record value) throws IOException {
      out.writeInt(value.magnitude);
      out.writeLong(value.date.getTime());
      out.writeLong(value.configurationHash);
    }

    @Override
    public Record read(@Nonnull DataInput in) throws IOException {
      return new Record(in.readInt(), new Date(in.readLong()), in.readLong());
    }
  }, 4096, CURRENT_VERSION);
}
 
示例17
@Override
public <T, E extends Throwable> T computePrioritized(@Nonnull ThrowableComputable<T, E> computable) throws E {
  Thread thread = Thread.currentThread();

  if (!Registry.is("ide.prioritize.threads") || isPrioritizedThread(thread)) {
    return computable.compute();
  }

  synchronized (myPrioritizationLock) {
    if (myPrioritizedThreads.isEmpty()) {
      myPrioritizingStarted = System.nanoTime();
    }
    myPrioritizedThreads.add(thread);
    updateEffectivePrioritized();
  }
  try {
    return computable.compute();
  }
  finally {
    synchronized (myPrioritizationLock) {
      myPrioritizedThreads.remove(thread);
      updateEffectivePrioritized();
    }
  }
}
 
示例18
@javax.annotation.Nullable
private static VirtualFile getValidParentUnderReadAction(@Nonnull FilePath filePath) {
  ThrowableComputable<VirtualFile,RuntimeException> action = () -> {
    VirtualFile result = null;
    FilePath parent = filePath;
    LocalFileSystem lfs = LocalFileSystem.getInstance();

    while (result == null && parent != null) {
      result = lfs.findFileByPath(parent.getPath());
      parent = parent.getParentPath();
    }

    return result;
  };
  return AccessRule.read(action);
}
 
示例19
public void createSessionFor(final VcsKey vcsKey, final FilePath filePath, final Consumer<VcsHistorySession> continuation,
                             @Nullable VcsBackgroundableActions actionKey,
                             final boolean silent,
                             @Nullable final Consumer<VcsHistorySession> backgroundSpecialization) {
  final ThrowableComputable<VcsHistorySession, VcsException> throwableComputable =
          myHistoryComputerFactory.create(filePath, backgroundSpecialization, vcsKey);
  final VcsBackgroundableActions resultingActionKey = actionKey == null ? VcsBackgroundableActions.CREATE_HISTORY_SESSION : actionKey;
  final Object key = VcsBackgroundableActions.keyFrom(filePath);

  if (silent) {
    VcsBackgroundableComputable.createAndRunSilent(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                                   throwableComputable, continuation);
  } else {
    VcsBackgroundableComputable.createAndRun(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                             VcsBundle.message("message.title.could.not.load.file.history"), throwableComputable, continuation, null);
  }
}
 
示例20
private void collectDiagnostics(String uri, IPsiUtils utils, DocumentFormat documentFormat,
                                List<Diagnostic> diagnostics) {
    PsiFile typeRoot = ApplicationManager.getApplication().runReadAction((Computable<PsiFile>) () -> resolveTypeRoot(uri, utils));
    if (typeRoot == null) {
        return;
    }

    try {
        Module module = ApplicationManager.getApplication().runReadAction((ThrowableComputable<Module, IOException>) () -> utils.getModule(uri));
        DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
            // Collect all adapted diagnostics participant
            JavaDiagnosticsContext context = new JavaDiagnosticsContext(uri, typeRoot, utils, module, documentFormat);
            List<IJavaDiagnosticsParticipant> definitions = IJavaDiagnosticsParticipant.EP_NAME.extensions()
                    .filter(definition -> definition.isAdaptedForDiagnostics(context))
                    .collect(Collectors.toList());
            if (definitions.isEmpty()) {
                return;
            }

            // Begin, collect, end participants
            definitions.forEach(definition -> definition.beginDiagnostics(context));
            definitions.forEach(definition -> {
                List<Diagnostic> collectedDiagnostics = definition.collectDiagnostics(context);
                if (collectedDiagnostics != null && !collectedDiagnostics.isEmpty()) {
                    diagnostics.addAll(collectedDiagnostics);
                }
            });
            definitions.forEach(definition -> definition.endDiagnostics(context));
        });
    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
    }
}
 
示例21
public static void runInWriteAction(RunnableThatThrows callback) throws Exception {
  final ThrowableComputable<Object, Exception> action = () -> {
    callback.run();
    return null;
  };
  runOnDispatchThread(() -> ApplicationManager.getApplication().runWriteAction(action));
}
 
示例22
@SuppressWarnings("RedundantTypeArguments")
public static <T> T computeInWriteAction(ThrowableComputable<T, Exception> callback) throws Exception {
  return computeOnDispatchThread(() -> {
    final Application app = ApplicationManager.getApplication();
    return app.<T, Exception>runWriteAction(callback);
  });
}
 
示例23
public static void runInWriteAction(RunnableThatThrows callback) throws Exception {
  final ThrowableComputable<Object, Exception> action = () -> {
    callback.run();
    return null;
  };
  runOnDispatchThread(() -> ApplicationManager.getApplication().runWriteAction(action));
}
 
示例24
@Override
public void delete() throws IOException {
  FilesystemRunner.runWriteAction(
      (ThrowableComputable<Void, IOException>)
          () -> {
            deleteInternal();

            return null;
          },
      ModalityState.defaultModalityState());
}
 
示例25
@Override
public void create() throws IOException {
  FilesystemRunner.runWriteAction(
      (ThrowableComputable<Void, IOException>)
          () -> {
            createInternal();

            return null;
          },
      ModalityState.defaultModalityState());
}
 
示例26
@Override
public void delete() throws IOException {
  FilesystemRunner.runWriteAction(
      (ThrowableComputable<Void, IOException>)
          () -> {
            deleteInternal();

            return null;
          },
      ModalityState.defaultModalityState());
}
 
示例27
@Override
public void setContents(@Nullable InputStream input) throws IOException {
  FilesystemRunner.runWriteAction(
      (ThrowableComputable<Void, IOException>)
          () -> {
            setContentsInternal(input);

            return null;
          },
      ModalityState.defaultModalityState());
}
 
示例28
@Override
public void create(@Nullable InputStream input) throws IOException {
  FilesystemRunner.runWriteAction(
      (ThrowableComputable<Void, IOException>)
          () -> {
            createInternal(input);

            return null;
          },
      ModalityState.defaultModalityState());
}
 
示例29
@Nonnull
private static File createTempFile(@Nonnull final DocumentContent content, @Nonnull FileNameInfo fileName) throws IOException {
  FileDocumentManager.getInstance().saveDocument(content.getDocument());

  LineSeparator separator = content.getLineSeparator();
  if (separator == null) separator = LineSeparator.getSystemLineSeparator();

  Charset charset = content.getCharset();
  if (charset == null) charset = Charset.defaultCharset();

  Boolean hasBom = content.hasBom();
  if (hasBom == null) hasBom = CharsetToolkit.getMandatoryBom(charset) != null;

  ThrowableComputable<String,RuntimeException> action = () -> {
    return content.getDocument().getText();
  };
  String contentData = AccessRule.read(action);
  if (separator != LineSeparator.LF) {
    contentData = StringUtil.convertLineSeparators(contentData, separator.getSeparatorString());
  }

  byte[] bytes = contentData.getBytes(charset);

  byte[] bom = hasBom ? CharsetToolkit.getPossibleBom(charset) : null;
  if (bom != null) {
    bytes = ArrayUtil.mergeArrays(bom, bytes);
  }

  return createFile(bytes, fileName);
}
 
示例30
@javax.annotation.Nullable
@Override
public DocumentContent createDocument(@javax.annotation.Nullable Project project, @Nonnull final VirtualFile file) {
  // TODO: add notification, that file is decompiled ?
  if (file.isDirectory()) return null;
  ThrowableComputable<Document, RuntimeException> action = () -> {
    return FileDocumentManager.getInstance().getDocument(file);
  };
  Document document = AccessRule.read(action);
  if (document == null) return null;
  return new FileDocumentContentImpl(project, document, file);
}