Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libExceptions / src / org / gvsig / exceptions / BaseException.java @ 23150

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

    
28
        protected String messageKey;
29

    
30
        /**
31
     * TODO: remove the variable, use the Exception get/setMessage() instead.
32
     */
33
        protected String formatString;
34

    
35
        /**
36
         * Unique code of error.
37
         */
38
        protected long code;
39
        
40
    /**
41
     * Empty constructor, don't use it anymore.
42
     * 
43
     * @deprecated
44
     */
45
    public BaseException() {
46
    }
47

    
48
    /**
49
     * Constructs a BaseException with a default message format, a key to find a
50
     * localized message format, and a unique code to identify the exception.
51
     * 
52
     * @param message
53
     *            the default messageFormat to describe the exception
54
     * @param key
55
     *            the key to use to search a localized messageFormnata
56
     * @param code
57
     *            the unique code to identify the exception
58
     */
59
    public BaseException(String message, String key, long code) {
60
        super(message);
61
        this.formatString = message;
62
        this.messageKey = key;
63
        this.code = code;
64
    }
65

    
66
    /**
67
     * Constructs a BaseException with a default message format, a key to find a
68
     * localized message format, and a unique code to identify the exception.
69
     * 
70
     * @param message
71
     *            the default messageFormat to describe the exception
72
     * @param cause
73
     *            the original cause of the exception
74
     * @param key
75
     *            the key to use to search a localized messageFormnata
76
     * @param code
77
     *            the unique code to identify the exception
78
     */
79
    public BaseException(String message, Throwable cause, String key, long code) {
80
        super(message, cause);
81
        this.formatString = message;
82
        this.messageKey = key;
83
        this.code = code;
84
    }
85

    
86
        /**
87
     * Returns the format string received in the parameter with its keys
88
     * replaced with the corresponding values of the map.
89
     * 
90
     * @param formatString
91
     * @param values
92
     *            map
93
     * @return string formatted
94
     */
95
    private String format(String formatString, Map values) {
96
        if (values != null) {
97

    
98
            // If there is no message format, create a text with the values.
99
            if (formatString == null) {
100
                return "values = ".concat(values.toString());
101
            } else {
102
                // Replace the keys as variables with the values in the Map
103
                Iterator keys = values.keySet().iterator();
104
                String message = formatString;
105
                while (keys.hasNext()) {
106
                    String key = (String) keys.next();
107
                    String varName = "%\\(".concat(key).concat("\\)");
108
                    message = message.replaceAll(varName, (String) values
109
                            .get(key));
110
                }
111
                return message;
112
            }
113
        }
114
        // Return the original format message in any other case
115
        return formatString;
116
    }
117

    
118
        /* (non-Javadoc)
119
         * @see java.lang.Throwable#getMessage()
120
         */
121
        public String getMessage() {
122
                return format(this.formatString, values());
123
        }
124

    
125
        /* (non-Javadoc)
126
         * @see org.gvsig.exceptions.IBaseException#getMessage(int)
127
         */
128
        public String getMessage(int indent) {
129
                return insertBlanksAtStart(format(formatString, values()),indent);
130
        }
131

    
132
        /* (non-Javadoc)
133
         * @see java.lang.Throwable#getLocalizedMessage()
134
         */
135
        public String getLocalizedMessage() {
136
                return getLocalizedMessage(translator,0);
137
        }
138

    
139
        /* (non-Javadoc)
140
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessage(org.gvsig.exceptions.IExceptionTranslator, int)
141
         */
142
        public String getLocalizedMessage(IExceptionTranslator translator, int indent){
143

    
144
                String fmt;
145
                if (translator == null){
146
                        translator = BaseException.translator;
147
                }
148
                if (translator == null){
149
                        fmt = getFormatString();
150
                } else {
151
                        fmt = getMessageKey();
152
                        if (fmt == null){
153
                                fmt = getFormatString();
154
                        } else {
155
                                fmt = translator.getText(fmt);
156
                        }
157
                }
158
                return insertBlanksAtStart(format(fmt,values()),indent);
159
        }
160

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

    
168
        /* (non-Javadoc)
169
         * @see org.gvsig.exceptions.IBaseException#getMessageStack(int)
170
         */
171
        public String getMessageStack(int indent) {
172
                Iterator iter = this.iterator();
173
                StringBuffer msgBuffer = new StringBuffer();
174
                int i = 1;
175
                while (iter.hasNext()){
176
                    Exception ex = ((Exception) iter.next());
177
                        
178
            if (msgBuffer.length() > 0) {
179
                msgBuffer.append("\n");
180
            }
181
                        
182
                        if ( ex instanceof BaseException ) {
183
                                BaseException bex = (BaseException) ex;
184
                                msgBuffer.append(bex.getMessage(indent * i));
185
                        } else {
186
                            msgBuffer.append(insertBlanksAtStart(ex.getMessage(), indent
187
                        * i));
188
                        }
189
                        
190
                        i++;
191
                }
192
                return msgBuffer.toString();
193
        }
