/* (non-Javadoc)
     * @see org.jdesktop.swingworker.SwingWorker#doInBackground()
     */
    @Override
    protected Void doInBackground() throws Exception {

      if (errorInfo != null) {
        Throwable t = errorInfo.getErrorException();
        String osMessage =
            "An error occurred on "
                + System.getProperty("os.name")
                + " version "
                + System.getProperty("os.version");
        StringBuffer message = new StringBuffer();
        message.append("System Info : ").append(osMessage).append(NEW_LINE_CHAR);
        message.append("Message : ").append(t.toString()).append(NEW_LINE_CHAR);
        message.append("Level : ").append(errorInfo.getErrorLevel()).append(NEW_LINE_CHAR);
        message.append("Stack Trace : ").append(NEW_LINE_CHAR);
        message.append(stackTraceToString(t));

        // copy error message to system clipboard
        StringSelection stringSelection = new StringSelection(message.toString());
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        // open errorReportingURL
        OpenBrowserAction openBrowserAction = new OpenBrowserAction(errorReportingURL);
        openBrowserAction.actionPerformed(null);
      }

      return null;
    }
예제 #2
0
 public void actionPerformed(ActionEvent e) {
   BasePanel panel = frame.basePanel();
   if (panel == null) return;
   TableColumnModel colMod = panel.mainTable.getColumnModel();
   colSetup.setValueAt("" + colMod.getColumn(0).getWidth(), 0, 1);
   for (int i = 1; i < colMod.getColumnCount(); i++) {
     try {
       String name = panel.mainTable.getColumnName(i).toLowerCase();
       int width = colMod.getColumn(i).getWidth();
       // Util.pr(":"+((String)colSetup.getValueAt(i-1, 0)).toLowerCase());
       // Util.pr("-"+name);
       if ((i <= tableRows.size())
           && (((String) colSetup.getValueAt(i, 0)).toLowerCase()).equals(name))
         colSetup.setValueAt("" + width, i, 1);
       else { // Doesn't match; search for a matching col in our table
         for (int j = 0; j < colSetup.getRowCount(); j++) {
           if ((j < tableRows.size())
               && (((String) colSetup.getValueAt(j, 0)).toLowerCase()).equals(name)) {
             colSetup.setValueAt("" + width, j, 1);
             break;
           }
         }
       }
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     colSetup.revalidate();
     colSetup.repaint();
   }
 }
 @Override
 public synchronized void write(byte[] ba, int str, int len) {
   try {
     curLength += len;
     if (bytesEndWith(ba, str, len, LINE_SEP)) {
       lineLengths.addLast(new Integer(curLength));
       curLength = 0;
       if (lineLengths.size() > maxLines) {
         textArea.replaceRange(null, 0, lineLengths.removeFirst().intValue());
       }
     }
     for (int xa = 0; xa < 10; xa++) {
       try {
         textArea.append(new String(ba, str, len));
         break;
       } catch (
           Throwable
               thr) { // sometimes throws a java.lang.Error: Interrupted attempt to aquire write
                      // lock
         if (xa == 9) {
           thr.printStackTrace();
         }
       }
     }
     textArea.setCaretPosition(textArea.getText().length());
   } catch (Throwable thr) {
     CharArrayWriter caw = new CharArrayWriter();
     thr.printStackTrace(new PrintWriter(caw, true));
     textArea.append(System.getProperty("line.separator", "\n"));
     textArea.append(caw.toString());
   }
 }
    public void actionPerformed(ActionEvent e) {
      try {
        MockResult mockResult = mockResponse.getMockResult();
        mockResponse.evaluateScript(mockResult == null ? null : mockResult.getMockRequest());

        StringToStringMap values = null;
        if (mockResponse.getMockResult() != null) {
          values = mockResponse.getMockResult().getMockRequest().getContext().toStringToStringMap();
        }

        if (values == null || values.isEmpty()) {
          UISupport.showInfoMessage("No values were returned");
        } else {
          String msg = "<html><body>Returned values:<br>";

          for (String name : values.keySet()) {
            msg += XmlUtils.entitize(name) + " : " + XmlUtils.entitize(values.get(name)) + "<br>";
          }

          msg += "</body></html>";

          UISupport.showExtendedInfo(
              "Result", "Result of MockResponse Script", msg, new Dimension(500, 400));
        }
      } catch (Throwable e1) {
        responseScriptEditor.selectError(e1.getMessage());
        UISupport.showErrorMessage(e1.toString());
      }
    }
  public final void showError(@NotNull String message, @NotNull Throwable e) {
    if (getProject().isDisposed()) {
      return;
    }

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

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

    if (info.myShowMessage) {
      showErrorPage(info);
    }
    if (info.myShowLog) {
      LOG.error(
          LogMessageEx.createEvent(
              info.myDisplayMessage,
              info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable),
              new Attachment(myFile)));
    } else {
      LOG.info(info.myDisplayMessage + "\n" + info.myMessage, info.myThrowable);
    }
  }
