KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > ext > authentication > manager > JdbcAuthenticationManager


1 /*
2  jGuard is a security framework based on top of jaas (java authentication and authorization security).
3  it is written for web applications, to resolve simply, access control problems.
4  version $Name$
5  http://sourceforge.net/projects/jguard/
6
7  Copyright (C) 2004 Charles GAY
8
9  This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Lesser General Public
11  License as published by the Free Software Foundation; either
12  version 2.1 of the License, or (at your option) any later version.
13
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  Lesser General Public License for more details.
18
19  You should have received a copy of the GNU Lesser General Public
20  License along with this library; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24  jGuard project home page:
25  http://sourceforge.net/projects/jguard/
26
27  */

28 package net.sf.jguard.ext.authentication.manager;
29
30 import java.io.File JavaDoc;
31 import java.io.FileInputStream JavaDoc;
32 import java.io.FileNotFoundException JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.net.URI JavaDoc;
35 import java.net.URISyntaxException JavaDoc;
36 import java.security.Principal JavaDoc;
37 import java.sql.Connection JavaDoc;
38 import java.sql.PreparedStatement JavaDoc;
39 import java.sql.ResultSet JavaDoc;
40 import java.sql.SQLException JavaDoc;
41 import java.util.ArrayList JavaDoc;
42 import java.util.Collection JavaDoc;
43 import java.util.HashMap JavaDoc;
44 import java.util.HashSet JavaDoc;
45 import java.util.Iterator JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Properties JavaDoc;
49 import java.util.Set JavaDoc;
50 import java.util.logging.Level JavaDoc;
51 import java.util.logging.Logger JavaDoc;
52
53 import javax.security.auth.Subject JavaDoc;
54
55 import net.sf.jguard.core.CoreConstants;
56 import net.sf.jguard.core.authentication.credentials.JGuardCredential;
57 import net.sf.jguard.core.principals.RolePrincipal;
58 import net.sf.jguard.core.util.FileUtils;
59 import net.sf.jguard.ext.SecurityConstants;
60 import net.sf.jguard.ext.authentication.AuthenticationException;
61 import net.sf.jguard.ext.database.ConnectionFactory;
62 import net.sf.jguard.ext.database.DatabaseUtils;
63 import net.sf.jguard.ext.principals.PrincipalUtils;
64 import net.sf.jguard.ext.registration.SubjectTemplate;
65 import net.sf.jguard.ext.util.XMLUtils;
66
67 /**
68  * AuthenticationManager implementation providing a database backend. differences between database "dialects", are handled through
69  * specific properties files loaded during the init method.these properties files contains specific SQL queries.
70  *
71  * @author <a HREF="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
72  * @author <a HREF="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
73  * @author <a HREF="mailto:vberetti@users.sourceforge.net">Vincent Beretti</a>
74  * @see AuthenticationManager
75  */

76 public class JdbcAuthenticationManager extends AbstractAuthenticationManager implements AuthenticationManager {
77
78     private static final Logger JavaDoc logger = Logger.getLogger(JdbcAuthenticationManager.class.getName());
79     private Properties JavaDoc properties = null;
80     private String JavaDoc dbPropertiesLocation = null;
81     private ConnectionFactory connectionFactory = null;
82
83     public JdbcAuthenticationManager() {
84         super();
85     }
86
87     protected void persistPrincipal(Principal JavaDoc principal) throws AuthenticationException {
88         Connection JavaDoc connection = null;
89         try {
90             connection = connectionFactory.getConnection();
91             PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("ADD_PRINCIPAL"));
92             
93             if (principal instanceof RolePrincipal) {
94                 pst.setString(1, ((RolePrincipal) principal).getLocalName());
95                 pst.setString(2, ((RolePrincipal) principal).getApplicationName());
96             } else {
97                 pst.setString(1, principal.getName());
98                 pst.setString(2, applicationName);
99             }
100             pst.setString(3, principal.getClass().getName());
101             pst.executeUpdate();
102             pst.close();
103
104             localPrincipals.put(principal.getName(), principal);
105             localPrincipalsSet.add(principal);
106
107         } catch (SQLException JavaDoc e) {
108             logger.log(Level.SEVERE, " persistPrincipal(Principal) ", e);
109             throw new AuthenticationException(e);
110         } finally {
111             try {
112                 connection.close();
113             } catch (SQLException JavaDoc e) {
114                 logger.log(Level.SEVERE, " persistPrincipal(Principal) ", e);
115                 throw new AuthenticationException(e);
116             }
117         }
118
119     }
120
121     public void init(Map JavaDoc map) {
122
123         dbPropertiesLocation = (String JavaDoc) map.get(SecurityConstants.AUTHENTICATION_DATABASE_FILE_LOCATION);
124         dbPropertiesLocation = XMLUtils.resolveLocation(dbPropertiesLocation);
125         properties = new Properties JavaDoc();
126         try {
127             File JavaDoc file = FileUtils.getFile(new URI JavaDoc(dbPropertiesLocation));
128             properties.load(new FileInputStream JavaDoc(file));
129         } catch (FileNotFoundException JavaDoc e) {
130             logger.severe(" authorization database properties file is not found at this location " + dbPropertiesLocation);
131         } catch (IOException JavaDoc e) {
132             logger.severe(" authorization database properties file is not accesible this location " + dbPropertiesLocation + "\n "
133                     + e.getMessage());
134         } catch (URISyntaxException JavaDoc e) {
135             logger.log(Level.SEVERE, " uri of the authorization database properties file hasn't got a valid synthax ", e);
136         }
137
138         logger.finest("JdbcAuthenticationManager connectionFactory init map =" + map);
139         logger.finest("JdbcAuthenticationManager connectionFactory properties=" + properties);
140         // initialize database connection factory
141
connectionFactory = new ConnectionFactory(map);
142         super.applicationName = (String JavaDoc) map.get(CoreConstants.APPLICATION_NAME);
143         createRequiredDatabaseEntities(properties, this.connectionFactory);
144
145         boolean empty = isEmpty();
146         if (empty) {
147             insertRequiredData();
148         }
149
150         // we don't grab all the users like in XMLAuthenticationManager,
151
// because XML is only used for small applications
152
// it will be not suited to load all the users in memory
153

154         try {
155             initPrincipals();
156         } catch (SQLException JavaDoc e) {
157             logger.log(Level.SEVERE, " principals cannot be initialized ", e);
158         }
159
160         try {
161             subjectTemplate = getSubjectTemplate(DEFAULT);
162         } catch (AuthenticationException e) {
163             logger.log(Level.SEVERE, " default subjectTemplate cannot be initialized ", e);
164         }
165
166     }
167
168     private static void createRequiredDatabaseEntities(Properties JavaDoc properties, ConnectionFactory connectionFactory) {
169         List JavaDoc tablesNames = new ArrayList JavaDoc();
170         tablesNames.add("JG_PRINCIPAL");
171         tablesNames.add("JG_USER");
172         tablesNames.add("JG_CREDENTIAL");
173         tablesNames.add("JG_USER_PRINCIPAL");
174
175         tablesNames.add("JG_ST_CREDENTIAL");
176         tablesNames.add("JG_ST_PRINCIPAL");
177         tablesNames.add("JG_ST_USER");
178
179         List JavaDoc foreignkeysNames = new ArrayList JavaDoc();
180         foreignkeysNames.add("FK_USER_USER_PRINCIPAL");
181         foreignkeysNames.add("FK_USER_PRINCIPAL");
182         foreignkeysNames.add("FK_CREDENTIAL_USER_ID");
183
184         foreignkeysNames.add("FK_ST_USER_PRINCIPAL");
185         foreignkeysNames.add("FK_ST_USER_CREDENTIAL");
186
187         List JavaDoc sequencesNames = new ArrayList JavaDoc();
188         sequencesNames.add("JG_PRINCIPAL_SEQ");
189         sequencesNames.add("JG_USER_SEQ");
190         sequencesNames.add("JG_CREDENTIAL_SEQ");
191
192         sequencesNames.add("JG_ST_CREDENTIAL_SEQ");
193         sequencesNames.add("JG_ST_PRINCIPAL_SEQ");
194         sequencesNames.add("JG_ST_USER_SEQ");
195         // initialise database
196
DatabaseUtils.createRequiredDatabaseEntities(properties, connectionFactory, sequencesNames, tablesNames, foreignkeysNames);
197     }
198
199     /**
200      * initialize Principals declared in the application, and principals owned by the default
201      * @throws SQLException
202      * @see SubjectTemplate
203      */

