You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ErrorManager.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*
  2. * Copyright (c) 2006-2013 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.logger;
  23. import com.dmdirc.config.ConfigManager;
  24. import com.dmdirc.config.IdentityManager;
  25. import com.dmdirc.interfaces.ConfigChangeListener;
  26. import com.dmdirc.interfaces.IdentityController;
  27. import com.dmdirc.ui.FatalErrorDialog;
  28. import com.dmdirc.util.collections.ListenerList;
  29. import java.awt.GraphicsEnvironment;
  30. import java.util.Date;
  31. import java.util.LinkedList;
  32. import java.util.List;
  33. import java.util.concurrent.BlockingQueue;
  34. import java.util.concurrent.LinkedBlockingQueue;
  35. import java.util.concurrent.atomic.AtomicLong;
  36. /**
  37. * Error manager.
  38. */
  39. public class ErrorManager implements ConfigChangeListener {
  40. /** Previously instantiated instance of ErrorManager. */
  41. private static ErrorManager me;
  42. /** A list of exceptions which we don't consider bugs and thus don't report. */
  43. private static final Class<?>[] BANNED_EXCEPTIONS = new Class<?>[]{
  44. NoSuchMethodError.class, NoClassDefFoundError.class,
  45. UnsatisfiedLinkError.class, AbstractMethodError.class,
  46. IllegalAccessError.class, OutOfMemoryError.class,
  47. NoSuchFieldError.class,
  48. };
  49. /** Whether or not to send error reports. */
  50. private boolean sendReports;
  51. /** Whether or not to log error reports. */
  52. private boolean logReports;
  53. /** Queue of errors to be reported. */
  54. private final BlockingQueue<ProgramError> reportQueue = new LinkedBlockingQueue<>();
  55. /** Thread used for sending errors. */
  56. private volatile Thread reportThread;
  57. /** Error list. */
  58. private final List<ProgramError> errors;
  59. /** Listener list. */
  60. private final ListenerList errorListeners = new ListenerList();
  61. /** Next error ID. */
  62. private final AtomicLong nextErrorID;
  63. /** Creates a new instance of ErrorListDialog. */
  64. public ErrorManager() {
  65. errors = new LinkedList<>();
  66. nextErrorID = new AtomicLong();
  67. }
  68. /**
  69. * Initialiases the error manager.
  70. *
  71. * @param controller The controller to use to read/write settings.
  72. */
  73. public void initialise(final IdentityController controller) {
  74. final ConfigManager config = controller.getGlobalConfiguration();
  75. config.addChangeListener("general", "logerrors", this);
  76. config.addChangeListener("general", "submitErrors", this);
  77. config.addChangeListener("temp", "noerrorreporting", this);
  78. updateSettings();
  79. }
  80. /**
  81. * Returns the instance of ErrorManager.
  82. *
  83. * @return Instance of ErrorManager
  84. */
  85. public static synchronized ErrorManager getErrorManager() {
  86. if (me == null) {
  87. me = new ErrorManager();
  88. me.initialise(IdentityManager.getIdentityManager());
  89. }
  90. return me;
  91. }
  92. /**
  93. * Sets the singleton instance of the error manager.
  94. *
  95. * @param errorManager The error manager to use.
  96. */
  97. public static void setErrorManager(final ErrorManager errorManager) {
  98. me = errorManager;
  99. }
  100. /**
  101. * Adds a new error to the manager with the specified details. It is
  102. * assumed that errors without exceptions or details are not application
  103. * errors.
  104. *
  105. * @param level The severity of the error
  106. * @param message The error message
  107. * @since 0.6.3m1
  108. */
  109. protected void addError(final ErrorLevel level, final String message) {
  110. addError(level, message, new String[0], false);
  111. }
  112. /**
  113. * Adds a new error to the manager with the specified details.
  114. *
  115. * @param level The severity of the error
  116. * @param message The error message
  117. * @param exception The exception that caused this error
  118. * @param appError Whether or not this is an application error
  119. * @since 0.6.3m1
  120. */
  121. protected void addError(final ErrorLevel level, final String message,
  122. final Throwable exception, final boolean appError) {
  123. addError(level, message, getTrace(exception), appError, isValidError(exception));
  124. }
  125. /**
  126. * Adds a new error to the manager with the specified details.
  127. *
  128. * @param level The severity of the error
  129. * @param message The error message
  130. * @param details The details of the exception
  131. * @param appError Whether or not this is an application error
  132. * @since 0.6.3m1
  133. */
  134. protected void addError(final ErrorLevel level, final String message,
  135. final String[] details, final boolean appError) {
  136. addError(level, message, details, appError, true);
  137. }
  138. /**
  139. * Adds a new error to the manager with the specified details.
  140. *
  141. * @param level The severity of the error
  142. * @param message The error message
  143. * @param details The details of the exception
  144. * @param appError Whether or not this is an application error
  145. * @param canReport Whether or not this error can be reported
  146. * @since 0.6.3m1
  147. */
  148. protected void addError(final ErrorLevel level, final String message,
  149. final String[] details, final boolean appError, final boolean canReport) {
  150. final ProgramError error = getError(level, message, details, appError);
  151. final boolean dupe = addError(error);
  152. if (level.equals(ErrorLevel.FATAL)) {
  153. if (dupe) {
  154. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  155. error.setFixedStatus(ErrorFixedStatus.DUPLICATE);
  156. }
  157. } else if (!canReport || (appError && !error.isValidSource())) {
  158. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  159. error.setFixedStatus(ErrorFixedStatus.INVALID);
  160. } else if (!appError) {
  161. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  162. error.setFixedStatus(ErrorFixedStatus.UNREPORTED);
  163. } else if (dupe) {
  164. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  165. error.setFixedStatus(ErrorFixedStatus.DUPLICATE);
  166. } else if (sendReports) {
  167. sendError(error);
  168. }
  169. if (logReports) {
  170. error.save();
  171. }
  172. if (!dupe) {
  173. if (level == ErrorLevel.FATAL) {
  174. fireFatalError(error);
  175. } else {
  176. fireErrorAdded(error);
  177. }
  178. }
  179. }
  180. /**
  181. * Adds the specified error to the list of known errors and determines if
  182. * it was previously added.
  183. *
  184. * @param error The error to be added
  185. * @return True if a duplicate error has already been registered, false
  186. * otherwise
  187. */
  188. protected boolean addError(final ProgramError error) {
  189. int index;
  190. synchronized (errors) {
  191. index = errors.indexOf(error);
  192. if (index == -1) {
  193. errors.add(error);
  194. } else {
  195. errors.get(index).updateLastDate();
  196. }
  197. }
  198. return index > -1;
  199. }
  200. /**
  201. * Retrieves a {@link ProgramError} that represents the specified details.
  202. *
  203. * @param level The severity of the error
  204. * @param message The error message
  205. * @param details The details of the exception
  206. * @param appError Whether or not this is an application error
  207. * @since 0.6.3m1
  208. * @return A corresponding ProgramError
  209. */
  210. protected ProgramError getError(final ErrorLevel level, final String message,
  211. final String[] details, final boolean appError) {
  212. return new ProgramError(nextErrorID.getAndIncrement(), level, message,
  213. details, new Date());
  214. }
  215. /**
  216. * Determines whether or not the specified exception is one that we are
  217. * willing to report.
  218. *
  219. * @param exception The exception to test
  220. * @since 0.6.3m1
  221. * @return True if the exception may be reported, false otherwise
  222. */
  223. protected boolean isValidError(final Throwable exception) {
  224. Throwable target = exception;
  225. while (target != null) {
  226. for (Class<?> bad : BANNED_EXCEPTIONS) {
  227. if (bad.equals(target.getClass())) {
  228. return false;
  229. }
  230. }
  231. target = target.getCause();
  232. }
  233. return true;
  234. }
  235. /**
  236. * Converts an exception into a string array.
  237. *
  238. * @param throwable Exception to convert
  239. * @since 0.6.3m1
  240. * @return Exception string array
  241. */
  242. public static String[] getTrace(final Throwable throwable) {
  243. String[] trace;
  244. if (throwable == null) {
  245. trace = new String[0];
  246. } else {
  247. final StackTraceElement[] traceElements = throwable.getStackTrace();
  248. trace = new String[traceElements.length + 1];
  249. trace[0] = throwable.toString();
  250. for (int i = 0; i < traceElements.length; i++) {
  251. trace[i + 1] = traceElements[i].toString();
  252. }
  253. if (throwable.getCause() != null) {
  254. final String[] causeTrace = getTrace(throwable.getCause());
  255. final String[] newTrace = new String[trace.length + causeTrace.length];
  256. trace[0] = "\nWhich caused: " + trace[0];
  257. System.arraycopy(causeTrace, 0, newTrace, 0, causeTrace.length);
  258. System.arraycopy(trace, 0, newTrace, causeTrace.length, trace.length);
  259. trace = newTrace;
  260. }
  261. }
  262. return trace;
  263. }
  264. /**
  265. * Sends an error to the developers.
  266. *
  267. * @param error error to be sent
  268. */
  269. public void sendError(final ProgramError error) {
  270. if (error.getReportStatus() != ErrorReportStatus.ERROR
  271. && error.getReportStatus() != ErrorReportStatus.WAITING) {
  272. return;
  273. }
  274. error.setReportStatus(ErrorReportStatus.QUEUED);
  275. reportQueue.add(error);
  276. if (reportThread == null || !reportThread.isAlive()) {
  277. reportThread = new ErrorReportingThread(reportQueue);
  278. reportThread.start();
  279. }
  280. }
  281. /**
  282. * Called when an error needs to be deleted from the list.
  283. *
  284. * @param error ProgramError that changed
  285. */
  286. public void deleteError(final ProgramError error) {
  287. synchronized (errors) {
  288. errors.remove(error);
  289. }
  290. fireErrorDeleted(error);
  291. }
  292. /**
  293. * Deletes all errors from the manager.
  294. *
  295. * @since 0.6.3m1
  296. */
  297. public void deleteAll() {
  298. synchronized (errors) {
  299. for (ProgramError error : errors) {
  300. fireErrorDeleted(error);
  301. }
  302. errors.clear();
  303. }
  304. }
  305. /**
  306. * Returns the number of errors.
  307. *
  308. * @return Number of ProgramErrors
  309. */
  310. public int getErrorCount() {
  311. return errors.size();
  312. }
  313. /**
  314. * Returns the list of program errors.
  315. *
  316. * @return Program error list
  317. */
  318. public List<ProgramError> getErrors() {
  319. synchronized (errors) {
  320. return new LinkedList<>(errors);
  321. }
  322. }
  323. /**
  324. * Adds an ErrorListener to the listener list.
  325. *
  326. * @param listener Listener to add
  327. */
  328. public void addErrorListener(final ErrorListener listener) {
  329. if (listener == null) {
  330. return;
  331. }
  332. errorListeners.add(ErrorListener.class, listener);
  333. }
  334. /**
  335. * Removes an ErrorListener from the listener list.
  336. *
  337. * @param listener Listener to remove
  338. */
  339. public void removeErrorListener(final ErrorListener listener) {
  340. errorListeners.remove(ErrorListener.class, listener);
  341. }
  342. /**
  343. * Fired when the program encounters an error.
  344. *
  345. * @param error Error that occurred
  346. */
  347. protected void fireErrorAdded(final ProgramError error) {
  348. int firedListeners = 0;
  349. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  350. if (listener.isReady()) {
  351. listener.errorAdded(error);
  352. firedListeners++;
  353. }
  354. }
  355. if (firedListeners == 0) {
  356. System.err.println("An error has occurred: " + error.getLevel()
  357. + ": " + error.getMessage());
  358. for (String line : error.getTrace()) {
  359. System.err.println("\t" + line);
  360. }
  361. }
  362. }
  363. /**
  364. * Fired when the program encounters a fatal error.
  365. *
  366. * @param error Error that occurred
  367. */
  368. protected void fireFatalError(final ProgramError error) {
  369. final boolean restart;
  370. if (GraphicsEnvironment.isHeadless()) {
  371. System.err.println("A fatal error has occurred: " + error.getMessage());
  372. for (String line : error.getTrace()) {
  373. System.err.println("\t" + line);
  374. }
  375. restart = false;
  376. } else {
  377. final FatalErrorDialog fed = new FatalErrorDialog(error);
  378. fed.setVisible(true);
  379. try {
  380. synchronized (fed) {
  381. while (fed.isWaiting()) {
  382. fed.wait();
  383. }
  384. }
  385. } catch (InterruptedException ex) {
  386. //Oh well, carry on
  387. }
  388. restart = fed.getRestart();
  389. }
  390. try {
  391. synchronized (error) {
  392. while (!error.getReportStatus().isTerminal()) {
  393. error.wait();
  394. }
  395. }
  396. } catch (InterruptedException ex) {
  397. // Do nothing
  398. }
  399. if (restart) {
  400. System.exit(42);
  401. } else {
  402. System.exit(1);
  403. }
  404. }
  405. /**
  406. * Fired when an error is deleted.
  407. *
  408. * @param error Error that has been deleted
  409. */
  410. protected void fireErrorDeleted(final ProgramError error) {
  411. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  412. listener.errorDeleted(error);
  413. }
  414. }
  415. /**
  416. * Fired when an error's status is changed.
  417. *
  418. * @param error Error that has been altered
  419. */
  420. protected void fireErrorStatusChanged(final ProgramError error) {
  421. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  422. listener.errorStatusChanged(error);
  423. }
  424. }
  425. /** {@inheritDoc} */
  426. @Override
  427. public void configChanged(final String domain, final String key) {
  428. updateSettings();
  429. }
  430. /** Updates the settings used by this error manager. */
  431. protected void updateSettings() {
  432. final ConfigManager config = IdentityManager.getIdentityManager().getGlobalConfiguration();
  433. try {
  434. sendReports = config.getOptionBool("general", "submitErrors")
  435. && !config.getOptionBool("temp", "noerrorreporting");
  436. logReports = config.getOptionBool("general", "logerrors");
  437. } catch (IllegalArgumentException ex) {
  438. sendReports = false;
  439. logReports = true;
  440. }
  441. }
  442. }