예제 #6
0
 private void logTrace(StringBuilder builder, Throwable e) {
   Throwable parent = e;
   String indent = "    ";
   while (parent != null) {
     if (parent == e) {
       builder.append(indent).append("Trace:").append("\n");
     } else {
       builder
           .append(indent)
           .append("Caused By: (")
           .append(parent.getClass().getSimpleName())
           .append(")")
           .append("\n");
       builder
           .append(indent)
           .append("    ")
           .append("[")
           .append(parent.getMessage())
           .append("]")
           .append("\n");
     }
     for (StackTraceElement ele : e.getStackTrace()) {
       builder.append(indent).append("    ").append(ele.toString()).append("\n");
     }
     indent += "    ";
     parent = parent.getCause();
   }
 }
  /**
   * Clear the results and display notice to say an error occurred.
   *
   * @param error the error that occurred.
   */
  public void displayErrorResult(final Throwable error) {
    // match some friendly error messages.
    String errorText = null;
    if (error.getCause() != null && error.getCause() instanceof CheckstyleException) {

      for (final Pattern errorPattern : CHECKSTYLE_ERROR_PATTERNS.keySet()) {
        final Matcher errorMatcher = errorPattern.matcher(error.getCause().getMessage());
        if (errorMatcher.find()) {
          final Object[] args = new Object[errorMatcher.groupCount()];

          for (int i = 0; i < errorMatcher.groupCount(); ++i) {
            args[i] = errorMatcher.group(i + 1);
          }

          errorText = CheckStyleBundle.message(CHECKSTYLE_ERROR_PATTERNS.get(errorPattern), args);
        }
      }
    }

    if (errorText == null) {
      errorText = CheckStyleBundle.message("plugin.results.error");
    }

    treeModel.clear();
    treeModel.setRootText(errorText);

    clearProgress();
  }
 private XmlUIElement getXmlUIElementFor(String typeArg) {
   if (typeToClassMappingProp == null) {
     setUpMappingsHM();
   }
   String clsName = (String) typeToClassMappingProp.get(typeArg);
   if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) {
     try {
       Class cls = Class.forName(clsName);
       return (XmlUIElement) cls.newInstance();
     } catch (Throwable th) {
       typeToClassMappingProp.put(typeArg, "*EXCEPTION*");
       showErrorMessage(
           MessageFormat.format(
               ProvClientUtils.getString(
                   "{0} occurred when trying to get the XmlUIElement for type : {1}"),
               new Object[] {th.getClass().getName(), typeArg}));
       th.printStackTrace();
       return null;
     }
   } else if (clsName == null) {
     typeToClassMappingProp.put(typeArg, "*NOTFOUND*");
     showErrorMessage(
         MessageFormat.format(
             ProvClientUtils.getString(
                 "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"),
             new Object[] {typeArg}));
   }
   return null;
 }
  private boolean loadWebPage(final JWebBrowser webBrowser) {
    try {
      final String language = Locale.getDefault().getLanguage();
      File html =
          Externalization.extractFile(
              "slash/navigation/converter/gui/mapview/routeconverter.html",
              language,
              new TokenResolver() {
                public String resolveToken(String tokenName) {
                  if (tokenName.equals("locale")) return language;
                  if (tokenName.equals("percent")) return Platform.isWindows() ? "99" : "100";
                  if (tokenName.equals("mapserver"))
                    return preferences.get(MAP_SERVER_PREFERENCE, "maps.google.com");
                  return tokenName;
                }
              });
      if (html == null) throw new IllegalArgumentException("Cannot extract routeconverter.html");
      Externalization.extractFile("slash/navigation/converter/gui/mapview/contextmenucontrol.js");

      final String url = html.toURI().toURL().toExternalForm();
      webBrowser.runInSequence(
          new Runnable() {
            public void run() {
              webBrowser.navigate(url);
            }
          });
      log.fine(System.currentTimeMillis() + " loadWebPage thread " + Thread.currentThread());
    } catch (Throwable t) {
      log.severe("Cannot create WebBrowser: " + t.getMessage());
      setInitializationCause(t);
      return false;
    }
    return true;
  }
 public void actionPerformed(ActionEvent e) {
   try {
     String scannedDestination = ((JTextField) e.getSource()).getText().toUpperCase();
     validateDestinationScan(scannedDestination);
     DefaultListModel listModel = (DefaultListModel) destinationsList.getModel();
     int lastPosition = listModel.getSize();
     int seedsCount = 0;
     // todo: do we have to worry about more trays than required..?
     for (int i = 0; i < seedPlates.length; i++) {
       if (seedPlates[i].getSeedPlateBarcode() != null
           && SCANNED.equals(seedPlates[i].getStatus())
           && !isContainedInList(seedPlates[i].getSeedPlateBarcode(), failedPlatesList)) {
         seedsCount++;
       }
     }
     if (lastPosition >= seedsCount) {
       throw new ChippingManagerException(DESTINATIONS_LIMIT_EXCEEDED);
     }
     addDestination(scannedDestination);
   } catch (Throwable cmException) {
     logger.error("Unable to scan destination ", cmException);
     JOptionPane.showMessageDialog(
         new JFrame(),
         cmException.getMessage(),
         TITLE_CHIPPING_MANAGER,
         JOptionPane.WARNING_MESSAGE);
   }
   scanDestination.setText(BLANK);
 }
  public static void processException(Throwable t) {
    StartupAbortedException se = null;

    if (t instanceof StartupAbortedException) {
      se = (StartupAbortedException) t;
    } else if (t.getCause() instanceof StartupAbortedException) {
      se = (StartupAbortedException) t.getCause();
    } else if (!IdeaApplication.isLoaded()) {
      se = new StartupAbortedException(t);
    }

    if (se != null) {
      if (se.logError()) {
        try {
          if (Logger.isInitialized() && !(t instanceof ProcessCanceledException)) {
            getLogger().error(t);
          }
        } catch (Throwable ignore) {
        }

        Main.showMessage("Start Failed", t);
      }

      System.exit(se.exitCode());
    }

    if (!(t instanceof ProcessCanceledException)) {
      getLogger().error(t);
    }
  }
