Revision 31567

View differences:

tags/tmp_build/libraries/libAuthenticationService/.project
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>libAuthenticationService</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
	</buildSpec>
14
	<natures>
15
		<nature>org.eclipse.jdt.core.javanature</nature>
16
	</natures>
17
</projectDescription>
0 18

  
tags/tmp_build/libraries/libAuthenticationService/src-test/org/gvsig/authentication/TestAuthentication.java
1
package org.gvsig.authentication;
2

  
3
import java.util.Hashtable;
4

  
5
import org.gvsig.authentication.Authentication;
6
import org.gvsig.authentication.exception.InvalidUserException;
7

  
8

  
9
import junit.framework.Assert;
10
import junit.framework.TestCase;
11

  
12
public class TestAuthentication extends TestCase {
13

  
14
	protected void setUp() throws Exception {
15
		super.setUp();
16
	}
17

  
18
	protected void tearDown() throws Exception {
19
		super.tearDown();
20
	}
21

  
22
	public void testLogin(){
23
		Authentication authentication = new Authentication();
24
		Assert.assertFalse(authentication.login("lau","laura")>-1);
25
	}
26
	
27
	public void testGetConfig(){
28
		Authentication authentication = new Authentication();
29
		try{
30
			
31
			Hashtable ht = authentication.getConfig("laura","laura");
32
			String map = (String)ht.get("mapserver_file" );
33
			Hashtable config= (Hashtable)ht.get("gvsig_config");
34
						
35
			Assert.assertTrue(map.compareTo("users.map")==0);
36
			Assert.assertTrue(((String)(config.get("plugin2"))).compareTo("users.config")==0);
37
			
38
		}catch(InvalidUserException e)
39
		{
40
			e.printStackTrace(); 
41
		}
42
	}
43
	
44
	public void testGetMapFile(){
45
		Authentication authentication = new Authentication();
46
		try{
47
			
48
			String userMap = authentication.getMapFile("laura","laura");
49
			String adminMap = authentication.getMapFile("admin","admin");
50
			Assert.assertTrue(userMap.compareTo("users.map")==0);
51
			Assert.assertTrue(adminMap.compareTo("administratormap.map")==0);
52
			
53
		}catch(InvalidUserException e)
54
		{
55
			e.printStackTrace(); 
56
		}
57
	}
58
	
59
	public void testGvSigConfig(){
60
		Authentication authentication = new Authentication();
61
		try{
62
			
63
			Hashtable userConfig = authentication.getGvSigConfig("laura","laura");
64
			Hashtable adminConfig = authentication.getGvSigConfig("admin","admin");
65
			Assert.assertTrue(((String)(userConfig.get("plugin2"))).compareTo("users.config")==0);
66
			Assert.assertTrue(((String)(adminConfig.get("plugin1"))).compareTo("administrator.config")==0);
67
			
68
		}catch(InvalidUserException e)
69
		{
70
			e.printStackTrace(); 
71
		}
72
	}	
73
}
0 74

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/exception/AuthenticationException.java
1
package org.gvsig.authentication.exception;
2

  
3
public class AuthenticationException extends Exception{
4
	
5
		private String as_message = null;
6
		
7

  
8
		public AuthenticationException() {
9
			super();
10
		}
11

  
12

  
13
		public AuthenticationException(String message) {
14
			super(message);
15
		}
16

  
17

  
18
		public AuthenticationException(String message, Throwable cause) {
19
			super(message, cause);
20
		}
21

  
22

  
23
		public AuthenticationException(Throwable cause) {
24
			super(cause);
25
		}
26
		
27
		public String getAuthenticationServiceExceptionMessage()
28
		{
29
			if (as_message == null)
30
				return "";
31
			else
32
				return as_message;
33
		}
34
		
35
		public void setAuthenticationServiceExceptionMessage(String mes)
36
		{
37
			as_message = mes;
38
		}
39
	}
0 40

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/exception/DBConnectionException.java
1
package org.gvsig.authentication.exception;
2

  
3
public class DBConnectionException extends AuthenticationException {	
4

  
5
		public DBConnectionException() {
6
			super();
7
		}
8

  
9
		public DBConnectionException(String message) {
10
			super(message);
11
		}
12

  
13
		public DBConnectionException(String message, Throwable cause) {
14
			super(message, cause);
15
		}
16

  
17

  
18
		public DBConnectionException(Throwable cause) {
19
			super(cause);
20
		}
21
		
22

  
23
	}
0 24

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/exception/InvalidUserException.java
1
package org.gvsig.authentication.exception;
2

  
3
/**
4
 * Exeption to be thrown when an invalid user/password is given
5
 * @author laura
6
 *
7
 */
8
public class InvalidUserException extends AuthenticationException {	
9

  
10
		public InvalidUserException() {
11
			super();
12
		}
13

  
14
		public InvalidUserException(String message) {
15
			super(message);
16
		}
17

  
18
		public InvalidUserException(String message, Throwable cause) {
19
			super(message, cause);
20
		}
21

  
22

  
23
		public InvalidUserException(Throwable cause) {
24
			super(cause);
25
		}
26
		
27

  
28
	}
