com.intellij.util.ThrowableRunnable Java Examples

The following examples show how to use com.intellij.util.ThrowableRunnable. 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: MacOSDefaultMenuInitializer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Inject
@ReviewAfterMigrationToJRE(9)
public MacOSDefaultMenuInitializer(AboutManager aboutManager, DataManager dataManager, WindowManager windowManager) {
  myAboutManager = aboutManager;
  myDataManager = dataManager;
  myWindowManager = windowManager;
  if (SystemInfo.isMac) {
    try {
      ThrowableRunnable<Throwable> task = SystemInfo.isJavaVersionAtLeast(9) ? new Java9Worker(this::showAbout) : new PreJava9Worker(this::showAbout);

      task.run();

      installAutoUpdateMenu();
    }
    catch (Throwable t) {
      LOGGER.warn(t);
    }
  }
}
 
Example #2
Source File: HTMLExportUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void runExport(final Project project, @Nonnull ThrowableRunnable<IOException> runnable) {
  try {
    runnable.run();
  }
  catch (IOException e) {
    Runnable showError = new Runnable() {
      @Override
      public void run() {
        Messages.showMessageDialog(
          project,
          InspectionsBundle.message("inspection.export.error.writing.to", "export file"),
          InspectionsBundle.message("inspection.export.results.error.title"),
          Messages.getErrorIcon()
        );
      }
    };
    ApplicationManager.getApplication().invokeLater(showError, ModalityState.NON_MODAL);
    throw new ProcessCanceledException();
  }
}
 
Example #3
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Throwable> void performActionWithFormatterDisabled(final ThrowableRunnable<T> r) throws T {
  final Throwable[] throwable = new Throwable[1];

  performActionWithFormatterDisabled(() -> {
    try {
      r.run();
    }
    catch (Throwable t) {
      throwable[0] = t;
    }
    return null;
  });

  if (throwable[0] != null) {
    //noinspection unchecked
    throw (T)throwable[0];
  }
}
 
Example #4
Source File: ExportHTMLAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private void exportHTML(HTMLExportFrameMaker frameMaker, InspectionNode node) {
  final Set<InspectionToolWrapper> toolWrappers = getWorkedTools(node);
  final InspectionToolWrapper toolWrapper = node.getToolWrapper();

  final HTMLExporter exporter =
    new HTMLExporter(frameMaker.getRootFolder() + "/" + toolWrapper.getShortName(), myView.getGlobalInspectionContext().getPresentation(toolWrapper).getComposer());
  frameMaker.startInspection(toolWrapper);
  HTMLExportUtil.runExport(myView.getProject(), new ThrowableRunnable<IOException>() {
    @Override
    @RequiredReadAction
    public void run() throws IOException {
      exportHTML(toolWrappers, exporter);
      exporter.generateReferencedPages();
    }
  });
}
 
Example #5
Source File: BackgroundTaskGroup.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void runInEdt(@Nonnull ThrowableRunnable<VcsException> task) {
  myProcessor.add(continuation -> {
    boolean isSuccess = false;
    try {
      task.run();
      isSuccess = true;
    }
    catch (VcsException e) {
      addError(e);
      isSuccess = e.isWarning();
    }
    finally {
      if (!isSuccess) {
        end();
      }
      continuation.run();
    }
  });
}
 
Example #6
Source File: IndexInfrastructure.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void executeNestedInitializationTask(@Nonnull ThrowableRunnable<?> callable, CountDownLatch proceedLatch) {
  Application app = ApplicationManager.getApplication();
  try {
    // To correctly apply file removals in indices's shutdown hook we should process all initialization tasks
    // Todo: make processing removed files more robust because ignoring 'dispose in progress' delays application exit and
    // may cause memory leaks IDEA-183718, IDEA-169374,
    if (app.isDisposed() /*|| app.isDisposeInProgress()*/) return;
    callable.run();
  }
  catch (Throwable t) {
    onThrowable(t);
  }
  finally {
    proceedLatch.countDown();
  }
}
 
