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); } }
/** * 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(); }
public static <T> void assertUnorderedCollection( Collection<? extends T> collection, Consumer<T>... checkers) { Assert.assertNotNull(collection); if (collection.size() != checkers.length) { Assert.fail(toString(collection)); } Set<Consumer<T>> checkerSet = new HashSet<Consumer<T>>(Arrays.asList(checkers)); int i = 0; Throwable lastError = null; for (final T actual : collection) { boolean flag = true; for (final Consumer<T> condition : checkerSet) { Throwable error = accepts(condition, actual); if (error == null) { checkerSet.remove(condition); flag = false; break; } else { lastError = error; } } if (flag) { lastError.printStackTrace(); Assert.fail("Incorrect element(" + i + "): " + actual); } i++; } }
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; }
private File getCachedImage(File file, int size) throws IOException { String md5 = DigestUtils.md5Hex(file.getPath()); File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg"); // Is cache missing or obsolete? if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) { InputStream in = null; OutputStream out = null; try { in = getImageInputStream(file); out = new FileOutputStream(cachedImage); BufferedImage image = ImageIO.read(in); if (image == null) { throw new Exception("Unable to decode image."); } image = scale(image, size, size); ImageIO.write(image, "jpeg", out); } catch (Throwable x) { // Delete corrupt (probably empty) thumbnail cache. LOG.warn("Failed to create thumbnail for " + file, x); IOUtils.closeQuietly(out); cachedImage.delete(); throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return cachedImage; }
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; }
/** * Called to process events. Mouse events will be rewritten to indicate the position in the * document clicked, instead of the position of the panel. * * @param event to process. */ protected void processEvent(AWTEvent event) { try { if (event instanceof MouseEvent) { final Point scrollPosition = getScrollPosition(); if (scrollPosition != null) { final MouseEvent mouseEvent = (MouseEvent) event; event = new MouseEvent( (Component) mouseEvent.getSource(), mouseEvent.getID(), mouseEvent.getWhen(), mouseEvent.getModifiers(), mouseEvent.getX() + scrollPosition.x, mouseEvent.getY() + scrollPosition.y, mouseEvent.getClickCount(), mouseEvent.isPopupTrigger()); } } } catch (final Throwable exp) { exp.printStackTrace(DjVuOptions.err); System.gc(); } super.processEvent(event); }
/* (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; }
public void outputError(Throwable exception) { addDebugMessage(exception.toString()); // Copied from throwable.java StackTraceElement[] trace = exception.getStackTrace(); for (StackTraceElement traceElement : trace) addDebugMessage("\tat " + traceElement); }
/** If there's anything to print, initiate a print job */ public synchronized void actionPerformed(ActionEvent ae) { if (isPrintUnderway) { out("ignoring [" + ae.getActionCommand() + "]; print already underway."); return; } LWMap map = VUE.getActiveMap(); Rectangle2D bounds = map.getBounds(); if (bounds.isEmpty()) { out("nothing to print in " + map); return; } boolean viewerPrint = false; if (ae.getActionCommand() != null && ae.getActionCommand().indexOf("Visible") >= 0) viewerPrint = true; // if any tool windows open in W2K/1.4.2 when start this thread, // the print dialog get's obscured! isPrintUnderway = true; setEnabled(false); try { new PrintJob(VUE.getActiveViewer(), viewerPrint).start(); // if (DEBUG.Enabled) // new PrintJob(VUE.getActiveViewer(), viewerPrint).start(); // else // new PrintJob(VUE.getActiveViewer(), viewerPrint).runPrint(); } catch (Throwable t) { out("exception creating or running PrintJob: " + t); t.printStackTrace(); isPrintUnderway = false; setEnabled(true); } }
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()); } }
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(); } }
/** 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(); } }
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()); }
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()); }
protected void assertNoThrowable(final Runnable closure) { String throwableName = null; try { closure.run(); } catch (Throwable thr) { throwableName = thr.getClass().getName(); } assertNull(throwableName); }
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()); } }
/** * Called to process scrollbar events. * * @param event to process. */ public void adjustmentValueChanged(AdjustmentEvent event) { try { final Scrollbar hScroll = getScrollbar(Scrollbar.HORIZONTAL); final Scrollbar vScroll = getScrollbar(Scrollbar.VERTICAL); final Point scrollPosition = getScrollPosition(); setScrollPosition( (hScroll != null) ? hScroll.getValue() : scrollPosition.x, (vScroll != null) ? vScroll.getValue() : scrollPosition.y); } catch (final Throwable exp) { exp.printStackTrace(DjVuOptions.err); System.gc(); } }
public boolean runAutodetection() { try { if (AutoDetectPaths.checkAutoDetectedPaths()) { return true; } init(); getWorker().run(); update(); return foundPaths; } catch (Throwable e) { e.printStackTrace(); return false; } }
void printException(Throwable tr) { CAT.error("exception", tr); // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.p rintStackTrace(pw); // pw.flush(); // sw.flush(); log( getMyLoginId() + " reports exception:\r\n " + tr.getClass().getName() + "\r\n " + tr.getMessage()); // sw.toString()); }
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(); }
/** 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(); } }
/** * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly * duplicates tryMethod in JGEngine. * * @return null means method does not exist or returned null/void */ static Object tryMethod(Object o, String name, Object[] args) { try { Method met = JREEngine.getMethod(o.getClass(), name, args); if (met == null) return null; return met.invoke(o, args); } catch (InvocationTargetException ex) { Throwable ex_t = ex.getTargetException(); ex_t.printStackTrace(); return null; } catch (IllegalAccessException ex) { System.err.println("Unexpected exception:"); ex.printStackTrace(); return null; } }
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. } }
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 } }
private void destroyCommunicator() { if (_communicator == null) { return; } // // Destroy the Ice communicator. // try { _communicator.destroy(); } catch (Throwable ex) { ex.printStackTrace(); } finally { _communicator = null; } }
private String formatXML(String str) { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); // Surround this setting in a try/catch for compatibility with Java 1.4. This setting is // required // for Java 1.5 try { tFactory.setAttribute("indent-number", 2); } catch (IllegalArgumentException e) { // Ignore } Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Transform the requested string into a nice formatted XML string StreamSource source = new StreamSource(new StringReader(str)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return sw.toString(); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("\n** Transformer Factory error"); System.out.println(" " + tce.getMessage()); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser System.out.println("\n** Transformation error"); System.out.println(" " + te.getMessage()); // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } return str; }
/** * {@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(); } }
public static String throwableToString(final Throwable t) { if (t != null) { final Writer exception = new StringWriter(); final PrintWriter printWriter = new PrintWriter(exception); t.printStackTrace(printWriter); return exception.toString(); } return ""; }
@Override protected void handleInitComponentError( final Throwable ex, final boolean fatal, final String componentClassName) { if (PluginManager.isPluginClass(componentClassName)) { LOG.error(ex); PluginId pluginId = PluginManager.getPluginByClassName(componentClassName); @NonNls final String errorMessage = "Plugin " + pluginId.getIdString() + " failed to initialize and will be disabled:\n" + ex.getMessage() + "\nPlease restart " + ApplicationNamesInfo.getInstance().getFullProductName() + "."; PluginManager.disablePlugin(pluginId.getIdString()); if (!myHeadlessMode) { JOptionPane.showMessageDialog(null, errorMessage); } else { //noinspection UseOfSystemOutOrSystemErr System.out.println(errorMessage); System.exit(1); } return; // do not call super } if (fatal) { LOG.error(ex); @NonNls final String errorMessage = "Fatal error initializing class " + componentClassName + ":\n" + ex.toString() + "\nComplete error stacktrace was written to idea.log"; if (!myHeadlessMode) { JOptionPane.showMessageDialog(null, errorMessage); } else { //noinspection UseOfSystemOutOrSystemErr System.out.println(errorMessage); } } super.handleInitComponentError(ex, fatal, componentClassName); }