204     private void initPrincipals() throws SQLException JavaDoc {
205         Connection JavaDoc connection = null;
206         ResultSet JavaDoc rs = null;
207         PreparedStatement JavaDoc pst = null;
208         try{
209         connection = connectionFactory.getConnection();
210         pst = connection.prepareStatement(properties.getProperty("LOCAL_PRINCIPALS"));
211         pst.setString(1, this.applicationName);
212         rs = pst.executeQuery();
213         while (rs.next()) {
214             String JavaDoc name = rs.getString(2);
215             String JavaDoc applicationName = rs.getString(3);
216             String JavaDoc className = rs.getString(4);
217             if (className.equals(RolePrincipal.class.getName())) {
218                 name = RolePrincipal.getName(name,applicationName);
219             }
220             Principal JavaDoc principal = PrincipalUtils.getPrincipal(className, name);
221             localPrincipalsSet.add(principal);
222             localPrincipals.put(principal.getName(), principal);
223         }
224         }finally{
225             rs.close();
226             pst.close();
227             connection.close();
228         }
229     }
230
231     private void insertRequiredData() {
232         Map JavaDoc options = new HashMap JavaDoc();
233         options.put(CoreConstants.APPLICATION_NAME, applicationName);
234         String JavaDoc XmlFileLocation = dbPropertiesLocation.substring(0, dbPropertiesLocation.lastIndexOf('/'))
235                 + "/jGuardUsersPrincipals.xml";
236         options.put(SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION, XmlFileLocation);
237         AuthenticationManager authentManager = new XmlAuthenticationManager();
238         authentManager.init(options);
239         importAuthenticationManager(authentManager);
240
241     }
242
243     public boolean isEmpty() {
244         List JavaDoc selectQueries = new ArrayList JavaDoc();
245         selectQueries.add("PRINCIPALS");
246         selectQueries.add("CREDENTIALS");
247         selectQueries.add("CREDENTIALS");
248         selectQueries.add("USERS");
249
250         return DatabaseUtils.isEmpty(this.properties, connectionFactory, selectQueries);
251
252     }
253
254     protected void updateUserImpl(JGuardCredential cred, Subject JavaDoc user) throws AuthenticationException {
255
256         Connection JavaDoc connection = null;
257         try {
258             long subjectId = getSubjectId(cred, user);
259             connection = connectionFactory.getConnection();
260             // get user from DB
261
Subject JavaDoc oldUser = getUser(subjectId);
262
263             connection.setAutoCommit(false);
264
265             updatePrivateCredentials(connection, subjectId, user, oldUser);
266             updatePublicCredentials(connection, subjectId, user, oldUser);
267             updatePrincipals(connection, subjectId, user, oldUser);
268
269             connection.commit();
270             connection.setAutoCommit(true);
271         } catch (SQLException JavaDoc e) {
272             logger.log(Level.SEVERE, " user can not be updated ", e);
273             if (connection != null)
274                 try {
275                     connection.rollback();
276                 } catch (SQLException JavaDoc excep) {
277                     throw new AuthenticationException(e);
278                 }
279             throw new AuthenticationException(e);
280         } catch (SecurityException JavaDoc e) {
281             logger.log(Level.FINEST, " user can not be updated: you don't have the permission to update private credentials", e);
282             if (connection != null)
283                 try {
284                     connection.rollback();
285                 } catch (SQLException JavaDoc excep) {
286                     throw new AuthenticationException(excep);
287                 }
288             throw new AuthenticationException(e);
289         } finally {
290             try {
291                 connection.close();
292             } catch (SQLException JavaDoc e) {
293                 logger.log(Level.SEVERE, " user can not be updated ", e);
294                 throw new AuthenticationException(e);
295             }
296         }
297
298     }
299
300     //TODO think better how to deal with definition in RolePrincipal, because if we only update the definition attr
301
// the RolePrincipal is not updated with this method
302
// by now, we are deleting and creating again all user principals
303
/*
304     private void updatePrincipals(Connection connection, long subjectId, Subject user, Subject oldUser) throws SQLException {
305         Set deletedPrincipals = new HashSet(oldUser.getPrincipals());
306         deletedPrincipals.removeAll(user.getPrincipals());
307         unlinkUserFromPrincipals(connection, subjectId, deletedPrincipals);
308
309         Set newPrincipals = new HashSet(user.getPrincipals());
310         newPrincipals.removeAll(oldUser.getPrincipals());
311         linkUserToPrincipals(connection, subjectId, newPrincipals);
312     }
313     */

