Revision 4539

View differences:

tags/AS_STABLE/libraries/libDriverManager/.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="output" path="bin"/>
6
</classpath>
0 7

  
tags/AS_STABLE/libraries/libDriverManager/.project
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>libDriverManager</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.jdt.core.javabuilder</name>
10
			<arguments>
11
			</arguments>
12
		</buildCommand>
13
		<buildCommand>
14
			<name>de.loskutov.FileSync.FSBuilder</name>
15
			<arguments>
16
			</arguments>
17
		</buildCommand>
18
	</buildSpec>
19
	<natures>
20
		<nature>org.eclipse.jdt.core.javanature</nature>
21
	</natures>
22
</projectDescription>
0 23

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/pruebas/DriverManagerMain.java
1
package com.hardcode.driverManager.pruebas;
2

  
3
import java.io.File;
4
import java.io.IOException;
5

  
6
import com.hardcode.driverManager.DriverLoadException;
7
import com.hardcode.driverManager.DriverManager;
8

  
9
/**
10
 * @author Fernando Gonz?lez Cort?s
11
 */
12
public class DriverManagerMain {
13

  
14
	public static void main(String[] args) throws IOException, DriverLoadException {
15
		DriverManager dm = new DriverManager();
16
		dm.loadDrivers(new File ("c:\\tirar\\"));
17
		Adder a = (Adder) dm.getDriver("num");
18
		System.out.println(a.add("3", "4"));
19
		a = (Adder) dm.getDriver("txt");
20
		System.out.println(a.add("3", "4"));
21
	}
22
}
0 23

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/pruebas/NumericAdderDriver.java
1
package com.hardcode.driverManager.pruebas;
2

  
3
import com.hardcode.driverManager.Driver;
4

  
5
/**
6
 * @author Fernando Gonz?lez Cort?s
7
 */
8
public class NumericAdderDriver implements Driver, Adder{
9

  
10
	/**
11
	 * @see com.hardcode.driverManager.pruebas.Adder#add(java.lang.String, java.lang.String)
12
	 */
13
	public String add(String a, String b) {
14
		return new Integer(new Integer(a).intValue() + new Integer(b).intValue()).toString();
15
	}
16

  
17
	/**
18
	 * @see com.hardcode.driverManager.Driver#getName()
19
	 */
20
	public String getName() {
21
		return "drivers para n?meros del Fernan";
22
	}
23

  
24
}
0 25

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/pruebas/Adder.java
1
package com.hardcode.driverManager.pruebas;
2

  
3
/**
4
 * @author Fernando Gonz?lez Cort?s
5
 */
6
public interface Adder {
7

  
8
	public String add(String a, String b);
9

  
10
}
0 11

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/pruebas/TextAdderDriver.java
1
package com.hardcode.driverManager.pruebas;
2

  
3
import com.hardcode.driverManager.Driver;
4

  
5
/**
6
 * @author Fernando Gonz?lez Cort?s
7
 */
8
public class TextAdderDriver implements Driver, Adder{
9

  
10
	/**
11
	 * @see com.hardcode.driverManager.pruebas.Adder#add(java.lang.String, java.lang.String)
12
	 */
13
	public String add(String a, String b) {
14
		return a+b;
15
	}
16

  
17
	/**
18
	 * @see com.hardcode.driverManager.Driver#getName()
19
	 */
20
	public String getName() {
21
		return "Driver para texto del Fernan";
22
	}
23

  
24
}
0 25

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/DriverClassLoaderManager.java
1
package com.hardcode.driverManager;
2

  
3
import java.util.Hashtable;
4
import java.util.Vector;
5

  
6

  
7
/**
8
 * Esta clase mantiene la informaci?n sobre los classloader de los plugins con
9
 * la intenci?n de poder obtener dado el nombre de una clase la lista de
10
 * PluginClassLoader que pueden cargarla
11
 *
12
 * @author Fernando Gonz?lez Cort?s
13
 */
14
public abstract class DriverClassLoaderManager {
15
    private static Hashtable nombresLista = new Hashtable();
16

  
17
    /**
18
     * Registra un class loader para una clase determinada
19
     *
20
     * @param className Nombre de la clase
21
     * @param cl Classloader que puede cargar la clase
22
     */
23
    public static void registerClass(String className, ClassLoader cl) {
24
        Vector lista = (Vector) nombresLista.get(className);
25

  
26
        if (lista == null) {
27
            lista = new Vector();
28
            lista.add(cl);
29
            nombresLista.put(className, lista);
30
        } else {
31
            lista.add(cl);
32
        }
33
    }
34

  
35
    /**
36
     * Devuelve la lista de classloader que pueden cargar la clase
37
     *
38
     * @param className Nombre de la clase de la cual se quiere obtener un
39
     *        classloader que la cargue
40
     *
41
     * @return Vector de classLoaders que pueden cargar una clase con ese
42
     *         nombre
43
     */
44
    public static Vector getClassLoaderList(String className) {
45
        return (Vector) nombresLista.get(className);
46
    }
47
}
0 48

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/DriverManager.java
1
package com.hardcode.driverManager;
2

  
3
import java.io.File;
4
import java.io.IOException;
5

  
6
import java.net.MalformedURLException;
7
import java.net.URL;
8

  
9
import java.util.ArrayList;
10
import java.util.HashMap;
11
import java.util.Iterator;
12

  
13

  
14
/**
15
 * Para el driver manager, el driver viene determinado por un directorio dentro
16
 * del cual se encuentran uno o m?s jar's. La clase Driver ha de implementar
17
 * la interfaz Driver y su nombre debe terminar en "Driver" y tener un
18
 * constructor sin par?metros.
19
 * 
20
 * <p>
21
 * Esta clase es la encargada de la carga y validaci?n de los drivers y de la
22
 * obtenci?n de los mismo apartir de un tipo
23
 * </p>
24
 *
25
 * @author Fernando Gonz?lez Cort?s
26
 */