Example #7
Source File: VcsSynchronousProgressWrapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean wrap(final ThrowableRunnable<VcsException> runnable, final Project project, final String title) {
  final VcsException[] exc = new VcsException[1];
  final Runnable process = new Runnable() {
    @Override
    public void run() {
      try {
        runnable.run();
      }
      catch (VcsException e) {
        exc[0] = e;
      }
    }
  };
  final boolean notCanceled;
  if (ApplicationManager.getApplication().isDispatchThread()) {
    notCanceled = ProgressManager.getInstance().runProcessWithProgressSynchronously(process, title, true, project);
  } else {
    process.run();
    notCanceled = true;
  }
  if (exc[0] != null) {
    AbstractVcsHelper.getInstance(project).showError(exc[0], title);
    return false;
  }
  return notCanceled;
}
 
Example #8
Source File: TestUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void tearDownIgnoringObjectNotDisposedException(ThrowableRunnable<Exception> delegate) throws Exception {
	try {
		delegate.run();
	} catch (RuntimeException e) {
		// We don't want to release the editor in the Tool Output tool window, so we ignore
		// ObjectNotDisposedExceptions related to this particular editor
		if ( e.getClass().getName().equals("com.intellij.openapi.util.TraceableDisposable$ObjectNotDisposedException")
				|| e instanceof CompoundRuntimeException ) {
			StringWriter stringWriter = new StringWriter();
			e.printStackTrace(new PrintWriter(stringWriter));
			String stack = stringWriter.toString();
			if ( stack.contains("ANTLRv4PluginController.createToolWindows")
					|| stack.contains("org.antlr.intellij.plugin.preview.InputPanel.createPreviewEditor") ) {
				return;
			}
		}

		throw e;
	}
}
 
Example #9
Source File: VcsUtils.java    From Crucible4IDEA with MIT License 6 votes vote down vote up
@Nullable
public static CommittedChangeList loadRevisions(@NotNull final Project project, final VcsRevisionNumber number, final FilePath filePath) {
  final CommittedChangeList[] list = new CommittedChangeList[1];
  final ThrowableRunnable<VcsException> runnable = () -> {
    final AbstractVcs vcs = VcsUtil.getVcsFor(project, filePath);

    if (vcs == null) {
      return;
    }

    list[0] = vcs.loadRevisions(filePath.getVirtualFile(), number);
  };

  final boolean success = VcsSynchronousProgressWrapper.wrap(runnable, project, "Load Revision Contents");

  return success ? list[0] : null;
}
 
Example #10
Source File: ElementCreator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private Exception executeCommand(String commandName, ThrowableRunnable<Exception> invokeCreate) {
  final Exception[] exception = new Exception[1];
  CommandProcessor.getInstance().executeCommand(myProject, () -> {
    LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName);
    try {
      invokeCreate.run();
    }
    catch (Exception ex) {
      exception[0] = ex;
    }
    finally {
      action.finish();
    }
  }, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION);
  return exception[0];
}
 
Example #11
Source File: GetPathPerformanceTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testGetPath() throws IOException, InterruptedException {
  final File dir = FileUtil.createTempDirectory("GetPath","");
  dir.deleteOnExit();

  String path = dir.getPath() + StringUtil.repeat("/xxx", 50) + "/fff.txt";
  File ioFile = new File(path);
  boolean b = ioFile.getParentFile().mkdirs();
  assertTrue(b);
  boolean c = ioFile.createNewFile();
  assertTrue(c);
  final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(ioFile.getPath().replace(File.separatorChar, '/'));
  assertNotNull(file);

  PlatformTestUtil.startPerformanceTest("VF.getPath() performance failed", 4000, new ThrowableRunnable() {
    @Override
    public void run() {
      for (int i = 0; i < 1000000; ++i) {
        file.getPath();
      }
    }
  }).cpuBound().assertTiming();
}
 
