KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > ldap > LDAPNovell


1 package com.knowgate.ldap;
2
3 /*
4   Copyright (C) 2004 Know Gate S.L. All rights reserved.
5                       C/Oña, 107 1º2 28050 Madrid (Spain)
6
7   Redistribution and use in source and binary forms, with or without
8   modification, are permitted provided that the following conditions
9   are met:
10
11   1. Redistributions of source code must retain the above copyright
12      notice, this list of conditions and the following disclaimer.
13
14   2. The end-user documentation included with the redistribution,
15      if any, must include the following acknowledgment:
16      "This product includes software parts from hipergate
17      (http://www.hipergate.org/)."
18      Alternately, this acknowledgment may appear in the software itself,
19      if and wherever such third-party acknowledgments normally appear.
20
21   3. The name hipergate must not be used to endorse or promote products
22      derived from this software without prior written permission.
23      Products derived from this software may not be called hipergate,
24      nor may hipergate appear in their name, without prior written
25      permission.
26
27   This library is distributed in the hope that it will be useful,
28   but WITHOUT ANY WARRANTY; without even the implied warranty of
29   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
30
31   You should have received a copy of hipergate License with this code;
32   if not, visit http://www.hipergate.org or mail to info@hipergate.org
33 */

34
35 import java.io.UnsupportedEncodingException JavaDoc;
36 import java.util.Vector JavaDoc;
37 import java.util.Properties JavaDoc;
38
39 import com.novell.ldap.LDAPAttribute;
40 import com.novell.ldap.LDAPAttributeSet;
41 import com.novell.ldap.LDAPEntry;
42 import com.novell.ldap.LDAPConnection;
43 import com.novell.ldap.LDAPSearchResults;
44 import com.novell.ldap.LDAPException;
45
46 import java.sql.Connection JavaDoc;
47 import java.sql.Statement JavaDoc;
48 import java.sql.PreparedStatement JavaDoc;
49 import java.sql.ResultSet JavaDoc;
50 import java.sql.SQLException JavaDoc;
51 import java.sql.ResultSetMetaData JavaDoc;
52
53 import com.knowgate.debug.DebugFile;
54 import com.knowgate.misc.Gadgets;
55 import com.knowgate.dataobjs.*;
56
57 /**
58  * Very Basic LDAP interface API implementation
59  * @author Sergio Montoro Ten
60  * @version 2.1
61  */

62
63 public class LDAPNovell extends LDAPModel {
64   private LDAPConnection oConn;
65   private String JavaDoc sBase;
66
67   public LDAPNovell() {
68     oConn = null;
69     sBase = null;
70   }
71
72   // ---------------------------------------------------------------------------
73

74   /**
75    * <p>Connect to LDAP Service</p>
76    * At this point, there is no authentication, and any operations are conducted as an anonymous client.
77    * @param sConnStr ldap://<i>host</i>:port/<i>distinguished_name</i><br><b>Example</b> "ldap://fobos.kg.int:389/dc=hipergate,dc=org"
78    * @throws com.knowgate.ldap.LDAPException
79    */

80   public void connect(String JavaDoc sConnStr) throws com.knowgate.ldap.LDAPException {
81
82     if (DebugFile.trace) {
83       DebugFile.writeln("Begin LDAPNovell.connect(" + sConnStr + ")");
84       DebugFile.incIdent();
85     }
86
87     if (sConnStr.startsWith("ldap://")) sConnStr = sConnStr.substring(7);
88
89     String JavaDoc sService = sConnStr.substring(0, sConnStr.indexOf('/'));
90     String JavaDoc[] aService = Gadgets.split2(sService, ':');
91
92     try {
93       oConn = new LDAPConnection();
94       if (aService.length<2)
95         oConn.connect(aService[0].trim(), 389);
96       else
97         oConn.connect(aService[0].trim(), Integer.parseInt(aService[1]));
98       sBase = sConnStr.substring(sConnStr.indexOf('/')+1);
99     }
100     catch (com.novell.ldap.LDAPException xcpt) {
101       if (DebugFile.trace)
102         DebugFile.decIdent();
103       sBase = null;
104       if (DebugFile.trace) {
105         DebugFile.writeln("LDAPNovell.connect() LDAPException "+xcpt.getMessage());
106         DebugFile.decIdent();
107       }
108       throw new com.knowgate.ldap.LDAPException(xcpt.getMessage(), xcpt);
109     }
110     catch (java.lang.NumberFormatException JavaDoc nfe) {
111       if (DebugFile.trace) {
112         DebugFile.writeln("LDAPNovell.connect() NumberFormatException Invalid port number");
113         DebugFile.decIdent();
114       }
115       sBase = null;
116       throw new com.knowgate.ldap.LDAPException("Invalid port number", nfe);
117     }
118
119     if (DebugFile.trace) {
120       DebugFile.decIdent();
121       DebugFile.writeln("End LDAPNovell.connect()");
122     }
123   } // connect
124

125   // ---------------------------------------------------------------------------
126

127   /**
128    * <P>Connect to LDAP Server using a Properties object</P>
129    * @param oProps Properties for connecting to LDAP server.<BR>
130    * For example :<BR>
131    * ldapconnect=ldap://fobos.kg.int:389/dc=hipergate,dc=org<BR>
132    * ldapuser=cn=Manager,dc=hipergate,dc=org<BR>
133    * ldappassword=manager<BR>
134    * @throws com.knowgate.ldap.LDAPException
135    */

136   public void connectAndBind (Properties JavaDoc oProps)
137     throws com.knowgate.ldap.LDAPException {
138
139     connect (oProps.getProperty("ldapconnect"));
140     bind(oProps.getProperty("ldapuser"), oProps.getProperty("ldappassword"));
141   }
142
143   // ---------------------------------------------------------------------------
144

145   /**
146    * <p>Synchronously disconnects from the LDAP server</p>
147    * The disconnect method abandons any outstanding requests, issues an unbind request to the server, and then closes the socket.
148    * @throws com.knowgate.ldap.LDAPException
149    */

150   public void disconnect() throws com.knowgate.ldap.LDAPException {
151
152     if (DebugFile.trace) {
153       DebugFile.writeln("Begin LDAPNovell.disconnect()");
154       DebugFile.incIdent();
155     }
156
157     try {
158       if (oConn!=null) oConn.disconnect();
159       oConn = null;
160     }
161     catch (com.novell.ldap.LDAPException xcpt) {
162       if (DebugFile.trace)
163         DebugFile.decIdent();
164       throw new com.knowgate.ldap.LDAPException(xcpt.getMessage(), xcpt);
165     }
166
167     if (DebugFile.trace) {
168       DebugFile.decIdent();
169       DebugFile.writeln("End LDAPNovell.disconnect()");
170     }
171   } // disconnect
172

173   // ---------------------------------------------------------------------------
174

175   /**
176    * <p>Synchronously authenticates to the LDAP server using LDAP_V3.</p>
177    * If the object has been disconnected from an LDAP server, this method attempts to reconnect to the server. If the object has already authenticated, the old authentication is discarded.
178    * @param sUser If non-null and non-empty, specifies that the connection and all operations through it should be authenticated with dn as the distinguished name.
179    * @param sPass If non-null and non-empty, specifies that the connection and all operations through it should be authenticated with dn as the distinguished name and passwd as password.
180    * @throws LDAPException
181    * @throws IllegalStateException If not conencted to LDAP
182    */

183   public void bind(String JavaDoc sUser, String JavaDoc sPass) throws com.knowgate.ldap.LDAPException,IllegalStateException JavaDoc {
184
185     if (DebugFile.trace) {
186       DebugFile.writeln("Begin LDAPNovell.bind(" + sUser + ",...)");
187       DebugFile.incIdent();
188     }
189
190     if (null==oConn)
191       throw new IllegalStateException JavaDoc ("Not connected to LDAP");
192
193     try {
194       oConn.bind(LDAPConnection.LDAP_V3, sUser, sPass.getBytes("UTF8"));
195     }
196     catch (com.novell.ldap.LDAPException xcpt) {
197       throw new com.knowgate.ldap.LDAPException(xcpt.getMessage(), xcpt);
198     }
199     catch (java.io.UnsupportedEncodingException JavaDoc xcpt) {
200       // never thrown
201
}
202
203     if (DebugFile.trace) {
204       DebugFile.decIdent();
205       DebugFile.writeln("End LDAPNovell.bind()");
206     }
207   } // bind
208

209   // ---------------------------------------------------------------------------
210

211   /**
212    * <p>Check whether or not an LDAP entry exists</p>
213    * The directory is searched from the connection string key.<br>
214    * For example if ldapconnect connection property is ldap://192.168.1.1:389/dc=hipergate,dc=org
215    * then only entries under "dc=hipergate,dc=org" will be searched
216    * @param sSearchString LDAP search string, for example "cn=user@mail.com,dc=publicContacts,dc=my_workarea,dc=my_domain"
217    * @throws com.knowgate.ldap.LDAPException
218    */

219   public boolean exists (String JavaDoc sSearchString)
220     throws com.knowgate.ldap.LDAPException {
221
222     if (DebugFile.trace) {
223       DebugFile.writeln("Begin LDAPNovell.exists(" + sSearchString + ")");
224       DebugFile.incIdent();
225     }
226
227     LDAPSearchResults searchResults = null;
228
229     try {
230         searchResults = oConn.search(sBase, LDAPConnection.SCOPE_SUB, sSearchString, new String JavaDoc[] {"dn"}, true);
231     }
232     catch (com.novell.ldap.LDAPException e) {
233         throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
234     }
235
236     boolean bExists = searchResults.hasMore();
237
238     if (DebugFile.trace) {
239       DebugFile.decIdent();
240       DebugFile.writeln("End LDAPNovell.exists() : " + String.valueOf(bExists));
241     }
242
243     return bExists;
244   } // exists
245

246   // ---------------------------------------------------------------------------
247

248   private void addHive(String JavaDoc sDN, String JavaDoc sCN)
249     throws com.knowgate.ldap.LDAPException {
250     LDAPAttributeSet attrs;
251
252     if (DebugFile.trace) {
253       DebugFile.writeln("LDAPNovell.addHive(" + sDN + "," + sCN + ")");
254     }
255
256     try {
257       attrs = new LDAPAttributeSet();
258       attrs.add(new LDAPAttribute("objectClass", new String JavaDoc[] {"dcObject",
259                                   "organizationalUnit"}));
260       attrs.add(new LDAPAttribute("dc", sCN));
261       attrs.add(new LDAPAttribute("ou", sCN));
262       oConn.add(new LDAPEntry(sDN, attrs));
263     }
264     catch (com.novell.ldap.LDAPException xcpt) {
265       throw new com.knowgate.ldap.LDAPException(xcpt.getMessage(), xcpt);
266     }
267   }
268
269   // ---------------------------------------------------------------------------
270

271   private void addLeaf(String JavaDoc sDN, LDAPAttributeSet attrs)
272     throws com.knowgate.ldap.LDAPException {
273
274     if (DebugFile.trace) {
275       DebugFile.writeln("LDAPNovell.addLeaf(" + sDN + ", ...)");
276     }
277
278     try {
279       attrs.add(new LDAPAttribute("objectClass", new String JavaDoc[] {"inetOrgPerson",
280                                   "organizationalPerson"}));
281       oConn.add(new LDAPEntry(sDN, attrs));
282     }
283     catch (com.novell.ldap.LDAPException xcpt) {
284       throw new com.knowgate.ldap.LDAPException(xcpt.getMessage() + " " + sDN, xcpt);
285     }
286   }
287
288   // ---------------------------------------------------------------------------
289

290   private LDAPAttributeSet mapJdbcToLdap (ResultSet JavaDoc oRSet, ResultSetMetaData JavaDoc oMDat)
291     throws SQLException JavaDoc {
292
293     Object JavaDoc oFld;
294     String JavaDoc sFld;
295     String JavaDoc sCol;
296     LDAPAttributeSet oAttrs = new LDAPAttributeSet();
297
298     int iCols = oMDat.getColumnCount();
299
300     for (int c=1; c<=iCols; c++) {
301       oFld = oRSet.getObject(c);
302
303       if (!oRSet.wasNull()) {
304         sFld = oFld.toString();
305         sCol = oMDat.getColumnName(c).toLowerCase();
306         if (!sCol.startsWith("control_")) {
307           oAttrs.add(new LDAPAttribute(sCol, sFld));
308         }
309       }
310     } // next
311

312     return oAttrs;
313   }
314
315   // ---------------------------------------------------------------------------
316

317   /**
318    * <p>Add an address from v_ldap_contacts view to an LDAP directory</p>
319    * Addresses may be either public or private depending on the value of field
320    * v_ldap_contacts.bo_private. If bo_private is zero then the address is public,
321    * if bo_private is not zero then the address is private.<br>
322    * Private addresses are only visible to the user that created them.<br>
323    * Public addresses are stored at cn=<i>user@mail.com</i>,dc=publicContacts,dc=<i>workarea_name</i>,dc=<i>domain_name</i>,dc=hipergate,dc=org<br>
324    * Private addresses are stored at cn=<i>user@mail.com</i>,dc=privateContacts,cn=<i>owner_guid</i>,dc=users,dc=<i>domain_name</i>,dc=hipergate,dc=org
325    * @param oJdbc JDBC Connection
326    * @param sAddrId GUID of address to be added
327    * @throws com.knowgate.ldap.LDAPException If address already exists at directory
328    * @throws SQLException If sAddrId is not found at v_ldap_contacts SQL view
329    * @throws IllegalStateException If not connected to LDAP
330    */

331   public void addAddress (Connection oJdbc, String JavaDoc sAddrId)
332       throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc, java.lang.IllegalStateException JavaDoc {
333
334     PreparedStatement JavaDoc oStmt;
335     ResultSet JavaDoc oRSet;
336     ResultSetMetaData JavaDoc oMDat;
337     LDAPAttributeSet oAttrs = null;
338     boolean bPrivate = true;
339     String JavaDoc sDN = null, sOwner = null, sTxEmail = null;
340
341     if (null==oConn)
342       throw new IllegalStateException JavaDoc ("LDAPNovell.addAddress() Not connected to LDAP");
343
344     if (DebugFile.trace) {
345       DebugFile.writeln("Begin LDAPNovell.addAddress([Connection], " + sAddrId + ")");
346       DebugFile.incIdent();
347     }
348
349     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_contacts WHERE \"uid\"=" + sAddrId + ")");
350
351     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_contacts WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
352     oStmt.setString(1, sAddrId);
353     oRSet = oStmt.executeQuery();
354     oMDat = oRSet.getMetaData();
355     boolean bFound = oRSet.next();
356
357     if (bFound) {
358       sDN = "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name") + "," + sBase;
359       oAttrs = mapJdbcToLdap(oRSet, oMDat);
360       bPrivate = (oRSet.getShort("control_priv") != (short) 0);
361       sOwner = oRSet.getString("control_owner");
362       sTxEmail = oRSet.getString("mail");
363     }
364
365     oRSet.close();
366     oStmt.close();
367
368     if (!bFound)
369       throw new SQLException JavaDoc ("Address " + sAddrId + " could not be found at v_ldap_contacts view", "01S06");
370
371     if (bPrivate) {
372       // Contacto Privado
373
addLeaf ("cn=" + sTxEmail + "dc=privateContacts,cn=" + sOwner + ",dc=users," + sDN, oAttrs);
374     } else {
375       // Contacto Público (workarea)
376
addLeaf ("cn=" + sTxEmail + ",dc=publicContacts," + sDN, oAttrs);
377     }
378
379     if (DebugFile.trace) {
380       DebugFile.decIdent();
381       DebugFile.writeln("End LDAPNovell.addAddress()");
382     }
383   } // addAddress
384

385   // ---------------------------------------------------------------------------
386

387   /**
388    * <p>Add or replace an Address</p>
389    * This method is the same as addAddress() except that it does not raise an
390    * LDAPException if address already exists; in that case address is just replaced.
391    * @param oJdbc JDBC Connection
392    * @param sAddrId GUID of address to be added or replaced
393    * @throws com.knowgate.ldap.LDAPException
394    * @throws java.sql.SQLException
395    */

396   public void addOrReplaceAddress (Connection oJdbc, String JavaDoc sAddrId)
397     throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc {
398
399     PreparedStatement JavaDoc oStmt;
400     ResultSet JavaDoc oRSet;
401     ResultSetMetaData JavaDoc oMDat;
402     LDAPAttributeSet oAttrs = null;
403     boolean bPrivate = true;
404     String JavaDoc sDN = null, sOwner = null, sTxEmail = null;
405
406     if (null==oConn)
407       throw new IllegalStateException JavaDoc ("LDAPNovell.addOrReplaceAddress() Not connected to LDAP");
408
409     if (DebugFile.trace) {
410       DebugFile.writeln("Begin LDAPNovell.addOrReplaceAddress([Connection], " + sAddrId + ")");
411       DebugFile.incIdent();
412     }
413
414     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_contacts WHERE \"uid\"=" + sAddrId + ")");
415
416     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_contacts WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
417     oStmt.setString(1, sAddrId);
418     oRSet = oStmt.executeQuery();
419     oMDat = oRSet.getMetaData();
420     boolean bFound = oRSet.next();
421
422     if (bFound) {
423       sDN = "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name");
424       oAttrs = mapJdbcToLdap(oRSet, oMDat);
425       bPrivate = (oRSet.getShort("control_priv") != (short) 0);
426       sOwner = oRSet.getString("control_owner");
427       sTxEmail = oRSet.getString("mail");
428     }
429
430     oRSet.close();
431     oStmt.close();
432
433     if (!bFound)
434       throw new SQLException JavaDoc ("Address " + sAddrId + " could not be found at v_ldap_contacts view", "01S06");
435
436     if (bPrivate) {
437
438       // Contacto Privado
439
if (exists("cn=" + sTxEmail + "dc=privateContacts,cn=" + sOwner + ",dc=users," + sDN + "," + sBase))
440         deleteAddress (oJdbc, sAddrId);
441
442       addLeaf ("cn=" + sTxEmail + "dc=privateContacts,cn=" + sOwner + ",dc=users," + sDN + "," + sBase, oAttrs);
443     } else {
444
445       // Contacto Público (workarea)
446
if (exists("cn=" + sTxEmail + ",dc=publicContacts," + sDN + "," + sBase))
447         deleteAddress (oJdbc, sAddrId);
448
449       addLeaf ("cn=" + sTxEmail + ",dc=publicContacts," + sDN + "," + sBase, oAttrs);
450     }
451
452     if (DebugFile.trace) {
453       DebugFile.decIdent();
454       DebugFile.writeln("End LDAPNovell.addOrReplaceAddress()");
455     }
456   }
457
458   // ---------------------------------------------------------------------------
459

460   /**
461    * Delete an address from LDAP directory
462    * @param oJdbc JDBC Connection
463    * @param sAddrId GUID of address to be deleted
464    * @throws com.knowgate.ldap.LDAPException
465    * @throws SQLException If sAddrId is not found at v_ldap_contacts SQL view
466    * @throws IllegalStateException If not connected to LDAP
467    */

468   public void deleteAddress (Connection oJdbc, String JavaDoc sAddrId)
469       throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc, java.lang.IllegalStateException JavaDoc {
470
471     if (null==oConn)
472       throw new IllegalStateException JavaDoc ("LDAPNovell.deleteAddress() Not connected to LDAP");
473
474     if (DebugFile.trace) {
475       DebugFile.writeln("Begin LDAPNovell.deleteAddress([Connection], " + sAddrId + ")");
476       DebugFile.incIdent();
477     }
478
479     LDAPAttributeSet oAttrs;
480     PreparedStatement JavaDoc oStmt;
481     ResultSet JavaDoc oRSet;
482     boolean bPrivate = true;
483     String JavaDoc sDN = null, sOwner = null, sTxEmail = null;
484
485     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_contacts WHERE \"uid\"=" + sAddrId + ")");
486
487     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_contacts WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
488     oStmt.setString(1, sAddrId);
489     oRSet = oStmt.executeQuery();
490     boolean bFound = oRSet.next();
491
492     if (bFound) {
493       sDN = "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name") + "," + sBase;
494       bPrivate = (oRSet.getShort("control_priv") != (short) 0);
495       sOwner = oRSet.getString("control_owner");
496       sTxEmail = oRSet.getString("mail");
497     }
498
499     oRSet.close();
500     oStmt.close();
501
502     if (!bFound)
503       throw new SQLException JavaDoc ("Address " + sAddrId + " could not be found at v_ldap_contacts view", "01S06");
504
505     if (bPrivate)
506       sDN = "cn=" + sTxEmail + "dc=privateContacts,cn=" + sOwner + ",dc=users," + sDN;
507     else
508       sDN = "cn=" + sTxEmail + ",dc=publicContacts," + sDN;
509
510     if (DebugFile.trace) DebugFile.writeln("LDAPConnection.delete(" + sDN + ")");
511
512     try {
513       oConn.delete(sDN);
514     }
515     catch (com.novell.ldap.LDAPException xcpt) {
516       if (DebugFile.trace) DebugFile.decIdent();
517       throw new com.knowgate.ldap.LDAPException (xcpt.getMessage(), xcpt);
518     }
519
520     if (DebugFile.trace) {
521       DebugFile.decIdent();
522       DebugFile.writeln("End LDAPNovell.deleteAddress()");
523     }
524   } // deleteAddress
525

526   // ---------------------------------------------------------------------------
527

528
529   /**
530    * <p>Add a User from v_ldap_users view to an LDAP directory</p>
531    * Users are added under cn=<i>user@mail.com</i>,dc=users,dc=<i>workarea_name</i>,dc=<i>domain_name</i>,dc=hipergate,dc=org
532    * @param oJdbc JDBC Connection
533    * @param sUserId GUID of user to be added
534    * @throws LDAPException
535    * @throws SQLException If sUserId is not found at v_ldap_users SQL view
536    * @throws IllegalStateException If not connected to LDAP
537    */

538   public void addUser (Connection oJdbc, String JavaDoc sUserId)
539     throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc,IllegalStateException JavaDoc {
540
541     PreparedStatement JavaDoc oStmt;
542     ResultSet JavaDoc oRSet;
543     ResultSetMetaData JavaDoc oMDat;
544     LDAPAttributeSet oAttrs = null;
545     String JavaDoc sDN = null, sTxEmail = null;
546
547     if (DebugFile.trace) {
548       DebugFile.writeln("Begin LDAPNovell.addUser([Connection], " + sUserId + ")");
549       DebugFile.incIdent();
550     }
551
552     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_users WHERE \"uid\"=" + sUserId + ")");
553
554     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_users WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
555     oStmt.setString(1, sUserId);
556     oRSet = oStmt.executeQuery();
557     oMDat = oRSet.getMetaData();
558     boolean bFound = oRSet.next();
559
560     if (bFound) {
561       sDN = "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name") + "," + sBase;
562
563       oAttrs = mapJdbcToLdap(oRSet, oMDat);
564
565       sTxEmail = oRSet.getString("mail");
566     }
567
568     oRSet.close();
569     oStmt.close();
570
571     if (!bFound)
572       throw new SQLException JavaDoc ("User " + sUserId + " could not be found at v_ldap_users view", "01S06");
573
574     addLeaf ("cn=" + sTxEmail + ",dc=users," + sDN, oAttrs);
575
576     if (DebugFile.trace) {
577       DebugFile.decIdent();
578       DebugFile.writeln("End LDAPNovell.addUser()");
579     }
580   } // addUser
581

582   // ---------------------------------------------------------------------------
583

584   /**
585    * Add or replace a User from v_ldap_users SQL view to the LDAP directory
586    * @param oJdbc JDBC database connection
587    * @param sUserId GUID of user to be added or replaced
588    * @throws com.knowgate.ldap.LDAPException
589    * @throws java.sql.SQLException
590    */

591   public void addOrReplaceUser (Connection oJdbc, String JavaDoc sUserId)
592       throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc {
593
594
595     PreparedStatement JavaDoc oStmt;
596     ResultSet JavaDoc oRSet;
597     ResultSetMetaData JavaDoc oMDat;
598     LDAPAttributeSet oAttrs = null;
599     String JavaDoc sDN = null, sTxEmail = null;
600
601     if (DebugFile.trace) {
602       DebugFile.writeln("Begin LDAPNovell.addOrReplaceUser([Connection], " + sUserId + ")");
603       DebugFile.incIdent();
604     }
605
606     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_users WHERE \"uid\"=" + sUserId + ")");
607
608     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_users WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
609     oStmt.setString(1, sUserId);
610     oRSet = oStmt.executeQuery();
611     oMDat = oRSet.getMetaData();
612     boolean bFound = oRSet.next();
613
614     if (bFound) {
615       sDN = "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name");
616
617       oAttrs = mapJdbcToLdap(oRSet, oMDat);
618
619       sTxEmail = oRSet.getString("mail");
620     }
621
622     oRSet.close();
623     oStmt.close();
624
625     if (!bFound)
626       throw new SQLException JavaDoc ("User " + sUserId + " could not be found at v_ldap_users view", "01S06");
627
628     if (exists("cn=" + sTxEmail + ",dc=users," + sDN))
629       deleteUser(oJdbc, sUserId);
630
631     addLeaf ("cn=" + sTxEmail + ",dc=users," + sDN + "," + sBase, oAttrs);
632
633     if (DebugFile.trace) {
634       DebugFile.decIdent();
635       DebugFile.writeln("End LDAPNovell.addOrReplaceUser()");
636     }
637   }
638
639   // ---------------------------------------------------------------------------
640

641   /**
642    * Delete a User from LDAP directory
643    * @param oJdbc JDBC Connection
644    * @param sUserId GUID of user to be added
645    * @throws com.knowgate.ldap.LDAPException
646    * @throws SQLException If sUserId is not found at v_ldap_users SQL view
647    */

648   public void deleteUser (Connection oJdbc, String JavaDoc sUserId)
649     throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc {
650
651     LDAPAttributeSet oAttrs;
652     PreparedStatement JavaDoc oStmt;
653     ResultSet JavaDoc oRSet;
654     String JavaDoc sTxEmail = null, sDN = null;
655
656     if (DebugFile.trace) {
657       DebugFile.writeln("Begin LDAPNovell.deleteUser([Connection], " + sUserId + ")");
658       DebugFile.incIdent();
659     }
660
661     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_users WHERE \"uid\"=" + sUserId + ")");
662
663     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_users WHERE \"uid\"=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
664     oStmt.setString(1, sUserId);
665     oRSet = oStmt.executeQuery();
666     boolean bFound = oRSet.next();
667
668     if (bFound) {
669       sTxEmail = oRSet.getString("mail");
670       sDN = "cn=" + sTxEmail + ",dc=users," + "dc=" + oRSet.getString("control_workarea_name") + ",dc=" + oRSet.getString("control_domain_name") + "," + sBase;
671     }
672
673     oRSet.close();
674     oStmt.close();
675
676     if (!bFound)
677       throw new SQLException JavaDoc ("User " + sUserId + " could not be found at v_ldap_users view", "01S06");
678
679     if (DebugFile.trace) DebugFile.writeln("LDAPConnection.delete(" + sDN + ")");
680
681     try {
682       oConn.delete(sDN);
683     }
684     catch (com.novell.ldap.LDAPException xcpt) {
685       if (DebugFile.trace) DebugFile.decIdent();
686       throw new com.knowgate.ldap.LDAPException (xcpt.getMessage(), xcpt);
687     }
688
689     if (DebugFile.trace) {
690       DebugFile.decIdent();
691       DebugFile.writeln("End LDAPNovell.deleteUser()");
692     }
693   } // deleteUser
694

695   // ---------------------------------------------------------------------------
696

697   /**
698    * <P>Load all users and contact address from a Domain into an LDAP directory</P>
699    * @param oJdbc JDBC Connection
700    * @param iDomainId Numeric Identifier for Domain
701    * @throws com.knowgate.ldap.LDAPException
702    * @throws SQLException
703    */

704   public void loadDomain (Connection oJdbc, int iDomainId)
705     throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc {
706
707     LDAPAttributeSet oAttrs;
708     PreparedStatement JavaDoc oStmt;
709     ResultSet JavaDoc oRSet;
710     ResultSetMetaData JavaDoc oMDat;
711     String JavaDoc sDN, sDomainNm, sWorkAreaNm;
712     LDAPSearchResults searchResults = null;
713
714     if (DebugFile.trace) {
715       DebugFile.writeln("Begin LDAPNovell.loadDomain([Connection]" + String.valueOf(iDomainId) + ",...)");
716       DebugFile.incIdent();
717     }
718
719     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT nm_domain FROM k_domains WHERE id_domain=" + String.valueOf(iDomainId) + ")");
720
721     oStmt = oJdbc.prepareStatement("SELECT nm_domain FROM k_domains WHERE id_domain=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
722     oStmt.setInt(1, iDomainId);
723     oRSet = oStmt.executeQuery();
724     oRSet.next();
725     sDomainNm = oRSet.getString(1);
726     oRSet.close();
727     oStmt.close();
728
729     // *************
730
// Create Domain
731

732     sDN = "dc=" + sDomainNm + "," + sBase;
733
734     try {
735       searchResults = oConn.search(sBase, LDAPConnection.SCOPE_ONE,"(dc=" + sDomainNm + ")", new String JavaDoc[] {"dn"}, true);
736     }
737     catch (com.novell.ldap.LDAPException e) {
738       throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
739     }
740
741     if (!searchResults.hasMore())
742       addHive(sDN, sDomainNm);
743
744     // ****************
745
// Create Workareas
746

747     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT nm_workarea FROM k_workareas WHERE id_domain=" + String.valueOf(iDomainId) + ")");
748
749     oStmt = oJdbc.prepareStatement("SELECT nm_workarea FROM k_workareas WHERE id_domain=?",ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
750     oStmt.setInt(1, iDomainId);
751     oRSet = oStmt.executeQuery();
752
753     while (oRSet.next()) {
754       sWorkAreaNm = oRSet.getString(1);
755
756       sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
757
758       try {
759         searchResults = oConn.search("dc=" + sDomainNm + "," + sBase, LDAPConnection.SCOPE_ONE,"(dc=" + sWorkAreaNm + ")", new String JavaDoc[] {"dn"}, true);
760       }
761       catch (com.novell.ldap.LDAPException e) {
762         throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
763       }
764
765       if (!searchResults.hasMore()) {
766         // Primero crear la rama de la WorkArea
767
addHive (sDN, sWorkAreaNm);
768
769         // Despues se crean los subcontenedores necesarios
770
addHive ("dc=users," + sDN, "users");
771         addHive ("dc=publicContacts," + sDN, "publicContacts");
772         addHive ("dc=employees," + sDN, "employees");
773       }
774     } // wend
775

776     oRSet.close();
777     oStmt.close();
778
779     // ***************
780
// Create Users
781

782     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_users WHERE control_domain_guid=" + String.valueOf(iDomainId) + ")");
783
784     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_users WHERE control_domain_guid=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
785     oStmt.setInt(1, iDomainId);
786     oRSet = oStmt.executeQuery();
787     oMDat = oRSet.getMetaData();
788
789     while (oRSet.next()) {
790       sWorkAreaNm = oRSet.getString("control_workarea_name");
791       sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
792
793       oAttrs = mapJdbcToLdap(oRSet, oMDat);
794
795       // Usuario
796
addLeaf ("cn=" + oRSet.getString("mail") + ",dc=users," + sDN, oAttrs);
797       // Añadir el contenedor de contactos privados
798
addHive ("dc=privateContacts,cn=" + oRSet.getString("mail") + ",dc=users," + sDN, "privateContacts");
799     } // wend
800

801     oRSet.close();
802     oStmt.close();
803
804     // ***************
805
// Create Contacts
806

807     if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT * FROM v_ldap_contacts ld WHERE control_domain_guid=" + String.valueOf(iDomainId) + ")");
808
809     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_contacts ld WHERE control_domain_guid=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
810     oStmt.setInt(1, iDomainId);
811     oRSet = oStmt.executeQuery();
812     oMDat = oRSet.getMetaData();
813
814     while (oRSet.next()) {
815       sWorkAreaNm = oRSet.getString("control_workarea_name");
816       sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
817
818       oAttrs = mapJdbcToLdap(oRSet, oMDat);
819
820         if (oRSet.getShort("control_priv")!=(short)0) {
821           // Contacto Privado
822
addLeaf("cn=" + oRSet.getString("mail") + "dc=privateContacts,cn=" + oRSet.getString("control_owner") + ",dc=users," + sDN, oAttrs);
823         } else {
824           // Contacto Público (workarea)
825
addLeaf("cn=" + oRSet.getString("mail") + ",dc=publicContacts," + sDN, oAttrs);
826         }
827     } // wend
828

829     if (DebugFile.trace) {
830       DebugFile.decIdent();
831       DebugFile.writeln("End LDAPNovell.loadDomain()");
832     }
833   } // loadDomain
834

835   // ---------------------------------------------------------------------------
836

837   /**
838    * <P>Load all users and contact address from a WorkArea into an LDAP directory</P>
839    * @param oJdbc JDBC Connection
840    * @param sDomainNm Name for Domain containing the WorkArea
841    * @param sWorkAreaNm WorkArea Name
842    * @throws com.knowgate.ldap.LDAPException
843    * @throws SQLException
844    */

845   public void loadWorkArea (Connection oJdbc, String JavaDoc sDomainNm, String JavaDoc sWorkAreaNm)
846     throws com.knowgate.ldap.LDAPException, java.sql.SQLException JavaDoc {
847
848     LDAPAttributeSet oAttrs;
849     String JavaDoc sDN;
850     LDAPSearchResults searchResults = null;
851
852     if (DebugFile.trace) {
853       DebugFile.writeln("Begin LDAPNovell.loadWorkArea([Connection]" + sDomainNm + "," + sWorkAreaNm + ",...)");
854       DebugFile.incIdent();
855     }
856
857     // **********************************
858
// Create Domain if it does not exist
859

860     sDN = "dc=" + sDomainNm + "," + sBase;
861
862     try {
863       searchResults = oConn.search(sBase, LDAPConnection.SCOPE_ONE,"(dc=" + sDomainNm + ")", new String JavaDoc[] {"dn"}, true);
864     }
865     catch (com.novell.ldap.LDAPException e) {
866       throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
867     }
868
869     if (!searchResults.hasMore())
870       addHive(sDN, sDomainNm);
871
872     // ***************
873
// Create WorkArea
874

875     sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
876
877     try {
878         searchResults = oConn.search("dc=" + sDomainNm + "," + sBase, LDAPConnection.SCOPE_ONE,"(dc=" + sWorkAreaNm + ")", new String JavaDoc[] {"dn"}, true);
879     }
880     catch (com.novell.ldap.LDAPException e) {
881         throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
882     }
883
884     if (!searchResults.hasMore()) {
885       // Primero crear la rama de la WorkArea
886
addHive (sDN, sWorkAreaNm);
887
888       // Despues se crean los subcontenedores necesarios
889
addHive ("dc=users," + sDN, "users");
890       addHive ("dc=publicContacts," + sDN, "publicContacts");
891       addHive ("dc=employees," + sDN, "employees");
892     } // fi
893

894
895     // ***************
896
// Create Users
897

898     PreparedStatement JavaDoc oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_users WHERE control_domain_name=? AND control_workarea_name=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
899     oStmt.setString(1, sDomainNm);
900     oStmt.setString(2, sWorkAreaNm);
901     ResultSet JavaDoc oRSet = oStmt.executeQuery();
902     ResultSetMetaData JavaDoc oMDat = oRSet.getMetaData();
903
904     while (oRSet.next()) {
905       sWorkAreaNm = oRSet.getString("control_workarea_name");
906       sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
907
908       oAttrs = mapJdbcToLdap(oRSet, oMDat);
909
910       // Usuario
911
addLeaf ("cn=" + oRSet.getString("mail") + ",dc=users," + sDN, oAttrs);
912       // Añadir el contenedor de contactos privados
913
addHive ("dc=privateContacts,cn=" + oRSet.getString("mail") + ",dc=users," + sDN, "privateContacts");
914     } // wend
915

916     oRSet.close();
917     oStmt.close();
918
919     // ***************
920
// Create Contacts
921

922     oStmt = oJdbc.prepareStatement("SELECT * FROM v_ldap_contacts ld WHERE control_domain_name=? AND control_workarea_name=?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
923     oStmt.setString(1, sDomainNm);
924     oStmt.setString(2, sWorkAreaNm);
925     oRSet = oStmt.executeQuery();
926     oMDat = oRSet.getMetaData();
927
928     while (oRSet.next()) {
929       sWorkAreaNm = oRSet.getString("control_workarea_name");
930       sDN = "dc=" + sWorkAreaNm + ",dc=" + sDomainNm + "," + sBase;
931
932       oAttrs = mapJdbcToLdap(oRSet, oMDat);
933
934         if (oRSet.getShort("control_priv")!=(short)0) {
935           // Contacto Privado
936
addLeaf("cn=" + oRSet.getString("mail") + "dc=privateContacts,cn=" + oRSet.getString("control_owner") + ",dc=users," + sDN, oAttrs);
937         } else {
938           // Contacto Público (workarea)
939
addLeaf("cn=" + oRSet.getString("mail") + ",dc=publicContacts," + sDN, oAttrs);
940         }
941     } // wend
942

943     if (DebugFile.trace) {
944       DebugFile.decIdent();
945       DebugFile.writeln("End LDAPNovell.loadWorkArea()");
946     }
947   } // loadWorkArea
948

949   // ---------------------------------------------------------------------------
950

951   /**
952    * Delete LDAP entry and all its childs
953    * @param oEntry LDAPEntry to be deleted
954    * @throws com.knowgate.ldap.LDAPException
955    * @throws IllegalStateException If not connected to LDAP
956    */

957   private void deleteEntry (LDAPEntry oEntry)
958     throws com.knowgate.ldap.LDAPException, IllegalStateException JavaDoc {
959
960     if (null==oConn)
961       throw new IllegalStateException JavaDoc ("LDAPNovell.deleteEntry() Not connected to LDAP");
962
963     String JavaDoc sDN = oEntry.getDN();
964     LDAPEntry nextEntry;
965
966     try {
967
968       LDAPSearchResults searchResults = oConn.search(sDN, LDAPConnection.SCOPE_ONE,"(objectClass=*)",new String JavaDoc[] {"dn"}, true);
969
970       while (searchResults.hasMore()) {
971         try {
972           nextEntry = searchResults.next();
973         }
974         catch (com.novell.ldap.LDAPException e) { continue; }
975
976         deleteEntry (nextEntry);
977       } // wend
978

979       if (DebugFile.trace) DebugFile.writeln("LDAPConnection.delete(" + sDN + ")");
980
981       oConn.delete(sDN);
982     }
983     catch (com.novell.ldap.LDAPException xcpt) {
984       throw new com.knowgate.ldap.LDAPException (xcpt.getMessage(), xcpt);
985     }
986   } // deleteEntry
987

988   // ---------------------------------------------------------------------------
989

990   /**
991    * <p>Delete a WorkArea from the LDAP directory</p>
992    * All entries under dc=<i>sDomainNm</i>,dc=hipergate,dc=org that match dc=<i>sWorkAreaNm</i> are deleted
993    * @param sDomainNm Domain Name
994    * @param sWorkAreaNm WorkArea Name
995    * @throws com.knowgate.ldap.LDAPException
996    * @throws IllegalStateException If not connected to LDAP
997    */

998   public void deleteWorkArea (String JavaDoc sDomainNm, String JavaDoc sWorkAreaNm)
999     throws com.knowgate.ldap.LDAPException, IllegalStateException JavaDoc {
1000
1001    String JavaDoc sDN = "dc=" + sDomainNm + "," + sBase;
1002    LDAPEntry oWrkAHive = null;
1003
1004    try {
1005      LDAPSearchResults searchResults = oConn.search(sDN, LDAPConnection.SCOPE_ONE,"(dc=" + sWorkAreaNm + ")", new String JavaDoc[] {"dn"}, true);
1006
1007      if (searchResults.hasMore()) {
1008        oWrkAHive = searchResults.next();
1009      }
1010    }
1011    catch (com.novell.ldap.LDAPException e) {
1012      throw new com.knowgate.ldap.LDAPException(e.getMessage(), e);
1013    }
1014
1015    if (oWrkAHive!=null)
1016      deleteEntry (oWrkAHive);
1017  } // deleteWorkArea
1018

1019  // ---------------------------------------------------------------------------
1020

1021  /**
1022   * Drop an entire LDAP directory
1023   * @throws com.knowgate.ldap.LDAPException
1024   * @throws IllegalStateException If not connected to LDAP
1025   */

1026  public void dropAll ()
1027    throws com.knowgate.ldap.LDAPException, IllegalStateException JavaDoc {
1028
1029    if (null==oConn)
1030      throw new IllegalStateException JavaDoc ("LDAPNovell.dropAll() Not connected to LDAP");
1031
1032    if (DebugFile.trace) {
1033      DebugFile.writeln("Begin LDAPNovell.dropAll()");
1034      DebugFile.incIdent();
1035    }
1036
1037    LDAPSearchResults searchResults = null;
1038    LDAPEntry nextEntry = null;
1039
1040    try {
1041        // Dropar todo el modelo de datos
1042

1043        searchResults = oConn.search(sBase, LDAPConnection.SCOPE_ONE,"(objectClass=*)",new String JavaDoc[] {"dn"}, true);
1044
1045        while (searchResults.hasMore()) {
1046          try {
1047            nextEntry = searchResults.next();
1048          }
1049          catch (LDAPException e) { continue; }
1050
1051          if (!sBase.equals(nextEntry.getDN()))
1052            deleteEntry(nextEntry); // No borrar el elemento raíz!!!
1053
} // wend
1054
}
1055    catch (com.novell.ldap.LDAPException xcpt) {
1056      throw new com.knowgate.ldap.LDAPException (xcpt.getMessage(), xcpt);
1057    }
1058
1059    if (DebugFile.trace) {
1060      DebugFile.decIdent();
1061      DebugFile.writeln("End LDAPNovell.dropAll()");
1062    }
1063  } // dropAll
1064

1065  // ---------------------------------------------------------------------------
1066

1067  private static void printUsage() {
1068    System.out.println("");
1069    System.out.println("Usage:");
1070    System.out.println("LDAPNovell path load all");
1071    System.out.println("path: path to hipergate.cnf file ej. /opt/knowgate/hipergate.cnf");
1072  }
1073
1074  public static void main(String JavaDoc[] argv)
1075     throws java.lang.ClassNotFoundException JavaDoc, java.io.IOException JavaDoc, java.sql.SQLException JavaDoc, com.knowgate.ldap.LDAPException {
1076
1077     if (argv.length<3 || argv.length>3)
1078       printUsage();
1079     else {
1080       java.util.Properties JavaDoc oProps = new java.util.Properties JavaDoc();
1081       java.io.FileInputStream JavaDoc ioProps = new java.io.FileInputStream JavaDoc(argv[0]);
1082       oProps.load(ioProps);
1083       ioProps.close();
1084
1085       LDAPNovell oLDP = new LDAPNovell();
1086
1087       oLDP.connectAndBind(oProps);
1088
1089       Class JavaDoc oDriver = Class.forName(oProps.getProperty("driver"));
1090
1091       Connection oCon = java.sql.DriverManager.getConnection(oProps.getProperty("dburl"), oProps.getProperty("dbuser"), oProps.getProperty("dbpassword"));
1092
1093       oLDP.dropAll();
1094
1095       Statement JavaDoc oStm = oCon.createStatement();
1096       ResultSet JavaDoc oRst = oStm.executeQuery("SELECT id_domain FROM k_domains WHERE bo_active<>0");
1097
1098       while (oRst.next()) {
1099         oLDP.loadDomain(oCon, oRst.getInt(1));
1100       }
1101
1102       oRst.close();
1103       oStm.close();
1104
1105       oCon.close();
1106       oLDP.disconnect();
1107     }
1108   }
1109}
1110
Popular Tags