27
public class DriverManager {
28
	private File extDir;
29
	private DriverValidation validation;
30
	private HashMap nombreDriverClass = new HashMap();
31
	private ArrayList failures = new ArrayList();
32

  
33
	/**
34
	 * Devuelve un array con los directorios de los plugins
35
	 *
36
	 * @param dirExt Directorio a partir del que se cuelgan los directorios de
37
	 * 		  los drivers
38
	 *
39
	 * @return Array de los subdirectorios
40
	 */
41
	private File[] getPluginDirs(File dirExt) {
42
		if (!dirExt.exists()) {
43
			return new File[0];
44
		}
45

  
46
		ArrayList ret = new ArrayList();
47
		File[] files = dirExt.listFiles();
48

  
49
		for (int i = 0; i < files.length; i++) {
50
			if (files[i].isDirectory()) {
51
				ret.add(files[i]);
52
			}
53
		}
54

  
55
		return (File[]) ret.toArray(new File[0]);
56
	}
57

  
58
	/**
59
	 * Obtiene los jar's de un directorio y los devuelve en un array
60
	 *
61
	 * @param dir Directorio del que se quieren obtener los jars
62
	 *
63
	 * @return Array de jars
64
	 */
65
	private URL[] getJars(File dir) {
66
		ArrayList ret = new ArrayList();
67
		File[] dirContent = dir.listFiles();
68

  
69
		for (int i = 0; i < dirContent.length; i++) {
70
			if (dirContent[i].getName().toLowerCase().endsWith(".jar")) {
71
				try {
72
					ret.add(new URL("file:" + dirContent[i].getAbsolutePath()));
73
				} catch (MalformedURLException e) {
74
					//No se puede dar
75
				}
76
			}
77
		}
78

  
79
		return (URL[]) ret.toArray(new URL[0]);
80
	}
81

  
82
	/**
83
	 * Carga los drivers y asocia con el tipo del driver.
84
	 *
85
	 * @param dir Directorio ra?z de los drivers
86
	 */
87
	public void loadDrivers(File dir) {
88
		try {
89
			if (validation == null) {
90
				validation = new DriverValidation() {
91
							public boolean validate(Driver d) {
92
								return true;
93
							}
94
						};
95
			}
96

  
97
			//Se obtiene la lista de directorios
98
			File[] dirs = getPluginDirs(dir);
99

  
100
			//Para cada directorio se obtienen todos sus jars
101
			for (int i = 0; i < dirs.length; i++) {
102
				URL[] jars = getJars(dirs[i]);
103

  
104
				//Se crea el classloader
105
				DriverClassLoader cl = new DriverClassLoader(jars,
106
						dirs[i].getAbsolutePath(),
107
						this.getClass().getClassLoader());
108

  
109
				//Se obtienen los drivers
110
				Class[] drivers = cl.getDrivers();
111

  
112
				//Se asocian los drivers con su tipo si superan la validaci?n
113
				for (int j = 0; j < drivers.length; j++) {
114
					try {
115
						Driver driver = (Driver) drivers[j].newInstance();
116

  
117
						if (validation.validate(driver)) {
118
							if (nombreDriverClass.put(driver.getName(),
119
										drivers[j]) != null) {
120
								throw new IllegalStateException(
121
									"Two drivers with the same name");
122
							}
123
						}
124
					} catch (ClassCastException e) {
125
						/*
126
						 * No todos los que terminan en Driver son drivers
127
						 * de los nuestros, los ignoramos
128
						 */
129
					} catch (Throwable t) {
130
						/*
131
						 * A?n a riesgo de capturar algo que no debemos, ignoramos cualquier driver que pueda
132
						 * dar cualquier tipo de problema, pero continuamos
133
						 */
134
						failures.add(t);
135
					}
136
				}
137
			}
138
		} catch (ClassNotFoundException e) {
139
			failures.add((Throwable) e);
140
		} catch (IOException e) {
141
			failures.add((Throwable) e);
142
		}
143
	}
144

  
145
	/**
146
	 * DOCUMENT ME!
147
	 *
148
	 * @return DOCUMENT ME!
149
	 */
150
	public Throwable[] getLoadFailures() {
151
		return (Throwable[]) failures.toArray(new Throwable[0]);
152
	}
153

  
154
	/**
155
	 * Obtiene el Driver asociado al tipo que se le pasa como par?metro
156
	 *
157
	 * @param name Objeto que devolvi? alguno de los drivers en su m?todo
158
	 * 		  getType
159
	 *
160
	 * @return El driver asociado o null si no se encuentra el driver
161
	 *
162
	 * @throws DriverLoadException if this Class represents an abstract class,
163
	 * 		   an interface, an array class, a primitive type, or void; or if
164
	 * 		   the class has no nullary constructor; or if the instantiation
165
	 * 		   fails for some other reason
166
	 */
167
	public Driver getDriver(String name) throws DriverLoadException {
168
		try {
169
			Class driverClass = (Class) nombreDriverClass.get(name);
170
			if (driverClass == null) throw new DriverLoadException("No se encontr? el driver: " + name);
171
			return (Driver) driverClass.newInstance();
172
		} catch (InstantiationException e) {
173
			throw new DriverLoadException(e);
174
		} catch (IllegalAccessException e) {
175
			throw new DriverLoadException(e);
176
		}
177
	}
178

  
179
	/**
180
	 * Establece el objeto validador de los drivers. En la carga se comprobar?
181
	 * si cada driver es v?lido mediante el m?todo validate del objeto
182
	 * validation establecido con este m?todo. Pro defecto se validan todos
183
	 * los drivers
184
	 *
185
	 * @param validation objeto validador
186
	 */
187
	public void setValidation(DriverValidation validation) {
188
		this.validation = validation;
189
	}
190

  
191
	/**
192
	 * Obtiene los tipos de todos los drivers del sistema
193
	 *
194
	 * @return DOCUMENT ME!
195
	 */
196
	public String[] getDriverNames() {
197
		ArrayList names = new ArrayList(nombreDriverClass.size());
198

  
199
		Iterator iterator = nombreDriverClass.keySet().iterator();
200

  
201
		while (iterator.hasNext()) {
202
			names.add((String) iterator.next());
203
		}
204

  
205
		return (String[]) names.toArray(new String[0]);
206
	}
207

  
208
	/**
209
	 * Obtiene la clase del driver relacionado con el tipo que se pasa como
210
	 * par?metro
211
	 *
212
	 * @param driverName DOCUMENT ME!
213
	 *
214
	 * @return DOCUMENT ME!
215
	 */
216
	public Class getDriverClassByName(String driverName) {
217
		return (Class) nombreDriverClass.get(driverName);
218
	}
219

  
220
	/**
221
	 * DOCUMENT ME!
222
	 *
223
	 * @param driverName DOCUMENT ME!
224
	 * @param superClass DOCUMENT ME!
225
	 *
226
	 * @return DOCUMENT ME!
227
	 *
228
	 * @throws RuntimeException DOCUMENT ME!
229
	 */
230
	public boolean isA(String driverName, Class superClass) {
231
		Class driverClass = (Class) nombreDriverClass.get(driverName);
232

  
233
		if (driverClass == null) {
234
			throw new RuntimeException("No such driver");
235
		}
236

  
237
		Class[] interfaces = driverClass.getInterfaces();
238

  
239
		if (interfaces != null) {
240
			for (int i = 0; i < interfaces.length; i++) {
241
				if (interfaces[i] == superClass) {
242
					return true;
243
				} else {
244
					if (recursiveIsA(interfaces[i], superClass)) {
245
						return true;
246
					}
247
				}
248
			}
249
		}
250

  
251
		Class class_ = driverClass.getSuperclass();
252

  
253
		if (class_ != null) {
254
			if (class_ == superClass) {
255
				return true;
256
			} else {
257
				if (recursiveIsA(class_, superClass)) {
258
					return true;
259
				}
260
			}
261
		}
262

  
263
		return false;
264
	}
265

  
266
	/**
267
	 * DOCUMENT ME!
268
	 *
269
	 * @param interface_ DOCUMENT ME!
270
	 * @param superInterface DOCUMENT ME!
271
	 *
272
	 * @return DOCUMENT ME!
273
	 */
274
	private boolean recursiveIsA(Class interface_, Class superInterface) {
275
		Class[] interfaces = interface_.getInterfaces();
276

  
277
		if (interfaces != null) {
278
			for (int i = 0; i < interfaces.length; i++) {
279
				if (interfaces[i] == superInterface) {
280
					return true;
281
				} else {
282
					if (recursiveIsA(interfaces[i], superInterface)) {
283
						return true;
284
					}
285
				}
286
			}
287
		}
288

  
289
		Class class_ = interface_.getSuperclass();
290

  
291
		if (class_ != null) {
292
			if (class_ == superInterface) {
293
				return true;
294
			} else {
295
				if (recursiveIsA(class_, superInterface)) {
296
					return true;
297
				}
298
			}
299
		}
300

  
301
		return false;
302
	}
303
}
0 304

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/DriverValidation.java
1
package com.hardcode.driverManager;
2

  
3
/**
4
 * Interfaz a implementar por los objetos de validaci?n
5
 *
6
 * @author Fernando Gonz?lez Cort?s
7
 */
