Revision 21280

View differences:

branches/Mobile_Compatible_Hito_1/libExceptions/.cvsignore
1
bin
2
bin-test
3
dist/*
branches/Mobile_Compatible_Hito_1/libExceptions/build.xml
1
<project name="libExceptions" default="create-jar" basedir=".">
2
  	<!-- set global properties for this build -->
3
	<property name="src"  location="src"/>
4
	<property name="build"  location="bin"/>
5
	<property name="src-test"  location="src-test"/>
6
	<property name="build-test"  location="bin-test"/>
7
	<property name="dist"  location="dist"/>
8
	<property name="targetDir" location="dist"/>
9
	<property name="fmapLibs" location="../libFMap/lib" />
10
	<property name="andamiLibs" location="../_fwAndami/lib" />
11
	<property name="remoteServicesLibs" location="../libRemoteServices/lib" />
12
	<property name="jarName" value="org.gvsig.exceptions"/>
13
	<!--<property name="compile-classpath" value="" />-->
14
	<import file="../binaries/ant/utilities.xml"/>
15

  
16
  <target name="init">
17
    <!-- Create the time stamp -->
18
    <tstamp/>
19
	<echo>
20
		Compiling ${ant.project.name}...</echo>
21
  </target>
22

  
23
	<target name="batch-build"
24
				description="compile the sources, create the jar file"
25
				depends="init,compile,create-jar">
26
	</target>
27

  
28
	<target name="compile" description="compile the source">
29
		<!-- Compile the Java code from ${src} to ${build} -->
30
		<mkdir dir="${build}" />
31
		<loadEclipseClasspath project="${basedir}"/>
32
		<gvSIG-javac
33
			classpath="${eclipseClasspath}"
34
		/>
35

  
36
		<!--<javac	srcdir="${src}"
37
				destdir="${build}"
38
				source="1.4"
39
				target="1.4"
40
				debug="${debug}"
41
				debuglevel="${debuglevel}"
42
				classpath="${compile-classpath}"/>-->
43
		<!-- copy any images or resources present in the src dir -->
44
		<copy todir="${build}">
45
			<fileset dir="${src}" excludes="**/*.java" casesensitive="false"/>
46
		</copy>
47
	</target>
48

  
49
	<target name="create-jar" description="Crea el jar de la aplicacion">
50
		<mkdir dir="${dist}" />
51
	  	<jar jarfile="${targetDir}/${jarName}.jar" basedir="${build}"/>
52
		<copy todir="${andamiLibs}">
53
			<fileset dir="${targetDir}" includes="${jarName}.jar" />
54
		</copy>
55
	</target>
56

  
57
	<target name="clean" description="clean up">
58
		<!-- Delete the ${build} and ${dist} directory trees -->
59
		<delete dir="${build}" />
60
		<delete dir="${dist}" />
61
	</target>
62

  
63
	<target name="run-tests" depends="batch-build,compile-tests">
64
		<antcall target="generic-run-tests">
65
			<param name="TestSuite.Name" value="org.gvsig.gui.beans.AllTests"/>
66
		</antcall>
67
	</target>
68

  
69
</project>
branches/Mobile_Compatible_Hito_1/libExceptions/.classpath
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
5
	<classpathentry kind="src" output="bin-test" path="src-test"/>
6
	<classpathentry kind="var" path="JUNIT_HOME/junit.jar"/>
7
	<classpathentry kind="lib" path="lib/log4j-1.2.15.jar"/>
8
	<classpathentry kind="lib" path="lib/slf4j-api-1.5.0.jar"/>
9
	<classpathentry kind="lib" path="lib/slf4j-log4j12-1.5.0.jar"/>
10
	<classpathentry kind="lib" path="lib/org.gvsig.compat-desktop.jar"/>
11
	<classpathentry kind="output" path="bin"/>