예제 #12
0
  public void outputError(Throwable exception) {
    addDebugMessage(exception.toString());

    // Copied from throwable.java
    StackTraceElement[] trace = exception.getStackTrace();
    for (StackTraceElement traceElement : trace) addDebugMessage("\tat " + traceElement);
  }
  /** Example panel. Animate an example file (E short) and play a tone (D long). */
  public static void main(String[] args) {
    try {
      JFrame f = new JFrame(AnimationPanel.class.getName());
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      AnimationRenderer ani = new AnimationRenderer();

      final AnimationPanel view = new AnimationPanel(ani);

      f.getContentPane().add(view, BorderLayout.CENTER);
      f.pack();
      f.setLocationRelativeTo(null);
      f.setVisible(true);

      File file = new File("datafiles/examples/vis/es_.txt");

      final AnimationSequence animation = AnimationParser.parseFile(file);

      String filename =
          NotesEnum.D.toString().toLowerCase() + "_" + DurationEnum.LONG.codeString() + ".wav";
      // System.out.printf("sound clip filename = %s\n", filename);

      File dir = new File("datafiles/examples/aud");

      final Playable audio = SoundClip.findPlayable(filename, dir, false);

      Runnable r =
          new Runnable() {
            @Override
            public void run() {
              audio.play();
            }
          };

      long currentTime = System.nanoTime();
      ani.setAnimationSource(
          new AnimationSource() {
            public AnimationSequence getAnimationSequence() {
              return animation;
            }

            public int getNumPoints() {
              return 5;
            }

            public float getDiskRadius() {
              return 0.3f;
            }

            public boolean isConnected() {
              return true;
            }
          });

      ani.setNanoStartTime(currentTime);
      SwingUtilities.invokeLater(r);
    } catch (Throwable ex) {
      ex.printStackTrace();
    }
  }
 @Override
 public void processPacket(Packet packet) {
   try {
     doProcessPacket(packet);
   } catch (Throwable e) {
     LOG.error(e.getMessage(), e);
   }
 }