8
public interface DriverValidation {
9
    /**
10
     * El m?todo validate se invocar? al crear los drivers, y ser? el validador
11
     * el que indicar? qu? driver es v?lido para la aplicaci?n y cual no
12
     *
13
     * @param d Driver a validar
14
     *
15
     * @return true o false en caso de que el driver sea o no sea valido
16
     */
17
    public boolean validate(Driver d);
18
}
0 19

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/WriterManager.java
1
package com.hardcode.driverManager;
2

  
3
import java.io.File;
4
import java.io.IOException;
5

  
6
import java.net.MalformedURLException;
7
import java.net.URL;
8

  
9
import java.util.ArrayList;
10
import java.util.HashMap;
11
import java.util.Iterator;
12

  
13

  
14
/**
15
 * Para el writer manager, el writer viene determinado por un directorio dentro
16
 * del cual se encuentran uno o m?s jar's. La clase Writer ha de implementar
17
 * la interfaz Writer y su nombre debe terminar en "Writer" y tener un
18
 * constructor sin par?metros.
19
 *
20
 * <p>
21
 * Esta clase es la encargada de la carga y validaci?n de los writers y de la
22
 * obtenci?n de los mismo apartir de un tipo
23
 * </p>
24
 *
25
 * @author Vicente Caballero Navarro
26
 */