314
315     private void updatePrincipals(Connection JavaDoc connection, long subjectId, Subject JavaDoc user, Subject JavaDoc oldUser) throws SQLException JavaDoc {
316         unlinkUserFromPrincipals(connection, subjectId, oldUser.getPrincipals());
317         linkUserToPrincipals(connection, subjectId, user.getPrincipals());
318     }
319     
320     private long getPrincipalId(Principal JavaDoc principal) throws SQLException JavaDoc {
321         ResultSet JavaDoc rs = null;
322         Connection JavaDoc connection = null;
323         PreparedStatement JavaDoc pst = null;
324         long principalId = -1;
325         try{
326         connection = connectionFactory.getConnection();
327         pst = connection.prepareStatement(properties.getProperty("GET_PRINCIPAL_ID"));
328         
329         
330         if (principal instanceof RolePrincipal) {
331             pst.setString(1, ((RolePrincipal)principal).getLocalName());
332             pst.setString(2, ((RolePrincipal) principal).getApplicationName());
333         } else {
334             pst.setString(1, principal.getName());
335             pst.setString(2, applicationName);
336         }
337         rs = pst.executeQuery();
338         rs.next();
339         principalId = rs.getLong(1);
340         }finally{
341             rs.close();
342             pst.close();
343             connection.close();
344         }
345         
346         return principalId;
347     }
348
349     private void unlinkUserFromPrincipals(Connection JavaDoc connection, long subjectId, Set JavaDoc principals) throws SQLException JavaDoc {
350
351         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("UNLINK_USER_PRINCIPAL"));
352         Iterator JavaDoc it = principals.iterator();
353         while (it.hasNext()) {
354             Principal JavaDoc principal = (Principal JavaDoc) it.next();
355             long principalId = getPrincipalId(principal);
356             pst.setLong(1, subjectId);
357             pst.setLong(2, principalId);
358             pst.executeUpdate();
359         }
360         pst.close();
361     }
362
363     private void linkUserToPrincipals(Connection JavaDoc connection, long subjectId, Set JavaDoc principals) throws SQLException JavaDoc {
364         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("LINK_USER_PRINCIPAL"));
365         Iterator JavaDoc it = principals.iterator();
366         while (it.hasNext()) {
367             Principal JavaDoc principal = (Principal JavaDoc) it.next();
368             long principalId = getPrincipalId(principal);
369             pst.setLong(1, subjectId);
370             pst.setLong(2, principalId);
371             if(principal instanceof RolePrincipal) {
372                 pst.setString(3, ((RolePrincipal)principal).getDefinition());
373                 pst.setBoolean(4, ((RolePrincipal)principal).isActive());
374             }
375             pst.executeUpdate();
376         }
377         pst.close();
378     }
379
380     private void updatePrivateCredentials(Connection JavaDoc connection, long subjectId, Subject JavaDoc user, Subject JavaDoc oldUser)
381             throws SQLException JavaDoc {
382
383         // delete old private credentials
384
Set JavaDoc deletedPrivateCredentials = new HashSet JavaDoc(oldUser.getPrivateCredentials(JGuardCredential.class));
385         deletedPrivateCredentials.removeAll(user.getPrivateCredentials(JGuardCredential.class));
386         Iterator JavaDoc itDeletedPrivateCredentials = deletedPrivateCredentials.iterator();
387         while (itDeletedPrivateCredentials.hasNext()) {
388             deleteCredential(connection, (JGuardCredential) itDeletedPrivateCredentials.next(), subjectId);
389         }
390
391         // add new private credentials
392
Set JavaDoc newPrivateCredentials = new HashSet JavaDoc(user.getPrivateCredentials(JGuardCredential.class));
393         newPrivateCredentials.removeAll(oldUser.getPrivateCredentials(JGuardCredential.class));
394         Iterator JavaDoc itNewPrivateCredentials = newPrivateCredentials.iterator();
395         while (itNewPrivateCredentials.hasNext()) {
396             persistCredential(connection, (JGuardCredential) itNewPrivateCredentials.next(), subjectId, false);
397         }
398     }
399
400     private void updatePublicCredentials(Connection JavaDoc connection, long subjectId, Subject JavaDoc user, Subject JavaDoc oldUser)
401             throws SQLException JavaDoc {
402
403         // delete old public credentials
404
Set JavaDoc deletedPublicCredentials = new HashSet JavaDoc(oldUser.getPublicCredentials(JGuardCredential.class));
405         deletedPublicCredentials.removeAll(user.getPublicCredentials(JGuardCredential.class));
406         Iterator JavaDoc itDeletedPublicCredentials = deletedPublicCredentials.iterator();
407         while (itDeletedPublicCredentials.hasNext()) {
408             deleteCredential(connection, (JGuardCredential) itDeletedPublicCredentials.next(), subjectId);
409         }
410
411         // add new public credentials
412
Set JavaDoc newPublicCredentials = new HashSet JavaDoc(user.getPublicCredentials(JGuardCredential.class));
413         newPublicCredentials.removeAll(oldUser.getPublicCredentials(JGuardCredential.class));
414         Iterator JavaDoc itNewPublicCredentials = newPublicCredentials.iterator();
415         while (itNewPublicCredentials.hasNext()) {
416             persistCredential(connection, (JGuardCredential) itNewPublicCredentials.next(), subjectId, true);
417         }
418     }
419
420     public void deleteUser(Subject JavaDoc user) throws AuthenticationException {
421         
422         PreparedStatement JavaDoc pst = null;
423         Connection JavaDoc connection = null;
424         try {
425             connection = connectionFactory.getConnection();
426             connection.setAutoCommit(false);
427             long subjectId = getSubjectId(user);
428
429             deleteCredentials(connection, subjectId);
430             deletePrincipals(connection, subjectId);
431
432             pst = connection.prepareStatement(properties.getProperty("DELETE_SUBJECT"));
433             pst.setLong(1, subjectId);
434             pst.executeUpdate();
435             pst.close();
436
437             connection.commit();
438             connection.setAutoCommit(true);
439
440         } catch (SQLException JavaDoc e) {
441             logger.log(Level.SEVERE, "deleteUser(Subject user)", e);
442             if (connection != null)
443                 try {
444                     connection.rollback();
445                 } catch (SQLException JavaDoc excep) {
446                     throw new AuthenticationException(excep);
447                 }
448             throw new AuthenticationException(e);
449         } finally {
450             try {
451                 connection.close();
452             } catch (SQLException JavaDoc e) {
453                 logger.log(Level.SEVERE, "deleteUser(Subject user)", e);
454                 throw new AuthenticationException(e);
455             }
456         }
457
458     }
459
460     private long getSubjectId(Subject JavaDoc user) throws SQLException JavaDoc, AuthenticationException {
461         JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
462         return getSubjectId(identityCred, user);
463     }
464
465     private long getSubjectId(JGuardCredential identityCred, Subject JavaDoc user) throws SQLException JavaDoc, AuthenticationException {
466         long userId = -1;
467         Connection JavaDoc connection = null;
468         PreparedStatement JavaDoc pst = null;
469         ResultSet JavaDoc rs = null;
470         try{
471         connection = connectionFactory.getConnection();
472         pst = connection.prepareStatement(properties.getProperty("GET_USER_ID"));
473         pst.setString(1, identityCred.getId());
474         pst.setString(2, (String JavaDoc) identityCred.getValue());
475
476         rs = pst.executeQuery();
477         while (rs.next()) {
478             if (userId != -1) {
479                 logger.severe("it exists more than one user with this identity credential ");
480                 throw new AuthenticationException("it exists more than one user with this identity credential ");
481             }
482             userId = rs.getLong(1);
483         }
484         if (userId == -1) {
485             logger.severe("no user exists with this identity credential ");
486             throw new AuthenticationException("no user exists with this identity credential ");
487         }
488         }finally{
489             rs.close();
490             pst.close();
491             connection.close();
492         }
493         return userId;
494     }
495
496     private void deletePrincipals(Connection JavaDoc connection, long subjectId) throws SQLException JavaDoc {
497         PreparedStatement JavaDoc pst = null;
498         pst = connection.prepareStatement(properties.getProperty("DELETE_USER_PRINCIPALS"));
499         pst.setLong(1, subjectId);
500         pst.executeUpdate();
501         pst.close();
502     }
503
504     private void deleteCredentials(Connection JavaDoc connection, long subjectId) throws SQLException JavaDoc {
505         PreparedStatement JavaDoc pst = null;
506         pst = connection.prepareStatement(properties.getProperty("DELETE_USER_CREDENTIALS"));
507         pst.setLong(1, subjectId);
508         pst.executeUpdate();
509         pst.close();
510     }
511
512     private void persistCredentials(Connection JavaDoc connection, Subject JavaDoc subject, long subjectId) throws SQLException JavaDoc {
513         Set JavaDoc publicCredentials = subject.getPublicCredentials();
514         Iterator JavaDoc itPublic = publicCredentials.iterator();
515         while (itPublic.hasNext()) {
516             JGuardCredential jgCred = (JGuardCredential) itPublic.next();
517             persistCredential(connection, jgCred, subjectId, true);
518         }
519
520         Set JavaDoc privateCredentials = subject.getPrivateCredentials();
521         Iterator JavaDoc itPrivate = privateCredentials.iterator();
522         while (itPrivate.hasNext()) {
523             JGuardCredential jgCred = (JGuardCredential) itPrivate.next();
524             persistCredential(connection, jgCred, subjectId, false);
525         }
526
527     }
528
529     private void persistCredential(Connection JavaDoc connection, JGuardCredential jgCred, long userId, boolean publicVisibility)
530             throws SQLException JavaDoc {
531
532         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("ADD_CREDENTIAL"));
533         pst.setLong(1, userId);
534         pst.setBoolean(2, publicVisibility);
535         pst.setString(3, jgCred.getId());
536         pst.setString(4, (String JavaDoc) jgCred.getValue());
537         pst.executeUpdate();
538         pst.close();
539     }
540
541     // TODO VBE : remove this method. Credentials are not updated anymore, they are removed and added.
542
// This is done because this method is not handling multivalued credentials
543
private void updateCredential(Connection JavaDoc connection, JGuardCredential jgCred, long userId) throws SQLException JavaDoc {
544
545         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("UPDATE_CREDENTIAL"));
546         pst.setString(1, (String JavaDoc) jgCred.getValue());
547         pst.setLong(2, userId);
548         pst.setString(3, jgCred.getId());
549         pst.executeUpdate();
550         pst.close();
551     }
552
553     private void deleteCredential(Connection JavaDoc connection, JGuardCredential jgCred, long userId) throws SQLException JavaDoc {
554
555         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("DELETE_CREDENTIAL"));
556         pst.setLong(1, userId);
557         pst.setString(2, jgCred.getId());
558         pst.setString(3, (jgCred.getValue() != null ? jgCred.getValue().toString() : ""));
559         pst.executeUpdate();
560         pst.close();
561     }
562
563     private void persistPrincipals(Connection JavaDoc connection, Subject JavaDoc subject, long subjectId) throws SQLException JavaDoc,
564             AuthenticationException {
565
566         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("LINK_USER_PRINCIPAL"));
567         Set JavaDoc principals = subject.getPrincipals();
568         Iterator JavaDoc it = principals.iterator();
569         while (it.hasNext()) {
570             Principal JavaDoc ppal = (Principal JavaDoc) it.next();
571             createPrincipal(ppal);
572
573             long principalId = getPrincipalId(ppal);
574
575             pst.setLong(1, subjectId);
576             pst.setLong(2, principalId);
577             if(ppal instanceof RolePrincipal) {
578                 pst.setString(3, ((RolePrincipal)ppal).getDefinition());
579                 pst.setBoolean(4, ((RolePrincipal)ppal).isActive());
580             }
581             
582             pst.executeUpdate();
583         }
584         pst.close();
585     }
586
587     protected void persistUser(Subject JavaDoc user) throws AuthenticationException {
588         
589         PreparedStatement JavaDoc pst = null;
590         PreparedStatement JavaDoc pst2 = null;
591         ResultSet JavaDoc rs2 = null;
592         Connection JavaDoc connection = null;
593         try {
594             connection = connectionFactory.getConnection();
595             connection.setAutoCommit(false);
596
597             pst = connection.prepareStatement(properties.getProperty("ADD_SUBJECT"));
598             pst.executeUpdate();
599             pst.close();
600
601             pst2 = connection.prepareStatement(properties.getProperty("GET_SUBJECT_ID"));
602             rs2 = pst2.executeQuery();
603             rs2.next();
604             long subjectId = rs2.getLong(1);
605             rs2.close();
606             pst2.close();
607
608             persistCredentials(connection, user, subjectId);
609             persistPrincipals(connection, user, subjectId);
610
611             connection.commit();
612             connection.setAutoCommit(true);
613
614         } catch (SQLException JavaDoc e) {
615             logger.log(Level.SEVERE, "persistUser(Subject user)", e);
616             if (connection != null)
617                 try {
618                     connection.rollback();
619                 } catch (SQLException JavaDoc excep) {
620                     throw new AuthenticationException(excep);
621                 }
622             throw new AuthenticationException(e);
623         } finally {
624             try {
625                 connection.close();
626             } catch (SQLException JavaDoc e) {
627                 logger.log(Level.SEVERE, "persistUser(Subject user)", e);
628                 throw new AuthenticationException(e);
629             }
630         }
631
632     }
633
634     public void updateDefaultSubjectTemplate(SubjectTemplate template) throws AuthenticationException {
635         Connection JavaDoc connection = null;
636
637         try {
638             connection = connectionFactory.getConnection();
639             connection.setAutoCommit(false);
640             long defaultSubjecttemplateID = getSubjectTemplateID(DEFAULT);
641             persistSubjectTemplateCredentials(connection, template, defaultSubjecttemplateID);
642             persistSubjectTemplatePrincipals(connection, template, defaultSubjecttemplateID);
643
644             connection.commit();
645             connection.setAutoCommit(true);
646         } catch (SQLException JavaDoc e) {
647             logger.log(Level.SEVERE, " default subject_template cannot be updated ", e);
648             if (connection != null)
649                 try {
650                     connection.rollback();
651                 } catch (SQLException JavaDoc excep) {
652                     throw new AuthenticationException(excep);
653                 }
654             throw new AuthenticationException(e);
655         }finally {
656             try {
657                 connection.close();
658             } catch (SQLException JavaDoc e) {
659                 logger.log(Level.SEVERE, "default subject_template cannot be updated ", e);
660                 throw new AuthenticationException(e);
661             }
662         }
663
664     }
665
666     public void persistSubjectTemplate(SubjectTemplate template) throws AuthenticationException {
667         Connection JavaDoc connection = null;
668         long stId = -1;
669         try {
670             connection = connectionFactory.getConnection();
671             connection.setAutoCommit(false);
672
673             PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("ADD_SUBJECT_TEMPLATE"));
674             pst.setString(1, template.getName());
675             pst.executeUpdate();
676             pst.close();
677
678             PreparedStatement JavaDoc pst2 = connection.prepareStatement(properties.getProperty("GET_SUBJECT_TEMPLATE_ID"));
679             ResultSet JavaDoc rs2 = pst2.executeQuery();
680             rs2.next();
681             stId = rs2.getLong(1);
682             rs2.close();
683             pst2.close();
684
685             persistSubjectTemplateCredentials(connection, template, stId);
686             persistSubjectTemplatePrincipals(connection, template, stId);
687
688             connection.commit();
689             connection.setAutoCommit(true);
690         } catch (SQLException JavaDoc e) {
691             logger.log(Level.SEVERE, " subject_template cannot be created ", e);
692             if (connection != null)
693                 try {
694                     connection.rollback();
695                 } catch (SQLException JavaDoc excep) {
696                     throw new AuthenticationException(excep);
697                 }
698             throw new AuthenticationException(e);
699         } finally {
700             try {
701                 connection.close();
702             } catch (SQLException JavaDoc e) {
703                 logger.log(Level.SEVERE, "subject_template cannot be created", e);
704                 throw new AuthenticationException(e);
705             }
706         }
707     }
708
709     private void persistSubjectTemplatePrincipals(Connection JavaDoc connection, SubjectTemplate template, long stId) throws SQLException JavaDoc {
710
711         Set JavaDoc genericPrincipals = template.getPrincipals();
712         Iterator JavaDoc itGenPrincipals = genericPrincipals.iterator();
713         while (itGenPrincipals.hasNext()) {
714             Principal JavaDoc ppal = (Principal JavaDoc) itGenPrincipals.next();
715             persistSubjectTemplatePrincipal(connection, ppal, stId);
716         }
717     }
718
719     private void persistSubjectTemplatePrincipal(Connection JavaDoc connection, Principal JavaDoc principal, long stId) throws SQLException JavaDoc {
720
721         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("ADD_ST_PRINCIPAL"));
722         if (principal instanceof RolePrincipal) {
723             pst.setString(1, ((RolePrincipal)principal).getLocalName());
724             pst.setString(2, ((RolePrincipal) principal).getApplicationName());
725         } else {
726             pst.setString(1, principal.getName());
727             pst.setString(2, applicationName);
728         }
729         pst.setString(3, principal.getClass().getName());
730
731         pst.setLong(4, stId);
732         pst.executeUpdate();
733         pst.close();
734
735         localPrincipals.put(principal.getName(), principal);
736         localPrincipalsSet.add(principal);
737     }
738
739     private void persistSubjectTemplateCredentials(Connection JavaDoc connection, SubjectTemplate st, long subjectTemplateId)
740             throws SQLException JavaDoc {
741
742         Set JavaDoc privateRequiredCred = st.getPrivateRequiredCredentials();
743         Iterator JavaDoc itPrivateRequiredCred = privateRequiredCred.iterator();
744         while (itPrivateRequiredCred.hasNext()) {
745             JGuardCredential jgCred = (JGuardCredential) itPrivateRequiredCred.next();
746             // required and public: 'true' and 'false'
747
persistStCredential(connection, jgCred, subjectTemplateId, true, false);
748         }
749
750         Set JavaDoc publicRequiredCreds = st.getPublicRequiredCredentials();
751         Iterator JavaDoc itPublicRequiredCred = publicRequiredCreds.iterator();
752         while (itPublicRequiredCred.hasNext()) {
753             JGuardCredential jgCred = (JGuardCredential) itPublicRequiredCred.next();
754             // required and public: both 'true'
755
persistStCredential(connection, jgCred, subjectTemplateId, true, true);
756         }
757
758         Set JavaDoc privateOptionalCred = st.getPrivateOptionalCredentials();
759         Iterator JavaDoc itPrivateOptionalCred = privateOptionalCred.iterator();
760         while (itPrivateOptionalCred.hasNext()) {
761             JGuardCredential jgCred = (JGuardCredential) itPrivateOptionalCred.next();
762             // required and public: both 'false'
763
persistStCredential(connection, jgCred, subjectTemplateId, false, false);
764         }
765
766         Set JavaDoc publicOptionalCreds = st.getPublicOptionalCredentials();
767         Iterator JavaDoc itPublicOptionalCred = publicOptionalCreds.iterator();
768         while (itPublicOptionalCred.hasNext()) {
769             JGuardCredential jgCred = (JGuardCredential) itPublicOptionalCred.next();
770             // required and public: 'false' and 'true'
771
persistStCredential(connection, jgCred, subjectTemplateId, false, true);
772         }
773     }
774
775     private void persistStCredential(Connection JavaDoc connection, JGuardCredential jgCred, long subjectTemplateId, boolean required,
776             boolean public_visibility) throws SQLException JavaDoc {
777
778         PreparedStatement JavaDoc pst = connection.prepareStatement(properties.getProperty("ADD_ST_CREDENTIAL"));
779         pst.setString(1, jgCred.getId());
780         pst.setBoolean(2, public_visibility);
781         pst.setBoolean(3, required);
782         pst.setBoolean(4, jgCred.isIdentity());
783         pst.setLong(5, subjectTemplateId);
784         pst.executeUpdate();
785         pst.close();
786     }
787
788     public final ConnectionFactory getConnectionFactory() {
789         return connectionFactory;
790     }
791
792     public final Properties JavaDoc getProperties() {
793         return properties;
794     }
795
796     public final void setProperties(Properties JavaDoc properties) {
797         this.properties = properties;
798     }
799
800     public SubjectTemplate getSubjectTemplate(String JavaDoc name) throws AuthenticationException {
801         
802         SubjectTemplate st = new SubjectTemplate();
803         try {
804             long subjectTemplateId = getSubjectTemplateID(name);
805             populateSubjectTemplatePrincipals(st, subjectTemplateId);
806             populateSubjectTemplateCredentials(st, subjectTemplateId);
807
808         } catch (SQLException JavaDoc e) {
809             logger.log(Level.SEVERE, " subject_template cannot be grabbed ", e);
810             throw new AuthenticationException(e);
811         }
812
813         return st;
814
815     }
816
817     private void populateSubjectTemplatePrincipals(SubjectTemplate st, long subjectTemplateId) throws SQLException JavaDoc {
818         Connection JavaDoc connection= null;
819         
820         try{
821             connection = connectionFactory.getConnection();
822             PreparedStatement JavaDoc pst2 = connection.prepareStatement(properties.getProperty("GET_ST_PRINCIPALS"));
823             pst2.setLong(1, subjectTemplateId);
824             ResultSet JavaDoc rs2 = pst2.executeQuery();
825             Set JavaDoc genericPrincipals = new HashSet JavaDoc();
826             while (rs2.next()) {
827                 String JavaDoc className = rs2.getString(4);
828                 String JavaDoc principalName = (String JavaDoc) rs2.getString(2);
829                 if (className.equals(RolePrincipal.class.getName())) {
830                     principalName = RolePrincipal.getName(principalName,rs2.getString(3));
831                 }
832                 Principal JavaDoc ppal = PrincipalUtils.getPrincipal(className, principalName);
833                 genericPrincipals.add(ppal);
834             }
835             rs2.close();
836             pst2.close();
837             st.setPrincipals(genericPrincipals);
838         }finally{
839             connection.close();
840         }
841         
842     }
843
844     private void populateSubjectTemplateCredentials(SubjectTemplate st, long subjectTemplateId) throws SQLException JavaDoc {
845         Connection JavaDoc connection = null;
846         try{
847             
848         connection = connectionFactory.getConnection();
849         PreparedStatement JavaDoc pst3 = connection.prepareStatement(properties.getProperty("GET_ST_CREDENTIALS"));
850         pst3.setLong(1, subjectTemplateId);
851         ResultSet JavaDoc rs3 = pst3.executeQuery();
852         Set JavaDoc privateOptionalCredentials = new HashSet JavaDoc();
853         Set JavaDoc privateRequiredCredentials = new HashSet JavaDoc();
854         Set JavaDoc publicOptionalCredentials = new HashSet JavaDoc();
855         Set JavaDoc publicRequiredCredentials = new HashSet JavaDoc();
856
857         while (rs3.next()) {
858             JGuardCredential cred = new JGuardCredential();
859             cred.setId(rs3.getString(2));
860             boolean public_visibility = rs3.getBoolean(3);
861             boolean required = rs3.getBoolean(4);
862             cred.setIdentity(rs3.getBoolean(5));
863             if (public_visibility && required) {
864                 publicRequiredCredentials.add(cred);
865             } else if (!public_visibility && required) {
866                 privateRequiredCredentials.add(cred);
867             } else if (public_visibility && !required) {
868                 publicOptionalCredentials.add(cred);
869             } else if (!public_visibility && !required) {
870                 privateOptionalCredentials.add(cred);
871             }
872
873         }
874         rs3.close();
875         pst3.close();
876         st.setPrivateOptionalCredentials(privateOptionalCredentials);
877         st.setPrivateRequiredCredentials(privateRequiredCredentials);
878         st.setPublicOptionalCredentials(publicOptionalCredentials);
879         st.setPublicRequiredCredentials(publicRequiredCredentials);
880         }finally{
881             connection.close();
882         }
883     }
884
885     /**
886      * return the row id for the {@link SubjectTemplate} identified by its name.
887      * @param name
888      * @return
889      * @throws SQLException
890      * @throws AuthenticationException thrown when either no ID is found or more than one ID are found
891      */

