com.intellij.openapi.util.ThrowableComputable Java Examples

The following examples show how to use com.intellij.openapi.util.ThrowableComputable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example #2
Source File: TreeStructureWrappenModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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();
      }
    });
  }
}
 
Example #3
Source File: NoSqlConfigurable.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #4
Source File: ApplyPatchDefaultExecutor.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example #5
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: ProjectStructureDaemonAnalyzer.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
    }
  });
}
 
Example #7
Source File: VcsHistoryProviderBackgroundableProxy.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #8
Source File: ChangesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: AccessRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: PatchReader.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
Source File: CoreProgressManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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();
    }
  }
}
 
Example #12
Source File: TestStateStorage.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: DvcsCommitAdditionalComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #14
Source File: ChangesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: VcsBackgroundableComputable.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: ExtractMethodHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example #17
Source File: FSRecords.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #18
Source File: EncodingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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");
    }
  });
}
 
Example #19
Source File: VcsBackgroundableComputable.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #20
Source File: BackgroundTaskUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean registerIfParentNotDisposed(@Nonnull Disposable parent, @Nonnull Disposable disposable) {
  ThrowableComputable<Boolean, RuntimeException> action = () -> {
    if (Disposer.isDisposed(parent)) return false;
    try {
      Disposer.register(parent, disposable);
      return true;
    }
    catch (IncorrectOperationException ioe) {
      LOG.error(ioe);
      return false;
    }
  };
  return AccessRule.read(action);
}
 
Example #21
Source File: BackgroundTaskUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps {@link MessageBus#syncPublisher(Topic)} in a dispose check,
 * and throws a {@link ProcessCanceledException} if the application is disposed,
 * instead of throwing an assertion which would happen otherwise.
 *
 * @see #syncPublisher(Project, Topic)
 */
@Nonnull
public static <L> L syncPublisher(@Nonnull Topic<L> topic) throws ProcessCanceledException {
  ThrowableComputable<L,RuntimeException> action = () -> {
    if (ApplicationManager.getApplication().isDisposed()) throw new ProcessCanceledException();
    return ApplicationManager.getApplication().getMessageBus().syncPublisher(topic);
  };
  return AccessRule.read(action);
}
 
Example #22
Source File: Testing.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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);
  });
}
 
Example #23
Source File: Testing.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void runInWriteAction(RunnableThatThrows callback) throws Exception {
  final ThrowableComputable<Object, Exception> action = () -> {
    callback.run();
    return null;
  };
  runOnDispatchThread(() -> ApplicationManager.getApplication().runWriteAction(action));
}
 
Example #24
Source File: ModuleBasedConfiguration.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Module[] getModules() {
  ThrowableComputable<Module[],RuntimeException> action = () -> {
    final Module module = getConfigurationModule().getModule();
    return module == null ? Module.EMPTY_ARRAY : new Module[]{module};
  };
  return AccessRule.read(action);
}
 
Example #25
Source File: VcsLogObjectsFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public VcsFullCommitDetails createFullDetails(@Nonnull Hash hash, @Nonnull List<Hash> parents, long commitTime, VirtualFile root,
                                              @Nonnull String subject, @Nonnull String authorName, @Nonnull String authorEmail,
                                              @Nonnull String message, @Nonnull String committerName, @Nonnull String committerEmail,
                                              long authorTime,
                                              @Nonnull ThrowableComputable<Collection<Change>, ? extends Exception> changesGetter) {
  VcsUser author = createUser(authorName, authorEmail);
  VcsUser committer = createUser(committerName, committerEmail);
  return new VcsChangesLazilyParsedDetails(hash, parents, commitTime, root, subject, author, message, committer, authorTime,
                                           changesGetter);
}
 
Example #26
Source File: VcsChangesLazilyParsedDetails.java    From consulo with Apache License 2.0 5 votes vote down vote up
public VcsChangesLazilyParsedDetails(@Nonnull Hash hash, @Nonnull List<Hash> parents, long commitTime, @Nonnull VirtualFile root,
                                     @Nonnull String subject, @Nonnull VcsUser author, @Nonnull String message,
                                     @Nonnull VcsUser committer, long authorTime,
                                     @Nonnull ThrowableComputable<Collection<Change>, ? extends Exception> changesGetter) {
  super(hash, parents, commitTime, root, subject, author, message, committer, authorTime);
  myChangesGetter = changesGetter;
}
 
Example #27
Source File: AstLoadingFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T, E extends Throwable> T forceAllowTreeLoading(@Nonnull VirtualFile virtualFile, @Nonnull ThrowableComputable<? extends T, E> computable) throws E {
  Set<VirtualFile> enabledFiles = myForcedAllowedFiles.get();
  if (enabledFiles.add(virtualFile)) {
    try {
      return computable.compute();
    }
    finally {
      enabledFiles.remove(virtualFile);
    }
  }
  else {
    return computable.compute();
  }
}
 
Example #28
Source File: AstLoadingFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T, E extends Throwable> T disallowTreeLoading(@Nonnull ThrowableComputable<? extends T, E> computable, @Nonnull Supplier<String> debugInfo) throws E {
  if (myDisallowedInfo.get() != null) {
    return computable.compute();
  }
  else {
    try {
      myDisallowedInfo.set(debugInfo);
      return computable.compute();
    }
    finally {
      myDisallowedInfo.set(null);
    }
  }
}
 
Example #29
Source File: WriteCommandAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public <R, E extends Throwable> R compute(@Nonnull final ThrowableComputable<R, E> action) throws E {
  return new WriteCommandAction<R>(myProject, myCommandName, myGroupId, myFiles) {
    @Override
    protected void run(@Nonnull Result<R> result) throws Throwable {
      result.setResult(action.compute());
    }
  }.execute().getResultObject();
}
 
Example #30
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public <T, E extends Throwable> T runWriteActionNoIntentLock(@Nonnull ThrowableComputable<T, E> computation) throws E {
  Class<? extends ThrowableComputable> clazz = computation.getClass();

  startWrite(clazz);
  try {
    return computation.compute();
  }
  finally {
    endWrite(clazz);
  }
}