27
public class WriterManager {
28
	private DriverValidation validation;
29
	private HashMap nombreWriterClass = new HashMap();
30
	private ArrayList failures = new ArrayList();
31

  
32
	/**
33
	 * Devuelve un array con los directorios de los plugins
34
	 *
35
	 * @param dirExt Directorio a partir del que se cuelgan los directorios de
36
	 * 		  los drivers
37
	 *
38
	 * @return Array de los subdirectorios
39
	 */
40
	private File[] getPluginDirs(File dirExt) {
41
		if (!dirExt.exists()) {
42
			return new File[0];
43
		}
44

  
45
		ArrayList ret = new ArrayList();
46
		File[] files = dirExt.listFiles();
47

  
48
		for (int i = 0; i < files.length; i++) {
49
			if (files[i].isDirectory()) {
50
				ret.add(files[i]);
51
			}
52
		}
53

  
54
		return (File[]) ret.toArray(new File[0]);
55
	}
56

  
57
	/**
58
	 * Obtiene los jar's de un directorio y los devuelve en un array
59
	 *
60
	 * @param dir Directorio del que se quieren obtener los jars
61
	 *
62
	 * @return Array de jars
63
	 */
64
	private URL[] getJars(File dir) {
65
		ArrayList ret = new ArrayList();
66
		File[] dirContent = dir.listFiles();
67

  
68
		for (int i = 0; i < dirContent.length; i++) {
69
			if (dirContent[i].getName().toLowerCase().endsWith(".jar")) {
70
				try {
71
					ret.add(new URL("file:" + dirContent[i].getAbsolutePath()));
72
				} catch (MalformedURLException e) {
73
					//No se puede dar
74
				}
75
			}
76
		}
77

  
78
		return (URL[]) ret.toArray(new URL[0]);
79
	}
80

  
81
	/**
82
	 * Carga los drivers y asocia con el tipo del driver.
83
	 *
84
	 * @param dir Directorio ra?z de los drivers
85
	 */
86
	public void loadWriters(File dir) {
87
		try {
88
			if (validation == null) {
89
				validation = new DriverValidation() {
90
							public boolean validate(Driver d) {
91
								return true;
92
							}
93
						};
94
			}
95

  
96
			//Se obtiene la lista de directorios
97
			File[] dirs = getPluginDirs(dir);
98

  
99
			//Para cada directorio se obtienen todos sus jars
100
			for (int i = 0; i < dirs.length; i++) {
101
				URL[] jars = getJars(dirs[i]);
102

  
103
				//Se crea el classloader
104
				DriverClassLoader cl = new DriverClassLoader(jars,
105
						dirs[i].getAbsolutePath(),
106
						this.getClass().getClassLoader());
107

  
108
				//Se obtienen los drivers
109
				Class[] writers = cl.getWriters();
110

  
111
				//Se asocian los drivers con su tipo si superan la validaci?n
112
				for (int j = 0; j < writers.length; j++) {
113
					try {
114
						Driver driver = (Driver) writers[j].newInstance();
115

  
116
						if (validation.validate(driver)) {
117
							if (nombreWriterClass.put(driver.getName(),
118
										writers[j]) != null) {
119
								throw new IllegalStateException(
120
									"Two drivers with the same name");
121
							}
122
						}
123
					} catch (ClassCastException e) {
124
						/*
125
						 * No todos los que terminan en Driver son drivers
126
						 * de los nuestros, los ignoramos
127
						 */
128
					} catch (Throwable t) {
129
						/*
130
						 * A?n a riesgo de capturar algo que no debemos, ignoramos cualquier driver que pueda
131
						 * dar cualquier tipo de problema, pero continuamos
132
						 */
133
						failures.add(t);
134
					}
135
				}
136
			}
137
		} catch (ClassNotFoundException e) {
138
			failures.add((Throwable) e);
139
		} catch (IOException e) {
140
			failures.add((Throwable) e);
141
		}
142
	}
143
	/**
144
	 * DOCUMENT ME!
145
	 *
146
	 * @return DOCUMENT ME!
147
	 */
148
	public Throwable[] getLoadFailures() {
149
		return (Throwable[]) failures.toArray(new Throwable[0]);
150
	}
151

  
152
	/**
153
	 * Obtiene el Writer asociado al tipo que se le pasa como par?metro
154
	 *
155
	 * @param name Objeto que devolvi? alguno de los writers en su m?todo
156
	 * 		  getType
157
	 *
158
	 * @return El writer asociado o null si no se encuentra el driver
159
	 *
160
	 * @throws DriverLoadException if this Class represents an abstract class,
161
	 * 		   an interface, an array class, a primitive type, or void; or if
162
	 * 		   the class has no nullary constructor; or if the instantiation
163
	 * 		   fails for some other reason
164
	 */
165
	public Driver getWriter(String name) throws DriverLoadException {
166
		try {
167
			Class driverClass = (Class) nombreWriterClass.get(name);
168
			if (driverClass == null) throw new DriverLoadException("No se encontr? el writer: " + name);
169
			return (Driver) driverClass.newInstance();
170
		} catch (InstantiationException e) {
171
			throw new DriverLoadException(e);
172
		} catch (IllegalAccessException e) {
173
			throw new DriverLoadException(e);
174
		}
175
	}
176

  
177
	/**
178
	 * Establece el objeto validador de los drivers. En la carga se comprobar?
179
	 * si cada driver es v?lido mediante el m?todo validate del objeto
180
	 * validation establecido con este m?todo. Pro defecto se validan todos
181
	 * los drivers
182
	 *
183
	 * @param validation objeto validador
184
	 */
185
	public void setValidation(DriverValidation validation) {
186
		this.validation = validation;
187
	}
188

  
189
	/**
190
	 * Obtiene los tipos de todos los writers del sistema
191
	 *
192
	 * @return DOCUMENT ME!
193
	 */
194
	public String[] getWriterNames() {
195
		ArrayList names = new ArrayList(nombreWriterClass.size());
196

  
197
		Iterator iterator = nombreWriterClass.keySet().iterator();
198

  
199
		while (iterator.hasNext()) {
200
			names.add((String) iterator.next());
201
		}
202

  
203
		return (String[]) names.toArray(new String[0]);
204
	}
205

  
206
	/**
207
	 * Obtiene la clase del writer relacionado con el tipo que se pasa como
208
	 * par?metro
209
	 *
210
	 * @param driverName DOCUMENT ME!
211
	 *
212
	 * @return DOCUMENT ME!
213
	 */
214
	public Class getWriterClassByName(String writerName) {
215
		return (Class) nombreWriterClass.get(writerName);
216
	}
217

  
218
	/**
219
	 * DOCUMENT ME!
220
	 *
221
	 * @param writerName DOCUMENT ME!
222
	 * @param superClass DOCUMENT ME!
223
	 *
224
	 * @return DOCUMENT ME!
225
	 *
226
	 * @throws RuntimeException DOCUMENT ME!
227
	 */
228
	public boolean isA(String writerName, Class superClass) {
229
		Class writerClass = (Class) nombreWriterClass.get(writerName);
230

  
231
		if (writerClass == null) {
232
			throw new RuntimeException("No such driver");
233
		}
234

  
235
		Class[] interfaces = writerClass.getInterfaces();
236

  
237
		if (interfaces != null) {
238
			for (int i = 0; i < interfaces.length; i++) {
239
				if (interfaces[i] == superClass) {
240
					return true;
241
				} else {
242
					if (recursiveIsA(interfaces[i], superClass)) {
243
						return true;
244
					}
245
				}
246
			}
247
		}
248

  
249
		Class class_ = writerClass.getSuperclass();
250

  
251
		if (class_ != null) {
252
			if (class_ == superClass) {
253
				return true;
254
			} else {
255
				if (recursiveIsA(class_, superClass)) {
256
					return true;
257
				}
258
			}
259
		}
260

  
261
		return false;
262
	}
263

  
264
	/**
265
	 * DOCUMENT ME!
266
	 *
267
	 * @param interface_ DOCUMENT ME!
268
	 * @param superInterface DOCUMENT ME!
269
	 *
270
	 * @return DOCUMENT ME!
271
	 */
272
	private boolean recursiveIsA(Class interface_, Class superInterface) {
273
		Class[] interfaces = interface_.getInterfaces();
274

  
275
		if (interfaces != null) {
276
			for (int i = 0; i < interfaces.length; i++) {
277
				if (interfaces[i] == superInterface) {
278
					return true;
279
				} else {
280
					if (recursiveIsA(interfaces[i], superInterface)) {
281
						return true;
282
					}
283
				}
284
			}
285
		}
286

  
287
		Class class_ = interface_.getSuperclass();
288

  
289
		if (class_ != null) {
290
			if (class_ == superInterface) {
291
				return true;
292
			} else {
293
				if (recursiveIsA(class_, superInterface)) {
294
					return true;
295
				}
296
			}
297
		}
298

  
299
		return false;
300
	}
301
}
0 302

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/DriverClassLoader.java
1
package com.hardcode.driverManager;
2

  
3
import java.io.DataInputStream;
4
import java.io.File;
5
import java.io.IOException;
6
import java.io.InputStream;
7

  
8
import java.net.MalformedURLException;
9
import java.net.URL;
10
import java.net.URLClassLoader;
11

  
12
import java.security.AllPermission;
13
import java.security.CodeSource;
14
import java.security.PermissionCollection;
15
import java.security.Permissions;
16

  
17
import java.util.ArrayList;
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import java.util.List;
21
import java.util.StringTokenizer;
22
import java.util.Vector;
23
import java.util.jar.JarException;
24
import java.util.zip.ZipEntry;
25
import java.util.zip.ZipFile;
26

  
27

  
28
/**
29
 * Class loader que carga las clases pedidas por los plugins de manera que
30
 * primero busca en el classpath, luego busca en el directorio del propio
31
 * plugin en los jars especificados por el xml y en caso de no encontrar la
32
 * clase pide al PluginClassLoaderManager la lista de plugins que pueden
33
 * satisfacer la clase e intenta cargarlo con cada un de ellos hasta que lo
34
 * consigue con uno.
35
 *
36
 * @author Fernando Gonz?lez Cort?s
37
 */