12
</classpath>
branches/Mobile_Compatible_Hito_1/libExceptions/src-test/org/gvsig/exceptions/BaseExceptionTest.java
1
package org.gvsig.exceptions;
2

  
3
import junit.framework.TestCase;
4

  
5
public class BaseExceptionTest extends TestCase {
6

  
7
	protected void setUp() throws Exception {
8
		super.setUp();
9
	}
10

  
11
	protected void tearDown() throws Exception {
12
		super.tearDown();
13
	}
14
	
15
	public void testSimple(){
16
		try {
17
			throw new NullPointerException("Excepcion de puntero nulo");
18
		} catch (NullPointerException e){
19
			DriverException de = new DriverException("SimpleDriver", e);
20
			assertEquals("Error in the driver SimpleDrivers",de.getMessage());
21
			assertEquals("Error in the driver SimpleDrivers\nExcepcion de puntero nulo",de.getMessageStack());
22
		}
23
	}
24

  
25
	public void testSimpleLocalized(){
26
		class MyTranslator implements IExceptionTranslator {
27
			public String getText(String clave) {
28
				return clave.toUpperCase();
29
			}
30
		}
31
		BaseException.setTranslator(new MyTranslator());
32
		try {
33
			throw new NullPointerException("Excepcion de puntero nulo");
34
		} catch (NullPointerException e){
35
			DriverException de = new DriverException("SimpleDriver", e);
36
			assertEquals("ERROR_IN_THE_DRIVER_%(DRIVERNAME)S",de.getLocalizedMessage());
37
			assertEquals("ERROR_IN_THE_DRIVER_%(DRIVERNAME)S\nExcepcion de puntero nulo",de.getLocalizedMessageStack());
38
		}
39
		BaseException.setTranslator(null);
40
	}
41

  
42
	public void testSimple2(){
43
		try {
44
			throw new NullPointerException("Excepcion de puntero nulo");
45
		} catch (NullPointerException e){
46
			BadDateException de = new BadDateException("SimpleDriver", e);
47
			assertEquals("Driver SimpleDrivers: Formato de fecha incorrecto",de.getMessage());
48
			assertEquals("Driver SimpleDrivers: Formato de fecha incorrecto\nExcepcion de puntero nulo",de.getMessageStack());
49
		}
50
	}
51

  
52
	public void testSimpleLocalized2(){
53
		class MyTranslator implements IExceptionTranslator {
54
			public String getText(String clave) {
55
				return clave.toUpperCase();
56
			}
57
		}
58
		BaseException.setTranslator(new MyTranslator());
59
		try {
60
			throw new NullPointerException("Excepcion de puntero nulo");
61
		} catch (NullPointerException e){
62
			BadDateException de = new BadDateException("SimpleDriver", e);
63
			assertEquals("DRIVER_%(DRIVERNAME)S_FORMATO_DE_FECHA_INCORRECTO",de.getLocalizedMessage());
64
			assertEquals("DRIVER_%(DRIVERNAME)S_FORMATO_DE_FECHA_INCORRECTO\nExcepcion de puntero nulo",de.getLocalizedMessageStack());
65
		}
66
		BaseException.setTranslator(null);
67
	}
68

  
69
	public void testTranslatorWithoutInterface(){
70
		class MyTranslator {
71
			public MyTranslator(){
72
				super();
73
			}
74
			public String getText(String clave) {
75
				return clave.toUpperCase();
76
			}
77
		}
78
		BaseException.setTranslator(new MyTranslator());
79
		try {
80
			throw new NullPointerException("Excepcion de puntero nulo");
81
		} catch (NullPointerException e){
82
			BadDateException de = new BadDateException("SimpleDriver", e);
83
			assertEquals("DRIVER_%(DRIVERNAME)S_FORMATO_DE_FECHA_INCORRECTO",de.getLocalizedMessage());
84
			assertEquals("DRIVER_%(DRIVERNAME)S_FORMATO_DE_FECHA_INCORRECTO\nExcepcion de puntero nulo",de.getLocalizedMessageStack());
85
		}
86
		BaseException.setTranslator(null);
87
	}
88

  
89
	class BadDateException extends DriverException {
90
		private static final long serialVersionUID = -8985920349210629998L;
91
		
92
		public BadDateException(String driverName, Throwable cause){
93
			super(driverName, cause);
94
			messageKey="Driver_%(driverName)s_Formato_de_fecha_incorrecto";
95
			formatString="Driver %(driverName)s: Formato de fecha incorrecto";
96
			code = serialVersionUID;
97
		}
98
	}
99
}
branches/Mobile_Compatible_Hito_1/libExceptions/src-test/org/gvsig/exceptions/DriverException.java
1
package org.gvsig.exceptions;
2

  
3
import java.util.HashMap;
4
import java.util.Map;
5

  
6
public class DriverException extends BaseException {
7
	
8
	private static final long serialVersionUID = -8985920349210629999L;
9
	private String driverName;
10
	
11
	public DriverException() {
12
		init();
13
	}
14
	
15
	public DriverException(String driverName) {
16
		init();
17
		this.driverName = driverName;
18
	}
19
	
20
	public DriverException(String driverName, Throwable cause) {
21
		init();
22
		this.driverName = driverName;
23
		initCause(cause);
24
	}
25

  
26
	public void init() {
27
		messageKey="Error_in_the_driver_%(driverName)s";
28
		formatString="Error in the driver %(driverName)s";
29
		code = serialVersionUID;
30
	}
31

  
32
	
33
	public String getDriverName() {
34
		return driverName;
35
	}
36
	
37
	public void setDriverName(String driverName) {
38
		this.driverName = driverName;
39
	}
40
	
41
	protected Map values() {
42
		HashMap values = new HashMap();
43
		values.put("driverName",this.driverName);
44
		return values;
45
	}
46
}
branches/Mobile_Compatible_Hito_1/libExceptions/src-test/org/gvsig/exceptions/AllTests.java
1
package org.gvsig.exceptions;
2

  
3
import junit.framework.Test;
4
import junit.framework.TestSuite;
5

  
6
public class AllTests {
7

  
8
	public static Test suite() {
9
		TestSuite suite = new TestSuite("Test for org.gvsig.exceptions");
10
		//$JUnit-BEGIN$
11
		suite.addTestSuite(SimpleSLF4JTest.class);
12
		suite.addTestSuite(ListBaseExceptionTest.class);
13
		suite.addTestSuite(BaseExceptionTest.class);
14
		//$JUnit-END$
15
		return suite;
16
	}
17

  
18
}
branches/Mobile_Compatible_Hito_1/libExceptions/src-test/org/gvsig/exceptions/SimpleSLF4JTest.java
1
package org.gvsig.exceptions;
2

  
3
/* gvSIG. Geographic Information System of the Valencian Government
4
*
5
* Copyright (C) 2007-2008 Infrastructures and Transports Department
6
* of the Valencian Government (CIT)
7
* 
8
* This program is free software; you can redistribute it and/or
9
* modify it under the terms of the GNU General Public License
10
* as published by the Free Software Foundation; either version 2
11
* of the License, or (at your option) any later version.
12
* 
13
* This program is distributed in the hope that it will be useful,
14
* but WITHOUT ANY WARRANTY; without even the implied warranty of
15
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
* GNU General Public License for more details.
17
* 
18
* You should have received a copy of the GNU General Public License
19
* along with this program; if not, write to the Free Software
20
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
21
* MA  02110-1301, USA.
22
* 
23
*/
24

  
25
/*
26
* AUTHORS (In addition to CIT):
27
* 2008 PRODEVELOP S.L. Main Development
28
*/
29

  
30
import org.slf4j.Logger;
31
import org.slf4j.LoggerFactory;
32

  
33
import junit.framework.TestCase;
34

  
35

  
36
public class SimpleSLF4JTest extends TestCase {
37
	private Logger logger = LoggerFactory.getLogger(SimpleSLF4JTest.class);
38
	
39
	protected void setUp() throws Exception {
40
		super.setUp();
41
	}
42

  
43
	protected void tearDown() throws Exception {
44
		super.tearDown();
45
	}
46

  
47
	public void testSLF4J(){
48
		assertEquals("MENSAJE DE ERROR ENVIADO POR SLF4J",getError());
49
	}
50
	private String getError(){
51
		String mensj="MENSAJE DE ERROR ENVIADO POR SLF4J";
52
		logger.error(mensj);
53
		return mensj;
54
	}
55
}
branches/Mobile_Compatible_Hito_1/libExceptions/src-test/org/gvsig/exceptions/ListBaseExceptionTest.java
1
package org.gvsig.exceptions;
2

  
3
import junit.framework.TestCase;
4

  
5
public class ListBaseExceptionTest extends TestCase {
6

  
7
	protected void setUp() throws Exception {
8
		super.setUp();
9
	}
10

  
11
	protected void tearDown() throws Exception {
12
		super.tearDown();
13
	}
14

  
15
	public void testSimple(){
16
	}
17

  
18
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/org/gvsig/exceptions/IExceptionTranslator.java
1
package org.gvsig.exceptions;
2

  
3
/**
4
 * 
5
 * @author Equipo de desarrollo de gvSIG
6
 *
7
 */
8
public interface IExceptionTranslator {
9
	
10
	/** 
11
	 *  @param key The key of the message error.
12
	 *  @return The translated error message
13
	 *  corresponding to the key that it
14
	 *  obtains as parameter.
15
	 */
16
	public String getText(String key);
17
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/org/gvsig/exceptions/IBaseException.java
1
package org.gvsig.exceptions;
2

  
3
import java.util.Iterator;
4

  
5
/**
6
 * 
7
 * 
8
 * @author Equipo de desarrollo de gvSIG
9
 *
10
 */
11
public interface IBaseException {
12
	
13
	/** 
14
	 *  Returns the message that describes the exception.
15
	 *  
16
	 *  @return The message.
17
	 */
18
	public String getMessage();
19

  
20
	/** 
21
	 *  Returns the message that describes the exception, with indentation.
22
	 *  
23
	 *  @param indent Quantity of blanks to insert
24
	 *         at the start of the message.
25
	 *  @return The message with indentation.
26
	 */
27
	public String getMessage(int indent);
28

  
29
	/** 
30
	 *  Returns the translated message that describes the exception.
31
	 *  
32
	 *  @return The translated message with indentation.
33
	 */
34
	public String getLocalizedMessage();
35
	
36
	/** 
37
	 *  Returns the translated message that
38
	 *  describes the exception with indentation.
39
	 *
40
	 *  @param translator Instance of a class that fulfills
41
	 *         the IExceptionTranslator interface.
42
	 *         His method "getText" takes charge returning
43
	 *         the expression, correspondent to the key that
44
	 *         delivers him, translated into the configured language.
45
	 *  @param indent Quantity of blanks to insert
46
	 *         at the start of the message.
47
	 *  @return The translated message with indentation.
48
	 */
49
	public String getLocalizedMessage(IExceptionTranslator translator, int indent);
50
	
51
	/** 
52
	 *  Crosses the exceptions chained through cause to conform
53
	 *  the message.
54
	 *  
55
	 *  @return The compound message with all the messages
56
	 *          of the stack of exceptions.
57
	 */
58
	public String getMessageStack();
59

  
60
	/** 
61
	 *  Crosses the exceptions chained through cause to conform
62
	 *  the compound message with indentation.
63
	 *  
64
	 *  @param indent Quantity of blanks to insert
65
	 *         at the start of the messages.
66
	 *  @return The compound message with all the messages
67
	 *          of the stack of exceptions.
68

  
69
	 */
70
	public String getMessageStack(int indent);
71

  
72
	/** 
73
	 *  Crosses the exceptions chained through cause
74
	 *  to conform the compound message in the corresponding language.
75
	 *  
76
	 *  @return The translated compound message.
77
	 *    
78
	 */
79
	public String getLocalizedMessageStack();
80

  
81
	/** 
82
	 *  Crosses the exceptions chained through cause
83
	 *  to conform the compound message in the corresponding language.
84
	 *  
85
	 *  @param translator Instance of a class that fulfills
86
	 *         the IExceptionTranslator interface.
87
	 *         His method "getText" takes charge returning
88
	 *         the expression, correspondent to the key that
89
	 *         delivers him, translated into the configured language.
90
	 *  @param indent Quantity of blanks to insert
91
	 *         at the start of the messages.
92
	 *  @return The translated message with indentation.
93
	 *  
94
	 */
95
	public String getLocalizedMessageStack(IExceptionTranslator translator, int indent);
96
	
97
	
98
	/** 
99
	 *  @return The exception's code.
100
	 */
101
	public long getCode();
102
	
103
	/** 
104
	 *  @return The format string.
105
	 */
106
	public String getFormatString();
107
	
108
	/** 
109
	 *  @return The message key associated to the exception.
110
	 */
111
	public String getMessageKey();
112
	
113
	/** 
114
	 *  @return A iterator for the chained exceptions.
115
	 */
116
	public Iterator iterator();
117
	
118
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/org/gvsig/exceptions/BaseExceptionIterator.java
1
package org.gvsig.exceptions;
2

  
3
import java.util.Iterator;
4

  
5
class BaseExceptionIterator implements Iterator {
6
	
7
	Exception exception;
8
	
9
	BaseExceptionIterator(BaseException exception){
10
		this.exception = exception;
11
	}
12
	/** 
13
	 *  @return true if the iteration has more elements.
14
	 */
15
	public boolean hasNext() {
16
		return this.exception != null;
17
	}
18
	
19
	/** 
20
	 *  @return The next element in the iteration.
21
	 */
22
	public Object next() {
23
		Exception exception;
24
		exception = this.exception;
25
		this.exception = (Exception) exception.getCause();
26
		return exception;
27
	}
28
	
29
	/** 
30
	 *  @throws "UnsupportedOperationException" because
31
	 *  the remove operation will not be supported
32
	 *  by this Iterator.
33
	 */
34
	public void remove() {
35
		throw new UnsupportedOperationException();
36
	}
37
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/org/gvsig/exceptions/ListBaseException.java
1
package org.gvsig.exceptions;
2

  
3
import java.util.ArrayList;
4
import java.util.Collection;
5
import java.util.Iterator;
6
import java.util.List;
7
import java.util.ListIterator;
8

  
9
/**
10
 * @author Equipo de desarrollo de gvSIG
11
 *
12
 */
13
public abstract class ListBaseException extends BaseException implements List{
14
	private List exceptions = new ArrayList();
15
	
16
	/* (non-Javadoc)
17
	 * @see java.util.Collection#size()
18
	 */
19
	public int size() {
20
		return this.exceptions.size();
21
	}
22

  
23
	/* (non-Javadoc)
24
	 * @see java.util.Collection#isEmpty()
25
	 */
26
	public boolean isEmpty() {
27
		return this.exceptions.isEmpty();
28
	}
29

  
30
	/* (non-Javadoc)
31
	 * @see java.util.Collection#contains(java.lang.Object)
32
	 */
33
	public boolean contains(Object arg0) {
34
		return this.exceptions.contains(arg0);
35
	}
36

  
37
	/* (non-Javadoc)
38
	 * @see java.util.Collection#toArray()
39
	 */
40
	public Object[] toArray() {
41
		return this.exceptions.toArray();
42
	}
43

  
44
	/**
45
	 * @param arg0
46
	 * @return
47
	 */
48
	public Object[] toArray(Object[] arg0) {
49
		return this.exceptions.toArray(arg0);
50
	}
51

  
52
	/**
53
	 * @param arg0
54
	 * @return
55
	 */
56
	public boolean add(Object arg0) {
57
		return this.exceptions.add(arg0);
58
	}
59

  
60
	/* (non-Javadoc)
61
	 * @see java.util.Collection#remove(java.lang.Object)
62
	 */
63
	public boolean remove(Object arg0) {
64
		return this.exceptions.remove(arg0);
65
	}
66

  
67
	/**
68
	 * @param arg0
69
	 * @return
70
	 */
71
	public boolean containsAll(Collection arg0) {
72
		return this.exceptions.contains(arg0);
73
	}
74

  
75
	/**
76
	 * @param arg0
77
	 * @return
78
	 */
79
	public boolean addAll(Collection arg0) {
80
		return this.exceptions.addAll(arg0);
81
	}
82

  
83
	/**
84
	 * @param arg0
85
	 * @param arg1
86
	 * @return
87
	 */
88
	public boolean addAll(int arg0, Collection arg1) {
89
		return this.exceptions.addAll(arg0, arg1);
90
	}
91

  
92
	/**
93
	 * @param arg0
94
	 * @return
95
	 */
96
	public boolean removeAll(Collection arg0) {
97
		return this.exceptions.removeAll(arg0);
98
	}
99

  
100
	/**
101
	 * @param arg0
102
	 * @return
103
	 */
104
	public boolean retainAll(Collection arg0) {
105
		return this.exceptions.retainAll(arg0);
106
	}
107

  
108
	/* (non-Javadoc)
109
	 * @see java.util.Collection#clear()
110
	 */
111
	public void clear() {
112
		this.exceptions.clear();
113
	}
114

  
115
	/* (non-Javadoc)
116
	 * @see java.util.List#get(int)
117
	 */
118
	public Object get(int arg0) {
119
		return this.exceptions.get(arg0);
120
	}
121

  
122
	/**
123
	 * @param arg0
124
	 * @param arg1
125
	 * @return
126
	 */
127
	public Object set(int arg0, Object arg1) {
128
		return this.exceptions.set(arg0, arg1);
129
	}
130

  
131
	/**
132
	 * @param arg0
133
	 * @param arg1
134
	 */
135
	public void add(int arg0, Object arg1) {
136
		this.exceptions.add(arg0, arg1);
137
	}
138

  
139
	/* (non-Javadoc)
140
	 * @see java.util.List#remove(int)
141
	 */
142
	public Object remove(int arg0) {
143
		return this.exceptions.remove(arg0);
144
	}
145

  
146
	/* (non-Javadoc)
147
	 * @see java.util.List#indexOf(java.lang.Object)
148
	 */
149
	public int indexOf(Object arg0) {
150
		return this.exceptions.indexOf(arg0);
151
	}
152

  
153
	/* (non-Javadoc)
154
	 * @see java.util.List#lastIndexOf(java.lang.Object)
155
	 */
156
	public int lastIndexOf(Object arg0) {
157
		return this.exceptions.lastIndexOf(arg0);
158
	}
159

  
160
	/* (non-Javadoc)
161
	 * @see java.util.List#listIterator()
162
	 */
163
	public ListIterator listIterator() {
164
		return this.exceptions.listIterator();
165
	}
166

  
167
	/* (non-Javadoc)
168
	 * @see java.util.List#listIterator(int)
169
	 */
170
	public ListIterator listIterator(int arg0) {
171
		return this.exceptions.listIterator(arg0);
172
	}
173

  
174
	/* (non-Javadoc)
175
	 * @see java.util.List#subList(int, int)
176
	 */
177
	public List subList(int arg0, int arg1) {
178
		return this.exceptions.subList(arg0, arg1);
179
	}
180
	
181
	/* (non-Javadoc)
182
	 * @see java.lang.Throwable#getMessage()
183
	 */
184
	public String getMessage() {
185
		String msg = super.getMessage();
186
		Exception bex;
187
		Iterator iter=this.exceptions.iterator();
188
		while (iter.hasNext()) {
189
			bex = (Exception) iter.next();
190
			msg = msg + "\n  " + bex.getMessage();
191
		}
192
		return msg;
193
	}
194
	
195
	/* (non-Javadoc)
196
	 * @see org.gvsig.exceptions.IBaseException#getLocalizedMessage(org.gvsig.exceptions.IExceptionTranslator, int)
197
	 */
198
	public String getLocalizedMessage(IExceptionTranslator exceptionTranslator, int indent) {
199
		String msg = super.getLocalizedMessage(exceptionTranslator, indent);
200
		Exception bex;
201
		Iterator iter=this.exceptions.iterator();
202
		while (iter.hasNext()) {
203
			bex = (Exception) iter.next();
204
			if( bex instanceof BaseException ) {
205
				msg = msg + "\n  " + ((BaseException)bex).getLocalizedMessage(exceptionTranslator, indent);				
206
			} else {
207
				msg = msg + "\n  " + bex.getLocalizedMessage();
208
			}
209
		}
210
		return BaseException.insertBlanksAtStart(msg,indent);
211
	}
212

  
213
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/org/gvsig/exceptions/BaseException.java
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.gvsig.compatible.StringUtil;
8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10

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

  
32

  
33
	protected String messageKey;
34

  
35
	protected String formatString;
36

  
37
	/**
38
	 * Unique code of error.
39
	 */
40
	protected long code;
41

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

  
86
	/* (non-Javadoc)
87
	 * @see java.lang.Throwable#getMessage()
88
	 */
89
	public String getMessage() {
90
		return format(this.formatString, values());
91
	}
92

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

  
100
	/* (non-Javadoc)
101
	 * @see java.lang.Throwable#getLocalizedMessage()
102
	 */
103
	public String getLocalizedMessage() {
104
		return getLocalizedMessage(translator,0);
105
	}
106

  
107
	/* (non-Javadoc)
108
	 * @see org.gvsig.exceptions.IBaseException#getLocalizedMessage(org.gvsig.exceptions.IExceptionTranslator, int)
109
	 */
110
	public String getLocalizedMessage(IExceptionTranslator translator, int indent){
111

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

  
129
	/* (non-Javadoc)
130
	 * @see org.gvsig.exceptions.IBaseException#getMessageStack()
131
	 */
132
	public String getMessageStack() {
133
		return getMessageStack(0);
134
	}
135

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

  
165

  
166
	/* (non-Javadoc)
167
	 * @see org.gvsig.exceptions.IBaseException#getLocalizedMessageStack()
168
	 */
169
	public String getLocalizedMessageStack() {
170
		return getLocalizedMessageStack(BaseException.translator,0);
171
	}
172

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

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

  
216
	/* (non-Javadoc)
217
	 * @see org.gvsig.exceptions.IBaseException#getCode()
218
	 */
219
	public long getCode() {
220
		return this.code;
221
	}
222

  
223
	/**
224
	 * Sets the exception's code.
225
	 */
226
	public void setCode(long code) {
227
		this.code = code;
228
	}
229

  
230
	/* (non-Javadoc)
231
	 * @see org.gvsig.exceptions.IBaseException#getFormatString()
232
	 */
233
	public String getFormatString() {
234
		return this.formatString;
235
	}
236

  
237
	/**
238
	 * Sets the format string.
239
	 *
240
	 * @param formatString
241
	 */
242
	public void setFormatString(String formatString) {
243
		this.formatString = formatString;
244
	}
245

  
246
	/* (non-Javadoc)
247
	 * @see org.gvsig.exceptions.IBaseException#getMessageKey()
248
	 */
249
	public String getMessageKey() {
250
		return this.messageKey;
251
	}
252

  
253
	/**
254
	 * Sets the property messageKey.
255
	 *
256
	 * @param messageKey
257
	 */
258
	public void setMessageKey(String messageKey) {
259
		this.messageKey = messageKey;
260
	}
261

  
262
	/* (non-Javadoc)
263
	 * @see org.gvsig.exceptions.IBaseException#iterator()
264
	 */
265
	public Iterator iterator() {
266
		return new BaseExceptionIterator(this);
267
	}
268

  
269
	/**
270
	 * @return A map that serves to replace in the format string
271
	 * the keys with the corresponding values.
272
	 */
273
	abstract protected Map values();
274

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

  
284
	public static void setTranslator(Object translator){
285
		BaseException.translator = new TranslatorWraper(translator);
286
	}
287

  
288
	public String toString(){
289
		return format(this.formatString, values());
290
	}
291

  
292
}
293

  
294
class TranslatorWraper implements IExceptionTranslator {
295

  
296
	private Object translator = null;
297
	private Method method = null;
298

  
299
	public TranslatorWraper(Object translator) {
300
		Class theClass = translator.getClass();
301
		String s = "";
302

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

  
310
	}
311

  
312
	public String getText(String key) {
313
		try {
314
			return (String)(method.invoke(translator,new String[] { key }));
315
		} catch (Exception e) {
316
			return key;
317
		}
318
	}
319

  
320
}
branches/Mobile_Compatible_Hito_1/libExceptions/src/log4j.properties
1
# Set root logger level to DEBUG and its only appender to A1.
2
log4j.rootLogger=DEBUG, A1
3

  
4
# A1 is set to be a ConsoleAppender.
5
log4j.appender.A1=org.apache.log4j.ConsoleAppender
6

  
7
# A1 uses PatternLayout.
8
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
9
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c{1} %x - %m%n

Also available in: Unified diff