Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ProgramError.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /*
  2. * Copyright (c) 2006-2014 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.util.ClientInfo;
  24. import java.io.IOException;
  25. import java.io.OutputStream;
  26. import java.io.PrintWriter;
  27. import java.io.Serializable;
  28. import java.nio.file.Files;
  29. import java.nio.file.Path;
  30. import java.text.DateFormat;
  31. import java.text.SimpleDateFormat;
  32. import java.util.Date;
  33. import java.util.Objects;
  34. import java.util.concurrent.Semaphore;
  35. import java.util.concurrent.atomic.AtomicInteger;
  36. import javax.annotation.Nullable;
  37. /**
  38. * Stores a program error.
  39. */
  40. public final class ProgramError implements Serializable {
  41. /** A version number for this class. */
  42. private static final long serialVersionUID = 3;
  43. /** Directory used to store errors. */
  44. private static Path errorDir;
  45. /** Semaphore used to serialise write access. */
  46. private static final Semaphore WRITING_SEM = new Semaphore(1);
  47. /** The reporter to use to send this error. */
  48. private final ErrorReporter reporter;
  49. /** Error ID. */
  50. private final long id;
  51. /** Error icon. */
  52. private final ErrorLevel level;
  53. /** Error message. */
  54. private final String message;
  55. /** Underlying exception. */
  56. private final Throwable exception;
  57. /** Underlying details message. */
  58. private final String details;
  59. /** Date/time error first occurred. */
  60. private final Date firstDate;
  61. /** Date/time error last occurred. */
  62. private Date lastDate;
  63. /** Number of occurrences. */
  64. private final AtomicInteger count;
  65. /** Error report Status. */
  66. private ErrorReportStatus reportStatus;
  67. /** Has the error been output. */
  68. private boolean handled;
  69. /**
  70. * Creates a new instance of ProgramError.
  71. *
  72. * @param id error id
  73. * @param level Error level
  74. * @param message Error message
  75. * @param exception The exception that caused the error, if any.
  76. * @param details The detailed cause of the error, if any.
  77. * @param date Error time and date
  78. */
  79. public ProgramError(final long id, final ErrorLevel level, final String message,
  80. @Nullable final Throwable exception,
  81. @Nullable final String details,
  82. final Date date,
  83. final ClientInfo clientInfo) {
  84. if (id < 0) {
  85. throw new IllegalArgumentException("ID must be a positive integer: " + id);
  86. }
  87. if (level == null) {
  88. throw new IllegalArgumentException("Level cannot be null");
  89. }
  90. if (message == null || message.isEmpty()) {
  91. throw new IllegalArgumentException("Message cannot be null or an empty string");
  92. }
  93. if (date == null) {
  94. throw new IllegalArgumentException("date cannot be null");
  95. }
  96. this.id = id;
  97. this.level = level;
  98. this.message = message;
  99. this.exception = exception;
  100. this.details = details;
  101. this.firstDate = (Date) date.clone();
  102. this.lastDate = (Date) date.clone();
  103. this.count = new AtomicInteger(1);
  104. this.reportStatus = ErrorReportStatus.WAITING;
  105. this.reporter = new ErrorReporter(clientInfo);
  106. }
  107. /**
  108. * Returns this errors level.
  109. *
  110. * @return Error level
  111. */
  112. public ErrorLevel getLevel() {
  113. return level;
  114. }
  115. /**
  116. * Returns this errors message.
  117. *
  118. * @return Error message
  119. */
  120. public String getMessage() {
  121. return message;
  122. }
  123. /**
  124. * Returns this errors trace.
  125. *
  126. * @return Error trace
  127. */
  128. public String[] getTrace() {
  129. return exception == null ? (message == null ? new String[0] : new String[]{message})
  130. : getTrace(exception);
  131. }
  132. /**
  133. * Returns this errors time.
  134. *
  135. * @return Error time
  136. */
  137. public Date getDate() {
  138. return (Date) firstDate.clone();
  139. }
  140. /**
  141. * Returns the number of times this error has occurred.
  142. *
  143. * @return Error count
  144. */
  145. public int getCount() {
  146. return count.get();
  147. }
  148. /**
  149. * Returns the last time this error occurred.
  150. *
  151. * @return Last occurrence
  152. */
  153. public Date getLastDate() {
  154. return (Date) lastDate.clone();
  155. }
  156. /**
  157. * Returns the reportStatus of this error.
  158. *
  159. * @return Error reportStatus
  160. */
  161. public ErrorReportStatus getReportStatus() {
  162. return reportStatus;
  163. }
  164. /**
  165. * Sets the report Status of this error.
  166. *
  167. * @param newStatus new ErrorReportStatus for the error
  168. */
  169. public void setReportStatus(final ErrorReportStatus newStatus) {
  170. if (newStatus != null && reportStatus != newStatus) {
  171. reportStatus = newStatus;
  172. ErrorManager.getErrorManager().fireErrorStatusChanged(this);
  173. synchronized (this) {
  174. notifyAll();
  175. }
  176. }
  177. }
  178. /**
  179. * Returns the ID of this error.
  180. *
  181. * @return Error ID
  182. */
  183. public long getID() {
  184. return id;
  185. }
  186. /**
  187. * Saves this error to disk.
  188. *
  189. * @param directory The directory to save the error in.
  190. */
  191. public void save(final Path directory) {
  192. try (PrintWriter out = new PrintWriter(getErrorFile(directory), true)) {
  193. out.println("Date:" + getDate());
  194. out.println("Level: " + getLevel());
  195. out.println("Description: " + getMessage());
  196. out.println("Details:");
  197. for (String traceLine : getTrace()) {
  198. out.println('\t' + traceLine);
  199. }
  200. }
  201. }
  202. /**
  203. * Creates a new file for an error and returns the output stream.
  204. *
  205. * @param directory The directory to save the error in.
  206. *
  207. * @return BufferedOutputStream to write to the error file
  208. */
  209. @SuppressWarnings("PMD.SystemPrintln")
  210. private OutputStream getErrorFile(final Path directory) {
  211. WRITING_SEM.acquireUninterruptibly();
  212. try {
  213. if (errorDir == null || !Files.exists(errorDir)) {
  214. errorDir = directory;
  215. if (!Files.exists(errorDir)) {
  216. Files.createDirectories(errorDir);
  217. }
  218. }
  219. final String logName = getDate().getTime() + "-" + getLevel();
  220. final Path errorFile = errorDir.resolve(logName + ".log");
  221. if (Files.exists(errorFile)) {
  222. boolean rename = false;
  223. for (int i = 0; !rename; i++) {
  224. try {
  225. Files.move(errorFile, errorDir.resolve(logName + '-' + i + ".log"));
  226. rename = true;
  227. } catch (IOException ex) {
  228. rename = false;
  229. if (i > 20) {
  230. // Something's probably catestrophically wrong. Give up.
  231. throw ex;
  232. }
  233. }
  234. }
  235. }
  236. Files.createFile(errorFile);
  237. return Files.newOutputStream(errorFile);
  238. } catch (IOException ex) {
  239. System.err.println("Error creating new file: ");
  240. ex.printStackTrace();
  241. return new NullOutputStream();
  242. } finally {
  243. WRITING_SEM.release();
  244. }
  245. }
  246. /**
  247. * Sends this error report to the DMDirc developers.
  248. */
  249. public void send() {
  250. setReportStatus(ErrorReportStatus.SENDING);
  251. reporter.sendException(message, level, firstDate, exception, details);
  252. setReportStatus(ErrorReportStatus.FINISHED);
  253. }
  254. /**
  255. * Determines whether or not the stack trace associated with this error is from a valid source.
  256. * A valid source is one that is within a DMDirc package (com.dmdirc), and is not the DMDirc
  257. * event queue.
  258. *
  259. * @return True if the source is valid, false otherwise
  260. */
  261. public boolean isValidSource() {
  262. final String line = getSourceLine();
  263. return line.startsWith("com.dmdirc")
  264. && !line.startsWith("com.dmdirc.addons.ui_swing.DMDircEventQueue");
  265. }
  266. /**
  267. * Returns the "source line" of this error, which is defined as the first line starting with a
  268. * DMDirc package name (com.dmdirc). If no such line is found, returns the first line of the
  269. * message.
  270. *
  271. * @return This error's source line
  272. */
  273. public String getSourceLine() {
  274. final String[] trace = getTrace();
  275. for (String line : trace) {
  276. if (line.startsWith("com.dmdirc")) {
  277. return line;
  278. }
  279. }
  280. return trace[0];
  281. }
  282. /**
  283. * Updates the last date this error occurred.
  284. */
  285. public void updateLastDate() {
  286. updateLastDate(new Date());
  287. }
  288. /**
  289. * Updates the last date this error occurred.
  290. *
  291. * @param date Date error occurred
  292. */
  293. public void updateLastDate(final Date date) {
  294. lastDate = date;
  295. count.getAndIncrement();
  296. ErrorManager.getErrorManager().fireErrorStatusChanged(this);
  297. synchronized (this) {
  298. notifyAll();
  299. }
  300. }
  301. /**
  302. * Returns a human readable string describing the number of times this error occurred and when
  303. * these occurrences were.
  304. *
  305. * @return Occurrences description
  306. */
  307. public String occurrencesString() {
  308. final DateFormat format = new SimpleDateFormat("MMM dd hh:mm aa");
  309. if (count.get() == 1) {
  310. return "1 occurrence on " + format.format(getDate());
  311. } else {
  312. return count.get() + " occurrences between " + format.format(
  313. getDate()) + " and " + format.format(getLastDate()) + '.';
  314. }
  315. }
  316. /**
  317. * Set this error as handled.
  318. */
  319. public void setHandled() {
  320. handled = true;
  321. }
  322. /**
  323. * Has this error been handled?
  324. *
  325. * @return Handled state
  326. */
  327. public boolean isHandled() {
  328. return handled;
  329. }
  330. @Override
  331. public String toString() {
  332. return "ID" + id + " Level: " + getLevel() + " Status: " + getReportStatus()
  333. + " Message: '" + getMessage() + '\'';
  334. }
  335. @Override
  336. public boolean equals(final Object obj) {
  337. if (obj == null) {
  338. return false;
  339. }
  340. if (getClass() != obj.getClass()) {
  341. return false;
  342. }
  343. final ProgramError other = (ProgramError) obj;
  344. return this.level == other.level && this.message.equals(other.message) &&
  345. Objects.equals(this.exception, other.exception) &&
  346. Objects.equals(this.details, other.details);
  347. }
  348. @Override
  349. public int hashCode() {
  350. int hash = 7;
  351. hash = 67 * hash + this.level.hashCode();
  352. hash = 67 * hash + this.message.hashCode();
  353. hash = 67 * hash + (this.exception == null ? 1 : this.exception.hashCode());
  354. hash = 67 * hash + (this.details == null ? 1 : this.details.hashCode());
  355. return hash;
  356. }
  357. /**
  358. * Converts an exception into a string array.
  359. *
  360. * @param throwable Exception to convert
  361. *
  362. * @since 0.6.3m1
  363. * @return Exception string array
  364. */
  365. private static String[] getTrace(final Throwable throwable) {
  366. String[] trace;
  367. if (throwable == null) {
  368. trace = new String[0];
  369. } else {
  370. final StackTraceElement[] traceElements = throwable.getStackTrace();
  371. trace = new String[traceElements.length + 1];
  372. trace[0] = throwable.toString();
  373. for (int i = 0; i < traceElements.length; i++) {
  374. trace[i + 1] = traceElements[i].toString();
  375. }
  376. if (throwable.getCause() != null) {
  377. final String[] causeTrace = getTrace(throwable.getCause());
  378. final String[] newTrace = new String[trace.length + causeTrace.length];
  379. trace[0] = "\nWhich caused: " + trace[0];
  380. System.arraycopy(causeTrace, 0, newTrace, 0, causeTrace.length);
  381. System.arraycopy(trace, 0, newTrace, causeTrace.length, trace.length);
  382. trace = newTrace;
  383. }
  384. }
  385. return trace;
  386. }
  387. }