38
public class DriverClassLoader extends URLClassLoader {
39
    private Hashtable clasesJar = new Hashtable();
40
    private String baseDir;
41

  
42
    /**
43
     * Creates a new PluginClassLoader object.
44
     *
45
     * @param jars Array con la ruta de los jars en los que buscar? las clases
46
     *        el plugin
47
     * @param baseDir Directorio base del plugin que se carga. Es en directorio
48
     *        donde se buscan los resources en el m?todo getResources
49
     * @param cl ClassLoader padre del classLoader, al que se le pedir?
50
     *        resolver las clases antes de utilizar el algoritmo propio
51
     *
52
     * @throws IOException Si no se puede leer alguno de los jars
53
     * @throws IllegalArgumentException Si no se especifica un array de jars
54
     * @throws JarException Si hay dos clases con el mismo nombre en el plugin
55
     */
56
    public DriverClassLoader(URL[] jars, String baseDir, ClassLoader cl)
57
        throws IOException {
58
        super(jars, cl);
59
        this.baseDir = baseDir;
60

  
61
        if (jars == null) {
62
            throw new IllegalArgumentException("jars cannot be null"); //$NON-NLS-1$
63
        }
64

  
65
        //Se itera por las URLS que deben de ser jar's
66
        ZipFile[] jarFiles = new ZipFile[jars.length];
67

  
68
        for (int i = 0; i < jars.length; i++) {
69
            jarFiles[i] = new ZipFile(jars[i].getPath());
70

  
71
            Enumeration entradas = jarFiles[i].entries();
72

  
73
            //Se itera por todos los .class del jar
74
            while (entradas.hasMoreElements()) {
75
                //Se obtiene la entrada
76
                ZipEntry file = (ZipEntry) entradas.nextElement();
77
                String fileName = file.getName();
78

  
79
                //Se obtiene el nombre de la clase
80
                if (!fileName.toLowerCase().endsWith(".class")) { //$NON-NLS-1$
81

  
82
                    continue;
83
                }
84

  
85
                fileName = fileName.substring(0, fileName.length() - 6).replace('/',
86
                        '.');
87

  
88
                //Se cromprueba si ya hab?a una clase con dicho nombre
89
                if (clasesJar.get(fileName) != null) {
90
                    throw new JarException(
91
                        "two or more classes with the same name in the jars: " +
92
                        fileName);
93
                }
94

  
95
                //Se registra la clase
96
                clasesJar.put(fileName, jarFiles[i]);
97
                DriverClassLoaderManager.registerClass(fileName, this);
98
            }
99
        }
100
    }
101

  
102
    /**
103
     * Carga la clase
104
     *
105
     * @param name Nombre de la clase
106
     * @param resolve SI se ha de resolver la clase o no
107
     *
108
     * @return Clase cargada
109
     *
110
     * @throws ClassNotFoundException Si no se pudo encontrar la clase
111
     */
112
    protected Class loadClass(String name, boolean resolve)
113
        throws ClassNotFoundException {
114
    	Class c = null;
115

  
116
        try {
117
            c = super.loadClass(name, resolve);
118
        } catch (ClassNotFoundException e1) {
119
            if (c == null) {
120
                // Convert class name argument to filename
121
                // Convert package names into subdirectories
122
                try {
123
                    ZipFile jar = (ZipFile) clasesJar.get(name);
124

  
125
                    if (jar == null) {
126
                        Vector cls = (Vector) DriverClassLoaderManager.getClassLoaderList(name);
127

  
128
                        if (cls != null) {
129
                            for (int i = 0; i < cls.size(); i++) {
130
                                c = ((DriverClassLoader) cls.elementAt(i)).loadClass(name,
131
                                        resolve);
132

  
133
                                if (c != null) {
134
                                    break;
135
                                }
136
                            }
137
                        }
138
                    } else {
139
                        String fileName = name.replace('.', '/') + ".class"; //$NON-NLS-1$
140
                        ZipEntry classFile = jar.getEntry(fileName);
141
                        byte[] data = loadClassData(classFile,
142
                                jar.getInputStream(classFile));
143

  
144
                        c = defineClass(name, data, 0, data.length);
145
                    }
146

  
147
                    if (c == null) {
148
                        throw new ClassNotFoundException(name);
149
                    }
150
                } catch (IOException e) {
151
                    throw new ClassNotFoundException("Error_reading_file" +
152
                        name); //$NON-NLS-1$
153
                }
154
            }
155
        }
156

  
157
        if (resolve) {
158
            resolveClass(c);
159
        }
160

  
161
        return c;
162
    }
163

  
164
    /**
165
     * obtiene el array de bytes de la clase
166
     *
167
     * @param classFile Entrada dentro del jar contiene los bytecodes de la
168
     *        clase (el .class)
169
     * @param is InputStream para leer la entrada del jar
170
     *
171
     * @return Bytes de la clase
172
     *
173
     * @throws IOException Si no se puede obtener el .class del jar
174
     */
175
    private byte[] loadClassData(ZipEntry classFile, InputStream is)
176
        throws IOException {
177
        // Get size of class file
178
        int size = (int) classFile.getSize();
179

  
180
        // Reserve space to read
181
        byte[] buff = new byte[size];
182

  
183
        // Get stream to read from
184
        DataInputStream dis = new DataInputStream(is);
185

  
186
        // Read in data
187
        dis.readFully(buff);
188

  
189
        // close stream
190
        dis.close();
191

  
192
        // return data
193
        return buff;
194
    }
195

  
196
    /**
197
     * Obtiene los recursos tomando como la raiz el directorio base del plugin.
198
     * Si no se encuentra el recurso ah? se invoca a getResource del
199
     * classloader padre, que buscar? en el jar de la aplicaci?n. Si ah?
200
     * tampoco se encuentra nada se devolver? null.
201
     *
202
     * @param res Nombre del recurso
203
     *
204
     * @return URL del recurso o null si no se pudo encontrar
205
     */
206
    public URL getResource(String res) {
207
        File dir = new File(baseDir);
208

  
209
        try {
210
            ArrayList resource = new ArrayList();
211
            StringTokenizer st = new StringTokenizer(res, "\\/");
212

  
213
            while (st.hasMoreTokens()) {
214
                String token = st.nextToken();
215
                resource.add(token);
216
            }
217

  
218
            URL ret = getResource(dir, resource);
219

  
220
            if (ret != null) {
221
                return ret;
222
            }
223
        } catch (Exception e) {
224
            e.printStackTrace();
225
        }
226

  
227
        return super.getResource(res);
228
    }
229

  
230
    /**
231
     * Busca recursivamente el recurso res en el directorio base. res es una
232
     * lista de String's con los directorios del path y base es el directorio
233
     * a partir del cual se busca dicho recurso. En cada ejecuci?n del m?todo
234
     * se toma el primer elemento de res y se busca dicho directorio en el
235
     * directorio base. Si se encuentra, ser? el directorio base para una
236
     * nueva llamada.
237
     *
238
     * @param base Directorio desde donde parte la b?squeda del recurso.
239
     * @param res Lista de strings con el path del recurso que se quiere
240
     *        encontrar
241
     *
242
     * @return URL con el recurso
243
     */
244
    private URL getResource(File base, List res) {
245
        File[] files = base.listFiles();
246

  
247
        String parte = (String) res.get(0);
248

  
249
        for (int i = 0; i < files.length; i++) {
250
            if (files[i].getName().compareTo(parte) == 0) {
251
                if (res.size() == 1) {
252
                    try {
253
                        return new URL("file:" + files[i].toString());
254
                    } catch (MalformedURLException e) {
255
                        return null;
256
                    }
257
                } else {
258
                    return getResource(files[i], res.subList(1, res.size()));
259
                }
260
            }
261
        }
262

  
263
        return null;
264
    }
265

  
266
    /**
267
     * Devuelve el nombre del directorio del plugin
268
     *
269
     * @return
270
     */
271
    public String getPluginName() {
272
        String ret = baseDir.substring(baseDir.lastIndexOf(File.separatorChar) +
273
                1);
274

  
275
        return ret;
276
    }
277

  
278
    /**
279
     * @see java.security.SecureClassLoader#getPermissions(java.security.CodeSource)
280
     */
281
    protected PermissionCollection getPermissions(CodeSource codesource) {
282
        Permissions perms = new Permissions();
283
        perms.add(new AllPermission());
284

  
285
        return (perms);
286
    }
287

  
288
    /**
289
     * Devuelve una instancia de cada driver encontrado en los jars del
290
     * classloader
291
     *
292
     * @return array de drivers
293
     *
294
     * @throws ClassNotFoundException if the class cannot be located by the
295
     *         specified class loader
296
     */
297
    public Class[] getDrivers() throws ClassNotFoundException{
298
        ArrayList drivers = new ArrayList();
299
        Enumeration e = clasesJar.keys();
300

  
301
        while (e.hasMoreElements()) {
302
            String fileName = (String) e.nextElement();
303

  
304
            if (fileName.endsWith("Driver")) {
305
                Class driver = (Class) this.loadClass(fileName);
306
                drivers.add(driver);
307
            }
308
        }
309

  
310
        return (Class[]) drivers.toArray(new Class[0]);
311
    }
312
    /**
313
     * Devuelve una instancia de cada writer encontrado en los jars del
314
     * classloader
315
     *
316
     * @return array de drivers
317
     *
318
     * @throws ClassNotFoundException if the class cannot be located by the
319
     *         specified class loader
320
     */
321
    public Class[] getWriters() throws ClassNotFoundException{
322
        ArrayList writers = new ArrayList();
323
        Enumeration e = clasesJar.keys();
324

  
325
        while (e.hasMoreElements()) {
326
            String fileName = (String) e.nextElement();
327

  
328
            if (fileName.endsWith("Writer")) {
329
                Class driver = (Class) this.loadClass(fileName);
330
                writers.add(driver);
331
            }
332
        }
333

  
334
        return (Class[]) writers.toArray(new Class[0]);
335
    }
336
}
0 337

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/DriverLoadException.java
1
package com.hardcode.driverManager;
2

  
3

  
4
public class DriverLoadException extends RuntimeException {
5

  
6
	/**
7
	 * 
8
	 */
9
	public DriverLoadException() {
10
		super();
11

  
12
	}
13
	/**
14
	 * @param message
15
	 */
16
	public DriverLoadException(String message) {
17
		super(message);
18

  
19
	}
20
	/**
21
	 * @param message
22
	 * @param cause
23
	 */
24
	public DriverLoadException(String message, Throwable cause) {
25
		super(message, cause);
26

  
27
	}
28
	/**
29
	 * @param cause
30
	 */
31
	public DriverLoadException(Throwable cause) {
32
		super(cause);
33

  
34
	}
35
}
0 36

  
tags/AS_STABLE/libraries/libDriverManager/src/com/hardcode/driverManager/Driver.java
1
package com.hardcode.driverManager;
2

  
3
/**
4
 * Interfaz que debe ser implementada por todos l
5
 *
6
 * @author Fernando Gonz?lez Cort?s
7
 */
