diff options
| author | Andrew Branson <andrew.branson@cern.ch> | 2013-02-22 14:04:33 +0100 |
|---|---|---|
| committer | Andrew Branson <andrew.branson@cern.ch> | 2013-03-18 14:03:54 +0100 |
| commit | 6e35118970c7af70eb0ac938859d794f7348d367 (patch) | |
| tree | c85299f5a174a04c9df2847c1f469ff427dd6f64 /src/main/java/com/c2kernel/lookup/ldap | |
| parent | d6cfc7505be13b3b09adf423206cf75d9f806c12 (diff) | |
Extracted LDAP specifics into subpackage
Diffstat (limited to 'src/main/java/com/c2kernel/lookup/ldap')
10 files changed, 1601 insertions, 0 deletions
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPAgentPath.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPAgentPath.java new file mode 100644 index 0000000..bae2d4f --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPAgentPath.java @@ -0,0 +1,90 @@ +/*
+ * LDAPAgentPath.java
+ *
+ * Copyright (c) 2013, The CRISTAL Consortium. All rights reserved.
+ *
+ * CRISTAL kernel is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see:
+ * http://www.gnu.org/licenses/
+ */
+
+package com.c2kernel.lookup.ldap;
+
+import java.security.NoSuchAlgorithmException;
+
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.lookup.AgentPath;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.lookup.InvalidAgentPathException;
+import com.c2kernel.lookup.InvalidEntityPathException;
+import com.c2kernel.process.Gateway;
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPAttributeSet;
+
+public class LDAPAgentPath extends AgentPath {
+
+ /**
+ * @param syskey
+ * @param agentName
+ * @throws InvalidAgentPathException
+ * @throws InvalidEntityPathException
+ */
+ public LDAPAgentPath(int syskey, String agentName)
+ throws InvalidAgentPathException, InvalidEntityPathException {
+ super(syskey, agentName);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param syskey
+ * @throws InvalidEntityPathException
+ */
+ public LDAPAgentPath(int syskey) throws InvalidEntityPathException {
+ super(syskey);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param entity
+ */
+ public LDAPAgentPath(EntityPath entity) {
+ super(entity);
+ // TODO Auto-generated constructor stub
+ }
+ @Override
+ public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated
+ {
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass","cristalagent"));
+ attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey)));
+ attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1]));
+ if (mIOR != null)
+ attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR)));
+
+ if (mAgentName!=null && mAgentName.length()>0)
+ attrs.add(new LDAPAttribute("uid",mAgentName));
+ else
+ throw new ObjectCannotBeUpdated("Cannot create agent. No userId specified", "");
+
+ if (mPassword!=null && mPassword.length()>0)
+ try {
+ attrs.add(new LDAPAttribute("userPassword",AgentPath.generateUserPassword(mPassword, "SHA")));
+ } catch (NoSuchAlgorithmException ex) {
+ throw new ObjectCannotBeUpdated("Cryptographic libraries for password hashing not found.", "");
+ }
+ else
+ throw new ObjectCannotBeUpdated("Cannot create agent. No password given", "");
+
+ return attrs;
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPEntityPath.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPEntityPath.java new file mode 100644 index 0000000..9e27525 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPEntityPath.java @@ -0,0 +1,87 @@ +/*
+ * LDAPEntityPath.java
+ *
+ * Copyright (c) 2013, The CRISTAL Consortium. All rights reserved.
+ *
+ * CRISTAL kernel is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see:
+ * http://www.gnu.org/licenses/
+ */
+
+package com.c2kernel.lookup.ldap;
+
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.lookup.InvalidEntityPathException;
+import com.c2kernel.process.Gateway;
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPAttributeSet;
+
+public class LDAPEntityPath extends EntityPath {
+
+ /**
+ * @param syskey
+ * @throws InvalidEntityPathException
+ */
+ public LDAPEntityPath(int syskey) throws InvalidEntityPathException {
+ super(syskey);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ *
+ */
+ public LDAPEntityPath() {
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param path
+ * @throws InvalidEntityPathException
+ */
+ public LDAPEntityPath(String[] path) throws InvalidEntityPathException {
+ super(path);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param path
+ * @throws InvalidEntityPathException
+ */
+ public LDAPEntityPath(String path) throws InvalidEntityPathException {
+ super(path);
+ // TODO Auto-generated constructor stub
+ }
+
+ /**
+ * @param parent
+ * @param child
+ * @throws InvalidEntityPathException
+ */
+ public LDAPEntityPath(EntityPath parent, String child)
+ throws InvalidEntityPathException {
+ super(parent, child);
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated {
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass","cristalentity"));
+ attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey)));
+ attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1]));
+ if (mIOR != null)
+ attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR)));
+ return attrs;
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java new file mode 100644 index 0000000..3ca1749 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java @@ -0,0 +1,494 @@ +/*
+ * Directory Lookup Service *
+ * author: Florida Estrella
+*/
+
+package com.c2kernel.lookup.ldap;
+
+import java.util.StringTokenizer;
+
+import com.c2kernel.common.ObjectAlreadyExistsException;
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.entity.TraceableEntity;
+import com.c2kernel.entity.agent.ActiveEntity;
+import com.c2kernel.entity.proxy.EntityProxyManager;
+import com.c2kernel.entity.proxy.ProxyMessage;
+import com.c2kernel.lookup.AgentPath;
+import com.c2kernel.lookup.DomainPath;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.lookup.InvalidEntityPathException;
+import com.c2kernel.lookup.Lookup;
+import com.c2kernel.lookup.Path;
+import com.c2kernel.lookup.RolePath;
+import com.c2kernel.process.Gateway;
+import com.c2kernel.utils.Logger;
+import com.c2kernel.utils.Resource;
+import com.novell.ldap.LDAPAttributeSet;
+import com.novell.ldap.LDAPConnection;
+import com.novell.ldap.LDAPDN;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+import com.novell.ldap.LDAPSearchConstraints;
+import com.novell.ldap.LDAPSearchResults;
+
+/**
+ * The LDAPLookup object, statically accessible through the Gateway, manages
+ * the LDAP connection for the cristal process. It provides:
+ * <ul>
+ * <li>Authentication - returning an AgentProxy object if a user has logged in
+ * <li>System key generation - through the NextKeyManager
+ * <li>Agent and Role lookup/modification - through the RoleManager
+ * <li>
+ * @version $Revision: 1.113 $ $Date: 2006/03/03 13:52:21 $
+ * @author $Author: abranson $
+ */
+
+public class LDAPLookup implements Lookup
+
+{
+ private LDAPConnection mLDAPConn;
+ private final LDAPProperties mLDAPProps;
+ private final NextKeyManager mNextKeyManager;
+ private LDAPPropertyManager mPropManager;
+ private final LDAPRoleManager mRoleManager;
+
+
+
+ /**
+ * Creates a new LDAPLookup manager with the properties supplied.
+ * This should be only done by the Gateway during initialisation.
+ *
+ * @param props The LDAP properties object that extracts LDAP connection properties from the global c2kprops
+ */
+ public LDAPLookup(LDAPProperties props) throws LDAPException
+ {
+ Logger.msg(8,"LDAPLookup - initialising.");
+
+ mLDAPProps = props;
+
+ mLDAPConn = createConnection(mLDAPProps);
+
+ Path.mGlobalPath=props.mGlobalPath;
+ Path.mRootPath=props.mRootPath;
+ Path.mLocalPath=props.mLocalPath;
+
+ EntityPath.mTypeRoot = "cn=entity,"+props.mLocalPath;
+ DomainPath.mTypeRoot = "cn=domain,"+props.mLocalPath;
+
+ mNextKeyManager = new NextKeyManager(this, "cn=last,"+EntityPath.mTypeRoot);
+ Logger.msg(7, "LDAP.useOldProps="+Gateway.getProperty("LDAP.useOldProps", "false"));
+ if (Gateway.getProperty("LDAP.useOldProps", "false").equals("true")) {
+ Logger.debug(1, "Using Kernel 2.1 LDAP Property Format");
+ mPropManager = new LegacyLDAPPropertyManager(this);
+ }
+ else {
+ Logger.debug(1, "Using Kernel 2.2 LDAP Property Format");
+ mPropManager = new LDAPPropertyManager(this);
+ }
+ mRoleManager = new LDAPRoleManager(this, "cn=agent,"+DomainPath.mTypeRoot, EntityPath.mTypeRoot);
+
+ }
+
+ /**
+ * Utility method to connect to an LDAP server
+ * @param lp LDAP properties to connect with
+ * @return a novell LDAPConnection object
+ * @throws LDAPException when the connection was unsuccessful
+ */
+ public static LDAPConnection createConnection(LDAPProperties lp) throws LDAPException {
+ LDAPConnection ld = new LDAPConnection();
+
+ Logger.msg(3, "LDAPLookup - connecting to " + lp.mHost);
+ ld.connect(lp.mHost, Integer.valueOf(lp.mPort).intValue());
+
+ Logger.msg(3, "LDAPLookup - authenticating user:" + lp.mUser);
+ ld.bind( LDAPConnection.LDAP_V3, lp.mUser,
+ String.valueOf(lp.mPassword).getBytes());
+
+ Logger.msg(3, "LDAPLookup - authentication successful");
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setMaxResults(0);
+ ld.setConstraints(searchCons);
+
+ return ld;
+ }
+
+ /**
+ * Gets the entity key generator, used to get a unique system key for new entities.
+ * @return the global NextKeyManager
+ */
+ @Override
+ public NextKeyManager getNextKeyManager()
+ {
+ return mNextKeyManager;
+ }
+
+ /**
+ * Gets the property manager, that is used to read and write cristal properties to the LDAP store.
+ * @return Returns the global LDAPPropertyManager.
+ */
+ public LDAPPropertyManager getPropManager() {
+ return mPropManager;
+ }
+ /**
+ * Gets the role manager, that is used to add and remove roles and agents.
+ * @return Returns the mRoleManager.
+ */
+ @Override
+ public LDAPRoleManager getRoleManager() {
+ return mRoleManager;
+ }
+
+ /**
+ * Returns the current LDAP connection, and attempts to reconnect if it has been closed.
+ * @return
+ */
+ protected LDAPConnection getConnection()
+ {
+ if (!mLDAPConn.isConnected()) {
+ Logger.warning("LDAPLookup - lost connection to LDAP server. Attempting to reconnect.");
+ try {
+ mLDAPConn = createConnection(mLDAPProps);
+ } catch (LDAPException ex) { }
+ }
+ return mLDAPConn;
+ }
+
+ /**
+ * Disconnects the connection with the LDAP server during shutdown
+ */
+ @Override
+ public void disconnect() {
+ Logger.msg(1, "LDAP Lookup: Shutting down LDAP connection.");
+ if (mLDAPConn != null) {
+ try {
+ mLDAPConn.disconnect();
+ } catch (LDAPException e) {
+ Logger.error(e);
+ }
+ mLDAPConn = null;
+ }
+ }
+
+ /**
+ * Attempts to resolve the CORBA object for a Path, either directly or through an alias.
+ * @param path the path to resolve
+ * @return the CORBA object
+ * @throws ObjectNotFoundException When the path does not exist
+ */
+ @Override
+ public org.omg.CORBA.Object resolve(Path path)
+ throws ObjectNotFoundException
+ {
+ return resolveObject(path.getFullDN());
+ }
+
+ /**
+ * Attempts to resolve the CORBA object from the IOR attribute of a DN, either directly or through an alias
+ * @param dn The String dn
+ * @throws ObjectNotFoundException when the dn or aliased dn does not exist
+ */
+ private org.omg.CORBA.Object resolveObject(String dn)
+ throws ObjectNotFoundException
+ {
+ Logger.msg(8,"LDAPLookup.resolveObject("+dn+")");
+ LDAPEntry anEntry = LDAPLookupUtils.getEntry(getConnection(),dn,LDAPSearchConstraints.DEREF_NEVER);
+ if (anEntry != null)
+ {
+ String iorString;
+ try {
+ iorString = LDAPLookupUtils.getFirstAttributeValue(anEntry, "ior");
+ org.omg.CORBA.Object ior=Gateway.getORB().string_to_object(iorString);
+ if (ior!=null)
+ return ior;
+ else
+ throw new ObjectNotFoundException("LDAPLookup.resolveObject() - " + dn + " has no IOR", "");
+ } catch (ObjectNotFoundException ex) {
+ return resolveObject(LDAPLookupUtils.getFirstAttributeValue(anEntry,"aliasedObjectName"));
+ }
+ }
+ else
+ throw new ObjectNotFoundException("LDAPLookup.resolveObject() LDAP node " + dn + " is not in LDAP or has no IOR.", "");
+ }
+
+ /**
+ *
+ * @param domPath
+ * @return
+ * @throws InvalidEntityPathException
+ * @throws ObjectNotFoundException
+ */
+ @Override
+ public EntityPath resolvePath(DomainPath domPath)
+ throws InvalidEntityPathException, ObjectNotFoundException {
+ EntityPath referencedPath = null;
+ LDAPEntry domEntry = LDAPLookupUtils.getEntry(getConnection(), domPath
+ .getFullDN(), LDAPSearchConstraints.DEREF_ALWAYS);
+ String entityKey = LDAPLookupUtils.getFirstAttributeValue(domEntry,
+ "intsyskey");
+ Logger.msg(7, "DomainPath " + domPath + " is a reference to "
+ + entityKey);
+ String objClass = LDAPLookupUtils.getFirstAttributeValue(domEntry,
+ "objectClass");
+ if (objClass.equals("cristalagent"))
+ referencedPath = new AgentPath(Integer.parseInt(entityKey));
+ else
+ referencedPath = new EntityPath(Integer.parseInt(entityKey));
+
+ return referencedPath;
+ }
+
+
+ @Override
+ public void add(Path path)
+ throws ObjectCannotBeUpdated, ObjectAlreadyExistsException
+ {
+ try {
+ checkLDAPContext(path);
+ LDAPAttributeSet attrSet = path.createAttributeSet();
+ LDAPEntry newEntry = new LDAPEntry(path.getFullDN(),attrSet);
+ LDAPLookupUtils.addEntry(getConnection(),newEntry);
+ if (path instanceof DomainPath)
+ EntityProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED));
+ } catch (LDAPException ex) {
+ if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)
+ throw new ObjectAlreadyExistsException(ex.getLDAPErrorMessage(), "");
+ else
+ throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), "");
+ }
+ }
+
+ //deletes a node
+ //throws LDAPexception if node cannot be deleted (eg node is not a leaf)
+ @Override
+ public void delete(Path path) throws ObjectCannotBeUpdated
+ {
+ try {
+ LDAPLookupUtils.delete(getConnection(),path.getDN()+Path.mLocalPath);
+ } catch (LDAPException ex) {
+ throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), "");
+ }
+ if (path instanceof DomainPath) {
+ EntityProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED));
+ }
+ }
+
+ //change specs, add boolean alias leaf context
+ protected void checkLDAPContext(Path path)
+ {
+ String dn = path.getFullDN();
+ if (!LDAPLookupUtils.exists(getConnection(),dn))
+ {
+ String listDN[] = path.getPath();
+ String name = "cn="+ path.getRoot() + "," + Path.mLocalPath;
+ int i=0;
+ while (i<listDN.length-1)
+ {
+ name= "cn="+listDN[i]+","+name;
+ if (!LDAPLookupUtils.exists(getConnection(),name))
+ {
+ try
+ {
+ //create cristalcontext
+ Logger.msg(8,"LDAPLookup::addLDAPContext() context added " + name);
+ LDAPLookupUtils.createCristalContext(getConnection(), name);
+ }
+ catch (Exception ex)
+ {
+ Logger.error("LDAPLookup::addContext() " + ex);
+ }
+ }
+ i++;
+ }
+ }
+ }
+ private void createBootTree()
+ {
+ Logger.msg(8,"Initializing LDAP Boot tree");
+
+ //create org
+ LDAPLookupUtils.createOrganizationContext(getConnection(), Path.mGlobalPath);
+ //create root
+ LDAPLookupUtils.createCristalContext(getConnection(), Path.mRootPath);
+ //create local
+ LDAPLookupUtils.createCristalContext(getConnection(), Path.mLocalPath);
+ }
+
+ @Override
+ public void install() throws ObjectNotFoundException
+ {
+ createBootTree();
+ initTree( Resource.getTextResource(null, "boot/LDAPboot.txt"));
+ }
+
+ public void initTree(String bootFile)
+ {
+ Logger.msg(8,"Verifying Cristal LDAP roots");
+ StringTokenizer strTokenizer = new StringTokenizer(bootFile, "\n\r");
+ while (strTokenizer.hasMoreTokens())
+ {
+ String line = strTokenizer.nextToken();
+ Logger.msg(8,"Checking " + line+Path.mLocalPath);
+ LDAPLookupUtils.createCristalContext(getConnection(), line+Path.mLocalPath);
+ }
+
+ }
+
+ //typically search for cn=barcode
+ @Override
+ public LDAPPathSet search(Path start, String filter)
+ {
+ Logger.msg(8,"LDAPLookup::search() From " + start.getDN() + " for cn=" + filter );
+ return search(start.getFullDN(),"cn="+LDAPLookupUtils.escapeSearchFilter(filter));
+ }
+
+ @Override
+ public LDAPPathSet search(Path start, String propname, String propvalue)
+ {
+ String val = propname+":"+propvalue;
+ Logger.msg(8,"LDAPLookup::search() From " + start.getDN() + " for cristalprop=" + val );
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_SEARCHING);
+ return search(start.getFullDN(),LDAPConnection.SCOPE_SUB,"cristalprop="+LDAPLookupUtils.escapeSearchFilter(val),searchCons);
+ }
+
+ protected LDAPPathSet search(String startDN, int scope, String filter, LDAPSearchConstraints searchCons)
+ {
+ Logger.msg(8,"Searching for "+filter+" in "+startDN);
+ searchCons.setMaxResults(0);
+ String[] attr = { LDAPConnection.ALL_USER_ATTRS };
+ try
+ {
+ LDAPSearchResults res = getConnection().search(LDAPLookupUtils.escapeDN(startDN),scope,
+ filter,attr,false,searchCons);
+ return new LDAPPathSet(res);
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error("LDAPException::LDAPLookup::search() " + ex.toString());
+ return new LDAPPathSet();
+ }
+ }
+ //typically search for (any filter combination)
+ public LDAPPathSet search(String startDN,String filter)
+ {
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);
+ return search(startDN,LDAPConnection.SCOPE_SUB,filter,searchCons);
+ }
+
+ @Override
+ public LDAPPathSet searchEntities(Path start) {
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_SEARCHING);
+ return search(start.getFullDN(), LDAPConnection.SCOPE_SUB, "objectClass=cristalentity", searchCons);
+ }
+
+ @Override
+ public LDAPPathSet searchAliases(DomainPath start) {
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);
+ return search(start.getFullDN(), LDAPConnection.SCOPE_SUB, "objectClass=aliasObject", searchCons);
+ }
+
+ @Override
+ public boolean exists(Path path) {
+ return LDAPLookupUtils.exists(getConnection(), path.getFullDN());
+ }
+
+ @Override
+ public Class<?> getEntityClass(Path path) throws ObjectNotFoundException {
+ String[] attr = { LDAPConnection.ALL_USER_ATTRS };
+ try {
+ LDAPEntry anEntry=getConnection().read(path.getDN()+Path.mLocalPath,attr);
+ String type = LDAPLookupUtils.getFirstAttributeValue(anEntry, "objectClass");
+ if (type.equals("cristalentity"))
+ return TraceableEntity.class;
+ else if (type.equals("cristalagent"))
+ return ActiveEntity.class;
+ else
+ throw new ObjectNotFoundException("Not an entity", "");
+
+ } catch (LDAPException ex) {
+ if (ex.getResultCode() == LDAPException.NO_SUCH_OBJECT)
+ throw new ObjectNotFoundException("Entity does not exist", "");
+ Logger.error(ex);
+ throw new ObjectNotFoundException("Error getting entity class", "");
+ }
+ }
+
+ /** converts an LDAPentry to a Path object
+ * Note that the search producing the entry should have retrieved the attrs
+ * 'ior' and 'uniquemember'
+ * @throws ObjectNotFoundException
+ * @throws ObjectNotFoundException
+ */
+ protected Path nodeToPath(LDAPEntry entry) throws InvalidEntityPathException, ObjectNotFoundException
+ {
+ String dn = entry.getDN();
+
+ // extract syskey
+ int entityKey = -1;
+ try {
+ String entityKeyStr = LDAPLookupUtils.getFirstAttributeValue(entry,"intsyskey");
+ entityKey = Integer.parseInt(entityKeyStr);
+ } catch (Exception e) { }
+
+ // extract IOR
+ org.omg.CORBA.Object ior = null;
+ try {
+ String stringIOR = LDAPLookupUtils.getFirstAttributeValue(entry,"ior");
+ ior = Gateway.getORB().string_to_object(stringIOR);
+ } catch (ObjectNotFoundException e2) { }
+
+ /* Find the right path class */
+ Path thisPath;
+ if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalagent"))
+ { //cristalagent
+ String agentID = LDAPLookupUtils.getFirstAttributeValue(entry,"uid");
+ thisPath = new AgentPath(entityKey, agentID);
+ }
+
+ else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalrole"))
+ { //cristalrole
+ thisPath = new RolePath(LDAPDN.explodeDN(dn,true)[0],
+ LDAPLookupUtils.getFirstAttributeValue(entry, "jobList").equals("TRUE"));
+ }
+ else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","aliasObject") ||
+ (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(DomainPath.mTypeRoot)))
+ {
+ DomainPath domainPath = new DomainPath();
+ domainPath.setDN(dn);
+ thisPath = domainPath;
+ }
+ else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalentity") ||
+ (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(EntityPath.mTypeRoot)))
+ {
+ if(dn.endsWith(EntityPath.mTypeRoot)) {
+ EntityPath entityPath;
+ if (entityKey != -1)
+ entityPath = new EntityPath(entityKey);
+ else {
+ entityPath = new EntityPath();
+ entityPath.setDN(dn);
+ }
+ thisPath = entityPath;
+ //set IOR if we have one
+ if (ior!=null) entityPath.setIOR(ior);
+ }
+ else
+ throw new ObjectNotFoundException("Entity found outside entity tree");
+ }
+ else
+ {
+ throw new ObjectNotFoundException("Unrecognised LDAP entry. Not a cristal entry");
+ }
+
+ return thisPath;
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java new file mode 100644 index 0000000..acf74e0 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java @@ -0,0 +1,318 @@ +/*
+ * Lookup helper class.
+ */
+
+package com.c2kernel.lookup.ldap;
+
+//import netscape.ldap.*;
+//import netscape.ldap.util.*;
+import com.c2kernel.common.ObjectAlreadyExistsException;
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.utils.Logger;
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPAttributeSet;
+import com.novell.ldap.LDAPConnection;
+import com.novell.ldap.LDAPDN;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+import com.novell.ldap.LDAPModification;
+import com.novell.ldap.LDAPSearchConstraints;
+import com.novell.ldap.LDAPSearchResults;
+
+/**
+ * @version $Revision: 1.74 $ $Date: 2006/03/03 13:52:21 $
+ * @author $Author: abranson $
+ */
+
+final public class LDAPLookupUtils
+{
+ static public LDAPEntry getEntry(LDAPConnection ld, String dn,int dereference)
+ throws ObjectNotFoundException
+ {
+ try {
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(dereference);
+ LDAPEntry thisEntry = ld.read(dn,searchCons);
+ if (thisEntry != null) return thisEntry;
+ } catch (LDAPException ex) {
+ throw new ObjectNotFoundException("LDAP Exception: "+ex.getMessage(), "");
+ }
+ throw new ObjectNotFoundException(dn+" does not exist", "");
+
+ }
+
+ //Given a DN, return an LDAP Entry
+ static public LDAPEntry getEntry(LDAPConnection ld, String dn)
+ throws ObjectNotFoundException
+ {
+ return getEntry(ld, dn, LDAPSearchConstraints.DEREF_NEVER);
+ }
+
+ static public String getFirstAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException
+ {
+ LDAPAttribute attr = anEntry.getAttribute(attribute);
+ if (attr==null)
+ throw new ObjectNotFoundException("No attributes named '"+attribute+"'", "");
+ return (String)attr.getStringValues().nextElement();
+ }
+
+ static public String[] getAllAttributeValues(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException
+ {
+ LDAPAttribute attr = anEntry.getAttribute(attribute);
+ if (attr!=null)
+ return attr.getStringValueArray();
+
+ throw new ObjectNotFoundException("No attributes named '"+attribute+"'", "");
+
+ }
+
+ static public boolean existsAttributeValue(LDAPEntry anEntry, String attribute, String value)
+ {
+ LDAPAttribute attr = anEntry.getAttribute(attribute);
+ if (attr!=null)
+ {
+ String[] attrValues = new String[attr.size()];
+ attrValues = attr.getStringValueArray();
+ for (int i=0;i<attr.size();i++)
+ if (attrValues[i].equalsIgnoreCase(value))
+ return true;
+ }
+ return false;
+ }
+ static public boolean hasOneAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException
+ {
+ int j =0;
+ LDAPAttribute attr = anEntry.getAttribute(attribute);
+ if (attr==null)
+ throw new ObjectNotFoundException("No attributes named '"+attribute+"'", "");
+ j=attr.size();
+ return j==1;
+ }
+
+ //this is for a single-valued attribute
+ static public void setAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String newValue)
+ throws ObjectNotFoundException, ObjectCannotBeUpdated
+ {
+ try {
+ if (!hasOneAttributeValue(anEntry, attribute))
+ throw new ObjectCannotBeUpdated("Attribute "+attribute + " of entry " + anEntry.getDN()+" has more than one value", "");
+ } catch (ObjectNotFoundException ex) {
+ addAttributeValue(ld, anEntry, attribute, newValue);
+ }
+ try
+ {
+ ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.REPLACE,new LDAPAttribute(attribute,newValue)));
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error(ex);
+ throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be modified", "");
+ }
+ }
+
+
+ //this is for a multi-valued attribute eg uniqueMember
+ static public void addAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value)
+ throws ObjectCannotBeUpdated
+ {
+ try
+ {
+ ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.ADD, new LDAPAttribute(attribute,value)));
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error(ex);
+ throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be added.", "");
+ }
+ }
+
+ //this is for a multi-valued attribute eg uniqueMember
+ static public void removeAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value)
+ throws ObjectCannotBeUpdated
+ {
+ try
+ {
+ ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.DELETE,new LDAPAttribute(attribute,value)));
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error(ex);
+ throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be deleted", "");
+ }
+ }
+
+ static public boolean exists(LDAPConnection ld, String name)
+ {
+ try {
+ String[] attr = { LDAPConnection.NO_ATTRS };
+ LDAPEntry anEntry=ld.read(name,attr);
+ if (anEntry!=null)
+ return true;
+ } catch (LDAPException ex)
+ {
+ Logger.debug(9, "LDAPLookupUtils.exists("+name+": "+ex.getMessage());
+ return false;
+ }
+ return false;
+ }
+
+ static public void addEntry(LDAPConnection ld,LDAPEntry myEntry)
+ throws ObjectAlreadyExistsException, LDAPException
+ {
+ try
+ {
+ ld.add( myEntry );
+ }
+ catch( LDAPException ex ) {
+ if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)
+ throw new ObjectAlreadyExistsException("Entry already present." + myEntry.getDN(), "");
+ throw ex;
+ }
+ }
+
+ static public boolean hasChildren(LDAPConnection ld, String dn, String filter)
+ {
+ String[] attr = { LDAPConnection.NO_ATTRS };
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);
+
+ try
+ {
+ LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons);
+ if (res.hasMore())
+ return true;
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error(ex);
+ }
+ return false;
+ }
+
+ //returns list of dns
+ static public String[] getChildrenDNs(LDAPConnection ld, String dn, String filter)
+ {
+ String[] result = null;
+ String[] attr = { LDAPConnection.NO_ATTRS };
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);
+
+ try
+ {
+ LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons);
+ result = new String[res.getCount()];
+ int i=0;
+ while (res.hasMore())
+ {
+ LDAPEntry findEntry=res.next();
+ if (findEntry!=null)
+ {
+ result[i++] = new String(findEntry.getDN());
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ Logger.error(ex);
+ }
+ return result;
+ }
+
+ static public void delete(LDAPConnection ld, String dn)
+ throws LDAPException
+ {
+ try
+ {
+ Logger.msg(7, "LDAPLookupUtils.delete() - "+dn);
+ ld.delete(dn);
+ }
+ catch (LDAPException ex)
+ {
+ Logger.error("LDAPLookupUtils.remove() - Cannot remove "+dn+": " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ //param dn is the DN of the name
+ //param name is the name of the node (also the RDN)
+ //example: cn=lab27,o=cern.ch lab27
+ //example: cn=product, cn=domain, cn=lab27, cn= cristal2, o=cern.ch product
+ static public void createCristalContext(LDAPConnection ld, String dn)
+ {
+ if (LDAPLookupUtils.exists(ld,dn))
+ return;
+ try
+ {
+ String name = LDAPDN.explodeDN(dn,true)[0];
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("cn",name));
+ String objectclass_values[] = new String[1];
+ objectclass_values[0] = "cristalcontext";
+ if (name.equals("last"))
+ attrs.add(new LDAPAttribute("intsyskey", "0"));
+
+ attrs.add(new LDAPAttribute("objectclass",objectclass_values));
+
+ LDAPLookupUtils.addEntry(ld,new LDAPEntry(dn,attrs));
+ }
+ catch (Exception ex)
+ {
+ Logger.error("LDAPLookupUtils.createCristalContext() " + ex.toString());
+ }
+ }
+
+ static public void createOrganizationContext(LDAPConnection ld, String dn)
+ {
+ if (LDAPLookupUtils.exists(ld,dn))
+ return;
+
+ try
+ {
+ String name = LDAPDN.explodeDN(dn,true)[0];
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ //No idea why this worked, or why it suddenly stopped working when we moved to maven
+ //attrs.add(new LDAPAttribute("objectclass","top"));
+ attrs.add(new LDAPAttribute("objectclass","organization"));
+ attrs.add(new LDAPAttribute("o",name));
+ LDAPLookupUtils.addEntry(ld,new LDAPEntry(dn,attrs));
+ }
+ catch (Exception ex)
+ {
+ Logger.msg(ex.toString());
+ }
+ }
+ public static String escapeDN (String name) {
+ //From RFC 2253 and the / character for JNDI
+ final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'};
+ String escapedStr = new String(name);
+
+ //Backslash is both a Java and an LDAP escape character, so escape it first
+ escapedStr = escapedStr.replaceAll("\\\\","\\\\");
+
+ //Positional characters - see RFC 2253
+ escapedStr = escapedStr.replaceAll("^#","\\\\#");
+ escapedStr = escapedStr.replaceAll("^ | $","\\\\ ");
+
+ for (char element : META_CHARS) {
+ escapedStr = escapedStr.replaceAll("\\"+element,"\\\\" + element);
+ }
+ Logger.msg(6, "LDAP DN "+name+" escaped to "+escapedStr);
+ return escapedStr;
+ }
+
+ public static String escapeSearchFilter (String filter) {
+ //From RFC 2254
+ String escapedStr = new String(filter);
+
+ escapedStr = escapedStr.replaceAll("\\\\","\\\\5c");
+ //escapedStr = escapedStr.replaceAll("\\*","\\\\2a"); // we need stars for searching
+ escapedStr = escapedStr.replaceAll("\\(","\\\\28");
+ escapedStr = escapedStr.replaceAll("\\)","\\\\29");
+ Logger.msg(6, "LDAP Search Filter "+filter+" escaped to "+escapedStr);
+ return escapedStr;
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java new file mode 100644 index 0000000..ffd8010 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java @@ -0,0 +1,78 @@ +package com.c2kernel.lookup.ldap;
+
+import java.util.Iterator;
+
+import com.c2kernel.lookup.Path;
+import com.c2kernel.process.Gateway;
+import com.c2kernel.utils.Logger;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+import com.novell.ldap.LDAPSearchResults;
+
+/**************************************************************************
+ *
+ * $Revision: 1.6 $
+ * $Date: 2005/12/01 14:23:14 $
+ *
+ * Copyright (C) 2003 CERN - European Organization for Nuclear Research
+ * All rights reserved.
+ **************************************************************************/
+
+
+
+public class LDAPPathSet implements Iterator<Path> {
+ LDAPSearchResults results;
+ LDAPEntry nextEntry;
+
+ public LDAPPathSet() { // empty
+ results = null;
+ }
+
+ public LDAPPathSet(LDAPSearchResults results) {
+ this.results = results;
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (results == null) return false;
+ if (nextEntry != null) return true;
+ if (results.hasMore())
+ try {
+ nextEntry = results.next();
+ return true;
+ } catch (LDAPException ex) {
+ if (ex.getResultCode()!=32) {// no results
+ Logger.error(ex);
+ Logger.error("Error loading LDAP result set: "+ex.getMessage());
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Path next() {
+ if (results == null) return null;
+ try {
+ if (nextEntry == null)
+ nextEntry = results.next();
+ Path nextPath = ((LDAPLookup)Gateway.getLookup()).nodeToPath(nextEntry);
+ nextEntry = null;
+ return nextPath;
+ } catch (Exception ex) {
+ Logger.error("Error loading next path");
+ Logger.error(ex);
+ nextEntry = null;
+ if (hasNext()) {
+ Logger.error("Skipping to next entry");
+ return next();
+ }
+ else
+ return null;
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new RuntimeException("Not implemented");
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java new file mode 100644 index 0000000..3f48935 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java @@ -0,0 +1,55 @@ +/*
+ * Directory Lookup Service
+*/
+
+package com.c2kernel.lookup.ldap;
+
+import java.math.BigInteger;
+import java.security.SecureRandom;
+
+import com.c2kernel.process.Gateway;
+
+/**
+ * @version $Revision: 1.16 $ $Date: 2005/10/12 12:51:54 $
+ * @author $Author: abranson $
+ */
+public class LDAPProperties
+{
+ public String mGlobalPath = null; //o=cern.ch
+ public String mRootPath = null; //cn=cristal2
+ public String mLocalPath = null; //cn=lab27
+ public Integer mPort = null;
+ public String mHost = null;
+ public String mUser = null;
+ public String mPassword = null;
+ public static String mGeneratedPassword = null;
+ public String mDbPath = null;
+
+ public LDAPProperties()
+ {
+ mGlobalPath = Gateway.getProperty( "LDAP.GlobalPath" );
+ mRootPath = Gateway.getProperty( "LDAP.RootPath" );
+ mLocalPath = Gateway.getProperty( "LDAP.LocalPath" );
+ mPort = Integer.valueOf(Gateway.getProperty( "LDAP.port", "389" ));
+ mHost = Gateway.getProperty( "LDAP.host" );
+ mUser = Gateway.getProperty( "LDAP.user" );
+ mPassword = Gateway.getProperty( "LDAP.password" );
+ mDbPath = Gateway.getProperty( "LDAP.dbPath" );
+
+ mRootPath += "," + mGlobalPath;
+ mLocalPath += "," + mRootPath;
+
+ }
+
+
+ public void generateRootPassword() {
+ if (mPassword == null) {
+ if (mGeneratedPassword == null) {
+ SecureRandom random = new SecureRandom();
+ mGeneratedPassword = new BigInteger(130, random).toString(32);
+ }
+ mPassword = mGeneratedPassword;
+ }
+ }
+}
+
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java new file mode 100644 index 0000000..2332fb5 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java @@ -0,0 +1,119 @@ +package com.c2kernel.lookup.ldap;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.property.Property;
+import com.c2kernel.utils.Logger;
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPEntry;
+
+/**************************************************************************
+ *
+ * $Revision: 1.3 $
+ * $Date: 2006/03/03 13:52:21 $
+ *
+ * Copyright (C) 2003 CERN - European Organization for Nuclear Research
+ * All rights reserved.
+ **************************************************************************/
+
+public class LDAPPropertyManager {
+ /**
+ *
+ */
+ protected LDAPLookup ldap;
+
+ public LDAPPropertyManager(LDAPLookup ldap) {
+ super();
+ this.ldap = ldap;
+ }
+
+ /**
+ * @param thisEntity - EntityPath of the subject entity
+ * @return
+ * @throws ObjectNotFoundException
+ */
+ public boolean hasProperties(EntityPath thisEntity) throws ObjectNotFoundException {
+ LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN());
+ return entityEntry.getAttribute("cristalprop") != null;
+ }
+
+ /**
+ * @param thisEntity - EntityPath of the subject entity
+ * @return array of Property
+ * @throws ObjectNotFoundException
+ */
+ public String[] getPropertyNames(EntityPath thisEntity) throws ObjectNotFoundException {
+ LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN());
+ ArrayList<String> propbag = new ArrayList<String>();
+ LDAPAttribute props = entityEntry.getAttribute("cristalprop");
+ for (Enumeration<?> e = props.getStringValues(); e.hasMoreElements();) {
+ String thisProp = (String)e.nextElement();
+ propbag.add(thisProp.substring(0, thisProp.indexOf(':')));
+ }
+
+ String[] retArr = new String[props.size()];
+ return propbag.toArray(retArr);
+ }
+
+ /**
+ * @param thisEntity - EntityPath of the subject entity
+ * @param propName - the name of the property to retrieve
+ * @return String the property value
+ * @throws ObjectNotFoundException
+ */
+ public String getPropertyValue(EntityPath thisEntity, String name) throws ObjectNotFoundException {
+ LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN());
+ return getPropertyAttr(entityEntry, name);
+ }
+
+ /**
+ * @param thisEntity - EntityPath of the subject entity
+ * @param name - the property name to delete
+ * @throws ObjectNotFoundException
+ * @throws ObjectCannotBeUpdated
+ */
+ public void deleteProperty(EntityPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated {
+ LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN());
+ String propVal = getPropertyAttr(entityEntry, name);
+ Logger.msg(6, "LDAPLookupUtils.deleteProperty("+name+") - Deleting property");
+ LDAPLookupUtils.removeAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", name+":"+propVal);
+ }
+
+ /**
+ * @param thisEntity - EntityPath of the subject entity
+ * @param prop - the property to store
+ * @throws ObjectNotFoundException
+ * @throws ObjectCannotBeUpdated
+ */
+ public void setProperty(EntityPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated {
+ LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN());
+ try {
+ String propVal = getPropertyAttr(entityEntry, prop.getName());
+ Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - Removing old value '"+propVal+"'");
+ LDAPLookupUtils.removeAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", prop.getName()+":"+propVal);
+ } catch (ObjectNotFoundException ex) {
+ Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - creating new property.");
+ }
+ Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - setting to '"+prop.getValue()+"'");
+ LDAPLookupUtils.addAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", prop.getName()+":"+prop.getValue());
+ }
+
+ private static String getPropertyAttr(LDAPEntry myEntry, String propName) throws ObjectNotFoundException {
+ // delete existing props
+ LDAPAttribute props = myEntry.getAttribute("cristalprop");
+ if (props == null)
+ throw new ObjectNotFoundException("Property "+propName+" does not exist", "");
+ String propPrefix = propName+":";
+ for (Enumeration<?> e = props.getStringValues(); e.hasMoreElements();) {
+ String val = (String)e.nextElement();
+ if (val.toLowerCase().startsWith(propPrefix.toLowerCase()))
+ return val.substring(propPrefix.length());
+ }
+ throw new ObjectNotFoundException("Property "+propName+" does not exist", "");
+ }
+
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPRoleManager.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPRoleManager.java new file mode 100644 index 0000000..816d1c4 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPRoleManager.java @@ -0,0 +1,210 @@ +package com.c2kernel.lookup.ldap;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import com.c2kernel.common.ObjectAlreadyExistsException;
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.lookup.AgentPath;
+import com.c2kernel.lookup.InvalidEntityPathException;
+import com.c2kernel.lookup.Path;
+import com.c2kernel.lookup.RoleManager;
+import com.c2kernel.lookup.RolePath;
+import com.c2kernel.utils.Logger;
+import com.novell.ldap.LDAPConnection;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+import com.novell.ldap.LDAPSearchConstraints;
+
+/**************************************************************************
+ *
+ * $Revision: 1.1 $
+ * $Date: 2005/04/26 06:48:12 $
+ *
+ * Copyright (C) 2003 CERN - European Organization for Nuclear Research
+ * All rights reserved.
+ **************************************************************************/
+
+// public static final String codeRevision = "$Revision: 1.1 $ $Date: 2005/04/26 06:48:12 $ $Author: abranson $";
+public class LDAPRoleManager implements RoleManager {
+
+ /**
+ *
+ */
+ LDAPLookup mLdap;
+ private final String mRolePath;
+ private final String mEntityPath;
+
+ public LDAPRoleManager(LDAPLookup ldap, String rolePath, String entityPath) {
+ super();
+ this.mLdap = ldap;
+ this.mRolePath = rolePath;
+ this.mEntityPath = entityPath;
+ }
+
+ //NOTE: A role must have at LEAST 1 userDN, cannot be empty...
+ //Creates a cristalRole
+ //CristalRole is-a specialized CristalContext which contains multi-valued uniqueMember attribute pointing to cristalagents
+ @Override
+ public RolePath createRole(String roleName, boolean jobList)
+ throws ObjectAlreadyExistsException, ObjectCannotBeUpdated
+ {
+
+ // create the role
+ RolePath rolePath = new RolePath(roleName, jobList);
+ String roleDN = rolePath.getFullDN();
+ LDAPEntry roleNode;
+ try
+ {
+ roleNode = LDAPLookupUtils.getEntry(mLdap.getConnection(), rolePath.getFullDN());
+ throw new ObjectAlreadyExistsException();
+ } catch (ObjectNotFoundException ex) { }
+
+ //create CristalRole if it does not exist
+ roleNode = new LDAPEntry(roleDN, rolePath.createAttributeSet());
+ try {
+ LDAPLookupUtils.addEntry(mLdap.getConnection(),roleNode);
+ } catch (LDAPException e) {
+ throw new ObjectCannotBeUpdated(e.getLDAPErrorMessage(), "");
+ }
+ return rolePath;
+
+
+ }
+ public void deleteRole(RolePath role) throws ObjectNotFoundException, ObjectCannotBeUpdated {
+ try {
+ LDAPLookupUtils.delete(mLdap.getConnection(), role.getFullDN());
+ } catch (LDAPException ex) {
+ throw new ObjectCannotBeUpdated("Could not remove role");
+ }
+ }
+
+ @Override
+ public void addRole(AgentPath agent, RolePath role)
+ throws ObjectCannotBeUpdated, ObjectNotFoundException
+ {
+ LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN());
+ //add memberDN to uniqueMember if it is not yet a member
+ if (!LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", agent.getFullDN()))
+ LDAPLookupUtils.addAttributeValue(mLdap.getConnection(), roleEntry, "uniqueMember", agent.getFullDN());
+ else
+ throw new ObjectCannotBeUpdated("Agent " + agent.getAgentName() + " already has role " + role.getName());
+ }
+
+ public void removeRole(AgentPath agent, RolePath role)
+ throws ObjectCannotBeUpdated, ObjectNotFoundException
+ {
+ LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN());
+ if (LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", agent.getFullDN()))
+ LDAPLookupUtils.removeAttributeValue(mLdap.getConnection(), roleEntry, "uniqueMember", agent.getFullDN());
+ else
+ throw new ObjectCannotBeUpdated("Agent did not have that role");
+ }
+
+ public boolean hasRole(AgentPath agent, RolePath role) {
+ String filter = "(&(objectclass=cristalrole)(uniqueMember="+agent.getFullDN()+")(cn="+role.getName()+"))";
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER );
+ return mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons).hasMoreElements();
+ }
+
+ @Override
+ public AgentPath[] getAgents(RolePath role)
+ throws ObjectNotFoundException
+ {
+ //get the roleDN entry, and its uniqueMember entry pointing to
+ LDAPEntry roleEntry;
+ try {
+ roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN());
+ } catch (ObjectNotFoundException e) {
+ throw new ObjectNotFoundException("Role does not exist", "");
+ }
+
+ String[] res = LDAPLookupUtils.getAllAttributeValues(roleEntry,"uniqueMember");
+ ArrayList<AgentPath> agents = new ArrayList<AgentPath>();
+ for (String userDN : res) {
+ try {
+ LDAPEntry userEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), userDN);
+ AgentPath path = (AgentPath)mLdap.nodeToPath(userEntry);
+ agents.add(path);
+ } catch (ObjectNotFoundException ex) {
+ Logger.error("Agent "+userDN+" does not exist");
+ } catch (InvalidEntityPathException ex) {
+ Logger.error("Agent "+userDN+" is not a valid entity");
+ }
+ }
+ AgentPath[] usersList = new AgentPath[0];
+ usersList = agents.toArray(usersList);
+ return usersList;
+ }
+
+ //returns the role/s of a user
+ @Override
+ public RolePath[] getRoles(AgentPath agentPath)
+ {
+ //search the mDomainPath tree uniqueMember=userDN
+ //filter = objectclass=cristalrole AND uniqueMember=userDN
+ String filter = "(&(objectclass=cristalrole)(uniqueMember="+agentPath.getFullDN()+"))";
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER );
+ Enumeration<?> roles = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons);
+ ArrayList<RolePath> roleList = new ArrayList<RolePath>();
+
+ while(roles.hasMoreElements())
+ {
+ RolePath path = (RolePath) roles.nextElement();
+ roleList.add(path);
+ }
+ RolePath[] roleArr = new RolePath[roleList.size()];
+ roleArr = roleList.toArray(roleArr);
+ return roleArr;
+ }
+
+ /**
+ * Utility for looking up a login name
+ *
+ * @param ld
+ * @param agentName
+ * @param baseDN
+ * @return
+ * @throws ObjectNotFoundException
+ */
+ @Override
+ public AgentPath getAgentPath(String agentName) throws ObjectNotFoundException
+ {
+ //search to get the userDN equivalent of the userID
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER );
+ String filter = "(&(objectclass=cristalagent)(uid="+agentName+"))";
+ Enumeration<Path> res = mLdap.search(mEntityPath,LDAPConnection.SCOPE_SUB,filter,searchCons);
+ if (!res.hasMoreElements())
+ throw new ObjectNotFoundException("Agent not found");
+ Path result = res.nextElement();
+ if (result instanceof AgentPath)
+ return (AgentPath)result;
+ else
+ throw new ObjectNotFoundException("Entry was not an Agent");
+ }
+
+ @Override
+ public RolePath getRolePath(String roleName) throws ObjectNotFoundException
+ {
+ LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
+ searchCons.setBatchSize(0);
+ searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER );
+ String filter = "(&(objectclass=cristalrole)(cn="+roleName+"))";
+ Enumeration<Path> res = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons);
+ if (!res.hasMoreElements())
+ throw new ObjectNotFoundException("Role not found");
+ Path result = res.nextElement();
+ if (result instanceof RolePath)
+ return (RolePath)result;
+ else
+ throw new ObjectNotFoundException("Entry was not a Role");
+ }
+
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/LegacyLDAPPropertyManager.java b/src/main/java/com/c2kernel/lookup/ldap/LegacyLDAPPropertyManager.java new file mode 100644 index 0000000..cf4892d --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LegacyLDAPPropertyManager.java @@ -0,0 +1,76 @@ +package com.c2kernel.lookup.ldap;
+
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.property.Property;
+import com.c2kernel.utils.Logger;
+import com.novell.ldap.LDAPAttribute;
+import com.novell.ldap.LDAPAttributeSet;
+import com.novell.ldap.LDAPDN;
+import com.novell.ldap.LDAPEntry;
+import com.novell.ldap.LDAPException;
+
+public class LegacyLDAPPropertyManager extends LDAPPropertyManager {
+
+ public LegacyLDAPPropertyManager(LDAPLookup ldap) {
+ super(ldap);
+ }
+
+ @Override
+ public void deleteProperty(EntityPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated {
+ try {
+ LDAPLookupUtils.delete(ldap.getConnection(), "cn="+name+","+thisEntity.getFullDN());
+ } catch (LDAPException ex) {
+ Logger.error("Error deleting prop "+name+" from "+thisEntity.getSysKey());
+ Logger.error(ex);
+ }
+ }
+
+ @Override
+ public String[] getPropertyNames(EntityPath thisEntity) throws ObjectNotFoundException {
+ String props[]= LDAPLookupUtils.getChildrenDNs(ldap.getConnection(), thisEntity.getFullDN(), "objectclass=cristalproperty");
+ String names[] = new String[props.length];
+ for (int i=0; i<props.length;i++)
+ names[i] = new String(LDAPDN.explodeDN(props[i],true)[0]);
+ return names;
+ }
+
+ @Override
+ public String getPropertyValue(EntityPath thisEntity, String name) throws ObjectNotFoundException {
+ LDAPEntry anEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),"cn="+name+","+thisEntity.getFullDN());
+ if (anEntry==null)
+ throw new ObjectNotFoundException("LDAPLookup: Property "+name+" not found in "+thisEntity.getSysKey(), "");
+ return LDAPLookupUtils.getFirstAttributeValue(anEntry,"propval");
+ }
+
+ @Override
+ public boolean hasProperties(EntityPath thisEntity) throws ObjectNotFoundException {
+ return LDAPLookupUtils.hasChildren(ldap.getConnection(), thisEntity.getFullDN(), "objectclass=cristalproperty" );
+ }
+
+ @Override
+ public void setProperty(EntityPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated {
+ try {
+ LDAPEntry anEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),"cn="+prop.getName()+","+thisEntity.getFullDN());
+ String currentVal = LDAPLookupUtils.getFirstAttributeValue(anEntry,"propval");
+ if (currentVal == null || !currentVal.equals(prop.getValue()) )
+ //change the propvalue if the prop.getValue() is not the same value in LDAP
+ LDAPLookupUtils.setAttributeValue(ldap.getConnection(), anEntry,"propval",prop.getValue());
+
+ } catch (ObjectNotFoundException ex) {
+ LDAPAttributeSet attrSet = new LDAPAttributeSet();
+ attrSet.add(new LDAPAttribute("objectclass","cristalproperty"));
+ attrSet.add(new LDAPAttribute("cn",prop.getName()));
+ if (prop.getValue()!=null && prop.getValue().length()!=0)
+ attrSet.add(new LDAPAttribute("propval",prop.getValue()));
+ LDAPEntry newEntry = new LDAPEntry("cn="+prop.getName()+","+thisEntity.getFullDN(),attrSet);
+ try {
+ LDAPLookupUtils.addEntry(ldap.getConnection(),newEntry);
+ } catch (Exception e) {
+ Logger.error(e);
+ throw new ObjectCannotBeUpdated(e.getMessage(), "");
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/c2kernel/lookup/ldap/NextKeyManager.java b/src/main/java/com/c2kernel/lookup/ldap/NextKeyManager.java new file mode 100644 index 0000000..305fe65 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/NextKeyManager.java @@ -0,0 +1,74 @@ +package com.c2kernel.lookup.ldap;
+
+import com.c2kernel.common.ObjectCannotBeUpdated;
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.lookup.AgentPath;
+import com.c2kernel.lookup.EntityPath;
+import com.c2kernel.lookup.InvalidEntityPathException;
+import com.novell.ldap.LDAPEntry;
+
+/**************************************************************************
+ *
+ * $Revision: 1.2 $
+ * $Date: 2005/04/27 13:47:24 $
+ *
+ * Copyright (C) 2003 CERN - European Organization for Nuclear Research
+ * All rights reserved.
+ **************************************************************************/
+
+// public static final String codeRevision = "$Revision: 1.2 $ $Date: 2005/04/27 13:47:24 $ $Author: abranson $";
+public class NextKeyManager {
+
+ LDAPLookup ldap;
+ String lastKeyPath;
+
+ public NextKeyManager(LDAPLookup ldap, String lastKeyPath) {
+ super();
+ this.ldap = ldap;
+ this.lastKeyPath = lastKeyPath;
+ }
+
+ public synchronized EntityPath generateNextEntityKey()
+ throws ObjectCannotBeUpdated, ObjectNotFoundException
+ {
+ EntityPath lastKey = getLastEntityPath();
+
+ try {
+ lastKey.setSysKey(lastKey.getSysKey()+1);
+ } catch (InvalidEntityPathException ex) {
+ throw new ObjectCannotBeUpdated("Invalid syskey "+(lastKey.getSysKey()+1)+". Maybe centre is full.");
+ }
+ //set the last key
+ writeLastEntityKey(lastKey.getSysKey());
+
+ return lastKey;
+ }
+
+ public synchronized AgentPath generateNextAgentKey()
+ throws ObjectCannotBeUpdated, ObjectNotFoundException {
+ EntityPath newEntity = generateNextEntityKey();
+ return new AgentPath(newEntity);
+ }
+
+ public void writeLastEntityKey(int sysKey) throws ObjectCannotBeUpdated, ObjectNotFoundException {
+ LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath);
+ LDAPLookupUtils.setAttributeValue(ldap.getConnection(), lastKeyEntry,"intsyskey",Integer.toString(sysKey));
+ }
+
+ public EntityPath getLastEntityPath() throws ObjectNotFoundException
+ {
+ LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath);
+ String lastKey = LDAPLookupUtils.getFirstAttributeValue(lastKeyEntry,"intsyskey");
+ try {
+ int sysKey = Integer.parseInt(lastKey);
+ EntityPath sysPath = new EntityPath(sysKey);
+ return sysPath;
+ } catch (InvalidEntityPathException ex) {
+ throw new ObjectNotFoundException("Invalid syskey. Maybe centre is full.");
+ } catch (NumberFormatException ex) {
+ throw new ObjectNotFoundException("Invalid syskey in lastkey.");
+ }
+
+ }
+
+}
|
