Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libExceptions / src / org / gvsig / exceptions / BaseException.java @ 17545

History | View | Annotate | Download (7.65 KB)

1
package org.gvsig.exceptions;
2

    
3
import java.lang.reflect.Method;
4
import java.util.Iterator;
5
import java.util.Map;
6

    
7
import org.apache.log4j.Logger;
8

    
9
/**
10
 *
11
 * Esta clase esta pensada para actuar como clase base para
12
 * las excepciones que se lanzan dentro del proyecto de gvSIG.
13
 *
14
 * A?ade la implementacion necesaria para disponer de mensajes
15
 * de error internacionalizables, a traves del metodo
16
 * getLocalizedMessage, asi como una serie de metodos que nos
17
 * permiten obtener los mesanes de error de la cadena de excepciones
18
 * enlazadas a traves de su "causa", asi como utilidades que
19
 * permitan recorrer de forma comoda esta cadena de excepciones
20
 * por medio de un Iterador.
21
 *
22
 * @author Equipo de desarrollo de gvSIG.
23
 *
24
 */
25
public abstract class BaseException extends Exception implements IBaseException {
26
        private final static String BLANKS ="                                                                                                     ";
27
        private static IExceptionTranslator translator= null;
28
        private static Logger logger = null;
29

    
30

    
31
        protected String messageKey;
32

    
33
        protected String formatString;
34

    
35
        /**
36
         * Unique code of error.
37
         */
38
        protected long code;
39

    
40
        /**
41
         * Returns the format string received in the parameter
42
         * with its keys replaced with the corresponding values of the map.
43
         *
44
         * @param formatString
45
         * @param values map
46
         * @return string formatted
47
         */
48
        private String format(String formatString, Map values) {
49
                String key;
50
                String ret = formatString;
51
                if(formatString == null){
52
                        Logger lLogger=getLogger();
53
                        lLogger.error(this.getClass().getName()+": formatString is null.");
54
                        if (values != null){
55
                                Iterator keys = values.keySet().iterator();
56
                                ret = "values = { ";
57
                                while (keys.hasNext()){
58
                                        key = (String) keys.next();
59
                                        ret = ret.concat(key+": "+ (String)values.get(key)+"; ");
60
                                }
61
                                ret = ret.concat(" }");
62
                        }
63
                        
64
                        return ret;
65
                }
66
                if (values != null){
67
                        Iterator keys = values.keySet().iterator();
68
                        while (keys.hasNext()){
69
                                key = (String) keys.next();
70
                                ret = ret.replaceAll("%\\("+key+"\\)", (String)values.get(key));
71
                        }
72
                }
73
                return ret;
74
        }
75
        protected Logger getLogger() {
76
                if(logger==null){
77
                        logger = Logger.getLogger(BaseException.class.getName());
78
                }
79
                return logger;
80
        }
81

    
82
        /* (non-Javadoc)
83
         * @see java.lang.Throwable#getMessage()
84
         */
85
        public String getMessage() {
86
                return format(this.formatString, values());
87
        }
88

    
89
        /* (non-Javadoc)
90
         * @see org.gvsig.exceptions.IBaseException#getMessage(int)
91
         */
92
        public String getMessage(int indent) {
93
                return insertBlanksAtStart(format(formatString, values()),indent);
94
        }
95

    
96
        /* (non-Javadoc)
97
         * @see java.lang.Throwable#getLocalizedMessage()
98
         */
99
        public String getLocalizedMessage() {
100
                return getLocalizedMessage(translator,0);
101
        }
102

    
103
        /* (non-Javadoc)
104
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessage(org.gvsig.exceptions.IExceptionTranslator, int)
105
         */
106
        public String getLocalizedMessage(IExceptionTranslator translator, int indent){
107

    
108
                String fmt;
109
                if (translator == null){
110
                        translator = BaseException.translator;
111
                }
112
                if (translator == null){
113
                        fmt = getFormatString();
114
                } else {
115
                        fmt = getMessageKey();
116
                        if (fmt == null){
117
                                fmt = getFormatString();
118
                        } else {
119
                                fmt = translator.getText(fmt);
120
                        }
121
                }
122
                return insertBlanksAtStart(format(fmt,values()),indent);
123
        }
124

    
125
        /* (non-Javadoc)
126
         * @see org.gvsig.exceptions.IBaseException#getMessageStack()
127
         */
128
        public String getMessageStack() {
129
                return getMessageStack(0);
130
        }
131

    
132
        /* (non-Javadoc)
133
         * @see org.gvsig.exceptions.IBaseException#getMessageStack(int)
134
         */
135
        public String getMessageStack(int indent) {
136
                Iterator iter = this.iterator();
137
                String msg="";
138
                String msg1;
139
                Exception ex;
140
                int i = 1;
141
                while (iter.hasNext()){
142
                        ex = ((Exception)iter.next());
143
                        if ( ex instanceof BaseException ) {
144
                                BaseException bex = (BaseException) ex;
145
                                msg1 = bex.getMessage(indent*i);
146
                        } else {
147
                                msg1 = insertBlanksAtStart(ex.getMessage(),indent*i);
148
                        }
149
                        if(msg1!=null && !msg1.equals("")){
150
                                if( msg.equals("")) {
151
                                        msg = msg1 ;                                        
152
                                } else {
153
                                        msg = msg + "\n" + msg1 ;
154
                                }
155
                        }
156
                        i++;
157
                }
158
                return msg;
159
        }
160

    
161

    
162
        /* (non-Javadoc)
163
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessageStack()
164
         */
165
        public String getLocalizedMessageStack() {
166
                return getLocalizedMessageStack(BaseException.translator,0);
167
        }
168

    
169
        /* (non-Javadoc)
170
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessageStack(org.gvsig.exceptions.IExceptionTranslator, int)
171
         */
172
        public String getLocalizedMessageStack(IExceptionTranslator translator, int indent) {
173
                Iterator iter = this.iterator();
174
                String msg="";
175
                Exception ex;
176
                while (iter.hasNext()){
177
                        ex = ((Exception)iter.next());
178
                        if ( ex instanceof BaseException ) {
179
                                BaseException bex = (BaseException) ex;
180
                                if( msg.equals("") ) {
181
                                        msg = bex.getLocalizedMessage(translator,indent);
182
                                } else {
183
                                        msg = msg + "\n" + bex.getLocalizedMessage(translator,indent).trim();
184
                                }
185
                        } else {
186
                                if( msg.equals("") ) {
187
                                        msg = ex.getLocalizedMessage();                        
188
                                } else {
189
                                        msg = msg + "\n" + ex.getLocalizedMessage();
190
                                }
191
                        }
192
                }
193
                return msg;
194
        }
195

    
196
        /**
197
         * Inserts blanks at the start of a string.
198
         *
199
         * @param str A string.
200
         * @param len Quantity of blanks to insert at the start of str.
201
         * @return A string compund by the quantity of blanks that
202
         *         len indicates and str.
203
         */
204
        static String insertBlanksAtStart(String str, int len){
205
                try {
206
                        return BLANKS.substring(0,len)+str;
207
                } catch (IndexOutOfBoundsException e) {
208
                        return BLANKS + str;
209
                }
210
        }
211

    
212
        /* (non-Javadoc)
213
         * @see org.gvsig.exceptions.IBaseException#getCode()
214
         */
215
        public long getCode() {
216
                return this.code;
217
        }
218

    
219
        /**
220
         * Sets the exception's code.
221
         */
222
        public void setCode(long code) {
223
                this.code = code;
224
        }
225

    
226
        /* (non-Javadoc)
227
         * @see org.gvsig.exceptions.IBaseException#getFormatString()
228
         */
229
        public String getFormatString() {
230
                return this.formatString;
231
        }
232

    
233
        /**
234
         * Sets the format string.
235
         *
236
         * @param formatString
237
         */
238
        public void setFormatString(String formatString) {
239
                this.formatString = formatString;
240
        }
241

    
242
        /* (non-Javadoc)
243
         * @see org.gvsig.exceptions.IBaseException#getMessageKey()
244
         */
245
        public String getMessageKey() {
246
                return this.messageKey;
247
        }
248

    
249
        /**
250
         * Sets the property messageKey.
251
         *
252
         * @param messageKey
253
         */
254
        public void setMessageKey(String messageKey) {
255
                this.messageKey = messageKey;
256
        }
257

    
258
        /* (non-Javadoc)
259
         * @see org.gvsig.exceptions.IBaseException#iterator()
260
         */
261
        public Iterator iterator() {
262
                return new BaseExceptionIterator(this);
263
        }
264

    
265
        /**
266
         * @return A map that serves to replace in the format string
267
         * the keys with the corresponding values.
268
         */
269
        abstract protected Map values();
270

    
271
        /**
272
         * Sets the property translator.
273
         * @param translator It(He,She) is used to translate
274
         *        the messages associated with the exceptions.
275
         */
276
        public static void setTranslator(IExceptionTranslator translator){
277
                BaseException.translator = translator;
278
        }
279

    
280
        public static void setTranslator(Object translator){
281
                BaseException.translator = new TranslatorWraper(translator);
282
        }
283

    
284
        public String toString(){
285
                return format(this.formatString, values());
286
        }
287

    
288
}
289

    
290
class TranslatorWraper implements IExceptionTranslator {
291

    
292
        private Object translator = null;
293
        private Method method = null;
294

    
295
        public TranslatorWraper(Object translator) {
296
                Class theClass = translator.getClass();
297
                String s = "";
298

    
299
                this.translator = translator;
300
                try {
301
                        method = theClass.getMethod("getText",new Class[] { s.getClass() });
302
                } catch (Exception e) {
303
                        throw new RuntimeException("El objeto translator suministrado no tiene el metodo getText apropiado.", e);
304
                }
305

    
306
        }
307

    
308
        public String getText(String key) {
309
                try {
310
                        return (String)(method.invoke(translator,new String[] { key }));
311
                } catch (Exception e) {
312
                        return key;
313
                }
314
        }
315

    
316
}