8
public interface Driver {
9
    /**
10
     * Debe devolver un objeto que se asociar? en el manager al driver. El
11
     * DriverManager recibir? peticiones de un objeto y deber? devolver el
12
     * driver asociado
13
     *
14
     * @return Objeto asociado al driver. Se recomienda que sea un String
15
     */
16
    public String getName();
17
}
0 18

  
tags/AS_STABLE/libraries/libDriverManager/.cvsignore
1
bin
0 2

  
tags/AS_STABLE/libraries/libDriverManager/build.xml
1
<project name="Driver Manager" default="generar-jar" basedir=".">
2
	<description>
3
        Instala el plugin
4
    </description>
5
	<!-- set global properties for this build
6
	<property name="drivers-dir" location="../Andami/gvSIG/extensiones/com.iver.cit.gvsig/drivers" />-->
7

  
8
	<target name="init">
9
		<!-- Create the time stamp -->
10
		<tstamp />
11
	</target>
12

  
13
	<target name="generar-jar" depends="init" description="Genera los jars del driver manager">
14
		<jar jarfile="driver-manager-1.1.jar" basedir="./bin"/>
15
	</target>
16
</project>
0 17

  
tags/AS_STABLE/libraries/libCorePlugin/build.xml
1
<project name="Core plugin" default="dist" basedir=".">
2
    <description>
