]> WPIA git - gigi.git/blob - src/org/cacert/gigi/GigiApiException.java
b858e7d9a35d662c5ecefc10375d9a798d33349b
[gigi.git] / src / org / cacert / gigi / GigiApiException.java
1 package org.cacert.gigi;
2
3 import java.io.PrintWriter;
4 import java.io.StringWriter;
5 import java.sql.SQLException;
6 import java.util.HashMap;
7 import java.util.LinkedList;
8 import java.util.Locale;
9
10 import org.cacert.gigi.localisation.Language;
11 import org.cacert.gigi.output.template.Outputable;
12 import org.cacert.gigi.output.template.TranslateCommand;
13
14 public class GigiApiException extends Exception {
15
16     private SQLException e;
17
18     private LinkedList<Outputable> messages = new LinkedList<>();
19
20     public GigiApiException(SQLException e) {
21         super(e);
22         this.e = e;
23     }
24
25     public GigiApiException(String message) {
26         super(message);
27         messages.add(new TranslateCommand(message));
28     }
29
30     public GigiApiException() {
31
32     }
33
34     public GigiApiException(Outputable out) {
35         messages.add(out);
36     }
37
38     public void mergeInto(GigiApiException e2) {
39         messages.addAll(e2.messages);
40         if (e == null) {
41             e = e2.e;
42         }
43     }
44
45     public boolean isInternalError() {
46         return e != null;
47     }
48
49     public void format(PrintWriter out, Language language) {
50         out.println("<div class='formError'>");
51         if (isInternalError()) {
52             e.printStackTrace();
53             out.print("<div>");
54             out.println(language.getTranslation("An internal error ouccured."));
55             out.println("</div>");
56         }
57         HashMap<String, Object> map = new HashMap<>();
58         for (Outputable message : messages) {
59             map.clear();
60
61             out.print("<div>");
62             message.output(out, language, map);
63             out.println("</div>");
64         }
65         out.println("</div>");
66
67     }
68
69     public boolean isEmpty() {
70         return e == null && messages.size() == 0;
71     }
72
73     @Override
74     public String getMessage() {
75         if (messages.size() != 0) {
76             StringWriter sw = new StringWriter();
77             PrintWriter pw = new PrintWriter(sw);
78
79             HashMap<String, Object> map = new HashMap<>();
80             for (Outputable message : messages) {
81                 map.clear();
82                 message.output(pw, Language.getInstance(Locale.ENGLISH), map);
83             }
84             pw.flush();
85
86             return sw.toString();
87         }
88         return "";
89     }
90
91 }