KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mr > kernel > security > impl > ldap > LDAPActions


1 /*
2  * Copyright 2002 by
3  * <a HREF="http://www.coridan.com">Coridan</a>
4  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with the
8  * License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is "MantaRay" (TM).
17  *
18  * The Initial Developer of the Original Code is Shirley Sasson.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * Coridan Inc. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source
23  * code where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
34
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Lesser General Public License as published by the Free Software Foundation;
39  * either version 2.1 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
43  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
44  * License for more details.
45  */

46
47 package org.mr.kernel.security.impl.ldap;
48
49 import org.mr.MantaAgent;
50 import org.mr.kernel.security.SecurityConfigurationPaths;
51
52 import javax.naming.*;
53 import javax.naming.directory.*;
54 import java.util.*;
55
56 import org.mr.kernel.security.SecurityConstants;
57 import org.mr.kernel.security.MantaSecurityException;
58 import org.apache.commons.logging.Log;
59 import org.apache.commons.logging.LogFactory;
60 import org.mr.kernel.security.impl.ldap.management.EntryAlreadyExistsException;
61 import org.mr.kernel.security.impl.ldap.management.EntryNotFoundException;
62
63 /**
64  * This class performs actions with an LDAP server. The actions are usually searching for entries,
65  * adding entries, deleting entries, modifying attributes, etc.
66  *
67  * This class is a singltone.
68  *
69  * @version 1.0
70  * @since Apr 12, 2006
71  * @author Shirley Sasson
72  *
73  */

74 public class LDAPActions implements SecurityConfigurationPaths, SecurityConstants, LDAPConstants {
75     //private static LDAPActions _instance;
76
private Hashtable _env;
77     private String JavaDoc _ip;
78     private int _port;
79     private Log _logger;
80
81     public LDAPActions(String JavaDoc configurationName) throws MantaSecurityException {
82         String JavaDoc initialContextFactory = MantaAgent.getInstance().getSingletonRepository().getConfigManager().getStringProperty(ACL_CONFIGURATIONS + "." + configurationName + "." + INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT_FACTORY);
83         _ip = MantaAgent.getInstance().getSingletonRepository().getConfigManager().getStringProperty(ACL_CONFIGURATIONS + "." + configurationName + "." + IP, DEFAULT_LDAP_IP);
84         _port = MantaAgent.getInstance().getSingletonRepository().getConfigManager().getIntProperty(ACL_CONFIGURATIONS + "." + configurationName + "." + PORT, DEFAULT_LDAP_PORT);
85
86         String JavaDoc securityPrincipal = MantaAgent.getInstance().getSingletonRepository().getConfigManager().getStringProperty(ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_PRINCIPAL);
87         if (securityPrincipal == null){
88             if (getLogger().isErrorEnabled())
89                 getLogger().error("[LDAPActions] Unable to find configuration parameter: " + ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_PRINCIPAL);
90             throw new MantaSecurityException("Unable to find configuration parameter: " + ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_PRINCIPAL);
91         }
92
93         String JavaDoc securityCredentials = MantaAgent.getInstance().getSingletonRepository().getConfigManager().getStringProperty(ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_CREDENTIALS);
94         if (securityCredentials == null){
95             if (getLogger().isErrorEnabled())
96                 getLogger().error("[LDAPActions] Unable to find configuration parameter: " + ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_CREDENTIALS);
97             throw new MantaSecurityException("Unable to find configuration parameter: " + ACL_CONFIGURATIONS + "." + configurationName + "." + SECURITY_CREDENTIALS);
98         }
99
100         _env = new Hashtable();
101         _env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
102         _env.put(Context.PROVIDER_URL,"ldap://" + _ip + ":" + _port);
103         _env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
104         _env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
105     }
106
107     /**
108       * Returns the single instance of LDAPActions.
109       *
110       * @return the single instance of LDAPActions
111       */

112     /*
113     public static LDAPActions getInstance() throws MantaSecurityException {
114         if (_instance == null){
115             synchronized(LDAPActions.class){
116                 if (_instance == null)
117                     _instance = new LDAPActions();
118             }
119         }
120         return _instance;
121     }
122     */

123
124     /**
125      * Determined whether or not a specific entry, with a given attribute, exists on the LDAP server.
126      *
127      * @param entry the full distinguished name of the entry to search
128      * @return true if the entryexists on the LDAP server, false otherwise
129      * @throws MantaSecurityException if an error occured
130      *
131      */

132     public boolean isExistEntry(LDAPDN entry) throws MantaSecurityException {
133         DirContext ctx = null;
134         try {
135             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
136             buf.append("ldap://").append(_ip).append(":").append(_port).append("/").append(entry.getStringParentDN());
137             String JavaDoc searchPath = new String JavaDoc(buf);
138             InitialContext iCtx = new InitialContext();
139             ctx = (DirContext)iCtx.lookup(searchPath);
140             SearchControls controls = new SearchControls();
141             ctx.search(entry.getStrFirstEntry(), "(objectclass=*)", controls);
142             return true;
143         }
144         catch (NamingException ne){
145             if (ne instanceof NameNotFoundException)
146                 return false;
147             if (getLogger().isErrorEnabled())
148                 getLogger().error("[isExistEntry] " + ne.getMessage());
149             throw new MantaSecurityException("Error looking for entry in LDAP");
150         }
151         finally {
152             if (ctx != null){
153                 try {
154                     ctx.close();
155                 }
156                 catch (NamingException ne2){
157                     if (getLogger().isErrorEnabled())
158                         getLogger().error("[isExistEntry] " + ne2.getMessage());
159                 }
160             }
161         }
162     }
163
164     /**
165      * Retrieves an attribute of a given entry, from the LDAP server.
166      *
167      * @param entry the entry name to search
168      * @param attributeName the attribute name to retrieve
169      * @return the value of the attribue if it exists, null otehrwise
170      * @throws MantaSecurityException if an error occured
171      *
172      */

173     public String JavaDoc getAttribute(LDAPDN entry, String JavaDoc attributeName) throws MantaSecurityException {
174         DirContext ctx = null;
175         try {
176             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
177             buf.append("ldap://").append(_ip).append(":").append(_port).append("/").append(entry.getStringParentDN());
178             String JavaDoc searchPath = new String JavaDoc(buf);
179             InitialContext iCtx = new InitialContext();
180             ctx = (DirContext)iCtx.lookup(searchPath);
181             Attributes attributes = ctx.getAttributes(entry.getStrFirstEntry());
182             Attribute attr = attributes.get(attributeName);
183             return (String JavaDoc) attr.get(0);
184         }
185         catch (NamingException ne){
186             if (ne instanceof NameNotFoundException)
187                 return null;
188             if (getLogger().isErrorEnabled())
189                 getLogger().error("[getAttribute] " + ne.getMessage());
190             throw new MantaSecurityException("Error looking for attribute in LDAP");
191         }
192         finally {
193             if (ctx != null){
194                 try {
195                     ctx.close();
196                 }
197                 catch (NamingException ne2){
198                     if (getLogger().isErrorEnabled())
199                         getLogger().error("[getAttribute] " + ne2.getMessage());
200                 }
201             }
202         }
203     }
204
205     /**
206      * Retrieves all attributes of a given entry, from the LDAP server.
207      *
208      * @param entry the entry name to search
209      * @return all attributes of a given entry
210      * @throws MantaSecurityException if an error occured
211      *
212      */

213     public Attributes getAttributes(LDAPDN entry) throws EntryNotFoundException, MantaSecurityException {
214         DirContext ctx = null;
215         try {
216             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
217             buf.append("ldap://").append(_ip).append(":").append(_port).append("/").append(entry.getStringParentDN());
218             String JavaDoc searchPath = new String JavaDoc(buf);
219             InitialContext iCtx = new InitialContext();
220             ctx = (DirContext)iCtx.lookup(searchPath);
221             return ctx.getAttributes(entry.getStrFirstEntry());
222         }
223         catch (NamingException ne){
224             if (ne instanceof NameNotFoundException){
225                 if (getLogger().isErrorEnabled())
226                     getLogger().error("[getAttributes] Entry " + entry.getPath() + " not found");
227                 throw new EntryNotFoundException(entry.getPath());
228             }
229             if (getLogger().isErrorEnabled())
230                 getLogger().error("[getAttributes] " + ne.getMessage());
231             throw new MantaSecurityException("Error looking for attribute in LDAP");
232         }
233         finally {
234             if (ctx != null){
235                 try {
236                     ctx.close();
237                 }
238                 catch (NamingException ne2){
239                     if (getLogger().isErrorEnabled())
240                         getLogger().error("[getAttributes] " + ne2.getMessage());
241                 }
242             }
243         }
244     }
245
246     /**
247      * Adds the given entry with the given attributes, to the LDAP server.
248      *
249      * @param entry the entry to add
250      * @param entryAttributes the entry attributes
251      * @throws MantaSecurityException if an error occured
252      * @throws EntryAlreadyExistsException if an entry with the same dinstigushed name already exists on the LDAP server
253      *
254      */

255     public void addEntry(LDAPDN entry, Map entryAttributes) throws MantaSecurityException, EntryAlreadyExistsException {
256         DirContext ctx = null;
257         String JavaDoc parent = entry.getStringParentDN();
258         Attributes attributes = new BasicAttributes(true);
259         if (entryAttributes != null){
260             Set set = entryAttributes.keySet();
261             Iterator iter = set.iterator();
262             while (iter.hasNext()){
263                 String JavaDoc key = (String JavaDoc) iter.next();
264                 Object JavaDoc value = entryAttributes.get(key);
265                 attributes.put(key, value);
266             }
267         }
268
269         // add the attribute that holds the name of the entry
270
attributes.put(entry.getFirstEntry().getName(), entry.getFirstEntry().getValue());
271
272         try {
273             InitialContext iCtx = new InitialContext(_env);
274             ctx = (DirContext)iCtx.lookup(parent);
275             ctx.createSubcontext(entry.getStrFirstEntry(), attributes);
276         }
277         catch (NameAlreadyBoundException nabe){
278             if (getLogger().isErrorEnabled())
279                 getLogger().error("[addEntry] Entry " + entry + " already exists");
280             throw new EntryAlreadyExistsException(entry.getPath());
281         }
282         catch (NamingException ne){
283             if (getLogger().isErrorEnabled())
284                 getLogger().error("[addEntry] " + ne.getMessage());
285             throw new MantaSecurityException("Error while creating new LDAP entry");
286         }
287         finally {
288             if (ctx != null){
289                 try {
290                     ctx.close();
291                 }
292                 catch (NamingException ne2){
293                     if (getLogger().isErrorEnabled())
294                         getLogger().error("[addEntry] " + ne2.getMessage());
295                 }
296             }
297         }
298     }
299
300     /**
301      * Deletes the given entry from the LDAP server.
302      *
303      * @param entry the entry to delete
304      * @throws MantaSecurityException if an error occured
305      * @throws EntryNotFoundException if the entry is not found on the LDAP server
306      *
307      */

308     public void deleteEntry(LDAPDN entry) throws MantaSecurityException, EntryNotFoundException {
309         InitialContext ctx = null;
310         try {
311             ctx = new InitialContext(_env);
312             ctx.destroySubcontext(entry.getPath());
313         }
314         catch (NameNotFoundException nnfe){
315             if (getLogger().isErrorEnabled())
316                 getLogger().error("[deleteEntry] Entry " + entry + " not found");
317             throw new EntryNotFoundException(entry.getPath());
318         }
319         catch (NamingException ne){
320             if (getLogger().isErrorEnabled())
321                 getLogger().error("[deleteEntry] " + ne.getMessage());
322             throw new MantaSecurityException("Error while deleting LDAP entry");
323         }
324         finally {
325             if (ctx != null){
326                 try {
327                     ctx.close();
328                 }
329                 catch (NamingException ne2){
330                     if (getLogger().isErrorEnabled())
331                         getLogger().error("[deleteEntry] " + ne2.getMessage());
332                 }
333             }
334         }
335     }
336
337     /**
338      * Retrieves all entries of a given path.
339      *
340      * @param entry the path to search the entries at
341      * @return a list of the entries found, the objects in the list are String objects that hold the
342      * distinguished name of the format (for example) "o=manta"
343      * @throws MantaSecurityException if an error occured
344      * @throws EntryNotFoundException if the entry is not found on the LDAP server
345      *
346      */

347     public List getEntries(LDAPDN entry) throws MantaSecurityException, EntryNotFoundException {
348         return getEntries(entry, null, null);
349     }
350
351     /**
352      * Retrieves all entries of a given path, with the given attribute filter.
353      *
354      * @param entry the path to search the entries at
355      * @param attributeName the name of the attribute to act as a filter for the search
356      * @param attributeValue the value of the attribute to act as a filter for the search
357      * @return a list of the entries found, the objects in the list are String objects that hold the
358      * distinguished name of the format (for example) "o=manta"
359      * @throws MantaSecurityException if an error occured
360      * @throws EntryNotFoundException if the entry is not found on the LDAP server
361      *
362      */

363     public List getEntries(LDAPDN entry, String JavaDoc attributeName, String JavaDoc attributeValue) throws MantaSecurityException, EntryNotFoundException {
364         List entries = new ArrayList();
365         DirContext ctx = null;
366         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
367         buf.append("ldap://").append(_ip).append(":").append(_port).append("/").append(entry.getPath());
368         String JavaDoc searchPath = new String JavaDoc(buf);
369         try {
370             InitialContext iCtx = new InitialContext();
371             ctx = (DirContext)iCtx.lookup(searchPath);
372             SearchControls controls = new SearchControls();
373             String JavaDoc name = "";
374             String JavaDoc filter;
375             if (attributeName == null || "".equals(attributeName) || attributeValue == null || "".equals(attributeValue))
376                 filter = "(objectclass=*)";
377             else
378                 filter = "(" + attributeName + "=" + attributeValue + ")";
379             NamingEnumeration enu = ctx.search(name, filter, controls);
380             while (enu.hasMore()){
381                 SearchResult result = (SearchResult) enu.next();
382                 String JavaDoc current = result.getName();
383                 entries.add(current);
384             }
385         }
386         catch (NameNotFoundException nnfe){
387             if (getLogger().isErrorEnabled())
388                 getLogger().error("[getEntries] Entry " + entry.getPath() + " not found");
389             throw new EntryNotFoundException(entry.getPath());
390         }
391         catch (NamingException ne){
392             if (getLogger().isErrorEnabled())
393                 getLogger().error("[getEntries] " + ne.getMessage());
394             throw new MantaSecurityException("Error while reading LDAP entries");
395         }
396         finally {
397             if (ctx != null){
398                 try {
399                     ctx.close();
400                 }
401                 catch (NamingException ne2){
402                     if (getLogger().isErrorEnabled())
403                         getLogger().error("[getEntries] " + ne2.getMessage());
404                 }
405             }
406         }
407         return entries;
408     }
409
410     /**
411      * Sets the value of the attributes of a specific entry.
412      *
413      * @param entry the entry to set its attributes
414      * @param entryAttributes a map holding the attributes to set
415      * @throws MantaSecurityException if an error occured
416      * @throws EntryNotFoundException if the entry is not found on the LDAP server
417      *
418      */

419     public void setAttributes(LDAPDN entry, Map entryAttributes) throws EntryNotFoundException, MantaSecurityException {
420         DirContext ctx = null;
421         try {
422             InitialContext iCtx = new InitialContext(_env);
423             ctx = (DirContext)iCtx.lookup("");
424             Attributes attributes = new BasicAttributes(true);
425             Set set = entryAttributes.keySet();
426             Iterator iter = set.iterator();
427             while (iter.hasNext()){
428                 String JavaDoc key = (String JavaDoc) iter.next();
429                 String JavaDoc value = (String JavaDoc) entryAttributes.get(key);
430                 attributes.put(key, value);
431             }
432             ctx.modifyAttributes(entry.getPath(), DirContext.REPLACE_ATTRIBUTE, attributes);
433         }
434         catch (NameNotFoundException nnfe){
435             if (getLogger().isErrorEnabled())
436                 getLogger().error("[setAttributes] Entry " + entry.getPath() + " not found");
437             throw new EntryNotFoundException(entry.getPath());
438         }
439         catch (NamingException ne){
440             if (getLogger().isErrorEnabled())
441                 getLogger().error("[setAttributes] " + ne.getMessage());
442             throw new MantaSecurityException("Error while setting LDAP attributes");
443         }
444         finally {
445             if (ctx != null){
446                 try {
447                     ctx.close();
448                 }
449                 catch (NamingException ne2){
450                     if (getLogger().isErrorEnabled())
451                         getLogger().error("[setAttributes] " + ne2.getMessage());
452                 }
453             }
454         }
455     }
456
457     /**
458      * Returns the instance of the logger for this class
459      *
460      * @return the instance of the logger
461      */

462     public Log getLogger(){
463         if (_logger == null){
464             _logger = LogFactory.getLog(getClass().getName());
465         }
466         return _logger;
467     }
468 }
469
Popular Tags