3
        Instala el plugin
4
    </description>
5
  <!-- set global properties for this build -->
6
  <property name="src" location="src"/>
7
  <property name="build" location="bin"/>
8
  <property name="dist"  location="dist"/>
9
  <property name="plugin" value="com.iver.core"/>
10
  <property name="targetDir" location="../_fwAndami/gvSIG/extensiones"/>
11

  
12
  <target name="init">
13
    <!-- Create the time stamp -->
14
    <tstamp/>
15
    <!-- Create the build directory structure used by compile -->
16
    <mkdir dir="${build}"/>
17
  </target>
18

  
19
  <target name="dist" description="generate the distribution" >
20
    <!-- Create the distribution directory -->
21
    <mkdir dir="${dist}"/>
22

  
23
    <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
24
    <copy todir="${build}">
25
    	<fileset dir="${src}" includes="**"/>
26
    </copy>
27
    <jar jarfile="${dist}/${plugin}.jar" basedir="${build}"/>
28
    <copy file="config.xml" todir="${dist}"/>
29
    <copy todir="${dist}">
30
    	<fileset dir="." includes="text*.properties"/>
31
    </copy>
32
    <copy todir="${dist}/images">
33
    	<fileset dir="images/" includes="*"/>
34
    </copy>
35
    <copy todir="${dist}">