0 29

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/Authentication.java
1
package org.gvsig.authentication;
2

  
3
import java.sql.ResultSet;
4
import java.sql.SQLException;
5
import java.sql.Statement;
6
import java.util.Hashtable;
7
import java.util.Vector;
8

  
9
import org.gvsig.authentication.db.DatabaseHandler;
10
import org.gvsig.authentication.db.QueryBuilder;
11
import org.gvsig.authentication.exception.DBConnectionException;
12
import org.gvsig.authentication.exception.InvalidUserException;
13
import org.gvsig.authentication.utils.LogManager;
14
import org.gvsig.authentication.utils.Logger;
15

  
16

  
17
/**
18
 *  Provides the functionality to process the authentication and the authorization in the DB. 
19
 * @author laura
20
 */
21
public class Authentication {
22
	
23
	private DatabaseHandler dbHandler;
24
	private Logger m_log = LogManager.getLogManager().getLogger(Authentication.class.getName());
25
	
26
	public Authentication()	{
27
		dbHandler = new DatabaseHandler(); 
28
	}
29
	
30
	/**
31
     * Tries to log in the db with the info sent by the user.
32
     * @param userName
33
     * @param password
34
     * @return
35
     */
36
    public int login(String userName, String password)
37
    {
38
    	Statement stm = null;
39
		ResultSet rs = null;
40
		String query = null;
41
		int userId = -1;	
42
    	   
43
    	try {
44
		
45
    		dbHandler.initConnection("default");
46
			query = QueryBuilder.getLoginQuery(userName, password);
47
			stm = dbHandler.getConnection().createStatement();
48
			rs = stm.executeQuery(query);
49
			if (rs.first()){
50
				userId = rs.getInt(QueryBuilder.USER_ID);
51
			}
52
			return userId;
53
			
54
    	} catch (SQLException e) {
55
    		m_log.error("DatabaseHandler.login()." ,e);
56
			e.printStackTrace();
57
			return userId;
58
		} catch (DBConnectionException e) {
59
			m_log.error("DatabaseHandler.login()." ,e);
60
			e.printStackTrace();
61
			return userId;
62
		}finally{
63
			if (dbHandler.getConnection() != null){
64
				try{
65
					stm.close();
66
					rs.close(); 
67
					dbHandler.releaseConnection("default");
68
				}catch(Exception fin){
69
					m_log.error("",fin);
70
					fin.printStackTrace(); 
71
					return userId;
72
				}
73
			}
74
		}
75
    }
76
    
77
    private Vector getRoles(String userId)
78
    {
79
    	Statement stm = null;
80
		ResultSet rs = null;
81
		String query = null;	
82
    	int roleId = -1;    	
83
    	Vector roles = new Vector();    	
84
		query = QueryBuilder.getUserRolesIds(userId);
85
		
86
		try {
87

  
88
			stm = dbHandler.getConnection().createStatement();
89
			rs = stm.executeQuery(query);			
90
			// rs contains the roles ids to which this user belongs
91
			// at this moment we are going to simplify this to one role per user			
92
			if (rs.first())
93
			{
94
				do{
95
					roleId = rs.getInt(QueryBuilder.USER_ROLES_ROLES_ID_COL);
96
					if(roleId > -1)
97
					{
98
						roles.add(""+roleId);
99
					}
100
				}while(rs.next());
101
			}
102
	    	
103
		} catch (SQLException e) {
104
			// TODO Auto-generated catch block
105
			e.printStackTrace();
106
		}finally{
107
			if (dbHandler.getConnection() != null){
108
				try{
109
					rs.close();
110
					stm.close();
111
				}catch(Exception fin){
112
					m_log.error("",fin);
113
					fin.printStackTrace(); 
114
					return null;
115
				}
116
			}
117
		}
118
		return roles;
119
    }
120
	
121
    /**
122
     * gets the gvSIG config file
123
     * @param userName
124
     * @param password
125
     * @return a String with the gvSIG confog file
126
     * @throws InvalidUserException
127
     */
128
    public Hashtable getGvSigConfig(String userName, String password)
129
    		throws InvalidUserException 
130
    {
131
    	int userId = login(userName, password);
132
    	if ( userId > -1){
133
    		return getGvSigConfig(userId);
134
    	}
135
    	else{
136
    		throw new InvalidUserException("Authentication ERROR: Invalid user trying to get gvSIG file");
137
    	}
138
    }
139
    
140
	/**
141
     * Gets the gvSig configuration file associated to the user role.
142
     * First checks if the user/password is correct.
143
     * @param userName
144
     * @param password
145
     * @return
146
     */
147
    private Hashtable getGvSigConfig(int userId)
148
    {
149
    	Statement stm = null;
150
		ResultSet rs = null;
151
		String query = null;	
152
    	Vector roles = new Vector();
153
    	Hashtable ht = new Hashtable();
154
    	try {
155
		
156
    		dbHandler.initConnection("default");
157
    		roles = getRoles(String.valueOf(userId));
158
			if (roles.size() > 0 )//if (roleId > -1)
159
			{
160
				query = QueryBuilder.getGvSigConfigDataQuery(roles);
161
				stm = dbHandler.getConnection().createStatement();
162
				rs = stm.executeQuery(query);				
163
				if (rs.first())
164
				{
165
					do{
166
						ht.put(rs.getString(QueryBuilder.GRANTS_NAME_COL),rs.getString(QueryBuilder.GRANTS_DATA_COL));
167
					}while (rs.next());
168
				}						
169
			}
170
			return ht;
171
			
172
    	} catch (SQLException e) {
173
    		m_log.error("DatabaseHandler.getGvSigConfig()." ,e);
174
			e.printStackTrace();
175
			return null;
176
		} catch (DBConnectionException e) {
177
			m_log.error("DatabaseHandler.getGvSigConfig()." ,e);
178
			e.printStackTrace();
179
			return null;
180
		}finally{
181
			if (dbHandler.getConnection() != null){
182
				try{
183
					rs.close();
184
					stm.close();
185
					dbHandler.releaseConnection("default");
186
				}catch(Exception fin){
187
					m_log.error("",fin);
188
					fin.printStackTrace(); 
189
					return null;
190
				}
191
			}
192
		}
193
    }    
194
  
195
    /**
196
     * Returns mapserver map file for this user
197
     * @param userName
198
     * @param password
199
     * @return
200
     * @throws InvalidUserException
201
     */
202
    public String getMapFile(String userName, String password)
203
    		throws InvalidUserException
204
    {
205
    	int userId = login(userName, password);
206
    	if (userId > -1){
207
    		return getMapFile(String.valueOf(userId));
208
    	}
209
    	else{
210
    		throw new InvalidUserException("Authentication ERROR: Invalid user trying to get gvSIG file");
211
    	}
212
    }    
213
	/**
214
     * Gets the mapserver map file associated to the user role.
215
     * First checks if the user/password is correct.
216
     * @param userName
217
     * @param password
218
     * @return
219
     */
220
    private String getMapFile(String userId)
221
    {
222
    	Statement stm = null;
223
		ResultSet rs = null;
224
		String query = null;	
225
    	Vector roles = new Vector();
226
    	try {
227
		
228
    		dbHandler.initConnection("default");
229
    		roles = getRoles(userId);
230
 
231
			if (roles.size() > 0 )//if (roleId > -1)
232
			{
233
				query = QueryBuilder.getMapConfigDataQuery(roles);
234
				stm = dbHandler.getConnection().createStatement();
235
				rs = stm.executeQuery(query);
236
//				esta ordenado por prioridad descendente, el ultimo es el de prioridad mas alta				
237
				if (rs.last())
238
				{					
239
					return rs.getString(QueryBuilder.GRANTS_DATA_COL);
240
				}					
241
			}
242
			return "";
243
			
244
    	} catch (SQLException e) {
245
    		m_log.error("DatabaseHandler.getGvSigConfig()." ,e);
246
			e.printStackTrace();
247
			return "";
248
		} catch (DBConnectionException e) {
249
			m_log.error("DatabaseHandler.getGvSigConfig()." ,e);
250
			e.printStackTrace();
251
			return "";
252
		}finally{
253
			if (dbHandler.getConnection() != null){
254
				try{
255
					dbHandler.releaseConnection("default");
256
					rs.close();
257
					stm.close();
258
				}catch(Exception fin){
259
					m_log.error("",fin);
260
					fin.printStackTrace(); 
261
					return "";
262
				}
263
			}
264
		}
265
    }     
266
	/**
267
     * Gets all the configuration associated to this user/password
268
     * returns the gvSIG config file and the mapserver map file 
269
     * First checks if the user/password is correct.
270
     * @param userName
271
     * @param password
272
     * @return
273
     */
274
    public Hashtable getConfig(String userName, String password)
275
    		throws InvalidUserException
276
    {
277
    	Hashtable ht = new Hashtable();
278
    	Hashtable configTable = new Hashtable();
279
    	String query;
280
    	int userId;
281
       	Statement stm = null;
282
		ResultSet rs = null;
283
		String mapserverFile = "";
284
		String hojasmapFile = "";
285
		String wms = "";
286
		Vector roles = new Vector();
287
    	try {
288
    		
289
    		userId = login(userName, password);
290
    		
291
			if(userId > -1){
292
				
293
				dbHandler.initConnection("default"); 
294
				roles = getRoles(String.valueOf(userId));
295
				if(roles.size() > 0 ) //if (roleId > -1)
296
				{
297
					query = QueryBuilder.getMapConfigDataQuery(roles);					
298
					stm = dbHandler.getConnection().createStatement(); 
299
					rs = stm.executeQuery(query);
300
					//el ultimo es del role de este usuario con mayor prioridad
301
					if (rs.last())
302
					{
303
						mapserverFile = rs.getString(QueryBuilder.GRANTS_DATA_COL);
304
					}	
305
					rs.close();
306
					rs = null;
307
					
308
					query = QueryBuilder.getWMSQuery(roles);		
309
					m_log.debug("getWMSQuery(roles): " + query);
310
					stm = dbHandler.getConnection().createStatement(); 
311
					rs = stm.executeQuery(query);
312
					//el ultimo es del role de este usuario con mayor prioridad
313
					if (rs.last())
314
					{
315
						wms = rs.getString(QueryBuilder.GRANTS_DATA_COL);
316
					}	
317
					rs.close();
318
					rs = null;
319
					
320
					query = QueryBuilder.getHojasMapDataQuery(roles);		
321
					m_log.debug("getHojasMapfile(roles): " + query);
322
					stm = dbHandler.getConnection().createStatement(); 
323
					rs = stm.executeQuery(query);
324
					if (rs.last())
325
					{
326
						hojasmapFile  = rs.getString(QueryBuilder.GRANTS_DATA_COL);
327
					}	
328
					rs.close();
329
					rs = null;
330
					
331
					query = QueryBuilder.getGvSigConfigDataQuery(roles);
332
					m_log.debug("getGvSigConfigDataQuery(roles): " + query);
333
					rs = stm.executeQuery(query);				
334
					if (rs.first())
335
					{
336
						do{
337
							configTable.put(rs.getString(QueryBuilder.GRANTS_NAME_COL),rs.getString(QueryBuilder.GRANTS_DATA_COL));
338
						}while (rs.next());
339
					}	
340
				}								  				    			
341
				ht.put("gvsig_config", configTable);
342
				ht.put("mapserver_file", mapserverFile);
343
				ht.put("wms", wms);
344
				ht.put("hojas_mapfile", hojasmapFile);
345
			}    		
346
    		else{
347
    			throw new InvalidUserException ("Authentication Error: Invalid user."); 			
348
    		}
349
    		return ht;
350
 
351
       	} catch (SQLException e) {
352
    		m_log.error("Authentication.getConfig()." ,e);
353
			e.printStackTrace();
354
			return null;
355
		} catch (DBConnectionException e) {
356
			m_log.error("Authentication.getConfig()." ,e);
357
			e.printStackTrace();
358
			return null;
359
		} catch (Exception e) {
360
			m_log.error("Authentication.getConfig()." ,e);
361
			e.printStackTrace();
362
			return null;				
363
		}finally{
364
			if (dbHandler.getConnection() != null){
365
				try{
366
					dbHandler.releaseConnection("default");
367
					rs.close();
368
					stm.close();
369
				}catch(Exception fin){
370
					m_log.error("",fin);
371
					fin.printStackTrace(); 
372
					return null;
373
				}
374
			}
375
		}    		
376

  
377
    }     
378
}
0 379

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/utils/LogManager.java
1
package org.gvsig.authentication.utils;
2

  
3
import java.util.HashMap;
4
import java.util.Properties;
5
import org.apache.log4j.PropertyConfigurator;
6

  
7
/**
8
 * @author        Laura diaz
9
 * @version       1.1
10
 */
