This GPRS stub contains two functions to search and delete the data on the GPRS LDAP macro. It also helps in validating the data present on the GPRS macro based on the subscriber id.
package abc; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.Vector; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; //import org.apache.commons.lang.StringUtils; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.sharkysoft.printf.Printf; //import org.apache.xmlbeans.XmlException; //import org.apache.xmlbeans.XmlOptions; import be.proximus.protestjavalib.ProtestTS; import be.proximus.protestjavalib.log4j.ProtestLog4jUtil; /** * * @author id829957
* Currently it supports DISPLAY/DELETE operations * javax.naming.directory API is used to interact with LDAP */ public class GprsTs{ static private Logger logger = Logger.getLogger(GprsTs.class); private static String url; // intialize the url private static String username; private static String password; private static String conTimeOut; private static String protocolVersion; private static String organisationUnit; private static String organisation; private static InitialLdapContext ctx = null; public static final String ELEMENT_PRESENT_VALUE = "_present_"; public GprsTs() { super(); } // RemoteTS constructor TS=> Test Stub public GprsTs(int _port, String _TSID) { super(_port, _TSID); } public static void main(String[] args) throws Exception { // Basic log4j configuration BasicConfigurator.configure(); Logger.getRootLogger().setLevel(Level.INFO); GprsTs gprsTs = new GprsTs(Integer.parseInt(args[0]), args[1]); gprsTs.start(); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { logger.debug("", e); } } } public Object init (Hashtable args) throws Exception { super.init(args); logger.info("init args: " + args.toString()); try { Hashtable env = new Hashtable(); env.put("java.naming.ldap.version", protocolVersion); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "Simple"); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.PROVIDER_URL, url); env.put("com.sun.jndi.ldap.connect.pool.timeout", conTimeOut); if(ctx == null) { ctx = new InitialLdapContext(env, null); logger.info("Initialized Ldap configuration - url[" + url + "] -"); return ctx; } return RpcOK; //RpcOK is an object that shows that the result is correct } catch (Exception e) { // TODO: handle exception logger.error(StackTraceAsString(e)); throw (e); } } public Object delete_subscriber(Hashtable args) throws Exception{ logger.info("delete_subscriber args: " + args.toString()); boolean ignore_error = false; try { String subscriberid = (String) args.get("subscriberid"); ignore_error = (Boolean)args.get("ignore_error"); String dn = "GprsUser=" + subscriberid + ",ou=" + organisationUnit + ",o= " + "" + organisation; if(ctx.lookup(dn).toString().length()>0) { ctx.destroySubcontext(dn); logger.info("Deleted Subscriber: "+subscriberid); } } catch (Exception e) { if (ignore_error) { logger.warn("Ignored exception: " + e.getMessage()); } else { logger.error(StackTraceAsString(e)); throw (e); } } return RpcOK; } public Object search_subscriber(Hashtable args) throws Exception { logger.info("search_subscriber args: " + args.toString()); String subscriberid = (String) args.get("subscriberid"); if(args.containsKey("present")){ TreeMap tmp_map1 = doSearchSubscriber(subscriberid); if((Boolean)(args.get("present"))){ if(tmp_map1.isEmpty()){ throw new Exception("Subscriber is not present but expected to be present"); }else{ logger.info("Subscriber is present"); } }else{ if(tmp_map1.isEmpty()){ logger.info("Subscriber is not present"); }else{ throw new Exception("Subscriber is present but expected not to be present"); } } } if(args.containsKey("attribute")) { // Start search and checking try { Vector check_attrlist = (Vector) args.get("attribute"); TreeMap allrespflat = doSearchSubscriber(subscriberid); dumpFlatDomMap(allrespflat, "Reponses", false); checkAttributeList(allrespflat, check_attrlist); } catch (SearchException e) { throw (e); } catch (CheckException e) { throw (e); } catch (Exception e) { logger.error(ProtestLog4jUtil.StackTraceAsString(e)); throw (e); } } return RpcOK; } protected TreeMap doSearchSubscriber(String subscriberid) throws Exception { TreeMap tmp_TreeMap = new TreeMap(); try { String filter = "(GprsUser="+subscriberid+")"; SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String dn = "ou=" + organisationUnit + ",o= " + "" + organisation; NamingEnumeration results = ctx.search(dn, filter, constraints); //now step through the search results //logger.info("--Search Results--" + results.hasMore()); //TODO: Write the display code as you wish while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); String dn1 = sr.getName(); //logger.info("Distinguished Name is "+dn1); Attributes attrs = sr.getAttributes(); TreeMap tmp_map = new TreeMap(); for (NamingEnumeration ne = attrs.getAll(); ne.hasMoreElements();) { Attribute attr = (Attribute)ne.next(); String attrID = attr.getID(); for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { Vector v = new Vector(); String tmp = (String)(vals.nextElement()); //logger.info(attrID+":"+tmp); v.add(tmp); tmp_map.put(attrID, v); } } tmp_TreeMap.putAll(tmp_map); } //logger.info("--Search Ends--"); } catch (Exception e) { logger.error(ProtestLog4jUtil.StackTraceAsString(e)); throw (e); } return tmp_TreeMap; } protected void checkAttributeList(TreeMap actual_attribute_list, Vector check_attribute_list) throws Exception { Vector errorlist = new Vector(); for (Iterator iter = check_attribute_list.iterator(); iter.hasNext();) { Hashtable check_ldapattr = (Hashtable) iter.next(); String check_name = (String) check_ldapattr.get("name"); String expected_value = (String) check_ldapattr.get("value"); Boolean expected_present = (Boolean) check_ldapattr.get("present"); Boolean expected_empty = (Boolean) check_ldapattr.get("empty"); Vector actual_attr_valV = (Vector) actual_attribute_list.get(check_name); String tmp; String tmpAttrCheckMsg = Printf.format( "Checking attribute='%s': expected_value='%s', expected_present='%s', expected_empty='%s': ", new Object[] { check_name, (expected_value == null ? "notchecked" : expected_value.toString()), (expected_present == null ? "notchecked" : expected_present.toString()), (expected_empty == null ? "notchecked" : expected_empty.toString()) }); // 1. Check presence ... if (expected_present == null || expected_present.booleanValue() == true) { if (!actual_attribute_list.containsKey(check_name)) { tmp = Printf.format( "Attribute '%s': Not present. Expected to be present.", new Object[] { check_name, expected_value }); errorlist.add(tmp); logger.error(tmpAttrCheckMsg + tmp + ": FAIL"); continue; } } // ... or not presence if (expected_present != null && expected_present.booleanValue() == false) { if (actual_attribute_list.containsKey(check_name)) { tmp = Printf.format( "Attribute '%s': Is present. Expected not to be present.", new Object[] { check_name, expected_value }); errorlist.add(tmp); logger.error(tmpAttrCheckMsg + tmp + ": FAIL"); continue; } } // 2. Check empty ... if (expected_empty != null && expected_empty.booleanValue() == true) { if (actual_attr_valV != null && actual_attr_valV.size() > 0) { tmp = Printf.format( "Attribute '%s': Not empty. Expected to be empty.", new Object[] { check_name, expected_value }); errorlist.add(tmp); logger.error(tmpAttrCheckMsg + tmp + ": FAIL"); continue; } } // ... or not empty if (expected_empty != null && expected_empty.booleanValue() == false) { if (actual_attr_valV != null && actual_attr_valV.size() == 0) { tmp = Printf.format( "Attribute '%s': Is empty. Expected not to be empty.", new Object[] { check_name, expected_value }); errorlist.add(tmp); logger.error(tmpAttrCheckMsg + tmp + ": FAIL"); continue; } } // 3. Check attribute value if ((expected_value != null) && (expected_present == null || expected_present.booleanValue() == true) && (expected_empty == null || expected_empty.booleanValue() == false)) { Vector tmpV = (Vector) actual_attr_valV.clone(); Vector tmpSV = new Vector(); tmpSV.add(expected_value); tmpV.retainAll(tmpSV); if (tmpV.size() == 0) { tmp = Printf.format( "Attribute '%s': Bad value: Actual value(s)='%s', expected value='%s'", new Object[] { check_name, actual_attr_valV, tmpSV }); errorlist.add(tmp); logger.error(tmpAttrCheckMsg + tmp + ": " + ": FAIL"); continue; } else if (tmpV.size() > 1) { tmp = Printf.format( "Attribute '%s': Attribute found multiple (%dx) times with value='%s'.", new Object[] { check_name, new Integer(tmpV.size()), tmpSV }); logger.warn(tmp); } else { } } /* * // Semantic error in checking condition else { tmp = * Printf.format( "Checking attribute '%s': Illegal combination of * expected_value='%s', expected_present='%s', expected_empty='%s'. * This can happen e.g. by checking value='abc' and * present='false'.", new Object[] { check_name, expected_value, * expected_present, expected_empty }); logger.error(tmp); throw new * Exception(tmp); } */ // Some info logging logger.info(tmpAttrCheckMsg + "OK"); } // Output result if (errorlist.size() > 0) { String errmsg = "Errorlist: "; for (Iterator iter = errorlist.iterator(); iter.hasNext();) { errmsg += ((String) iter.next()) + "\n"; } errmsg = errmsg.substring(0, errmsg.length() - 1); logger.error(errmsg); throw new CheckException(errmsg); } return; } protected void dumpFlatDomMap(Map docflat, String comment, boolean show_presence) { logger.info("---------- " + comment + ": starts here" + " ----------"); for (Iterator iter = docflat.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); Vector value = (Vector) docflat.get(key); if (value.size() == 1 && value.get(0) == ELEMENT_PRESENT_VALUE) { if (show_presence) logger.info(key + "=" + value); } else { logger.info(key + "=" + value); } } logger.info("---------- " + comment + ": ends here" + " ----------"); } public void teardown() { } }