892     private long getSubjectTemplateID(String JavaDoc name) throws SQLException JavaDoc, AuthenticationException {
893         Connection JavaDoc connection = null;
894         PreparedStatement JavaDoc pst;
895         ResultSet JavaDoc rs;
896         long subjectTemplateId = -1;
897         int subjectTemplateFound = 0;
898         try{
899             connection = connectionFactory.getConnection();
900             pst = connection.prepareStatement(properties.getProperty("GET_SUBJECT_TEMPLATE"));
901             pst.setString(1, name);
902             rs = pst.executeQuery();
903             
904             while (rs.next()) {
905                 subjectTemplateId = rs.getLong(1);
906                 subjectTemplateFound++;
907             }
908             rs.close();
909             pst.close();
910             
911         }finally{
912             connection.close();
913         }
914         if(subjectTemplateId==-1){
915             throw new AuthenticationException(" subjectTemplate ID intitled "+name+" cannot be found ");
916         }
917         if(subjectTemplateFound>1){
918             throw new AuthenticationException(" more than one ID for subjectTemplate intitled "+name+" has been found ");
919         }
920         return subjectTemplateId;
921     }
922
923     public Set JavaDoc getAllPrincipalsSet() throws AuthenticationException {
924         Set JavaDoc allPrincipals = new HashSet JavaDoc();
925         
926         PreparedStatement JavaDoc pst = null;
927         ResultSet JavaDoc rs = null;
928         Connection JavaDoc connection = null;
929         try {
930             connection = connectionFactory.getConnection();
931             pst = connection.prepareStatement(properties.getProperty("PRINCIPALS"));
932             rs = pst.executeQuery();
933             while (rs.next()) {
934                 String JavaDoc name = rs.getString(2);
935                 String JavaDoc className = rs.getString(4);
936                 String JavaDoc applicationName = rs.getString(3);
937                 if (RolePrincipal.class.getName().equals(className)) {
938                     name= RolePrincipal.getName(name, applicationName);
939                 }
940                 Principal JavaDoc principal = PrincipalUtils.getPrincipal(className, name);
941                 
942                 allPrincipals.add(principal);
943             }
944
945             rs.close();
946             pst.close();
947         } catch (SQLException JavaDoc e) {
948             logger.log(Level.SEVERE, " principals cannot be grabbed ", e);
949             throw new AuthenticationException(e);
950         } finally {
951             try {
952                 connection.close();
953             } catch (SQLException JavaDoc e) {
954                 logger.log(Level.SEVERE, " principals cannot be grabbed ", e);
955                 throw new AuthenticationException(e);
956             }
957         }
958         return allPrincipals;
959     }
960
961     /**
962      * search the users which matches ALL of the credentials criterions.
963      *
964      * @param credentials
965      * crierions used to grab the users
966      * @return users found
967      */