11
public class LogManager 
12
{
13
  private static Object s_lock;
14
  private static LogManager s_logManager;
15
  private static HashMap s_loggers;
16

  
17
  static
18
  {
19
    s_lock = new Object();
20
  }
21

  
22
  /**
23
  * Constructor
24
  *
25
  * Private so clients can not instanciate this directly
26
  */
27
  private LogManager()
28
  {
29
    try
30
    {
31
      s_loggers = new HashMap();
32
      Properties properties = PropertyManager.getProperties(PropertyManager.LOGGER_PROPERTIES);
33
      PropertyConfigurator.configure(properties);
34
    }
35
    catch(Exception ex)
36
    {
37
      System.out.println("Could not load properties " + PropertyManager.LOGGER_PROPERTIES);
38
    }
39
  }
40

  
41
  /**
42
  * Gets the instance of the LogManager 
43
  *
44
  *@return LogManager
45
  */
46
  public static LogManager getLogManager()
47
  {
48
    if (s_logManager == null)
49
    {
50
      synchronized (s_lock)
51
      {
52
        if (s_logManager == null)
53
        {
54
          s_logManager = new LogManager();
55
        }
56
      }
57
    }
58
    return s_logManager;
59
  }
60

  
61
  /**
62
  * Gets the appropriate Logger
63
  * 
64
  *@param String - name, usually the name of the class that calls this
65
  *@return Logger
66
  */
67
  public Logger getLogger(String name)
68
  {
69
    if (s_loggers.containsKey(name))
70
    {
71
      return (Logger)s_loggers.get(name);
72
    }
73

  
74
    Logger logger = new Logger(name);
75
    s_loggers.put(name, logger);
76
    return logger;
77
  }
78
}
79

  
0 80

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/utils/Logger.java
1
package org.gvsig.authentication.utils;
2

  
3
import org.apache.log4j.Category;
4

  
5
import java.io.CharArrayWriter;
6
import java.io.PrintWriter;
7
import java.io.IOException;
8
import java.util.Properties;
9

  
10
/**
11
 * @author        Laura Diaz
12
 * @version       1.0
13
 */