194

    
195

    
196
        /* (non-Javadoc)
197
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessageStack()
198
         */
199
        public String getLocalizedMessageStack() {
200
                return getLocalizedMessageStack(BaseException.translator,0);
201
        }
202

    
203
        /* (non-Javadoc)
204
         * @see org.gvsig.exceptions.IBaseException#getLocalizedMessageStack(org.gvsig.exceptions.IExceptionTranslator, int)
205
         */
206
        public String getLocalizedMessageStack(IExceptionTranslator translator, int indent) {
207
                Iterator iter = this.iterator();
208
        StringBuffer msgBuffer = new StringBuffer();
209
        Exception ex;
210
        while (iter.hasNext()) {
211
            ex = ((Exception) iter.next());
212
            if (msgBuffer.length() > 0) {
213
                msgBuffer.append("\n");
214
            }
215

    
216
            if (ex instanceof BaseException) {
217
                BaseException bex = (BaseException) ex;
218
                msgBuffer.append(bex.getLocalizedMessage(translator, indent));
219
            } else {
220
                msgBuffer.append(ex.getLocalizedMessage());
221
            }
222
        }
223
        return msgBuffer.toString();
224
        }
225

    
226
        /**
227
         * Inserts blanks at the start of a string.
228
         *
229
         * @param str A string.
230
         * @param len Quantity of blanks to insert at the start of str.
231
         * @return A string compund by the quantity of blanks that
232
         *         len indicates and str.
233
         */
234
        static String insertBlanksAtStart(String str, int len){
235
        int blanksLen = len > BLANKS.length() ? BLANKS.length() : (len < 0 ? 0
236
                : len);
237

    
238
        return BLANKS.substring(0, blanksLen) + str;
239
        }
240

    
241
        /* (non-Javadoc)
242
         * @see org.gvsig.exceptions.IBaseException#getCode()
243
         */
244
        public long getCode() {
245
                return this.code;
246
        }
247

    
248
        /**
249
         * Sets the exception's code.
250
         */
251
        public void setCode(long code) {
252
                this.code = code;
253
        }
254

    
255
        /* (non-Javadoc)
256
         * @see org.gvsig.exceptions.IBaseException#getFormatString()
257
         */
258
        public String getFormatString() {
259
                return this.formatString;
260
        }
261

    
262
        /**
263
         * Sets the format string.
264
         *
265
         * @param formatString
266
         */
267
        public void setFormatString(String formatString) {
268
                this.formatString = formatString;
269
        }
270

    
271
        /* (non-Javadoc)
272
         * @see org.gvsig.exceptions.IBaseException#getMessageKey()
273
         */
274
        public String getMessageKey() {
275
                return this.messageKey;
276
        }
277

    
278
        /**
279
         * Sets the property messageKey.
280
         *
281
         * @param messageKey
282
         */
283
        public void setMessageKey(String messageKey) {
284
                this.messageKey = messageKey;
285
        }
286

    
287
        /* (non-Javadoc)
288
         * @see org.gvsig.exceptions.IBaseException#iterator()
289
         */
290
        public Iterator iterator() {
291
                return new BaseExceptionIterator(this);
292
        }
293

    
294
        /**
295
         * @return A map that serves to replace in the format string
296
         * the keys with the corresponding values.
297
         */
298
        abstract protected Map values();
299

    
300
        /**
301
         * Sets the property translator.
302
         * @param translator It(He,She) is used to translate
303
         *        the messages associated with the exceptions.
304
         */
305
        public static void setTranslator(IExceptionTranslator translator){
306
                BaseException.translator = translator;
307
        }
308

    
309
        public static void setTranslator(Object translator){
310
                BaseException.translator = new TranslatorWraper(translator);
311
        }
312

    
313
        public String toString(){
314
                return format(this.formatString, values());
315
        }
316

    
317
}
318

    
319
class TranslatorWraper implements IExceptionTranslator {
320

    
321
        private Object translator = null;
322
        private Method method = null;
323

    
324
        public TranslatorWraper(Object translator) {
325
                Class theClass = translator.getClass();
326
                String s = "";
327

    
328
                this.translator = translator;
329
                try {
330
                        method = theClass.getMethod("getText",new Class[] { s.getClass() });
331
                } catch (Exception e) {
332
                        throw new RuntimeException("El objeto translator suministrado no tiene el metodo getText apropiado.", e);
333
                }
334

    
335
        }
336

    
337
        public String getText(String key) {
338
                try {
339
                        return (String)(method.invoke(translator,new String[] { key }));
340
                } catch (Exception e) {
341
                        return key;
342
                }
343
        }
344

    
345
}