968     public Set JavaDoc findUsers(Collection JavaDoc credentials) throws AuthenticationException {
969         Set JavaDoc users = new HashSet JavaDoc();
970
971         if (credentials.isEmpty())
972             return users;
973
974         Connection JavaDoc connection = null;
975         PreparedStatement JavaDoc pst = null;
976         ResultSet JavaDoc rs = null;
977         String JavaDoc findUsers = properties.getProperty("FIND_USERS");
978         String JavaDoc[] tokens = findUsers.split(" ");
979         String JavaDoc user_id = tokens[2];
980         String JavaDoc jg_credential = tokens[4];
981         String JavaDoc cred_name = tokens[6];
982         String JavaDoc cred_value = tokens[9];
983         try {
984             connection = connectionFactory.getConnection();
985             // we build the query
986
StringBuffer JavaDoc dynamicQuery = new StringBuffer JavaDoc();
987             StringBuffer JavaDoc tables = new StringBuffer JavaDoc();
988             StringBuffer JavaDoc conditions = new StringBuffer JavaDoc();
989
990             for (int count = 0; count < credentials.size(); count++) {
991                 if (count > 0) {
992                     tables.append(',');
993                     conditions.append(" and ");
994                 } else {
995                     conditions.append(" where ");
996                 }
997                 StringBuffer JavaDoc alias = new StringBuffer JavaDoc("cred").append(count);
998                 tables.append(' ').append(jg_credential).append(' ').append(alias);
999                 conditions.append(alias).append('.').append(cred_name).append("= ? and ");
1000                conditions.append(alias).append('.').append(cred_value).append("= ? ");
1001                if (count > 0) {
1002                    conditions.append(" and cred0.").append(user_id).append('=');
1003                    conditions.append(alias).append('.').append(user_id).append(' ');
1004                }
1005            }
1006
1007            dynamicQuery.append(" select distinct cred0.").append(user_id).append(" from ");
1008            dynamicQuery.append(tables);
1009            dynamicQuery.append(conditions);
1010            logger.finest(dynamicQuery.toString());
1011            pst = connection.prepareStatement(dynamicQuery.toString());
1012
1013            Iterator JavaDoc itCredentials = credentials.iterator();
1014            int count2 = 1;
1015            while (itCredentials.hasNext()) {
1016                JGuardCredential jcred = (JGuardCredential) itCredentials.next();
1017                pst.setString(count2, jcred.getId());
1018                count2++;
1019                pst.setString(count2, jcred.getValue().toString());
1020                count2++;
1021            }
1022            rs = pst.executeQuery();
1023            while (rs.next()) {
1024                Subject JavaDoc user = null;
1025                int userId = rs.getInt(1);
1026                user = getUser(userId);
1027                users.add(user);
1028            }
1029
1030            rs.close();
1031            pst.close();
1032        } catch (SQLException JavaDoc e) {
1033            logger.log(Level.SEVERE, " error when we try to find users which maps to credentials ", e);
1034            throw new AuthenticationException(e);
1035        } finally {
1036            try {
1037                connection.close();
1038            } catch (SQLException JavaDoc e) {
1039                logger.log(Level.SEVERE, "users cannot be found ", e);
1040                throw new AuthenticationException(e);
1041            }
1042        }
1043        return users;
1044    }
1045
1046    /**
1047     * search the user's principals .
1048     *
1049     * @param usrId
1050     * @return user principals
1051     * @throws SQLException
1052     */