14
public class Logger 
15
{
16
	private static final String DEBUG_MAXSIZE_PROPERTY = "log4j.debug.maxsize";
17
	private static final String INFO_MAXSIZE_PROPERTY = "log4j.info.maxsize";
18

  
19
	private static Category m_category;
20
	private int m_maxSizeDebugMsg;
21
	private int m_maxSizeInfoMsg;  
22

  
23
	/**
24
	 * Constructor
25
	 *
26
	 * Protected so, only classes in the same package or descendants can instanciate this
27
	 */
28
	protected Logger(String name)
29
	{
30
		m_category = Category.getInstance(name);
31
		
32
		m_maxSizeDebugMsg = readMaxSizeProperty(DEBUG_MAXSIZE_PROPERTY, 0);
33
		m_maxSizeInfoMsg = readMaxSizeProperty(INFO_MAXSIZE_PROPERTY, 0);
34
	}
35
	
36
	/**
37
	 * Adds a debug message
38
	 */
39
	public void debug(String msg)
40
	{
41
		/*
42
		 * Write message to log. If enabled, if the message is too long, it
43
		 * will be truncated.
44
		 */
45
		if (m_maxSizeDebugMsg <= 0)
46
		{
47
		  m_category.debug(msg + "\n");
48
		}
49
		else {
50
		  if (msg.length() <= m_maxSizeDebugMsg)
51
		  {
52
			m_category.debug(msg + "\n");
53
		  }
54
		  else
55
		  {
56
			StringBuffer sb = new StringBuffer(msg.substring(0, m_maxSizeDebugMsg));
57
			sb.append(" [TRUNCATED BY LOGGER SEE property \"");
58
			sb.append(DEBUG_MAXSIZE_PROPERTY);
59
			sb.append("\"]\n");
60
			m_category.debug(sb.toString());
61
		  }
62
		}
63
	}
64

  
65
	/**
66
	 * Adds an info message
67
	 */
68
	public void info(String msg)
69
	{
70
		/*
71
		 * Write message to log. If enabled, if the message is too long, it
72
		 * will be truncated.
73
		 */
74
		if (m_maxSizeInfoMsg <= 0)
75
		{
76
		  m_category.info(msg + "\n");
77
		}
78
		else {
79
		  if (msg.length() <= m_maxSizeInfoMsg)
80
		  {
81
			m_category.info(msg + "\n");
82
		  }
83
		  else
84
		  {
85
			StringBuffer sb = new StringBuffer(msg.substring(0, m_maxSizeInfoMsg));
86
			sb.append(" [TRUNCATED BY LOGGER SEE property \"");
87
			sb.append(INFO_MAXSIZE_PROPERTY);
88
			sb.append("\"]\n");
89
			m_category.info(sb.toString());
90
		  }
91
		}
92
	}
93

  
94
	/**
95
	 * Adds an warning message
96
	 */
97
	public void warning(String msg)
98
	{
99
		m_category.warn(msg + "\n");
100
	}
101

  
102
	/**
103
	 * Adds an error message
104
	 */
105
	public void error(String msg)
106
	{
107
		m_category.fatal(msg + "\n");
108
	}
109

  
110

  
111
	/**
112
	 * Writes a message to the error log. This message includes the
113
	 * detail message of the given exception as well as the
114
	 * exception's stack trace.
115
	 * 
116
	 * @param  descr  description of the error.
117
	 * @param  e      exception that was caught. 
118
	 */
119
	public void error(String descr, Exception e)
120
	{	
121
		m_category.fatal(descr + ": detail message = \"" + e.getMessage()
122
			+ "\", trace =\n" + Logger.stackTraceToString(e));
123
	}
124

  
125
	/**
126
	 * Converts the stack trace of the given exception to a string.
127
	 */  
128
	public static String stackTraceToString(Exception e)
129
	{
130
	  try
131
	  {
132
		CharArrayWriter writer = new CharArrayWriter();
133
  	
134
		e.printStackTrace(new PrintWriter(writer));
135
		return writer.toString();
136
	  }
137
	  catch(Exception e2)
138
	  {
139
		return " [failed to convert stacktrace to string] ";
140
	  }
141
	}
142

  
143
	/**
144
	 * Reads the named property from the logger properties file and returns
145
	 * it. If the property is missing or if its value is invalid, the value
146
	 * of <code>defValue</code> is returned.
147
	 */	
148
	private int readMaxSizeProperty(String propName, int defValue)
149
	{
150
		try
151
		{
152
			Properties props = PropertyManager.getProperties(
153
								PropertyManager.LOGGER_PROPERTIES);
154

  
155
			if (props == null)
156
			{
157
				System.err.println("[Logger] Failed to read property \""
158
					+ propName + "\": cannot get properties of "
159
					+ PropertyManager.LOGGER_PROPERTIES);
160
				return defValue;
161
			}
162
			
163
			int n = defValue;
164
			String s = props.getProperty(propName);
165

  
166
			if (s != null && s.length() != 0)
167
			{
168
				try
169
				{
170
					int k  = Integer.parseInt(s);
171
					if (k > 0)
172
					{
173
						n = k;
174
					}
175
				}
176
				catch(NumberFormatException e)
177
				{
178
					System.err.println("[Logger] invalid value for property \""
179
						+ propName + "\": not an integer: " + s
180
						+ "---ignoring property");
181
					return defValue;
182
				}
183
			}
184
			return n;
185
		}
186
		catch(IOException e)
187
		{
188
			System.err.println("[Logger] Failed to read property \"" + propName
189
				+ "\": I/O error: " + e.getMessage() + "---ignoring property");
190
				
191
			return defValue;
192
		}
193
	}
194
}
0 195

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/utils/PropertyManager.java
1
package org.gvsig.authentication.utils;
2

  
3
import java.util.Properties;
4
import java.util.Hashtable;
5
import java.io.InputStream;
6
import java.io.IOException;
7

  
8
/**
9
 * Description: Loads the configuration files
10
 *
11
 * @author  Laura Diaz
12
 * @version 1.0 
13
 */