Example #12
Source File: PropertyTable.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void restoreDefaultValue() {
  final Property property = getSelectionProperty();
  if (property != null) {
    if (isEditing()) {
      cellEditor.stopCellEditing();
    }

    doRestoreDefault(new ThrowableRunnable<Exception>() {
      @Override
      public void run() throws Exception {
        for (PropertiesContainer component : myContainers) {
          if (!property.isDefaultRecursively(component)) {
            property.setDefaultValue(component);
          }
        }
      }
    });

    repaint();
  }
}
 
Example #13
Source File: VirtualFilePointerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testManyPointersUpdatePerformance() throws IOException {
  LoggingListener listener = new LoggingListener();
  final List<VFileEvent> events = new ArrayList<VFileEvent>();
  final File ioTempDir = createTempDirectory();
  final VirtualFile temp = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioTempDir);
  for (int i=0; i<100000; i++) {
    myVirtualFilePointerManager.create(VfsUtilCore.pathToUrl("/a/b/c/d/" + i), disposable, listener);
    String name = "xxx" + (i % 20);
    events.add(new VFileCreateEvent(this, temp, name, true, null, null, true, null));
  }
  PlatformTestUtil.startPerformanceTest("vfp update", 10000, new ThrowableRunnable() {
    @Override
    public void run() throws Throwable {
      for (int i=0; i<100; i++) {
        // simulate VFS refresh events since launching the actual refresh is too slow
        AsyncFileListener.ChangeApplier applier = myVirtualFilePointerManager.prepareChange(events);
        applier.beforeVfsChange();
        applier.afterVfsChange();
      }
    }
  }).assertTiming();
}
 
Example #14
Source File: VfsEventGenerationHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
void scheduleCreation(@Nonnull VirtualFile parent,
                      @Nonnull String childName,
                      @Nonnull FileAttributes attributes,
                      @Nullable String symlinkTarget,
                      @Nonnull ThrowableRunnable<RefreshWorker.RefreshCancelledException> checkCanceled) throws RefreshWorker.RefreshCancelledException {
  if (LOG.isTraceEnabled()) LOG.trace("create parent=" + parent + " name=" + childName + " attr=" + attributes);
  ChildInfo[] children = null;
  if (attributes.isDirectory() && parent.getFileSystem() instanceof LocalFileSystem && !attributes.isSymLink()) {
    try {
      Path child = Paths.get(parent.getPath(), childName);
      if (shouldScanDirectory(parent, child, childName)) {
        Path[] relevantExcluded = ContainerUtil.mapNotNull(ProjectManagerEx.getInstanceEx().getAllExcludedUrls(), url -> {
          Path path = Paths.get(VirtualFileManager.extractPath(url));
          return path.startsWith(child) ? path : null;
        }, new Path[0]);
        children = scanChildren(child, relevantExcluded, checkCanceled);
      }
    }
    catch (InvalidPathException ignored) {
      // Paths.get() throws sometimes
    }
  }
  VFileCreateEvent event = new VFileCreateEvent(null, parent, childName, attributes.isDirectory(), attributes, symlinkTarget, true, children);
  myEvents.add(event);
}
 
Example #15
Source File: RangeMarkerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testRangeHighlighterLinesInRangeForLongLinePerformance() throws Exception {
  final int N = 50000;
  Document document = EditorFactory.getInstance().createDocument(StringUtil.repeatSymbol('x', 2 * N));

  final MarkupModelEx markupModel = (MarkupModelEx)DocumentMarkupModel.forDocument(document, ourProject, true);
  for (int i=0; i<N-1;i++) {
    markupModel.addRangeHighlighter(2*i, 2*i+1, 0, null, HighlighterTargetArea.EXACT_RANGE);
  }
  markupModel.addRangeHighlighter(N / 2, N / 2 + 1, 0, null, HighlighterTargetArea.LINES_IN_RANGE);

  PlatformTestUtil.startPerformanceTest("slow highlighters lookup", (int)(N*Math.log(N)/1000), new ThrowableRunnable() {
    @Override
    public void run() {
      List<RangeHighlighterEx> list = new ArrayList<RangeHighlighterEx>();
      CommonProcessors.CollectProcessor<RangeHighlighterEx> coll = new CommonProcessors.CollectProcessor<RangeHighlighterEx>(list);
      for (int i=0; i<N-1;i++) {
        list.clear();
        markupModel.processRangeHighlightersOverlappingWith(2*i, 2*i+1, coll);
        assertEquals(2, list.size());  // 1 line plus one exact range marker
      }
    }
  }).assertTiming();
}
 