1053    private static Set JavaDoc getUserPrincipals(long usrId) throws SQLException JavaDoc {
1054        JdbcAuthenticationManager authManager = (JdbcAuthenticationManager) AuthenticationManagerFactory
1055                .getAuthenticationManager();
1056        ConnectionFactory connectionFactory = authManager.getConnectionFactory();
1057        Connection JavaDoc connection = null;
1058        PreparedStatement JavaDoc pst = null;
1059        ResultSet JavaDoc rs = null;
1060        Set JavaDoc userPrincipals = new HashSet JavaDoc();
1061        try{
1062            connection = connectionFactory.getConnection();
1063            
1064            pst = connection.prepareStatement(authManager.getProperties().getProperty("GET_USER_PRINCIPALS"));
1065            pst.setLong(1, usrId);
1066            rs = pst.executeQuery();
1067            while (rs.next()) {
1068                RolePrincipal principal = new RolePrincipal();
1069                principal.setLocalName(rs.getString(1));
1070                principal.setApplicationName(rs.getString(2));
1071                logger.finest("principal added" + principal + " to user " + usrId);
1072                userPrincipals.add(principal);
1073                
1074            }
1075        }catch(SQLException JavaDoc e){
1076            logger.warning(" principals for user with id="+usrId+" cannot be found");
1077            throw e;
1078            
1079        }finally{
1080        rs.close();
1081        pst.close();
1082        connection.close();
1083        }
1084        return userPrincipals;
1085    }
1086
1087    /**
1088     * search the user's credentials .
1089     *
1090     * @param usrId
1091     * @param publicVisibility - indicate if the credentials to return are public or private
1092     * @return user credentials
1093     * @throws SQLException
1094     */