예제 #15
0
 private void populateException(Throwable e) {
   StringBuilder builder = new StringBuilder();
   builder.append("Stack Trace:").append("\n");
   builder.append("    Exception: ").append(e.getClass().getSimpleName()).append("\n");
   builder.append("    Message: ").append(e.getMessage()).append("\n");
   logTrace(builder, e);
   errorArea.setText(builder.toString());
 }
예제 #16
0
 private void handleException(final Throwable ex) {
   // Ignore CommunicatorDestroyedException which could occur on
   // shutdown.
   if (ex instanceof com.zeroc.Ice.CommunicatorDestroyedException) {
     return;
   }
   ex.printStackTrace();
   _status.setText(ex.getClass().getName());
 }
  /** Invoked when an action occurs. */
  public static BoxItem createNewElement(String className, int posX, int posY) {
    BoxItem ret = null;
    Element elem = null;
    try {
      if (debug) System.out.println("Creating new element '" + className + "'");
      elem = Element.newInstance(className);

      if (elem == null) {
        if (debug) System.out.println("Element '" + className + "' not found");
        return null;
      }

      ret = elem.getDesignerBox();
      ret.setBounds(
          (posX / DesignEventHandler.ELEM_STEP) * DesignEventHandler.ELEM_STEP,
          (posY / DesignEventHandler.ELEM_STEP) * DesignEventHandler.ELEM_STEP,
          ConfigurableSystemSettings.getDesignerElementWidth(),
          ConfigurableSystemSettings.getDesignerElementHeight());
      Main.app.designFrame.addElement(ret);
      Item.highlighted.clear();
      Item.highlighted.add(ret);
      Main.app.processor.add(elem);
      // elem.setActive(false);
      Main.app.designFrame.panel.repaint();

      if (elem instanceof Display) {
        Chart chart = ((Display) elem).newChart();
        ((Display) elem).setChart(chart);
        chart.setAtTopLayer();
        // System.out.println("c1 " + chart.getBounds());
        Main.app.runtimeFrame.addChart(chart);
        // Main.app.runtimeFrame.show();
        Main.app.runtimeFrame.setVisible();
        // Main.app.runtimeFrame.repaint();

        // Change runtime to edit mode if not now
        if (!Main.app.runtimeFrame.framedCharts) {
          Main.app.runtimeFrame.framedCharts = true;
          try {
            Main.app.runtimeFrame.reload();
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      }
      elem.reinit();
    } catch (Exception e) {
      if (elem != null) elem.disactivate(e);
      System.out.println("New element error: " + e);
      // e.printStackTrace();
    } catch (Throwable e) {
      System.out.println("Critical error occurred while creating new element: " + e);
      e.printStackTrace();
    }

    return ret;
  }
예제 #18
0
파일: Main.java 프로젝트: kdunzin/ipscan
  /**
   * The launching point
   *
   * <p>In development, pass the following on the JVM command line:
   * <tt>-Djava.util.logging.config.file=config/logging.properties</tt>
   *
   * <p>On Mac, add the following (otherwise SWT won't work): <tt>-XstartOnFirstThread</tt>
   */
  public static void main(String... args) {
    long startTime = System.currentTimeMillis();

    initSystemProperties();
    Display display;

    try {
      // this defines the Window class and app name on the Mac
      Display.setAppName(Version.NAME);
      display = Display.getDefault();
      LOG.finer("SWT initialized after " + (System.currentTimeMillis() - startTime));
    } catch (UnsatisfiedLinkError e) {
      JOptionPane.showMessageDialog(
          null,
          "Failed to load native code. Probably you are using a binary built for wrong OS or CPU - try downloading both 32-bit and 64-bit binaries");
      return;
    }

    // initialize Labels instance
    Labels.initialize(Locale.getDefault());
    // initialize Config instance
    Config globalConfig = Config.getConfig();
    LOG.finer("Labels and Config initialized after " + (System.currentTimeMillis() - startTime));

    ComponentRegistry componentRegistry = new ComponentRegistry();
    LOG.finer("ComponentRegistry initialized after " + (System.currentTimeMillis() - startTime));

    processCommandLine(args, componentRegistry);

    // create the main window using dependency injection
    MainWindow mainWindow = componentRegistry.getMainWindow();
    LOG.fine("Startup time: " + (System.currentTimeMillis() - startTime));

    while (!mainWindow.isDisposed()) {
      try {
        if (!display.readAndDispatch()) display.sleep();
      } catch (Throwable e) {
        if (e instanceof SWTException && e.getCause() != null) e = e.getCause();

        // display a nice error message
        String localizedMessage = getLocalizedMessage(e);
        Shell parent = display.getActiveShell();
        showMessage(
            parent != null ? parent : mainWindow.getShell(),
            e instanceof UserErrorException ? SWT.ICON_WARNING : SWT.ICON_ERROR,
            Labels.getLabel(e instanceof UserErrorException ? "text.userError" : "text.error"),
            localizedMessage);
      }
    }

    // save config on exit
    globalConfig.store();

    // dispose the native objects
    display.dispose();
  }
예제 #19
0
 /** If the exception is wrapped, unwrap it. */
 public static Throwable getActualException(Throwable e) {
   if (e instanceof ExecutionException) e = e.getCause();
   if (e instanceof MBeanException
       || e instanceof RuntimeMBeanException
       || e instanceof RuntimeOperationsException
       || e instanceof ReflectionException) {
     Throwable t = e.getCause();
     if (t != null) return t;
   }
   return e;
 }
예제 #20
0
 public void updateUI() {
   if (getUI() == null || !(getUI() instanceof WebMenuBarUI)) {
     try {
       setUI((WebMenuBarUI) ReflectUtils.createInstance(WebLookAndFeel.menuBarUI));
     } catch (Throwable e) {
       e.printStackTrace();
       setUI(new WebMenuBarUI());
     }
   } else {
     setUI(getUI());
   }
 }
예제 #21
0
 /** PUBLIC: Open a browser on the profiles. */
 public static void browseProfiles(List<Profile> profiles) {
   try {
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
     ProfileBrowser aProfileBrowserFrame;
     aProfileBrowserFrame = new ProfileBrowser();
     aProfileBrowserFrame.setVisible(true);
     aProfileBrowserFrame.setProfiles(profiles);
   } catch (Throwable exception) {
     System.err.println("Exception occurred in main() of javax.swing.JPanel");
     exception.printStackTrace(System.out);
   }
 }
예제 #22
0
  public static String toMessage(Throwable t) {
    String message;
    if (t.getLocalizedMessage() == null) {
      message = "No description was provided";
    } else if (t.getLocalizedMessage().toLowerCase().indexOf("side location conflict") > -1) {
      message = t.getLocalizedMessage() + " -- Check for invalid geometries.";
    } else {
      message = t.getLocalizedMessage();
    }

    return message + " (" + StringUtil.toFriendlyName(t.getClass().getName()) + ")";
  }
 public void actionPerformed(ActionEvent e) {
   try {
     validateUnloadPlatesDialog();
     unloadPlates();
   } catch (Throwable cmException) {
     logger.error("error to unload to multiple destinations", cmException);
     JOptionPane.showMessageDialog(
         new JFrame(),
         cmException.getMessage(),
         TITLE_CHIPPING_MANAGER,
         JOptionPane.WARNING_MESSAGE);
   }
 }
예제 #24
0
 public boolean runAutodetection() {
   try {
     if (AutoDetectPaths.checkAutoDetectedPaths()) {
       return true;
     }
     init();
     getWorker().run();
     update();
     return foundPaths;
   } catch (Throwable e) {
     e.printStackTrace();
     return false;
   }
 }
예제 #25
0
 private String generateExceptionReport() {
   StringBuilder builder = new StringBuilder("Spoutcraft Launcher Error Report:\n");
   builder.append("( Please submit this report to http://spout.in/issues )\n");
   builder.append("    Launcher Build: ").append(Settings.getLauncherBuild()).append("\n");
   builder
       .append("----------------------------------------------------------------------")
       .append("\n");
   builder.append("Stack Trace:").append("\n");
   builder.append("    Exception: ").append(cause.getClass().getSimpleName()).append("\n");
   builder.append("    Message: ").append(cause.getMessage()).append("\n");
   logTrace(builder, cause);
   builder
       .append("----------------------------------------------------------------------")
       .append("\n");
   builder.append("System Information:\n");
   builder.append("    Operating System: ").append(System.getProperty("os.name")).append("\n");
   builder
       .append("    Operating System Version: ")
       .append(System.getProperty("os.version"))
       .append("\n");
   builder
       .append("    Operating System Architecture: ")
       .append(System.getProperty("os.arch"))
       .append("\n");
   builder
       .append("    Java version: ")
       .append(System.getProperty("java.version"))
       .append(" ")
       .append(System.getProperty("sun.arch.data.model", "32"))
       .append(" bit")
       .append("\n");
   builder
       .append("    Total Memory: ")
       .append(Runtime.getRuntime().totalMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    Max Memory: ")
       .append(Runtime.getRuntime().maxMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    Memory Free: ")
       .append(Runtime.getRuntime().freeMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    CPU Cores: ")
       .append(Runtime.getRuntime().availableProcessors())
       .append("\n");
   return builder.toString();
 }
예제 #26
0
  /** Do screen capture and save it as image */
  private static void captureScreenAndSave() {

    try {
      Robot robot = new Robot();
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
      System.out.println("About to screen capture - " + rectangle);
      java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle);
      javax.imageio.ImageIO.write(image, "jpg", new java.io.File("ScreenImage.jpg"));
      robot.delay(3000);
    } catch (Throwable t) {
      System.out.println("WARNING: Exception thrown while screen capture!");
      t.printStackTrace();
    }
  }
예제 #27
0
 public void run() {
   try {
     while (true) {
       long ut = System.currentTimeMillis();
       m.step();
       ut = System.currentTimeMillis() - ut; // used time
       long sleepTime = 25 - ut;
       if (sleepTime > 1) {
         Thread.sleep(sleepTime);
       }
     }
   } catch (Throwable t) {
     t.printStackTrace();
     System.exit(0); // not a perfect solution
   }
 }
예제 #28
0
  private void destroyCommunicator() {
    if (_communicator == null) {
      return;
    }

    //
    // Destroy the Ice communicator.
    //
    try {
      _communicator.destroy();
    } catch (Throwable ex) {
      ex.printStackTrace();
    } finally {
      _communicator = null;
    }
  }
예제 #29
0
    private static void createBrokenMarkerFile(@Nullable Throwable reason) {
      final File brokenMarker = getCorruptionMarkerFile();

      try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          new Exception().printStackTrace(stream);
          if (reason != null) {
            stream.print("\nReason:\n");
            reason.printStackTrace(stream);
          }
        } finally {
          stream.close();
        }
        LOG.info("Creating VFS corruption marker; Trace=\n" + out.toString());

        final FileWriter writer = new FileWriter(brokenMarker);
        try {
          writer.write(
              "These files are corrupted and must be rebuilt from the scratch on next startup");
        } finally {
          writer.close();
        }
      } catch (IOException e) {
        // No luck.
      }
    }
예제 #30
0
 /**
  * {@link RemoteUtil#unwrap(Throwable) unwraps} given exception if possible and builds error
  * message for it.
  *
  * @param e exception to process
  * @return error message for the given exception
  */
 @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "IOResourceOpenedButNotSafelyClosed"})
 @NotNull
 public static String buildErrorMessage(@NotNull Throwable e) {
   Throwable unwrapped = RemoteUtil.unwrap(e);
   String reason = unwrapped.getLocalizedMessage();
   if (!StringUtil.isEmpty(reason)) {
     return reason;
   } else if (unwrapped.getClass() == GradleApiException.class) {
     return String.format(
         "gradle api threw an exception: %s",
         ((GradleApiException) unwrapped).getOriginalReason());
   } else {
     StringWriter writer = new StringWriter();
     unwrapped.printStackTrace(new PrintWriter(writer));
     return writer.toString();
   }
 }