Example #16
Source File: TokenSetTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void performance() throws Exception {
  final IElementType[] elementTypes = IElementType.enumerate(CommonProcessors.<IElementType>alwaysTrue());
  final TokenSet set = TokenSet.create();
  final int shift = new Random().nextInt(500000);

  PlatformTestUtil.startPerformanceTest("TokenSet.contains() performance", 25, new ThrowableRunnable() {
    @Override
    public void run() throws Throwable {
      for (int i = 0; i < 1000000; i++) {
        final IElementType next = elementTypes[((i + shift) % elementTypes.length)];
        assertFalse(set.contains(next));
      }
    }
  }).cpuBound().assertTiming();
}
 
Example #17
Source File: AbstractVcs.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public CommittedChangeList loadRevisions(final VirtualFile vf, final VcsRevisionNumber number) {
  final CommittedChangeList[] list = new CommittedChangeList[1];
  final ThrowableRunnable<VcsException> runnable = () -> {
    final Pair<CommittedChangeList, FilePath> pair =
            getCommittedChangesProvider().getOneList(vf, number);
    if (pair != null) {
      list[0] = pair.getFirst();
    }
  };
  return VcsSynchronousProgressWrapper.wrap(runnable, getProject(), "Load revision contents") ? list[0] : null;
}
 
Example #18
Source File: StartedActivated.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void callImpl(final MySection section, final boolean start) throws VcsException {
  final List<ThrowableRunnable<VcsException>> list = new ArrayList<ThrowableRunnable<VcsException>>(2);
  synchronized (myLock) {
    if (start) {
      section.start(list);
    } else {
      section.stop(list);
    }
  }
  for (ThrowableRunnable<VcsException> runnable : list) {
    runnable.run();
  }
}
 
Example #19
Source File: StartedActivated.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected StartedActivated(final Disposable parent) {
  myStart = new MySection(new ThrowableRunnable<VcsException>() {
    public void run() throws VcsException {
      start();
    }
  }, new ThrowableRunnable<VcsException>() {
    public void run() throws VcsException {
      shutdown();
    }
  });
  myActivate = new MySection(new ThrowableRunnable<VcsException>() {
    public void run() throws VcsException {
      activate();
    }
  }, new ThrowableRunnable<VcsException>() {
    public void run() throws VcsException {
      deactivate();
    }
  });
  myStart.setDependent(myActivate);
  myActivate.setMaster(myStart);

  myLock = new Object();

  Disposer.register(parent, new Disposable() {
    public void dispose() {
      try {
        doShutdown();
      }
      catch (Throwable t) {
        LOG.info(t);
      }
    }
  });
}
 
Example #20
Source File: StartedActivated.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void start(final List<ThrowableRunnable<VcsException>> callList) {
  if (myMaster != null) {
    myMaster.start(callList);
  }
  if (! ThreeState.YES.equals(myState)) {
    myState = ThreeState.YES;
    callList.add(myStart);
  }
}
 
Example #21
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static <T extends Throwable> void runWithDisabledPreview(ThrowableRunnable<T> runnable) throws T {
  PREVIEW_IN_TESTS = false;
  try {
    runnable.run();
  }
  finally {
    PREVIEW_IN_TESTS = true;
  }
}
 
Example #22
Source File: VcsLogPersistentIndex.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void catchAndWarn(@Nonnull ThrowableRunnable<IOException> runnable) {
  try {
    runnable.run();
  }
  catch (IOException e) {
    LOG.warn(e);
  }
}
 
Example #23
Source File: WriteCommandAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public <E extends Throwable> void run(@Nonnull final ThrowableRunnable<E> action) throws E {
  new WriteCommandAction(myProject, myCommandName, myGroupId, myFiles) {
    @Override
    protected void run(@Nonnull Result result) throws Throwable {
      action.run();
    }
  }.execute();
}
 
Example #24
Source File: DumbService.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the given runnable with alternative resolve set to true.
 *
 * @see #setAlternativeResolveEnabled(boolean)
 */
public <E extends Throwable> void runWithAlternativeResolveEnabled(@Nonnull ThrowableRunnable<E> runnable) throws E {
  setAlternativeResolveEnabled(true);
  try {
    runnable.run();
  }
  finally {
    setAlternativeResolveEnabled(false);
  }
}
 
Example #25
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static <T extends Throwable> void withIgnoredConflicts(@Nonnull ThrowableRunnable<T> r) throws T {
  try {
    myTestIgnore = true;
    r.run();
  }
  finally {
    myTestIgnore = false;
  }
}
 
Example #26
Source File: AccessRule.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static AsyncResult<Void> writeAsync(@RequiredWriteAction @Nonnull ThrowableRunnable<Throwable> action) {
  return writeAsync(() -> {
    action.run();
    return null;
  });
}
 
Example #27
Source File: AccessRule.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static AsyncResult<Void> readAsync(@RequiredReadAction @Nonnull ThrowableRunnable<Throwable> action) {
  return readAsync(() -> {
    action.run();
    return null;
  });
}
 
Example #28
Source File: WriterService.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
public void write(Project project, Editor editor, String text) {
    if (project == null || editor == null || StringUtils.isBlank(text)) {
        return;
    }
    try {
        WriteCommandAction.writeCommandAction(project).run(
            (ThrowableRunnable<Throwable>)() -> {
                int start = editor.getSelectionModel().getSelectionStart();
                EditorModificationUtil.insertStringAtCaret(editor, text);
                editor.getSelectionModel().setSelection(start, start + text.length());
            });
    } catch (Throwable throwable) {
        LOGGER.error("写入错误", throwable);
    }
}
 
Example #29
Source File: CompilerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T extends Throwable> void runInContext(CompileContext context, String title, ThrowableRunnable<T> action) throws T {
  if (title != null) {
    context.getProgressIndicator().pushState();
    context.getProgressIndicator().setText(title);
  }
  try {
    action.run();
  }
  finally {
    if (title != null) {
      context.getProgressIndicator().popState();
    }
  }
}
 
Example #30
Source File: ArtifactsCompilerInstance.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void processItems(@Nonnull final ArtifactBuildTarget target,
                         @Nonnull final List<GenericCompilerProcessingItem<ArtifactCompilerCompileItem, VirtualFilePersistentState, ArtifactPackagingItemOutputState>> changedItems,
                         @Nonnull List<GenericCompilerCacheState<String, VirtualFilePersistentState, ArtifactPackagingItemOutputState>> obsoleteItems,
                         @Nonnull OutputConsumer<ArtifactCompilerCompileItem> consumer) {

  final THashSet<String> deletedJars = deleteFiles(obsoleteItems, changedItems);

  final Set<String> writtenPaths = createPathsHashSet();
  final Ref<Boolean> built = Ref.create(false);
  final Set<ArtifactCompilerCompileItem> processedItems = new HashSet<ArtifactCompilerCompileItem>();
  CompilerUtil.runInContext(myContext, "Copying files", new ThrowableRunnable<RuntimeException>() {
    @Override
    public void run() throws RuntimeException {
      built.set(doBuild(target.getArtifact(), changedItems, processedItems, writtenPaths, deletedJars));
    }
  });
  if (!built.get()) {
    return;
  }

  myContext.getProgressIndicator().setText(CompilerBundle.message("packaging.compiler.message.updating.caches"));
  myContext.getProgressIndicator().setText2("");
  for (String path : writtenPaths) {
    consumer.addFileToRefresh(new File(path));
  }
  for (ArtifactCompilerCompileItem item : processedItems) {
    consumer.addProcessedItem(item);
  }
  ArtifactsCompiler.addWrittenPaths(myContext, writtenPaths);
  ArtifactsCompiler.addChangedArtifact(myContext, target.getArtifact());
}