1095    private static Set JavaDoc getUserCredentials(long usrId, boolean publicVisibility) throws SQLException JavaDoc {
1096        JdbcAuthenticationManager authManager = (JdbcAuthenticationManager) AuthenticationManagerFactory
1097                .getAuthenticationManager();
1098        ConnectionFactory connectionFactory = authManager.getConnectionFactory();
1099        Connection JavaDoc connection = null;
1100        PreparedStatement JavaDoc pst = null;
1101        ResultSet JavaDoc rs = null;
1102        Set JavaDoc userCredentials = new HashSet JavaDoc();
1103        try{
1104        connection = connectionFactory.getConnection();
1105        
1106        pst = connection.prepareStatement(authManager.getProperties().getProperty("GET_USER_CREDENTIALS"));
1107        pst.setLong(1, usrId);
1108        pst.setBoolean(2, publicVisibility);
1109        rs = pst.executeQuery();
1110        while (rs.next()) {
1111            JGuardCredential cred = new JGuardCredential();
1112            cred.setId(rs.getString(1));
1113            cred.setValue(rs.getString(2));
1114            userCredentials.add(cred);
1115            logger.finest(" credential added " + cred + " to user " + usrId);
1116        }
1117        }finally{
1118            rs.close();
1119            pst.close();
1120            connection.close();
1121        }
1122        
1123        return userCredentials;
1124    }
1125
1126    /**
1127     * return all users of jGuard.
1128     */

1129    public Set JavaDoc getUsers() throws AuthenticationException {
1130        Set JavaDoc users = new HashSet JavaDoc();
1131        
1132        PreparedStatement JavaDoc pst = null;
1133        ResultSet JavaDoc rs = null;
1134        Connection JavaDoc connection = null;
1135        try {
1136            connection = connectionFactory.getConnection();
1137            pst = connection.prepareStatement(properties.getProperty("GET_USERS"));
1138            rs = pst.executeQuery();
1139            while (rs.next()) {
1140                long userId = rs.getLong(1);
1141                Subject JavaDoc user = getUser(userId);
1142                users.add(user);
1143            }
1144
1145            rs.close();
1146            pst.close();
1147        } catch (SQLException JavaDoc e) {
1148            logger.log(Level.SEVERE, " users cannot be grabbed ", e);
1149            throw new AuthenticationException(e);
1150        } finally {
1151            try {
1152                connection.close();
1153            } catch (SQLException JavaDoc e) {
1154                logger.log(Level.SEVERE, " users cannot be grabbed ", e);
1155                throw new AuthenticationException(e);
1156            }
1157        }
1158        return users;
1159    }
1160
1161    /**
1162     *
1163     * @param userId
1164     * @return
1165     * @throws SQLException
1166     */

1167    public static Subject JavaDoc getUser(long userId) throws SQLException JavaDoc {
1168        // SQL exception is not catched because JdbcLoginModule need to have the exception to rollback
1169
Set JavaDoc userPrincipals = getUserPrincipals(userId);
1170        Set JavaDoc userPubCred = getUserCredentials(userId, true);
1171        Set JavaDoc userPrivCred = getUserCredentials(userId, false);
1172        // subject is not in read-only mode
1173
Subject JavaDoc user = new Subject JavaDoc(false, userPrincipals, userPubCred, userPrivCred);
1174        return user;
1175    }
1176
1177    public void updatePrincipal(String JavaDoc oldName, Principal JavaDoc principal) throws AuthenticationException {
1178        if (oldName.equals(principal.getName())) {
1179            return;
1180        }
1181        Connection JavaDoc connection = null;
1182        PreparedStatement JavaDoc pst = null;
1183        try {
1184            connection = connectionFactory.getConnection();
1185            pst = connection.prepareStatement(properties.getProperty("UPDATE_PRINCIPAL"));
1186            pst.setString(1, principal.getName());
1187            pst.setString(2, oldName);
1188            pst.setString(3, applicationName);
1189            pst.executeUpdate();
1190            pst.close();
1191
1192        } catch (SQLException JavaDoc e) {
1193            logger.log(Level.SEVERE, "updatePrincipal(String oldName, Principal principal)", e);
1194            throw new AuthenticationException(e);
1195        } finally {
1196            try {
1197                connection.close();
1198            } catch (SQLException JavaDoc e) {
1199                logger.log(Level.SEVERE, "updatePrincipal(String oldName, Principal principal)", e);
1200                throw new AuthenticationException(e);
1201            }
1202        }
1203
1204        // if the database update is right, we can update the in memory reference
1205
Principal JavaDoc oldPal = (Principal JavaDoc)localPrincipals.remove(oldName);
1206        localPrincipalsSet.remove(oldPal);
1207        localPrincipals.put(principal.getName(), principal);
1208        localPrincipalsSet.add(principal);
1209        
1210
1211    }
1212
1213    public boolean deletePrincipal(Principal JavaDoc principal) throws AuthenticationException {
1214        
1215        PreparedStatement JavaDoc pst = null;
1216        PreparedStatement JavaDoc pst2 = null;
1217        PreparedStatement JavaDoc pst3 = null;
1218        Connection JavaDoc connection = null;
1219        ResultSet JavaDoc rs = null;
1220        try {
1221            connection = connectionFactory.getConnection();
1222            connection.setAutoCommit(false);
1223
1224            // we are looking for the principalId
1225
pst = connection.prepareStatement(properties.getProperty("GET_PRINCIPAL_ID"));
1226            pst.setString(1, principal.getName());
1227            pst.setString(2, applicationName);
1228            rs = pst.executeQuery();
1229            long principalId = -1;
1230            if (rs.next()){
1231                principalId = rs.getLong(1);
1232            }else{
1233                logger.finest(" there is no principal to delete: " + principal.getName());
1234                return false;
1235            }
1236            
1237
1238            // we use principalId to delete links between users and this principal
1239
pst2 = connection.prepareStatement(properties.getProperty("DELETE_PRINCIPAL_USERS"));
1240            pst2.setLong(1, principalId);
1241            pst2.executeUpdate();
1242            pst2.close();
1243
1244            // we delete the principal
1245
pst3 = connection.prepareStatement(properties.getProperty("DELETE_PRINCIPAL"));
1246            pst3.setString(1, principal.getName());
1247            pst3.executeUpdate();
1248            pst3.close();
1249
1250            connection.commit();
1251            connection.setAutoCommit(true);
1252            
1253        } catch (SQLException JavaDoc e) {
1254            logger.log(Level.SEVERE, "deletePrincipal(Principal principal)", e);
1255            if (connection != null)
1256                try {
1257                    connection.rollback();
1258                } catch (SQLException JavaDoc excep) {
1259                    throw new AuthenticationException(e);
1260                }
1261            throw new AuthenticationException(e);
1262        } finally {
1263            try {
1264                rs.close();
1265                pst.close();
1266                connection.close();
1267            } catch (SQLException JavaDoc e) {
1268                logger.log(Level.SEVERE, "deletePrincipal(Principal principal)", e);
1269                throw new AuthenticationException(e);
1270            }
1271        }
1272        
1273        // if the database update is right, we can update the in memory reference
1274
Principal JavaDoc oldPal = (Principal JavaDoc)localPrincipals.remove(principal.getName());
1275        localPrincipalsSet.remove(oldPal);
1276        return true;
1277    }
1278
1279}
1280
Popular Tags