14
public class PropertyManager
15
{
16
 public final static String LOGGER_PROPERTIES = "org/gvsig/authentication/conf/logger.properties";
17
 public final static String DB_PROPERTIES = "org/gvsig/authentication/conf/connection.properties";
18
 
19
 //The property file names to load
20
 private final static String[] s_propertyFileNames = new String[]{	LOGGER_PROPERTIES
21
 																	,DB_PROPERTIES};
22

  
23
 //Hashtable containing all properties objects that are loaded
24
 private static Hashtable s_propertyFiles = null;
25

  
26
 /**
27
 * Gets a properties object
28
 * If the the property files are not yet loaded, then loads them first
29
 *
30
 * @param propertyFileName, String
31
 * @return Properties
32
 * @throws java.io.IOException
33
 */
34
 public static Properties getProperties(String propertyFileName) throws IOException
35
 {
36
   if (s_propertyFiles == null)
37
   {
38
     loadProperties();
39
   }
40

  
41
   return (Properties)s_propertyFiles.get(propertyFileName);
42
 }
43

  
44
 //Loads the property files
45
 private static synchronized void loadProperties() throws IOException
46
 {
47
   s_propertyFiles = new Hashtable(s_propertyFileNames.length);
48
   ClassLoader loader = PropertyManager.class.getClassLoader();
49

  
50
   for (int i = 0; i < s_propertyFileNames.length; i++)
51
   {
52
     try
53
     {
54
       InputStream input = loader.getResourceAsStream(s_propertyFileNames[i]);
55
       Properties props = new Properties();
56
       props.load(input);
57
       s_propertyFiles.put(s_propertyFileNames[i], props);
58
     }
59
     catch(Exception e)
60
     {
61
     	System.err.println("\n[PropertyManager] ERROR - Failed to read properties file \""
62
                          + s_propertyFileNames[i] + "\": "
63
                          + e.getMessage());       
64
     }
65
   }
66
 }
67
 
68
}
0 69

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/conf/connection.properties
1
# Connection PROPERTY FILE
2

  
3
# Set here if you want to make use of the Pool for getting a connection
4
# If you want a connectin from the pool set in "connection_name" 
5
# the name of the connection in the Pool that you want to use 
6
usepool=true
7
#connection_name=authenConn
8

  
9
# ----------- NORMAL CONNECTION ----------
10
# In case the connection Pool is not used, here we write the properties
11
# for a normal connection, URL, passwd and user
12
# The URL: jdbc_DB:driver_types:@IP_number:DB_port_number:SID
13
#jdbc:postgresql://host:port/database 
14
url=jdbc:postgresql://192.168.0.217:5432/costas
15
password=ldiaz
16
user=ldiaz
17

  
18
# ------------- COMMON -------------
19
# Drivers used for Java to connect to the DB, this property is for the POOL
20
# and for the normal connection
21
drivers=org.postgresql.Driver
22

  
23
# ---------------- POOL ------------------
24
# Here you write all the connections in the Pool
25
# Set here all their properties.
26
# NOTE : The Pool manager will create as many pools as
27
#       pool-configuration blocks are defined in here (pool names)
28

  
29
default.url=jdbc:postgresql://192.168.0.217:5432/costas
30
default.password=ldiaz
31
default.user=ldiaz
32
default.maxconns=200
33
default.initconns=10
34
default.logintimeout=5
35

  
36
authenConn.url=jdbc:postgresql://192.168.0.217:5432/costas
37
authenConn.password=ldiaz
38
authenConn.user=ldiaz
39
authenConn.maxconns=200
40
authenConn.initconns=10
41
authenConn.logintimeout=5
42

  
43
fran.url=jdbc:postgresql://fjp2/latin1
44
fran.password=aquilina
45
fran.user=postgres
46
fran.maxconns=200
47
fran.initconns=10
48
fran.logintimeout=5
0 49

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/conf/logger.properties
1
# LOGGER PROPERTIES
2

  
3
## limit is ignored if its value is empty or if its value is set to zero.
4
## Note: this property only affects info messages.
5
#log4j.info.maxsize=
6

  
7
## Set root category priority to DEBUG and its only appender to stdout.
8
## on a windows machine:
9
#log4j.rootCategory=DEBUG, stdout
10
# on the freya:
11
log4j.rootCategory=DEBUG, file
12
#log4j.rootCategory=FATAL
13

  
14
## stdout is set to be a ConsoleAppender which outputs to System.out.
15
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
16
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
17
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
18

  
19
log4j.appender.file=org.apache.log4j.RollingFileAppender
20
log4j.appender.file.File=C:\\projects\\gvsig\\AuthenticationService.log
21
log4j.appender.file.MaxBackupIndex=1
22
log4j.appender.file.MaxFileSize=100KB
23
log4j.appender.file.layout=org.apache.log4j.PatternLayout
24
log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
25

  
26

  
27
##
28
## Package Logging 
29
##
30
## Each package can have its own appender
31
##
32
## Priorities are as follows :
33
##
34
## 1. FATAL
35
## 2. ERROR
36
## 3. WARN
37
## 4. INFO
38
## 5. DEBUG
39
##
40
## If a package has a priority of DEBUG, this means all
41
## messages will be shown in the log. If the priority is
42
## INFO, then all messages with a minimum priory of INFO will
43
## be shown i.e. INFO, WARN, ERROR and FATAL
44
##
45
## For minimum log output, set the priority to FATAL
46
##
47

  
48

  
49
#log4j.category.nl.rivm.rrgs.log.NogEenTester=DEBUG, R1
50
 
51
#log4j.appender.R1=org.apache.log4j.RollingFileAppender
52
#log4j.appender.R1.File=d:\\Test1.log
53
#log4j.appender.R1.MaxBackupIndex=1
54
#log4j.appender.R1.MaxFileSize=100KB
55
#log4j.appender.R1.layout=org.apache.log4j.PatternLayout
56
#log4j.appender.R1.layout.ConversionPattern=%d %p %t %c - %m%n
57

  
58

  
59
#log4j.category.nl.rivm.rrgs.log.Tester=DEBUG, R
60

  
61
#log4j.appender.R=org.apache.log4j.RollingFileAppender
62
#log4j.appender.R.File=d:\\Test.log
63
#log4j.appender.R.MaxBackupIndex=1
64
#log4j.appender.R.MaxFileSize=100KB
65
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
66
#log4j.appender.R.layout.ConversionPattern=%d %p %t %c - %m%n
0 67

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/db/DatabaseHandler.java
1
package org.gvsig.authentication.db;
2

  
3
import java.sql.Connection;
4

  
5
import org.gvsig.authentication.exception.DBConnectionException;
6
import org.gvsig.authentication.utils.LogManager;
7
import org.gvsig.authentication.utils.Logger;
8

  
9

  
10
/**
11
 * This class will hold all the methods to perform actions in the DB
12
 * like initialize/release a connection, log in a user...
13
 * 
14
 * NOTE:
15
 *  As first approach we'll open a connection/action performed
16
 *  in the database, maybe we have to change it to open a connection
17
 *  per DatabaseHandler life cicle ???
18
 *  
19
 * @author laura
20
 *
21
 */