36
    	<fileset dir="." includes="*.jar"/>
37
    </copy>
38

  
39
    <move todir="${targetDir}/${plugin}/">
40
    	<fileset dir="${dist}" includes="**/**"/>
41
    </move>
42
  </target>
43

  
44
  <target name="clean"
45
        description="clean up" >
46
    <!-- Delete the ${build} and ${dist} directory trees -->
47
    <delete dir="${build}"/>
48
    <delete dir="${dist}"/>
49
  </target>
50
</project>
51

  
0 52

  
tags/AS_STABLE/libraries/libCorePlugin/.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="lib" path="/_fwAndami/lib/log4j-1.2.8.jar"/>
6
	<classpathentry kind="src" path="/_fwAndami"/>
7
	<classpathentry kind="lib" path="/_fwAndami/lib/castor-0.9.5.3-xml.jar"/>
8
	<classpathentry kind="lib" path="/_fwAndami/lib/iver-utiles.jar"/>
9
	<classpathentry kind="output" path="bin"/>
10
</classpath>
0 11

  
tags/AS_STABLE/libraries/libCorePlugin/text_en.properties
1
#text_en.properties
2
__catalan=valencian
3
aceptar=OK
4
cancelar=Cancel
5
Cascada=Cascade
6
cascada_enable=There must be at least one visible window
7
cascada_tooltip=Arrange windows in cascade
8
Configurar=Configure
9
configurar_ANDAMI=ANDAMI configuration dialog.
10
Consola=Console
11
descripcion=Description
12
directorio=Directory
13
directorio_extensiones=Extensions directory.
14
errores=Errors
15
examinar=Examine
16
extension_activada=Active extension.  
17
general=General
18
info=Information
19
opciones=Options
20
prioridad=Priority
21
Tile=Tile
22
tile_tooltip=Arrange the windows in tile
23
titulo_consola=Information console
24
todos=All
25
ventana=Window
26
Ver=Show
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff