Java 类com.intellij.util.ExceptionUtil 实例源码

项目:intellij-ce-playground    文件:JavacCompilerTool.java   
@NotNull
@Override
public JavaCompiler createCompiler() throws CannotCreateJavaCompilerException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  if (compiler != null) {
    return compiler;
  }

  String message = "System Java Compiler was not found in classpath";
  // trying to obtain additional diagnostic for the case when compiler.jar is present, but there were problems with compiler class loading:
  try {
    Class.forName("com.sun.tools.javac.api.JavacTool", false, JavacMain.class.getClassLoader());
  }
  catch (Throwable ex) {
    message = message + ":\n" + ExceptionUtil.getThrowableText(ex);
  }
  throw new CannotCreateJavaCompilerException(message);
}
项目:intellij-ce-playground    文件:RunResult.java   
public RunResult<T> run() {
  try {
    myActionRunnable.run(this);
  }
  catch (ProcessCanceledException e) {
    throw e; // this exception may occur from time to time and it shouldn't be caught
  }
  catch (Throwable t) {
    myThrowable = t;
    if (!myActionRunnable.isSilentExecution()) {
      ExceptionUtil.rethrowAllAsUnchecked(t);
    }
  }
  finally {
    myActionRunnable = null;
  }

  return this;
}
项目:intellij-ce-playground    文件:ProjectDataManager.java   
@SuppressWarnings("unchecked")
public <E, I> void removeData(@NotNull Key<E> key,
                              @NotNull Collection<I> toRemove,
                              @NotNull final Collection<DataNode<E>> toIgnore,
                              @NotNull final ProjectData projectData,
                              @NotNull Project project,
                              @NotNull final IdeModifiableModelsProvider modelsProvider,
                              boolean synchronous) {
  try {
    List<ProjectDataService<?, ?>> services = myServices.getValue().get(key);
    for (ProjectDataService service : services) {
      final long removeStartTime = System.currentTimeMillis();
      service.removeData(new Computable.PredefinedValueComputable<Collection>(toRemove), toIgnore, projectData, project, modelsProvider);
      final long removeTimeInMs = System.currentTimeMillis() - removeStartTime;
      LOG.debug(String.format("Service %s removed data in %d ms", service.getClass().getSimpleName(), removeTimeInMs));
    }

    commit(modelsProvider, project, synchronous, "Removed data");
  }
  catch (Throwable t) {
    dispose(modelsProvider, project, synchronous);
    ExceptionUtil.rethrowAllAsUnchecked(t);
  }
}
项目:intellij-ce-playground    文件:Logger.java   
public static void setFactory(Class<? extends Factory> factory) {
  if (isInitialized()) {
    if (factory.isInstance(ourFactory)) {
      return;
    }

    //noinspection UseOfSystemOutOrSystemErr
    System.out.println("Changing log factory\n" + ExceptionUtil.getThrowableText(new Throwable()));
  }

  try {
    Constructor<? extends Factory> constructor = factory.getDeclaredConstructor();
    constructor.setAccessible(true);
    ourFactory = constructor.newInstance();
  }
  catch (Exception e) {
    //noinspection CallToPrintStackTrace
    e.printStackTrace();
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:RunIdeConsoleAction.java   
private static void executeQuery(@NotNull Project project,
                                 @NotNull VirtualFile file,
                                 @NotNull Editor editor,
                                 @NotNull IdeScriptEngine engine) {
  String command = getCommand(editor);
  String profile = getProfile(file);
  RunContentDescriptor descriptor = getConsoleView(project, file);
  ConsoleViewImpl consoleView = (ConsoleViewImpl)descriptor.getExecutionConsole();

  prepareEngine(project, engine, descriptor);
  try {
    //myHistoryController.getModel().addToHistory(command);
    consoleView.print("> " + command, ConsoleViewContentType.USER_INPUT);
    consoleView.print("\n", ConsoleViewContentType.USER_INPUT);
    Object o = engine.eval(profile == null ? command : profile + "\n" + command);
    consoleView.print("=> " + o, ConsoleViewContentType.NORMAL_OUTPUT);
    consoleView.print("\n", ConsoleViewContentType.NORMAL_OUTPUT);
  }
  catch (Throwable e) {
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable ex = ExceptionUtil.getRootCause(e);
    consoleView.print(ex.getClass().getSimpleName() + ": " + ex.getMessage(), ConsoleViewContentType.ERROR_OUTPUT);
    consoleView.print("\n", ConsoleViewContentType.ERROR_OUTPUT);
  }
  selectContent(descriptor);
}
项目:intellij-ce-playground    文件:StubUpdatingIndex.java   
public static String getIndexingStampInfo(VirtualFile file) {
  try {
    DataInputStream stream = INDEXED_STAMP.readAttribute(file);
    if (stream == null) {
      return "no data";
    }

    long stamp = DataInputOutputUtil.readTIME(stream);
    long size = DataInputOutputUtil.readLONG(stream);
    stream.close();
    return "indexed at " + stamp + " with size " + size;
  }
  catch (IOException e) {
    return ExceptionUtil.getThrowableText(e);
  }
}
项目:intellij-ce-playground    文件:CompilerOutputModuleCustomizerTest.java   
public void testCustomizeModule() {
  File rootDir = androidProject.getRootDir();
  IdeaAndroidProject ideaAndroidProject = new IdeaAndroidProject(GradleConstants.SYSTEM_ID, myModule.getName(), rootDir, androidProject,
                                                                 "debug", AndroidProject.ARTIFACT_ANDROID_TEST);
  String compilerOutputPath = "";
  final IdeModifiableModelsProviderImpl modelsProvider = new IdeModifiableModelsProviderImpl(myProject);
  try {
    customizer.customizeModule(myProject, myModule, modelsProvider, ideaAndroidProject);
    CompilerModuleExtension compilerSettings = modelsProvider.getModifiableRootModel(myModule).getModuleExtension(CompilerModuleExtension.class);
    compilerOutputPath = compilerSettings.getCompilerOutputUrl();
    modelsProvider.commit();
  }
  catch (Throwable t) {
    modelsProvider.dispose();
    ExceptionUtil.rethrowAllAsUnchecked(t);
  }

  File classesFolder = ideaAndroidProject.getSelectedVariant().getMainArtifact().getClassesFolder();
  String path = FileUtil.toSystemIndependentName(classesFolder.getPath());
  String expected = VfsUtilCore.pathToUrl(ExternalSystemApiUtil.toCanonicalPath(path));
  assertEquals(expected, compilerOutputPath);
}
项目:intellij-ce-playground    文件:AndroidFacetModuleCustomizerTest.java   
public void testCustomizeModule() {
  File rootDir = myAndroidProject.getRootDir();
  VariantStub selectedVariant = myAndroidProject.getFirstVariant();
  assertNotNull(selectedVariant);
  String selectedVariantName = selectedVariant.getName();
  IdeaAndroidProject project = new IdeaAndroidProject(GradleConstants.SYSTEM_ID, myAndroidProject.getName(), rootDir, myAndroidProject,
                                                      selectedVariantName, AndroidProject.ARTIFACT_ANDROID_TEST);
  final IdeModifiableModelsProviderImpl modelsProvider = new IdeModifiableModelsProviderImpl(myProject);
  try {
    myCustomizer.customizeModule(myProject, myModule, modelsProvider, project);
    modelsProvider.commit();
  }
  catch (Throwable t) {
    modelsProvider.dispose();
    ExceptionUtil.rethrowAllAsUnchecked(t);
  }

  // Verify that AndroidFacet was added and configured.
  AndroidFacet facet = AndroidFacet.getInstance(myModule);
  assertNotNull(facet);
  assertSame(project, facet.getIdeaAndroidProject());

  JpsAndroidModuleProperties facetState = facet.getProperties();
  assertFalse(facetState.ALLOW_USER_CONFIGURATION);
}
项目:intellij-ce-playground    文件:GitHistoryUtilsTest.java   
@Test
public void testAppendableHistory() throws Exception {
  final List<GitFileRevision> revisions = new ArrayList<GitFileRevision>(3);
  Consumer<GitFileRevision> consumer = new Consumer<GitFileRevision>() {
    @Override
    public void consume(GitFileRevision gitFileRevision) {
      revisions.add(gitFileRevision);
    }
  };
  Consumer<VcsException> exceptionConsumer = new Consumer<VcsException>() {
    @Override
    public void consume(VcsException exception) {
      fail("No exception expected " + ExceptionUtil.getThrowableText(exception));
    }
  };
  GitHistoryUtils.history(myProject, toFilePath(bfile), null, consumer, exceptionConsumer);
  assertHistory(revisions);
}
项目:intellij-ce-playground    文件:DslErrorReporterImpl.java   
@Override
public void invokeDslErrorPopup(Throwable e, final Project project, @NotNull VirtualFile vfile) {
  if (!GroovyDslFileIndex.isActivated(vfile)) {
    return;
  }

  final String exceptionText = ExceptionUtil.getThrowableText(e);
  LOG.info(exceptionText);
  GroovyDslFileIndex.disableFile(vfile, DslActivationStatus.Status.ERROR, exceptionText);


  if (!ApplicationManagerEx.getApplicationEx().isInternal() && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(vfile)) {
    return;
  }

  String content = "<p>" + e.getMessage() + "</p><p><a href=\"\">Click here to investigate.</a></p>";
  NOTIFICATION_GROUP.createNotification("DSL script execution error", content, NotificationType.ERROR,
                                        new NotificationListener() {
                                          @Override
                                          public void hyperlinkUpdate(@NotNull Notification notification,
                                                                      @NotNull HyperlinkEvent event) {
                                            InvestigateFix.analyzeStackTrace(project, exceptionText);
                                            notification.expire();
                                          }
                                        }).notify(project);
}
项目:intellij-ce-playground    文件:DesignerEditorPanel.java   
public final void showError(@NotNull String message, @NotNull Throwable e) {
  if (isProjectClosed()) {
    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),
                                       getErrorAttachments(info)));
  }
}
项目:tools-idea    文件:StubUpdatingIndex.java   
public static String getIndexingStampInfo(VirtualFile file) {
  try {
    DataInputStream stream = INDEXED_STAMP.readAttribute(file);
    if (stream == null) {
      return "no data";
    }

    long stamp = stream.readLong();
    long size = stream.readLong();
    stream.close();
    return "indexed at " + stamp + " with size " + size;
  }
  catch (IOException e) {
    return ExceptionUtil.getThrowableText(e);
  }
}
项目:tools-idea    文件:GroovyDslFileIndex.java   
static void invokeDslErrorPopup(Throwable e, final Project project, @NotNull VirtualFile vfile) {
  if (!isActivated(vfile)) {
    return;
  }

  final String exceptionText = ExceptionUtil.getThrowableText(e);
  LOG.info(exceptionText);
  disableFile(vfile, exceptionText);


  if (!ApplicationManagerEx.getApplicationEx().isInternal() && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(vfile)) {
    return;
  }

  String content = "<p>" + e.getMessage() + "</p><p><a href=\"\">Click here to investigate.</a></p>";
  NOTIFICATION_GROUP.createNotification("DSL script execution error", content, NotificationType.ERROR,
                                        new NotificationListener() {
                                          @Override
                                          public void hyperlinkUpdate(@NotNull Notification notification,
                                                                      @NotNull HyperlinkEvent event) {
                                            GroovyDslAnnotator.analyzeStackTrace(project, exceptionText);
                                            notification.expire();
                                          }
                                        }).notify(project);
}
项目:tools-idea    文件:DesignerEditorPanel.java   
public final void showError(@NotNull String message, @NotNull Throwable e) {
  if (isProjectClosed()) {
    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),
                                       AttachmentFactory.createAttachment(myFile)));
  }
}
项目:jediterm    文件:Logger.java   
public static void setFactory(@NotNull Class<? extends Factory> factory) {
  if (isInitialized()) {
    if (factory.isInstance(ourFactory)) {
      return;
    }

    //noinspection UseOfSystemOutOrSystemErr
    System.out.println("Changing log factory\n" + ExceptionUtil.getThrowableText(new Throwable()));
  }

  try {
    Constructor<? extends Factory> constructor = factory.getDeclaredConstructor();
    constructor.setAccessible(true);
    ourFactory = constructor.newInstance();
  }
  catch (Exception e) {
    //noinspection CallToPrintStackTrace
    e.printStackTrace();
    throw new RuntimeException(e);
  }
}
项目:consulo    文件:Logger.java   
public static void setFactory(Class<? extends Factory> factory) {
  if (isInitialized()) {
    if (factory.isInstance(ourFactory)) {
      return;
    }

    //noinspection UseOfSystemOutOrSystemErr
    System.out.println("Changing log factory\n" + ExceptionUtil.getThrowableText(new Throwable()));
  }

  try {
    Constructor<? extends Factory> constructor = factory.getDeclaredConstructor();
    constructor.setAccessible(true);
    ourFactory = constructor.newInstance();
  }
  catch (Exception e) {
    //noinspection CallToPrintStackTrace
    e.printStackTrace();
    throw new RuntimeException(e);
  }
}
项目:consulo    文件:AbstractLayoutCodeProcessor.java   
public FutureTask<Boolean> preprocessFile(@Nonnull PsiFile file, boolean processChangedTextOnly) throws IncorrectOperationException {
  final FutureTask<Boolean> previousTask = getPreviousProcessorTask(file, processChangedTextOnly);
  final FutureTask<Boolean> currentTask = prepareTask(file, processChangedTextOnly);

  return new FutureTask<>(() -> {
    try {
      if (previousTask != null) {
        previousTask.run();
        if (!previousTask.get() || previousTask.isCancelled()) return false;
      }

      ApplicationManager.getApplication().runWriteAction(() -> currentTask.run());

      return currentTask.get() && !currentTask.isCancelled();
    }
    catch (ExecutionException e) {
      ExceptionUtil.rethrowUnchecked(e.getCause());
      throw e;
    }
  });
}
项目:intellij-ce-playground    文件:NotNullVerifyingInstrumenterTest.java   
public void testSkipBridgeMethods() throws Exception {
  final Class<?> testClass = prepareTest();
  try {
    testClass.getMethod("main").invoke(null);
    fail();
  }
  catch (InvocationTargetException e) {
    //noinspection ThrowableResultOfMethodCallIgnored
    assertInstanceOf(e.getCause(), IllegalArgumentException.class);
    String trace = ExceptionUtil.getThrowableText(e.getCause());
    assertEquals("Exception should happen in real, non-bridge method: " + trace,
                 2, StringUtil.getOccurrenceCount(trace, "B.getObject(SkipBridgeMethods"));
  }
}
项目:intellij-ce-playground    文件:IndexNotReadyException.java   
@Override
public String getMessage() {
  String msg = "Please change caller according to " + IndexNotReadyException.class.getName() + " documentation";
  if (myStartTrace != null) {
    msg += "\nIndexing started at: " + ExceptionUtil.getThrowableText(myStartTrace) + "\n-----------------------------\n";
  }
  return msg;
}
项目:intellij-ce-playground    文件:RunResult.java   
@NotNull
public RunResult<T> throwException() throws RuntimeException, Error {
  if (myThrowable != null) {
    ExceptionUtil.rethrowAllAsUnchecked(myThrowable);
  }

  return this;
}
项目:intellij-ce-playground    文件:PsiInvalidElementAccessException.java   
public PsiInvalidElementAccessException(@Nullable PsiElement element, @Nullable String message, @Nullable Throwable cause) {
  super(null, cause);
  myElementReference = new SoftReference<PsiElement>(element);

  if (element == null) {
    myMessage = message;
    myDiagnostic = Attachment.EMPTY_ARRAY;
  }
  else if (element == PsiUtilCore.NULL_PSI_ELEMENT) {
    myMessage = "NULL_PSI_ELEMENT ;" + message;
    myDiagnostic = Attachment.EMPTY_ARRAY;
  }
  else {
    boolean recursiveInvocation = Boolean.TRUE.equals(element.getUserData(REPORTING_EXCEPTION));
    element.putUserData(REPORTING_EXCEPTION, Boolean.TRUE);

    try {
      Object trace = recursiveInvocation ? null : findInvalidationTrace(element.getNode());
      myMessage = getMessageWithReason(element, message, recursiveInvocation, trace);
      if (trace == null) {
        myDiagnostic = Attachment.EMPTY_ARRAY;
      }
      else {
        String diagnostic = trace instanceof Throwable ? ExceptionUtil.getThrowableText((Throwable)trace) : trace.toString();
        myDiagnostic = new Attachment[]{new Attachment("diagnostic.txt", diagnostic)};
      }
    }
    finally {
      element.putUserData(REPORTING_EXCEPTION, null);
    }
  }
}
项目:intellij-ce-playground    文件:RestService.java   
@Override
public final boolean process(@NotNull QueryStringDecoder urlDecoder, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context) throws IOException {
  try {
    if (activateToolBeforeExecution()) {
      IdeFrame frame = IdeFocusManager.getGlobalInstance().getLastFocusedFrame();
      if (frame instanceof Window) {
        ((Window)frame).toFront();
      }
    }

    String error = execute(urlDecoder, request, context);
    if (error != null) {
      Responses.sendStatus(HttpResponseStatus.BAD_REQUEST, context.channel(), error, request);
    }
  }
  catch (Throwable e) {
    HttpResponseStatus status;
    // JsonReader exception
    //noinspection InstanceofCatchParameter
    if (e instanceof MalformedJsonException || (e instanceof IllegalStateException && e.getMessage().startsWith("Expected a "))) {
      LOG.warn(e);
      status = HttpResponseStatus.BAD_REQUEST;
    }
    else {
      LOG.error(e);
      status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    Responses.sendStatus(status, context.channel(), ExceptionUtil.getThrowableText(e), request);
  }
  return true;
}
项目:intellij-ce-playground    文件:ErrorBean.java   
public ErrorBean(Throwable throwable, String lastAction) {
  if (throwable != null) {
    message = throwable.getMessage();
    stackTrace = ExceptionUtil.getThrowableText(throwable);
  }
  this.lastAction = lastAction;
}
项目:intellij-ce-playground    文件:UiInspectorAction.java   
private static void processContainerEvent(ContainerEvent event) {
  Component child = event.getID() == ContainerEvent.COMPONENT_ADDED ? event.getChild() : null;
  if (child instanceof JComponent && !(event.getSource() instanceof CellRendererPane)) {
    String text = ExceptionUtil.getThrowableText(new Throwable());
    int first = text.indexOf("at com.intellij", text.indexOf("at java.awt"));
    int last = text.indexOf("at java.awt.EventQueue");
    if (last == -1) last = text.length();
    String val = last > first && first > 0 ?  text.substring(first, last): null;
    ((JComponent)child).putClientProperty("uiInspector.addedAt", val);
  }
}
项目:intellij-ce-playground    文件:DialogAppender.java   
private static IdeaLoggingEvent extractLoggingEvent(Object message, Throwable throwable) {
  //noinspection ThrowableResultOfMethodCallIgnored
  Throwable rootCause = ExceptionUtil.getRootCause(throwable);
  if (rootCause instanceof LogEventException) {
    return ((LogEventException)rootCause).getLogMessage();
  }

  String strMessage = message == null ? "<null> " : message.toString();
  ExceptionWithAttachments withAttachments = ExceptionUtil.findCause(throwable, ExceptionWithAttachments.class);
  if (withAttachments != null) {
    return LogMessageEx.createEvent(strMessage, ExceptionUtil.getThrowableText(throwable), withAttachments.getAttachments());
  }

  return new IdeaLoggingEvent(strMessage, throwable);
}
项目:intellij-ce-playground    文件:LogMessageEx.java   
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));
}
项目:intellij-ce-playground    文件:LogUtil.java   
public static String getProcessList() {
  try {
    @SuppressWarnings("SpellCheckingInspection") Process process = new ProcessBuilder()
      .command(SystemInfo.isWindows ? new String[]{System.getenv("windir") + "\\system32\\tasklist.exe", "/v"} : new String[]{"ps", "a"})
      .redirectErrorStream(true)
      .start();
    return FileUtil.loadTextAndClose(process.getInputStream());
  }
  catch (IOException e) {
    return ExceptionUtil.getThrowableText(e);
  }
}
项目:intellij-ce-playground    文件:LogUtil.java   
public static String getSystemMemoryInfo() {
  try {
    @SuppressWarnings("SpellCheckingInspection") Process process = new ProcessBuilder()
      .command(new String[]{SystemInfo.isWindows ? "systeminfo" : SystemInfo.isMac ? "vm_stat" : "free"})
      .redirectErrorStream(true)
      .start();
    return FileUtil.loadTextAndClose(process.getInputStream());
  }
  catch (IOException e) {
    return ExceptionUtil.getThrowableText(e);
  }
}
项目:intellij-ce-playground    文件:FrequentEventDetector.java   
public void eventHappened() {
  if (myEventsPosted.incrementAndGet() > myEventCountThreshold) {
    boolean shouldLog = false;

    synchronized (myEventsPosted) {
      if (myEventsPosted.get() > myEventCountThreshold) {
        long timeNow = System.currentTimeMillis();
        shouldLog = timeNow - myStartedCounting < myTimeSpanMs;
        myEventsPosted.set(0);
        myStartedCounting = timeNow;
      }
    }

    if (shouldLog) {
      String trace = ExceptionUtil.getThrowableText(new Throwable());
      boolean logTrace;
      int traceId;
      synchronized (myEventsPosted) {
        Integer existingTraceId = myRecentTraces.get(trace);
        logTrace = existingTraceId == null;
        if (logTrace) {
          myRecentTraces.put(trace, traceId = myLastTraceId.incrementAndGet());
        } else {
          traceId = existingTraceId;
        }
      }

      String message = "Too many events posted, #" + traceId  + (logTrace ? "\n" + trace : "");
      if (myLevel == Level.INFO) {
        LOG.info(message);
      }
      else if (myLevel == Level.WARN) {
        LOG.warn(message);
      }
      else {
        LOG.error(message);
      }
    }
  }
}
项目:intellij-ce-playground    文件:ApplicationUtil.java   
/**
 * Allows to interrupt a process which does not performs checkCancelled() calls by itself.
 * Note that the process may continue to run in background indefinitely - so <b>avoid using this method unless absolutely needed</b>.
 */
public static <T> T runWithCheckCanceled(@NotNull final Callable<T> callable,
                                         @NotNull final ProgressIndicator indicator, @NotNull ExecutorService executorService) throws Exception {
  final Ref<T> result = Ref.create();
  final Ref<Throwable> error = Ref.create();

  Future<?> future = executorService.submit(new Runnable() {
    @Override
    public void run() {
      ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() {
        @Override
        public void run() {
          try {
            result.set(callable.call());
          }
          catch (Throwable t) {
            error.set(t);
          }
        }
      }, indicator);
    }
  });

  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      future.cancel(true);
      throw e;
    }

    try {
      future.get(200, TimeUnit.MILLISECONDS);
      ExceptionUtil.rethrowAll(error.get());
      return result.get();
    }
    catch (TimeoutException ignored) { }
  }
}
项目:intellij-ce-playground    文件:PeriodicalTasksCloser.java   
private void throwCanceledException(final Project project, final Throwable t) {
  synchronized (myLock) {
    // allow NPE & assertion _catch_ only if project is closed and being disposed
    if (project.isOpen()) {
      ExceptionUtil.rethrowAllAsUnchecked(t);
    }
  }
  throw new ProcessCanceledException();
}
项目:intellij-ce-playground    文件:RemoteProcessSupport.java   
private void startProcess(Target target, Parameters configuration, @NotNull Pair<Target, Parameters> key) {
  ProgramRunner runner = new DefaultProgramRunner() {
    @Override
    @NotNull
    public String getRunnerId() {
      return "MyRunner";
    }

    @Override
    public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
      return true;
    }
  };
  Executor executor = DefaultRunExecutor.getRunExecutorInstance();
  ProcessHandler processHandler;
  try {
    RunProfileState state = getRunProfileState(target, configuration, executor);
    ExecutionResult result = state.execute(executor, runner);
    //noinspection ConstantConditions
    processHandler = result.getProcessHandler();
  }
  catch (Exception e) {
    dropProcessInfo(key, e instanceof ExecutionException? e.getMessage() : ExceptionUtil.getUserStackTrace(e, LOG), null);
    return;
  }
  processHandler.addProcessListener(getProcessListener(key));
  processHandler.startNotify();
}
项目:intellij-ce-playground    文件:BuildVariantUpdater.java   
@NotNull
private static Module invokeCustomizers(@NotNull Module module, @NotNull IdeaAndroidProject androidProject) {
  final IdeModifiableModelsProviderImpl modelsProvider = new IdeModifiableModelsProviderImpl(module.getProject());
  try {
    for (ModuleCustomizer<IdeaAndroidProject> customizer : getCustomizers(androidProject.getProjectSystemId())) {
      customizer.customizeModule(module.getProject(), module, modelsProvider, androidProject);
    }
    modelsProvider.commit();
  }
  catch (Throwable t) {
    modelsProvider.dispose();
    ExceptionUtil.rethrowAllAsUnchecked(t);
  }
  return module;
}
项目:intellij-ce-playground    文件:ContentRootModuleCustomizerTest.java   
public void testCustomizeModule() throws Exception {

    final IdeModifiableModelsProviderImpl modelsProvider = new IdeModifiableModelsProviderImpl(myProject);
    try {
      myCustomizer.customizeModule(myProject, myModule, modelsProvider, myIdeaAndroidProject);
      modelsProvider.commit();
    }
    catch (Throwable t) {
      modelsProvider.dispose();
      ExceptionUtil.rethrowAllAsUnchecked(t);
    }

    ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(myModule);
    ContentEntry contentEntry = moduleRootManager.getContentEntries()[0];

    SourceFolder[] sourceFolders = contentEntry.getSourceFolders();
    List<String> sourcePaths = Lists.newArrayListWithExpectedSize(sourceFolders.length);

    for (SourceFolder folder : sourceFolders) {
      if (!folder.isTestSource()) {
        VirtualFile file = folder.getFile();
        assertNotNull(file);
        sourcePaths.add(file.getPath());
      }
    }

    ContentRootSourcePaths expectedPaths = new ContentRootSourcePaths();
    expectedPaths.storeExpectedSourcePaths(myAndroidProject);


    List<String> allExpectedPaths = Lists.newArrayList();
    allExpectedPaths.addAll(expectedPaths.getPaths(ExternalSystemSourceType.SOURCE));
    allExpectedPaths.addAll(expectedPaths.getPaths(ExternalSystemSourceType.SOURCE_GENERATED));
    allExpectedPaths.addAll(expectedPaths.getPaths(ExternalSystemSourceType.RESOURCE));
    sort(allExpectedPaths);

    sort(sourcePaths);

    assertEquals(allExpectedPaths, sourcePaths);
  }
项目:intellij-ce-playground    文件:SceneBuilderEditor.java   
private void showErrorPage(State state, Throwable e) {
  if (e != null) {
    LOG.info(e);
  }

  removeSceneBuilder();

  if (e == null) {
    if (state == State.CREATE_ERROR) {
      myErrorLabel.setHyperlinkText("JavaFX Scene Builder initialize error", "", "");
      myErrorLabel.setIcon(Messages.getErrorIcon());
    }
    else {
      if (state == State.EMPTY_PATH) {
        myErrorLabel.setHyperlinkText("Please configure JavaFX Scene Builder ", "path", "");
      }
      else {
        myErrorLabel.setHyperlinkText("Please reconfigure JavaFX Scene Builder ", "path", "");
      }
      myErrorLabel.setIcon(Messages.getWarningIcon());
    }

    myErrorStack.setText(null);
    myErrorStack.setVisible(false);
  }
  else {
    String message = e.getMessage();
    if (message == null) {
      message = e.getClass().getName();
    }

    myErrorLabel.setHyperlinkText("Error: " + message, "", "");
    myErrorLabel.setIcon(Messages.getErrorIcon());

    myErrorStack.setText(ExceptionUtil.getThrowableText(e));
    myErrorStack.setVisible(true);
  }
  myLayout.show(myPanel, ERROR_CARD);
}
项目:tools-idea    文件:LogMessageEx.java   
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));
}
项目:tools-idea    文件:FrequentEventDetector.java   
public void eventHappened() {
  if (myEventsPosted.incrementAndGet() > myEventCountThreshold) {
    synchronized (myEventsPosted) {
      if (myEventsPosted.get() > myEventCountThreshold) {
        long timeNow = System.currentTimeMillis();
        if (timeNow - myStartedCounting < myTimeSpanMs) {
          LOG.info("Too many events posted\n" + ExceptionUtil.getThrowableText(new Throwable()));
        }
        myEventsPosted.set(0);
        myStartedCounting = timeNow;
      }
    }
  }

}
项目:tools-idea    文件:RemoteProcessSupport.java   
private void startProcess(Target target, Parameters configuration, Pair<Target, Parameters> key) {
  ProgramRunner runner = new DefaultProgramRunner() {
    @Override
    @NotNull
    public String getRunnerId() {
      return "MyRunner";
    }

    @Override
    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, e instanceof ExecutionException? e.getMessage() : ExceptionUtil.getUserStackTrace(e, LOG), processHandler);
    return;
  }
  processHandler.addProcessListener(getProcessListener(key));
  processHandler.startNotify();
}
项目:consulo    文件:VfsTestUtil.java   
public static void deleteFile(VirtualFile virtualFile) {
  Ref<Exception> exceptionRef = Ref.create();
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    try {
      WriteAction.run(() -> virtualFile.delete(null));
    }
    catch (IOException e) {
      exceptionRef.set(e);
    }
  });

  ExceptionUtil.rethrowAllAsUnchecked(exceptionRef.get());
}
项目:consulo    文件:TreeState.java   
@Override
public String toString() {
  Element st = new Element("TreeState");
  String content;
  try {
    writeExternal(st);
    content = JDOMUtil.writeChildren(st, "\n");
  }
  catch (IOException e) {
    content = ExceptionUtil.getThrowableText(e);
  }
  return "TreeState(" + myScrollToSelection + ")\n" + content;
}