22
public class DatabaseHandler {
23
	
24
	private Connection m_connection;
25
	private ConnectionManager m_connectionManager;	
26
	private Logger m_log;
27
	
28
	public DatabaseHandler()
29
	{
30
		m_log = LogManager.getLogManager().getLogger(getClass().getName());
31
		m_connectionManager = new ConnectionManager(); 
32
		m_log.debug("DatabaseHandler initialize.");
33
	}	
34
		
35
	public Connection getConnection()
36
	{
37
		return m_connection;
38
	}
39
	
40
   public void initConnection(String connectionName) throws DBConnectionException
41
    {
42
		if (m_connection == null)
43
		{
44
			m_connection = m_connectionManager.getConnection(connectionName);				
45
		}		
46
    }
47
    
48
	public void releaseConnection(String connectionName) throws DBConnectionException
49
	{	
50
		if (m_connection != null)
51
		{
52
			m_connectionManager.freeConnection(m_connection,connectionName);
53
			m_connection = null;
54
		}
55
	} 	
56
}
0 57

  
tags/tmp_build/libraries/libAuthenticationService/src/org/gvsig/authentication/db/PoolManager.java
1
package org.gvsig.authentication.db;
2

  
3
import java.sql.*;
4
import java.util.*;
5

  
6
import org.gvsig.authentication.utils.LogManager;
7
import org.gvsig.authentication.utils.Logger;
8
import org.gvsig.authentication.utils.PropertyManager;
9

  
10

  
11
public class PoolManager
12
{
13
   static private PoolManager m_instance;
14
   static private int m_clients;
15

  
16
   private Vector m_drivers = new Vector();
17
   
18
   /*
19
    * The connection pools. Once this map is initialized (during the construction of the
20
    * PoolManager) it will be used in read-only mode (i.e., it will never be modified)
21
    * until the PoolManager is released.
22
    */
23
   private HashMap m_pools = new HashMap();
24

  
25
   private Logger m_log = LogManager.getLogManager().getLogger(PoolManager.class.getName());  
26

  
27

  
28
   private PoolManager()
29
   {
30
      init();
31
   }
32

  
33
   static synchronized public PoolManager getInstance()
34
   {
35
      if (m_instance == null)
36
      {
37
         m_instance = new PoolManager();
38
      }
39
      m_clients++;
40
      return m_instance;
41
   }
42

  
43
   private void init()
44
   {
45
      Properties dbProps = new Properties();
46
      try
47
      {
48
        dbProps = PropertyManager.getProperties(PropertyManager.DB_PROPERTIES);
49
      }
50
      catch (Exception e)
51
      {
52
        m_log.error("Can't read the properties file. "
53
        	+ "Make sure " + PropertyManager.DB_PROPERTIES
54
            + " is in the CLASSPATH");
55
         return;
56
      }      
57
      loadDrivers(dbProps);
58
      createPools(dbProps);
59
   }
60

  
61
   private void loadDrivers(Properties props)
62
   {
63
      String driverClasses = props.getProperty("drivers");
64
      StringTokenizer st = new StringTokenizer(driverClasses);
65
      while (st.hasMoreElements())
66
      {
67
         String driverClassName = st.nextToken().trim();
68
         try
69
         {
70
            Driver driver = (Driver)
71
               Class.forName(driverClassName).newInstance();
72
            DriverManager.registerDriver(driver);
73
            m_drivers.addElement(driver);
74
            m_log.debug("Registered JDBC driver \"" + driverClassName + "\"");              
75
         }
76
         catch (Exception e)
77
         {
78
            logException("Can't register JDBC driver \""
79
              + driverClassName + "\"", e);
80
         }
81
      }
82
   }
83

  
84
   private void createPools(Properties props)
85
   {
86
      Enumeration propNames = props.propertyNames();
87
      while (propNames.hasMoreElements())
88
      {
89
         String name = (String) propNames.nextElement();
90
         if (name.endsWith(".url"))
91
         {
92
            String poolName = name.substring(0, name.lastIndexOf("."));
93
            String url = props.getProperty(poolName + ".url");
94
            if (url == null)
95
            {
96
               m_log.debug("No URL specified for \"" + poolName
97
                 + "\" -- skipped");
98
               continue;
99
            }
100

  
101
            String user = props.getProperty(poolName + ".user");
102
            String password = props.getProperty(poolName + ".password");
103

  
104
            String maxConns = props.getProperty(poolName +
105
               ".maxconns", "0");
106
            int max;
107
            try
108
            {
109
               max = Integer.parseInt(maxConns);
110
            }
111
            catch (NumberFormatException e)
112
            {
113
               m_log.error("Invalid maxconns value \"" + maxConns
114
                 + "\" for \"" + poolName + "\": not a valid number");
115
               max = 0;
116
            }
117

  
118
            String initConns = props.getProperty(poolName +
119
                              ".initconns", "0");
120
            int init;
121
            try
122
            {
123
               init = Integer.parseInt(initConns);
124
            }
125
            catch (NumberFormatException e)
126
            {
127
               m_log.error("Invalid initconns value \"" + initConns
128
                 + " for \"" + poolName
129
                 + "\": not a valid number -- setting value to 0");
130
               init = 0;
131
            }
132

  
133
            String loginTimeOut = props.getProperty(poolName +
134
               ".logintimeout", "5");
135
            int timeOut;
136
            try
137
            {
138
               timeOut = Integer.parseInt(loginTimeOut);
139
            }
140
            catch (NumberFormatException e)
141
            {
142
               m_log.error("Invalid logintimeout value \""
143
                 + loginTimeOut + "\" for \"" + poolName
144
                 + "\": not a valid number -- setting value to 5");
145
               timeOut = 5;
146
            }
147
/*
148
            String logLevelProp = props.getProperty(poolName +
149
                           ".loglevel", String.valueOf(LogWriter.ERROR));
150
            int logLevel = LogWriter.INFO;
151
            if (logLevelProp.equalsIgnoreCase("none"))
152
            {
153
               logLevel = LogWriter.NONE;
154
            }
155
            else if (logLevelProp.equalsIgnoreCase("error"))
156
            {
157
               logLevel = LogWriter.ERROR;
158
            }
159
            else if (logLevelProp.equalsIgnoreCase("debug"))
160
            {
161
               logLevel = LogWriter.DEBUG;
162
            }
163
*/            
164
            ConnectionPool pool =
165
                           new ConnectionPool(poolName, url, user, password,
166
                                            max, init, timeOut);
167
            m_pools.put(poolName, pool);
168
         }
169
      }
170

  
171
   }
172

  
173
   /** returns a connection from the pool named: 'default'*/
174
   public Connection getConnection()
175
   {
176
      Connection conn = null;
177
      ConnectionPool pool = (ConnectionPool) m_pools.get("default");
178
      if (pool != null)
179
      {
180
         try
181
         {
182
            conn = pool.getConnection();
183
         }
184
         catch (SQLException e)
185
         {
186
            logException("Failed to get pool connection", e);
187
         }
188
      }
189
      return conn;
190
   }
191

  
192
   public Connection getConnection(String name)
193
   {
194
      ConnectionPool pool = (ConnectionPool) m_pools.get(name);
195
      if (pool != null)
196
      {
197
         try
198
         {
199
            return pool.getConnection();
200
         }
201
         catch (SQLException e)
202
         {
203
            logException("Failed to get pool connection \""
204
              + name + "\"", e);
205
         }
206
      }
207
      return null;
208
   }
209

  
210
   /** Free a connection to the default database as specified in the
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff