KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > ldap > ImportExternalParticipants


1 /*
2  * Authors:
3  * Stefanovic Nenad chupo@iis.ns.ac.yu
4  * Bojanic Sasa sasaboy@neobee.net
5  * Puskas Vladimir vpuskas@eunet.yu
6  * Pilipovic Goran zboniek@uns.ac.yu
7  *
8  */

9
10 package org.enhydra.jawe.ldap;
11
12 import org.enhydra.jawe.*;
13 import org.enhydra.jawe.actions.*;
14
15 import org.enhydra.jawe.xml.*;
16 import org.enhydra.jawe.xml.elements.*;
17 import org.enhydra.jawe.xml.panels.*;
18
19
20 import javax.naming.*;
21 import javax.naming.directory.*;
22 import javax.naming.ldap.*;
23
24 import javax.swing.*;
25 import javax.swing.event.*;
26 import javax.swing.border.*;
27 import java.awt.*;
28 import java.awt.event.*;
29
30 /**
31 m * Class that realizes <B>import external process</B> action.
32  */

33 public class ImportExternalParticipants extends ActionBase {
34
35    private ExternalParticipants eps;
36    private XMLAttribute idMapping=new XMLAttribute("ChooseAttributeNameForIdMapping",
37             new String JavaDoc[] {
38                "NoMapping",
39                "uid",
40                "userId"
41             },0) {
42                // to enable manual enterance of object class
43
public XMLPanel getPanel () {
44                   return new XMLComboPanel(this,null,XMLPanel.BOX_LAYOUT,false,true);
45                }
46             };
47
48    public ImportExternalParticipants (PackageEditor editor) {
49       super(editor);
50    }
51
52    public void actionPerformed(ActionEvent e) {
53       PackageEditor pe=(PackageEditor)editor;
54       if (!pe.isInitialized()) {
55          pe.enterPackageID();
56       }
57
58       if (eps==null) {
59          eps=new ExternalParticipants(pe.getXMLPackage());
60       }
61
62       XMLElementDialog d=new XMLElementDialog((JFrame)pe.getWindow(),
63          ResourceManager.getLanguageDependentString("PackageKey")+" '"+
64          pe.getXMLPackage().get("Id").toString()+"' - "+
65          ResourceManager.getLanguageDependentString("ImportExternalParticipantsLabel"));
66       d.editXMLElement(eps.getPanel(),true,false);
67       if (!d.isCanceled()) {
68          // here is the place where connection to the LDAP server is made
69
// to collect informations
70
java.util.List JavaDoc allEntries=getEntries(eps);
71
72          java.util.List JavaDoc selectedEntries=
73                showDialog(editor.getWindow(),allEntries);
74          if (selectedEntries.size()>0) {
75             createParticipants(selectedEntries);
76          }
77       }
78    }
79
80    /**
81     * Connects to the LDAP server and retrieves wanted data.
82     * All neccessary information to establish connection to the server, and
83     * to retrieve data are hold within given parameter ep.
84     */

85    private java.util.List JavaDoc getEntries (ExternalParticipants ep) {
86       java.util.List JavaDoc entries=new java.util.ArrayList JavaDoc();
87
88       int ldapPort;
89       try {
90          ldapPort=Integer.valueOf(ep.get("Port").toString()).intValue();
91       } catch (Exception JavaDoc ex) {
92          System.err.println("Port invalid, using default port 389");
93          ldapPort=389 ;
94       }
95
96       int searchScope;
97       if (ep.get("SearchScope").toValue().toString().equals("SCOPE_ONE")) {
98          searchScope = SearchControls.ONELEVEL_SCOPE;
99       } else {
100          searchScope = SearchControls.SUBTREE_SCOPE;
101       }
102
103       //boolean attributeOnly = true; // returns attributes
104
boolean attributeOnly = false; // returns attributes and their values
105

106       String JavaDoc ldapHost = ep.get("Host").toString();
107       String JavaDoc searchBase = ep.get("BaseDN").toString();
108       //String searchFilter = "(objectclass=*)";
109
String JavaDoc searchFilter;
110       if (ep.get("ObjectClassFilter").toValue().toString().equals("AllListed")) {
111          searchFilter="(|(objectClass=organizationalUnit)"+
112                "(objectClass=organizationalRole)(objectClass=person)"+
113                "(objectClass=organizationalPerson)(objectClass=inetOrgPerson))";
114       } else {
115          searchFilter="(objectClass="+ep.get("ObjectClassFilter").toValue().toString()+")";
116       }
117
118       try {
119          /* Create an environment for the initial directory context.
120          The properties specify the LDAP provider, the LDAP server,
121          the LDAP version, and if needed username and password, or
122          if not, no security (anonymous bind). */

123          java.util.Properties JavaDoc env = new java.util.Properties JavaDoc();
124          env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
125          env.put(Context.REFERRAL, "throw");
126          env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
127
128          Security security=(Security)ep.get("Security");
129          if (!security.get("Level").toValue().toString().equals("Anonymous")) {
130             String JavaDoc ldapUser=security.get("UserDN").toString();
131             String JavaDoc ldapPassword=security.get("Password").toString();
132             env.put(Context.SECURITY_PRINCIPAL, ldapUser);
133             env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
134          }
135
136          /* Create the initial directory context. */
137          DirContext ctx = new InitialDirContext(env);
138          /* Set up and perform the search. Find all people in IBM in the
139          United States whose common name starts with Sue or Johan. */

140          SearchControls constraints = new SearchControls();
141          constraints.setSearchScope(searchScope);
142          try {
143             constraints.setCountLimit(JaWEConfig.getInstance().getLDAPCountLimit());
144          } catch (Exception JavaDoc ex) {
145             constraints.setCountLimit(0);
146          }
147          try {
148             constraints.setTimeLimit(JaWEConfig.getInstance().getLDAPTimeLimit());
149          } catch (Exception JavaDoc ex) {
150             constraints.setTimeLimit(0);
151          }
152          NamingEnumeration results = ctx.search(searchBase,searchFilter,constraints);
153
154          /* For each entry found. */
155          while (results.hasMore()) {
156             SearchResult sr = (SearchResult) results.next();
157             //System.out.println(sr.getName());
158
entries.add(sr);
159          }
160          ctx.close();
161       } catch (NamingException e) {
162          /* Handle any name/directory exceptions. */
163          if (e.getMessage().indexOf("Sizelimit Exceeded")!=-1) {
164             JaWE.getInstance().message(ResourceManager.getLanguageDependentString(
165                   "ErrorLDAPSearchPartiallyFailedSizelimitExceeded"),
166                   JOptionPane.ERROR_MESSAGE);
167
168          } else if (e.getMessage().indexOf("Timelimit Exceeded")!=-1) {
169             JaWE.getInstance().message(ResourceManager.getLanguageDependentString(
170                   "ErrorLDAPSearchPartiallyFailedTimelimitExceeded"),
171                   JOptionPane.ERROR_MESSAGE);
172
173          } else {
174             JaWE.getInstance().message(ResourceManager.getLanguageDependentString(
175                   "ErrorLDAPSearchFailed"),
176                   JOptionPane.ERROR_MESSAGE);
177          }
178          System.err.println("Search failed: " + e.getMessage());
179       } catch (Exception JavaDoc e) {
180          /* Handle any other types of exceptions. */
181          JaWE.getInstance().message(ResourceManager.getLanguageDependentString(
182                   "ErrorLDAPSearchFailed"),
183                   JOptionPane.ERROR_MESSAGE);
184          System.err.println("Non-naming error: " + e.getMessage());
185       }
186       return entries;
187    }
188
189    /**
190     * Shows the dialog for viewing LDAP search results.
191     *
192     * @return The list of LDAP entries for which participants are to be created.
193     */

194    private java.util.List JavaDoc showDialog (Window parent,final java.util.List JavaDoc allEntries) {
195       String JavaDoc title=ResourceManager.getLanguageDependentString("DialogLDAPEntries");
196       final JDialog myDialog;
197       if (parent instanceof JDialog) {
198          myDialog=new JDialog((JDialog)parent,title,true);
199       } else {
200          myDialog=new JDialog((JFrame)parent,title,true);
201       }
202
203       final XMLPanel idp=idMapping.getPanel();
204
205       final java.util.List JavaDoc selectedEntries=new java.util.ArrayList JavaDoc();
206
207       Dimension listFieldDimension=new Dimension(800,500);
208       final JList entries;
209
210       JScrollPane scrollActivities=new JScrollPane();
211       entries=new JList(allEntries.toArray());
212       scrollActivities.setViewportView(entries);
213       scrollActivities.setPreferredSize(new Dimension(listFieldDimension));
214
215       JPanel pm=new JPanel();
216       Border emptyb=BorderFactory.createEmptyBorder(10,10,10,10);
217       Border inb=BorderFactory.createMatteBorder(1,1,1,1,Color.darkGray);
218       inb=BorderFactory.createTitledBorder(inb,
219          ResourceManager.getLanguageDependentString("SelectActivityKey"));
220       pm.setBorder(BorderFactory.createCompoundBorder(emptyb,inb));
221       pm.setLayout(new BoxLayout(pm,BoxLayout.Y_AXIS));
222       pm.add(idp);
223       pm.add(scrollActivities);
224
225
226       JPanel btnPanel = new JPanel();
227       JButton dialogImportAllButton = new JButton(ResourceManager.getLanguageDependentString("ImportAllKey"));
228       java.net.URL JavaDoc u = ResourceManager.getResource("ImportAll"+JaWEConstants.IMAGE_SUFFIX);
229       if (u!=null) {
230          dialogImportAllButton.setIcon(new ImageIcon(u));
231       }
232       dialogImportAllButton.addActionListener(new ActionListener(){
233          public void actionPerformed(ActionEvent evt){
234             idp.setElements();
235             selectedEntries.addAll(allEntries);
236             myDialog.dispose();
237          }
238       });
239       btnPanel.add(dialogImportAllButton);
240
241       JButton dialogImportSelectedButton = new JButton(ResourceManager.getLanguageDependentString("ImportSelectedKey"));
242       u = ResourceManager.getResource("ImportSelected"+JaWEConstants.IMAGE_SUFFIX);
243       if (u!=null) {
244          dialogImportSelectedButton.setIcon(new ImageIcon(u));
245       }
246       dialogImportSelectedButton.addActionListener(new ActionListener(){
247          public void actionPerformed(ActionEvent evt){
248             idp.setElements();
249             selectedEntries.addAll(java.util.Arrays.asList(entries.getSelectedValues()));
250             myDialog.dispose();
251          }
252       });
253       btnPanel.add(dialogImportSelectedButton);
254
255       JButton dialogCancelButton = new JButton(ResourceManager.getLanguageDependentString("CancelKey"));
256       u = ResourceManager.getResource("Cancel"+JaWEConstants.IMAGE_SUFFIX);
257       if (u!=null) {
258          dialogCancelButton.setIcon(new ImageIcon(u));
259       }
260       dialogCancelButton.addActionListener(new ActionListener(){
261          public void actionPerformed(ActionEvent evt){
262             myDialog.dispose();
263          }
264       });
265       btnPanel.add(dialogCancelButton);
266
267       Container cp=myDialog.getContentPane();
268       cp.setLayout(new BorderLayout());
269       cp.add(pm,BorderLayout.CENTER);
270       cp.add(btnPanel,BorderLayout.SOUTH);
271
272       myDialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
273             .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0,false),"Cancel");
274       myDialog.getRootPane().getActionMap().put("Cancel", new AbstractAction() {
275          public void actionPerformed(ActionEvent e) {
276             myDialog.dispose();
277          }
278       });
279
280       myDialog.pack();
281
282       myDialog.setLocationRelativeTo(parent);
283       myDialog.setResizable(true);
284       myDialog.show();
285       return selectedEntries;
286    }
287
288    /**
289     * Creates participants based on LDAP entries.
290     *
291     * @param allEntries All retreived entries from LDAP server
292     */

293    private void createParticipants (java.util.List JavaDoc allEntries) {
294       PackageEditor pe=(PackageEditor)editor;
295       org.enhydra.jawe.xml.elements.Participants ps=
296             (org.enhydra.jawe.xml.elements.Participants)
297             pe.getXMLPackage().get("Participants");
298
299       java.util.Iterator JavaDoc iter = allEntries.iterator();
300       String JavaDoc mappingAttribute=idMapping.toValue().toString();
301       while (iter.hasNext()) {
302          Participant p=(Participant)ps.generateNewElement();
303
304          SearchResult nextEntry = (SearchResult)iter.next();
305          Attributes attributes = nextEntry.getAttributes();
306          String JavaDoc objectClass=null;
307
308          // Iterate through all object classes for entry, and if
309
// one with person in it's name is found, take it,
310
java.util.Enumeration JavaDoc allObjClasses=null;
311          try {
312             allObjClasses= attributes.
313                get("objectClass").getAll();
314          } catch (Exception JavaDoc ex) {}
315          if (allObjClasses!=null) {
316             while(allObjClasses.hasMoreElements()) {
317                String JavaDoc val = (String JavaDoc) allObjClasses.nextElement();
318                if (val.toLowerCase().endsWith("person")) {
319                   objectClass=val;
320                   break;
321                } else if (val.equals("organizationalRole")) {
322                   objectClass=val;
323                   break;
324                }
325             }
326          }
327
328          // Iterate through all object classes for entry, and if
329
// one if one of it's name is organizationalUnit, take it
330
if (objectClass==null) {
331             try {
332                allObjClasses= attributes.
333                      get("objectClass").getAll();
334             } catch (Exception JavaDoc ex) {}
335             if (allObjClasses!=null) {
336                while(allObjClasses.hasMoreElements()) {
337                   String JavaDoc val = (String JavaDoc) allObjClasses.nextElement();
338                   if (val.equals("organizationalUnit")) {
339                      objectClass=val;
340                      break;
341                   }
342                }
343             }
344          }
345          // If object class is not found till now, take the first one
346
if (objectClass==null) {
347             try {
348                objectClass=(String JavaDoc)attributes.get("objectClass").get();
349             } catch (Exception JavaDoc ex) {}
350          }
351          // if it is still null, take the Role
352
if (objectClass==null) {
353             objectClass="organizationalRole";
354          }
355
356
357          String JavaDoc id;
358          String JavaDoc name=null;
359          String JavaDoc pType;
360          String JavaDoc description=null;
361          try {
362             description=(String JavaDoc)attributes.get("description").get();
363          } catch (Exception JavaDoc ex) {}
364
365          // if objectClass has person in it's name, make a HUMAN type participant
366
if (objectClass.toLowerCase().endsWith("person")) {
367             pType=ResourceManager.getLanguageDependentString("HUMANKey");
368             try {
369                name=(String JavaDoc)attributes.get("cn").get();
370             } catch (Exception JavaDoc ex) {}
371          // make an ROLE or ORGANIZATIONAL_UNIT participant
372
} else if (objectClass.equals("organizationalRole")) {
373             pType=ResourceManager.getLanguageDependentString("ROLEKey");
374          } else if (objectClass.equals("organizationalUnit")) {
375             pType=ResourceManager.getLanguageDependentString("ORGANIZATIONAL_UNITKey");
376          } else {
377             pType=ResourceManager.getLanguageDependentString("ROLEKey");
378          }
379
380          if (name==null) {
381             // set name attribute of participant to be the bottom of the
382
// tree-structure of DN
383
try {
384                int ind1=nextEntry.getName().indexOf("=")+1;
385                int ind2=nextEntry.getName().indexOf(",");
386                if (ind2==-1) ind2=nextEntry.getName().length();
387                name=nextEntry.getName().substring(ind1,ind2);
388             } catch (Exception JavaDoc ex) {}
389          }
390
391          id=p.getID();
392          if (!mappingAttribute.equals("NoMapping")) {
393             // set id of participant to the attribute choosen for mapping, if it
394
// don't have it, leave the automatically generated id
395
String JavaDoc userId=null;
396             try {
397                userId=(String JavaDoc)attributes.get(mappingAttribute).get();
398             } catch (Exception JavaDoc ex) {}
399             // if id made from entry data is not null, and doesn't exist already
400
// make it to be the participant id
401
if (userId!=null && ps.getCollectionElement(userId)==null && XMLCollection.isIdValid(userId)) {
402                id=userId;
403             }
404          }
405
406          // Set the participant id, name, type and extended attribs
407
p.set("Id",id);
408          if (name!=null) {
409             p.set("Name",name);
410          }
411          ((ParticipantType)p.get("ParticipantType")).set("Type",pType);
412          if (description!=null) {
413             p.set("Description",description);
414          }
415
416          ExtendedAttributes eas=(ExtendedAttributes)p.get("ExtendedAttributes");
417          // put the DN of entry into extended attributes
418
ExtendedAttribute ea=new ExtendedAttribute(eas);
419          ea.set("Name","DN");
420          String JavaDoc eaVal=nextEntry.getName();
421          ea.set("Value",eaVal);
422          eas.add(ea);
423
424          ps.add(p);
425          JaWE.getInstance().setModified(true);
426       }
427    }
428
429    public void refreshLabels () {
430       if (eps!=null) {
431          eps.refreshLabelName();
432       }
433       idMapping.refreshLabelName();
434    }
435 }
436
Popular Tags