static boolean checkMatchingSearchResult( NamingEnumeration<SearchResult> result, String attrName, Object expValue) throws NamingException { while ((result != null) && result.hasMore()) { SearchResult sr = result.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> attrVals = attrs.getAll(); try { while ((attrVals != null) && attrVals.hasMore()) { Attribute a = attrVals.next(); String attrID = a.getID(); if (!attrName.equalsIgnoreCase(attrID)) { continue; } Object attrVal = a.get(); if (expValue.equals(attrVal)) { return true; } } } finally { if (attrVals != null) { attrVals.close(); } } } return false; }
private Object getResults(Attribute attr, Object obj) { try { String name = attr.getID().toString(); String Value = attr.get().toString(); Class class1 = obj.getClass(); String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length()); String[] methodnameIgnot = {"-"}; for (String ignore : methodnameIgnot) { methodName = methodName.replaceAll(ignore, ""); } Method method = class1.getMethod(methodName, String.class); String value = (String) method.invoke(obj, Value); } catch (NamingException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return obj; }
/** * Seeds the bound instance's local ads-truststore with a set of instance key-pair public key * certificates. The result is the instance will trust any instance posessing the private key * corresponding to one of the public-key certificates. This trust is necessary at least to * initialize replication, which uses the trusted certificate entries in the ads-truststore for * server authentication. * * @param ctx The bound instance. * @param keyEntryMap The set of valid (i.e., not tagged as compromised) instance key-pair * public-key certificate entries in ADS represented as a map from keyID to public-key * certificate (binary). * @throws NamingException in case an error occurs while updating the instance's ads-truststore * via LDAP. */ public static void seedAdsTrustStore(InitialLdapContext ctx, Map<String, byte[]> keyEntryMap) throws NamingException { /* TODO: this DN is declared in some core constants file. Create a constants file for the installer and import it into the core. */ final Attribute oc = new BasicAttribute("objectclass"); oc.add("top"); oc.add("ds-cfg-instance-key"); for (Map.Entry<String, byte[]> keyEntry : keyEntryMap.entrySet()) { final BasicAttributes keyAttrs = new BasicAttributes(); keyAttrs.put(oc); final Attribute rdnAttr = new BasicAttribute( ADSContext.ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyEntry.getKey()); keyAttrs.put(rdnAttr); keyAttrs.put( new BasicAttribute( ADSContext.ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName() + ";binary", keyEntry.getValue())); final LdapName keyDn = new LdapName( (new StringBuilder(rdnAttr.getID())) .append("=") .append(Rdn.escapeValue(rdnAttr.get())) .append(",") .append(TRUSTSTORE_DN) .toString()); try { ctx.createSubcontext(keyDn, keyAttrs).close(); } catch (NameAlreadyBoundException x) { ctx.destroySubcontext(keyDn); ctx.createSubcontext(keyDn, keyAttrs).close(); } } }
protected Map<String, ArrayList<String>> convertAttributes( NamingEnumeration<? extends Attribute> attributesEnumeration) { Map<String, ArrayList<String>> userInfo = new HashMap<String, ArrayList<String>>(); try { while (attributesEnumeration.hasMore()) { Attribute attr = attributesEnumeration.next(); String id = attr.getID(); ArrayList<String> values = userInfo.get(id); if (values == null) { values = new ArrayList<String>(); userInfo.put(id, values); } // --- loop on all attribute's values NamingEnumeration<?> valueEnum = attr.getAll(); while (valueEnum.hasMore()) { Object value = valueEnum.next(); // Only retrieve String attribute if (value instanceof String) { values.add((String) value); } } } } catch (NamingException e) { e.printStackTrace(); } return userInfo; }
public static int verifyMaliciousPassword(String login, String mail) { String mailAdresse = ""; Ldap adminConnection = new Ldap(); adminConnection.SetEnv( Play.configuration.getProperty("ldap.host"), Play.configuration.getProperty("ldap.admin.dn"), Play.configuration.getProperty("ldap.admin.password")); Attributes f = adminConnection.getUserInfo(adminConnection.getLdapEnv(), login); try { NamingEnumeration e = f.getAll(); while (e.hasMore()) { javax.naming.directory.Attribute a = (javax.naming.directory.Attribute) e.next(); String attributeName = a.getID(); String attributeValue = ""; Enumeration values = a.getAll(); while (values.hasMoreElements()) { attributeValue = values.nextElement().toString(); } if (attributeName.equals("mail")) { mailAdresse = attributeValue; } } } catch (javax.naming.NamingException e) { System.out.println(e.getMessage()); return 0; } finally { if (mailAdresse.equals("")) { return Invitation.USER_NOTEXIST; } else if (mailAdresse.equals(mail)) { return Invitation.ADDRESSES_MATCHE; } else { return Invitation.ADDRESSES_NOTMATCHE; } } }
public Map<String, String> getAttributes(User user) throws DataSourceException, ConfigException { try { String s = "(&(objectClass=" + source.getUsersObjectClassValue() + ")(" + source.getUsersIdKey() + "=" + user.getUid() + "))"; List<SearchResult> r = this.search(s, SecurityEntityType.USER); if (!r.isEmpty()) { Attributes attrs = r.get(0).getAttributes(); Map<String, String> items = new HashMap<String, String>(); NamingEnumeration<? extends Attribute> lst = attrs.getAll(); while (lst.hasMoreElements()) { Attribute attr = lst.nextElement(); if (attr.get() != null) { items.put(attr.getID(), attr.get().toString()); } } return items; } else { return null; } } catch (javax.naming.AuthenticationException e) { throw new ConfigException(e, "LDAP connection failed, please check your settings"); } catch (NamingException e) { throw new DataSourceException(e, "LDAP Exception : " + e.getMessage()); } }
/** * Gets an <code>LDAPDirectoryEntry</code> object that represent an entry on directory. You can * provide a list of attributes to be ignored when load the entry data. Look for attribute matches * using a map of values * * @param DN Distinguished Name of the entry * @param ignore_attributes You can indicate here a list of attribute to be ignored when load all * entry data. this is useful if you have some big data in some attributes and do you want to * ignore that * @param attribute_matches Map with attribute names and values to match * @return LDAPDirectoryEntry * @exception LDAPException */ public LDAPDirectoryEntry getEntry( final String DN, final List<String> ignore_attributes, final Map<String, String> attribute_matches) throws LDAPException { LDAPDirectoryEntry _e = null; try { _e = new LDAPDirectoryEntry(DN); DirContext ctx = connection.connect(); if (ctx == null) { throw new LDAPException("directory service not available"); } Attributes atts = ctx.getAttributes(DN); if (atts == null) { return null; } @SuppressWarnings("unchecked") NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) atts.getAll(); while (ne.hasMore()) { Attribute att = ne.next(); if (ignore_attributes == null || !ignore_attributes.contains(att.getID())) { List<Object> _values = new ArrayList<Object>(); @SuppressWarnings("unchecked") NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll(); while (nea.hasMore()) { Object _value = nea.next(); if (attribute_matches == null || !attribute_matches.containsKey(att.getID())) { _values.add(_value); } else if (attribute_matches.get(att.getID()) != null && String.valueOf(_value).contains(attribute_matches.get(att.getID()))) { _values.add(_value); } } _e.setAttribute(att.getID(), _values.toArray()); } } } catch (NullPointerException e) { _log.log(java.util.logging.Level.ALL, "getEntry() null pointer"); throw new LDAPException("get entry null pointer"); } catch (NamingException e) { _log.log(java.util.logging.Level.ALL, "getEntry() - " + e.getMessage()); throw new LDAPException(e.getMessage()); } finally { connection.disconnect(); } return _e; }
/** * Search for entry that matches the specific <code>DirectoryQuery</code> conditions * * @param q DirectoryQuery * @return List<DirectoryEntry> * @exception LDAPException */ public List<Identity> search(final LDAPDirectoryQuery q) throws LDAPException { List<Identity> results = new ArrayList<Identity>(); try { DirContext ctx = connection.connect(); if (ctx == null) { throw new LDAPException("directory service not available"); } SearchControls ctls = new SearchControls(); List<String> _aux = new ArrayList<String>(); _aux.add("modifyTimestamp"); _aux.add("*"); ctls.setReturningAttributes(_aux.toArray(new String[_aux.size()])); if (connection.hasCountLimit()) { ctls.setCountLimit(connection.getCountLimit()); } ctls.setSearchScope(connection.getScope()); String filter = getQueryString(ctx, q); NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls); while (answer.hasMoreElements()) { SearchResult sr = answer.nextElement(); LDAPDirectoryEntry _e = null; if (sr.getName().isEmpty()) { _e = new LDAPDirectoryEntry(baseDN); } else { _e = new LDAPDirectoryEntry(sr.getNameInNamespace()); /* * _e = new LDAPEntry(sr.getName() + "," + this.baseDN); if(_e.getID().matches( * "^(ldap|ldaps)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*[^\\.\\,\\)\\(\\s]$" * )) { URL _url = new URL(_e.getID()); _e.setID(_url.getPath()); } */ } @SuppressWarnings("unchecked") NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) sr.getAttributes().getAll(); while (ne.hasMore()) { Attribute att = ne.next(); Object[] attrs = new Object[att.size()]; @SuppressWarnings("unchecked") NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll(); for (int i = 0; nea.hasMore(); i++) { attrs[i] = nea.next(); } _e.setAttribute(att.getID(), attrs); } results.add(_e); } } catch (NullPointerException e) { _log.log(java.util.logging.Level.ALL, "search() null pointer"); throw new LDAPException("search null pointer"); } catch (NamingException e) { _log.log(java.util.logging.Level.ALL, "search() - " + e.getMessage()); throw new LDAPException(e.getMessage()); } finally { connection.disconnect(); } return results; }
/** * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Results will * be order using the values of a specific attribute * * @param q DirectoryQuery * @param attribute Name of the attribute that determines the order * @return java.util.List<DirectoryEntry> * @exception LDAPException */ public List<Identity> sortedSearch(final LDAPDirectoryQuery q, final String attribute) throws LDAPException { TreeMap<String, Identity> results = new TreeMap<String, Identity>(Collator.getInstance(new Locale("es"))); try { LdapContext ctx = connection.connect(); if (ctx == null) { throw new LDAPException("Directory service not available"); } SearchControls ctls = new SearchControls(); if (connection.hasCountLimit()) { ctls.setCountLimit(connection.getCountLimit()); } ctls.setSearchScope(connection.getScope()); ctx.setRequestControls(new Control[] {new SortControl(attribute, Control.NONCRITICAL)}); String filter = getQueryString(ctx, q); NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls); while (answer.hasMoreElements()) { SearchResult sr = answer.nextElement(); LDAPDirectoryEntry _e = new LDAPDirectoryEntry(sr.getNameInNamespace()); @SuppressWarnings("unchecked") NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) sr.getAttributes().getAll(); while (ne.hasMore()) { Attribute att = ne.next(); Object[] attrs = new Object[att.size()]; @SuppressWarnings("unchecked") NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll(); for (int i = 0; nea.hasMore(); i++) { attrs[i] = nea.next(); } _e.setAttribute(att.getID(), attrs); } String _value = String.valueOf(_e.getAttribute(attribute)[0]); while (results.containsKey(_value)) { _value = _value.concat("0"); } results.put(_value, _e); } } catch (NullPointerException e) { _log.log(java.util.logging.Level.ALL, "sortedSearch() null pointer"); throw new LDAPException("sorted search null pointer"); } catch (NamingException e) { _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage()); throw new LDAPException(e.getMessage()); } catch (IOException e) { _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage()); throw new LDAPException(e.getMessage()); } finally { connection.disconnect(); } return new ArrayList<Identity>(results.values()); }
public static void listerAttributs(Attributes atts) { try { for (NamingEnumeration e = atts.getAll(); e.hasMore(); ) { Attribute a = (Attribute) e.next(); System.out.println(a.getID() + ":"); Enumeration values = a.getAll(); while (values.hasMoreElements()) { System.out.println("valeur : " + values.nextElement().toString()); } } } catch (javax.naming.NamingException e) { System.out.println(e.getMessage()); } }
/** * Print Attributes to System.out * * @param attrs */ private static void dump(Attributes attrs) { if (attrs == null) { System.out.println("No attributes"); } else { /* Print each attribute */ try { for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMore(); ) { Attribute attr = ae.next(); System.out.println("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration<?> e = attr.getAll(); e.hasMore(); System.out.println(" value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } } } // dump
/** * Return true if the record contains all of the values of the given attribute. * * @param attr Attribute we're looking for * @return boolean true if we found it * @throws Throwable */ public boolean contains(Attribute attr) throws Throwable { if (attr == null) { return false; // protect } Attribute recAttr = getAttributes().get(attr.getID()); if (recAttr == null) { return false; } NamingEnumeration ne = attr.getAll(); while (ne.hasMore()) { if (!recAttr.contains(ne.next())) { return false; } } return true; }
/** * Constructs an Rdn from the given attribute set. See {@link javax.naming.directory.Attributes * Attributes}. * * <p>The string attribute values are not interpreted as <a * href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a> formatted RDN strings. That is, the * values are used literally (not parsed) and assumed to be unescaped. * * @param attrSet The non-null and non-empty attributes containing type/value mappings. * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot be used to construct a * valid RDN. */ public Rdn(Attributes attrSet) throws InvalidNameException { if (attrSet.size() == 0) { throw new InvalidNameException("Attributes cannot be empty"); } entries = new ArrayList<>(attrSet.size()); NamingEnumeration<? extends Attribute> attrs = attrSet.getAll(); try { for (int nEntries = 0; attrs.hasMore(); nEntries++) { RdnEntry entry = new RdnEntry(); Attribute attr = attrs.next(); entry.type = attr.getID(); entry.value = attr.get(); entries.add(nEntries, entry); } } catch (NamingException e) { InvalidNameException e2 = new InvalidNameException(e.getMessage()); e2.initCause(e); throw e2; } sort(); // arrange entries for comparison }
/** * LDAP属性 定义 o Organization:组织 ou Organization unit:组织单元 uid Userid:用户id cn Common name:常见名称 sn 姓 * givenname 首名 dn Distinguished Name:区分名称 * * @param username * @throws NamingException */ public void search(String username) throws NamingException { System.out.println("Searching..."); SearchControls searchCtls = new SearchControls(); // Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // specify the LDAP search filter String searchFilter = "uid=" + username; // Specify the Base for the search String searchBase = LDAP_BASE; // Specify the attributes to return String returnedAtts[] = {"cn"}; searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter NamingEnumeration<SearchResult> entries = ds.search(searchBase, searchFilter, searchCtls); // Loop through the search results while (entries.hasMoreElements()) { SearchResult entry = entries.next(); System.out.println(">>>" + entry.getName()); // Print out the groups Attributes attrs = entry.getAttributes(); if (attrs != null) { for (NamingEnumeration<? extends Attribute> names = attrs.getAll(); names.hasMore(); ) { Attribute attr = names.next(); System.out.println("AttributeID: " + attr.getID()); for (NamingEnumeration<?> e = attr.getAll(); e.hasMore(); ) { System.out.println("Attributes:" + e.next()); } } } } System.out.println("Search complete."); }
/** {@inheritDoc} */ @Override public void createEntry(LdapName dn, Attributes attributes) throws NamingException { Assert.assertFalse(alreadyAdded); Assert.assertEquals(dn, expectedDN); Map<String, List<String>> expected = new HashMap<String, List<String>>(this.attributes); NamingEnumeration<? extends Attribute> ne = attributes.getAll(); while (ne.hasMore()) { Attribute attribute = ne.next(); String attrID = attribute.getID(); List<String> values = expected.remove(attrID); if (values == null) { Assert.fail("Unexpected attribute " + attrID); } assertAttributeEquals(attribute, values); } if (!expected.isEmpty()) { Assert.fail("Missing expected attributes: " + expected.keySet()); } alreadyAdded = true; }
/** Parse Definition Attributes for a LDAP matching rule */ static LDAPMatchingRuleSchema parseDefAttributes(Attributes attrs) throws NamingException { String name = null, oid = null, desc = null, syntax = null; boolean obsolete = false; Vector applies = new Vector(); for (Enumeration attrEnum = attrs.getAll(); attrEnum.hasMoreElements(); ) { Attribute attr = (Attribute) attrEnum.nextElement(); String attrName = attr.getID(); if (attrName.equals(NAME)) { name = getSchemaAttrValue(attr); } else if (attrName.equals(NUMERICOID)) { oid = getSchemaAttrValue(attr); } else if (attrName.equals(SYNTAX)) { syntax = getSchemaAttrValue(attr); } else if (attrName.equals(DESC)) { desc = getSchemaAttrValue(attr); } else if (attrName.equals(APPLIES)) { for (Enumeration valEnum = attr.getAll(); valEnum.hasMoreElements(); ) { applies.addElement((String) valEnum.nextElement()); } } else if (attrName.equals(OBSOLETE)) { obsolete = parseTrueFalseValue(attr); } else { throw new NamingException( "Invalid schema attribute type for matching rule definition " + attrName); } } LDAPMatchingRuleSchema mrule = new LDAPMatchingRuleSchema(name, oid, desc, vectorToStringAry(applies), syntax); if (obsolete) { mrule.setQualifier(OBSOLETE, ""); } return mrule; }
public LDAPAuthenticationUser getUserAttributes(LdapSearch search, String[] attributes) throws SecurityException { LDAPAuthenticationUser ldapAUser = new LDAPAuthenticationUser(); if (search.getM_srAttrs() == null) { throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP); } else { try { Object object = null; for (NamingEnumeration enum1 = search.getM_srAttrs().getAll(); enum1.hasMore(); ) { Attribute attrib = (Attribute) enum1.next(); for (NamingEnumeration e = attrib.getAll(); e.hasMore(); ) { object = e.next(); try { if (attrib.getID().equals(attributes[0])) { ldapAUser.setGuid(object); } if (attrib.getID().equals(attributes[1])) { ldapAUser.setDn((String) object); } if (attrib.getID().equals(attributes[2])) { String obj = (String) object; if (attributes[2].equals("CN")) { if (obj != null && !obj.equals("")) { ldapAUser.setFullName((String) object); } } else { if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) { ldapAUser.setFullName((String) object); } } } if (attrib.getID().equals(attributes[3])) { String obj = (String) object; if (attributes[3].equals("cn")) { if (obj != null && !obj.equals("")) { ldapAUser.setFullName((String) object); } } else { if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) { ldapAUser.setFullName((String) object); } } } if (attrib.getID().equals(attributes[4])) { String obj = (String) object; if (ldapAUser.getFullName() == null && obj != null && !obj.equals("")) { ldapAUser.setFullName((String) object); } } if (attrib.getID().equals(attributes[5])) { ldapAUser.setGroups((String) object); } } catch (Exception ex) { } } } } catch (NamingException e) { throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP); } catch (Exception e) { throw new SecurityException(SecurityException.ERROR_CAN_NOT_FIND_USER_ATTRIBUTES_LDAP); } } return ldapAUser; }
public List<Users> getUsers(Users user) { LOG.info("Inside getUsers"); List<Users> userList = new ArrayList<Users>(); DirContext ctx = LDAPConstants.getLdapContext(); String baseDN = PropertyFileReader.getProperty(IAMApplicationConstants.BASEDN_USERS); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String retAttrs[] = { "whenChanged", "whenCreated", "name", "distinguishedName", "givenName", "cn", "initials", "displayName", "iboIsEmail", "iboCountryOfCitizenship2", "iboCountryOfCitizenship1", "iboIsIBIS", "iboPrefCommunicationMethod", "iboAuthorizedDate", "iboIsNetwork", "iboUserStatus", "iboIBSchoolCode", "iboPrefCommunicationLang", "iboRoles", "iboUserName", "iboSex", "iboStartDate", "iboUserGUID", "iboCountryOfBirth", "iboLanguagesSpoken", "iboEndDate", "iboAuthorizedBy", "iboEmailHome", "iboCountryCode", "iboMobileWork", "iboSchoolConnections", "iboEmailWork", "iboPhoneWork", "iboIBRegion", "iboPreferredName", "iboMiddlename", "physicalDeliveryOfficeName", "iboSource" }; sc.setReturningAttributes(retAttrs); String filter = buildFilter(user); LOG.info("Filter--" + filter); NamingEnumeration results = null; String isIboSource = null; try { results = ctx.search(baseDN, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); if (null != attrs && null != attrs.get("iboSource")) isIboSource = attrs.get("iboSource").toString(); if (null != isIboSource && isIboSource.length() > 0) { NamingEnumeration e = attrs.getAll(); Users ioUser = new Users(); while (e.hasMoreElements()) { Attribute attr = (Attribute) e.nextElement(); if (attr.getID().toString().length() > 0 && attr.getID().toString().equalsIgnoreCase("ibosource")) { if (attr.get().toString().length() > 0) { if (attr.get().toString().equalsIgnoreCase("sharepoint")) { LOG.trace("External"); ioUser.setIboUserType(LDAPConstants.IBOUSERTYPE_EXTERNAL); } else if (attr.get().toString().equalsIgnoreCase("UserApp") || attr.get().toString().equalsIgnoreCase("OracleHR") || attr.get().toString().equalsIgnoreCase("userapp Generic")) { LOG.trace("Internal"); ioUser.setIboUserType(LDAPConstants.IBOUSERTYPE_INTERNAL); } } } ioUser = (Users) getResults(attr, ioUser); } userList.add(ioUser); } } ctx.close(); } catch (NamingException e) { e.printStackTrace(); } return userList; }
public void produce(String name, Attributes attrs) throws SAXException, NamingException { AttributeListImpl attrList; Attribute attr; NamingEnumeration enumeration; NamingEnumeration values; Object value; leaveSchema(); enterDirectory(); // dsml:entry dn attrList = new AttributeListImpl(); attrList.addAttribute(XML.Entries.Attributes.DN, "CDATA", name); // dsml:entry _docHandler.startElement(prefix(XML.Entries.Elements.Entry), attrList); if (attrs != null) { attr = attrs.get("objectclass"); if (attr != null) { // dsml:objectclass attrList = new AttributeListImpl(); _docHandler.startElement(prefix(XML.Entries.Elements.ObjectClass), attrList); values = attr.getAll(); while (values.hasMore()) { char[] chars; // dsml:oc-value value = values.next(); if (value != null) chars = value.toString().toCharArray(); else chars = new char[0]; attrList = new AttributeListImpl(); _docHandler.startElement(prefix(XML.Entries.Elements.OCValue), attrList); _docHandler.characters(chars, 0, chars.length); _docHandler.endElement(prefix(XML.Entries.Elements.OCValue)); } _docHandler.endElement(prefix(XML.Entries.Elements.ObjectClass)); } enumeration = attrs.getAll(); while (enumeration.hasMore()) { // dsml:attr attr = (Attribute) enumeration.next(); if (attr.getID().equals("objectclass")) continue; attrList = new AttributeListImpl(); attrList.addAttribute(XML.Entries.Attributes.Name, "CDATA", attr.getID()); _docHandler.startElement(prefix(XML.Entries.Elements.Attribute), attrList); values = attr.getAll(); while (values.hasMore()) { char[] chars = null; byte[] bytes = null; attrList = new AttributeListImpl(); // dsml:value value = values.next(); if (value == null) { chars = new char[0]; } else if (value instanceof String) { chars = ((String) value).toCharArray(); } else if (value instanceof byte[]) { bytes = (byte[]) value; } else { chars = value.toString().toCharArray(); } if (chars != null) { boolean encode = false; boolean wchar = false; int i = 0; while (i < chars.length && !wchar) { char c = chars[i++]; if (c >= '\u0100') encode = wchar = true; else if (c >= '\u0080' || (c < ' ' && c != '\n' && c != '\t')) encode = true; } if (encode) { if (wchar) { bytes = new byte[chars.length << 1]; int j = 0; // bigendian for (i = 0; i < chars.length; i++) { bytes[j++] = (byte) (chars[i] >> 8); bytes[j++] = (byte) (0xff & chars[i]); } } else { bytes = new byte[chars.length]; for (i = 0; i < chars.length; i++) { bytes[i] = (byte) chars[i]; } } } } if (bytes != null) { chars = Base64Encoder.encode(bytes); attrList.addAttribute( XML.Entries.Attributes.Encoding, "NMTOKEN", XML.Entries.Attributes.Encodings.Base64); } _docHandler.startElement(prefix(XML.Entries.Elements.Value), attrList); _docHandler.characters(chars, 0, chars.length); _docHandler.endElement(prefix(XML.Entries.Elements.Value)); } _docHandler.endElement(prefix(XML.Entries.Elements.Attribute)); } } _docHandler.endElement(prefix(XML.Entries.Elements.Entry)); }
/** * Handle a {@code Callback} * * @param c callback * @throws UnsupportedCallbackException If the callback is not supported by this handler * @throws NamingException */ protected void handleCallBack(Callback c) throws UnsupportedCallbackException, NamingException { if (c instanceof VerifyPasswordCallback) { verifyPassword((VerifyPasswordCallback) c); return; } if (c instanceof PasswordCallback == false) return; PasswordCallback passwdCallback = (PasswordCallback) c; String bindDN = getBindDN(); String bindCredential = getBindCredential(); String tmp = options.get(PASSWORD_ATTRIBUTE_ID); if (tmp != null && tmp.length() > 0) { passwordAttributeID = tmp; } InitialLdapContext ctx; ClassLoader currentTCCL = SecurityActions.getContextClassLoader(); try { if (currentTCCL != null) SecurityActions.setContextClassLoader(null); ctx = this.constructInitialLdapContext(bindDN, bindCredential); } catch (NamingException e) { throw new RuntimeException(e); } String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT); if (timeLimit != null) { try { searchTimeLimit = Integer.parseInt(timeLimit); } catch (NumberFormatException e) { } } if (searchTimeLimit == 0) searchTimeLimit = 10000; String baseDN = options.get(BASE_CTX_DN); String baseFilter = options.get(BASE_FILTER_OPT); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setTimeLimit(searchTimeLimit); NamingEnumeration<SearchResult> results = null; Object[] filterArgs = {userName}; try { if (baseDN == null) throw PicketBoxMessages.MESSAGES.invalidNullBaseContextDN(); results = ctx.search(baseDN, baseFilter, filterArgs, constraints); if (results.hasMore() == false) { safeClose(results); throw PicketBoxMessages.MESSAGES.failedToFindBaseContextDN(baseDN); } SearchResult sr = results.next(); String name = sr.getName(); String userDN = null; if (sr.isRelative() == true) userDN = name + "," + baseDN; else throw PicketBoxMessages.MESSAGES.unableToFollowReferralForAuth(name); ; safeClose(results); // Finished Authentication. Lets look for the attributes filterArgs = new Object[] {userName, userDN}; results = ctx.search(userDN, baseFilter, filterArgs, constraints); try { while (results.hasMore()) { sr = results.next(); Attributes attributes = sr.getAttributes(); NamingEnumeration<? extends javax.naming.directory.Attribute> ne = attributes.getAll(); while (ne != null && ne.hasMoreElements()) { javax.naming.directory.Attribute ldapAtt = ne.next(); if (passwordAttributeID.equalsIgnoreCase(ldapAtt.getID())) { Object thePass = ldapAtt.get(); setPasswordCallbackValue(thePass, passwdCallback); } } } } finally { safeClose(results); safeClose(ctx); if (currentTCCL != null) SecurityActions.setContextClassLoader(currentTCCL); } } catch (NamingException ne) { PicketBoxLogger.LOGGER.error(ne); } }
/** * This compares all but the named attributes allbut true => All must be equal except those on the * list * * @param that * @param attrIDs * @return boolean * @throws Throwable */ public boolean equalsAllBut(DirRecord that, String[] attrIDs) throws Throwable { if (attrIDs == null) throw new Exception("DirectoryRecord: null attrID list"); if (!dnEquals(that)) { return false; } int n = attrIDs.length; if (n == 0) return true; Attributes thisAttrs = getAttributes(); Attributes thatAttrs = that.getAttributes(); if (thisAttrs == null) { if (thatAttrs == null) return true; return false; } if (thatAttrs == null) { return false; } /** * We need to ensure that all attributes are checked. We init thatLeft to the number of * attributes in the source. We decrement for each checked attribute. We then decrement for each * ignored attribute present in that If the result is non-zero, then there are some extra * attributes in that so we return unequal. */ int sz = thisAttrs.size(); int thatLeft = sz; if ((sz == 0) && (thatAttrs.size() == 0)) { return true; } NamingEnumeration ne = thisAttrs.getAll(); if (ne == null) { return false; } while (ne.hasMore()) { Attribute attr = (Attribute) ne.next(); String id = attr.getID(); boolean present = false; for (int i = 0; i < attrIDs.length; i++) { if (id.equalsIgnoreCase(attrIDs[i])) { present = true; break; } } if (present) { // We don't compare if (thatAttrs.get(id) != null) thatLeft--; } else { Attribute thatAttr = thatAttrs.get(id); if (thatAttr == null) { return false; } if (!thatAttr.contains(attr)) { return false; } thatLeft--; } } return (thatLeft == 0); }