private String getReferencedGroupValue(final DirContextOperations ctx) { final String referencedGroupValue; if (StringUtils.isBlank(userGroupReferencedGroupAttribute)) { referencedGroupValue = ctx.getDn().toString(); } else { final Attribute attributeName = ctx.getAttributes().get(userGroupReferencedGroupAttribute); if (attributeName == null) { throw new AuthorizationAccessException("Referenced group value attribute [" + userGroupReferencedGroupAttribute + "] does not exist."); } try { referencedGroupValue = (String) attributeName.get(); } catch (NamingException e) { throw new AuthorizationAccessException("Error while retrieving referenced group value attribute [" + userGroupReferencedGroupAttribute + "]."); } } return referencedGroupValue; }
@Before public void setupMocks() throws NamingException { SearchResult mockUserResult = mock(SearchResult.class); when(mockUserNamingEnum.nextElement()).thenReturn(mockUserResult); Attribute mockUidNumberAttr = mock(Attribute.class); Attribute mockGidNumberAttr = mock(Attribute.class); Attribute mockUidAttr = mock(Attribute.class); Attributes mockAttrs = mock(Attributes.class); when(mockUidAttr.get()).thenReturn("some_user"); when(mockUidNumberAttr.get()).thenReturn("700"); when(mockGidNumberAttr.get()).thenReturn("600"); when(mockAttrs.get(eq("uid"))).thenReturn(mockUidAttr); when(mockAttrs.get(eq("uidNumber"))).thenReturn(mockUidNumberAttr); when(mockAttrs.get(eq("gidNumber"))).thenReturn(mockGidNumberAttr); when(mockUserResult.getAttributes()).thenReturn(mockAttrs); }
/** * Performs the actual sync of the specified user. * @param ctx a DirContext * @param qm the AlpineQueryManager to use * @param sc the SearchControls to use * @param user the LdapUser instance to sync * @throws NamingException when a problem with the connection with the directory */ private void sync(DirContext ctx, AlpineQueryManager qm, SearchControls sc, LdapUser user) throws NamingException { final String searchFor = LDAP_ATTRIBUTE_NAME + "=" + formatPrincipal(user.getUsername()); LOGGER.debug("Syncing: " + user.getUsername()); final List<SearchResult> results = Collections.list(ctx.search(BASE_DN, searchFor, sc)); if (results.size() > 0) { // Should only return 1 result, but just in case, get the very first one final SearchResult result = results.get(0); user.setDN(result.getNameInNamespace()); final Attribute mail = result.getAttributes().get(ATTRIBUTE_MAIL); if (mail != null) { // user.setMail(mail.get()); //todo } } else { // This is an invalid user - a username that exists in the database that does not exist in LDAP user.setDN("INVALID"); // user.setMail(null); //todo } qm.updateLdapUser(user); }
/** * Test a conversion of an attributes from a LDIF file * @throws org.apache.directory.api.ldap.model.ldif.LdapLdifException */ @Test public void testConvertAttributesfromLdif() throws LdapException, LdapLdifException { Attributes attributes = new BasicAttributes( true ); Attribute oc = new BasicAttribute( "objectclass" ); oc.add( "top" ); oc.add( "person" ); oc.add( "inetorgPerson" ); attributes.put( oc ); attributes.put( "cn", "Saarbrucken" ); attributes.put( "sn", "test" ); String ldif = LdifUtils.convertToLdif( attributes, ( Dn ) null, 15 ); Attributes result = LdifUtils.getJndiAttributesFromLdif( ldif ); assertEquals( attributes, result ); }
/** * Create the Trigger execution subentry * * @param apCtx The administration point context * @param subentryCN The CN used by the suentry * @param subtreeSpec The subtree specification * @param prescriptiveTriggerSpec The prescriptive trigger specification * @throws NamingException If the operation failed */ public static void createTriggerExecutionSubentry( LdapContext apCtx, String subentryCN, String subtreeSpec, String prescriptiveTriggerSpec ) throws NamingException { Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true ); Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT ); subentry.put( objectClass ); objectClass.add( SchemaConstants.TOP_OC ); objectClass.add( SchemaConstants.SUBENTRY_OC ); objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC ); subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec ); subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec ); apCtx.createSubcontext( "cn=" + subentryCN, subentry ); }
/** * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and * end index, and j is '*' if it is at the end. * * @param attributes * the attributes * @param attributeName * the attribute name * @return the range restricted attribute * @throws NamingException * the naming exception */ private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName) throws NamingException { Attribute unrestricted = attributes.get(attributeName); if (unrestricted != null) { return unrestricted; } NamingEnumeration<? extends Attribute> i = attributes.getAll(); String searchString = attributeName.toLowerCase() + ';'; while (i.hasMore()) { Attribute attribute = i.next(); if (attribute.getID().toLowerCase().startsWith(searchString)) { return attribute; } } return null; }
/** * Return a String representing the value of the specified attribute. * * @param attrId Attribute name * @param attrs Attributes containing the required value * * @exception NamingException if a directory server error occurs */ private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return null; Object value = attr.get(); if (value == null) return null; String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
/** * Get name. * * @return Name value */ public String getName() { if (name != null) return name; if (attributes != null) { Attribute attribute = attributes.get(NAME); if (attribute != null) { try { name = attribute.get().toString(); } catch (NamingException e) { // No value for the attribute } } } return name; }
/** * Get resource type. * * @return String resource type */ public String getResourceType() { String result = null; if (attributes != null) { Attribute attribute = attributes.get(TYPE); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { // No value for the attribute } } } if (result == null) { if (collection) result = COLLECTION_TYPE; } return result; }
private String getValue(Attributes answer, String name) { Attribute attr = null; if( name != null ) { attr = answer.get(name); } if( attr == null ) { return ""; } try { return (String) attr.get(); } catch( NamingException ne ) { return ""; } }
/** * Return a String representing the value of the specified attribute. * * @param attrId Attribute name * @param attrs Attributes containing the required value * * @exception NamingException if a directory server error occurs */ private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return (null); Object value = attr.get(); if (value == null) return (null); String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
/** * Get resource type. * * @return String resource type */ public String getResourceType() { String result = null; if (attributes != null) { Attribute attribute = attributes.get(TYPE); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } if (result == null) { if (collection) result = COLLECTION_TYPE; else result = null; } return result; }
private String getUserIdentity(final DirContextOperations ctx) { final String identity; if (useDnForUserIdentity) { identity = ctx.getDn().toString(); } else { final Attribute attributeName = ctx.getAttributes().get(userIdentityAttribute); if (attributeName == null) { throw new AuthorizationAccessException("User identity attribute [" + userIdentityAttribute + "] does not exist."); } try { identity = (String) attributeName.get(); } catch (NamingException e) { throw new AuthorizationAccessException("Error while retrieving user name attribute [" + userIdentityAttribute + "]."); } } return IdentityMappingUtil.mapIdentity(identity, identityMappings); }
@Override public boolean getDisabledBoolean(Attributes attrs) { String ldapDisabledAttrStr = Configuration.get(ConfigurationKeys.LDAP_DISABLED_ATTR); if (ldapDisabledAttrStr.startsWith("!")) { ldapDisabledAttrStr = ldapDisabledAttrStr.substring(1); Attribute ldapDisabledAttr = attrs.get(ldapDisabledAttrStr); Boolean booleanValue = getAsBoolean(ldapDisabledAttr); if (booleanValue != null) { return !booleanValue; } else { // if there is no value, assume not disabled return false; } } else { return getAsBoolean(attrs.get(ldapDisabledAttrStr)); } }
public String ext2uid(String puid) { try { DirContext ctx = null; try { ctx = getDirContext(); Attributes attributes = ctx.getAttributes( ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ext2uid").replaceAll("%", puid), new String[] { ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid") }); if (attributes!=null) { Attribute uid = attributes.get(ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid")); if (uid!=null) return (String)uid.get(); } } finally { if (ctx!=null) ctx.close(); } } catch (Exception e) { Debug.error("Unable to translate ext to uid, "+e.getMessage()); } return null; }
/** * Get the values for the given attribute. If the attribute is null * or does not contain any values, a zero length byte array is * returned. NOTE that it is assumed that all values are byte arrays. */ private byte[][] getAttributeValues(Attribute attr) throws NamingException { byte[][] values; if (attr == null) { values = BB0; } else { values = new byte[attr.size()][]; int i = 0; NamingEnumeration<?> enum_ = attr.getAll(); while (enum_.hasMore()) { Object obj = enum_.next(); if (debug != null) { if (obj instanceof String) { debug.println("LDAPCertStore.getAttrValues() " + "enum.next is a string!: " + obj); } } byte[] value = (byte[])obj; values[i++] = value; } } return values; }
/** * 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 }
/** * Return a String representing the value of the specified attribute. * * @param attrId * Attribute name * @param attrs * Attributes containing the required value * * @exception NamingException * if a directory server error occurs */ private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return null; Object value = attr.get(); if (value == null) return null; String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
/** * Return a String representing the value of the specified attribute. * * @param attrId Attribute name * @param attrs Attributes containing the required value * * @exception NamingException if a directory server error occurs */ private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (debug >= 3) log(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return (null); Object value = attr.get(); if (value == null) return (null); String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; }
/** * Get name. * * @return Name value */ public String getName() { if (name != null) return name; if (attributes != null) { Attribute attribute = attributes.get(NAME); if (attribute != null) { try { name = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } return name; }
/** * Get resource type. * * @return String resource type */ public String getResourceType() { String result = null; if (attributes != null) { Attribute attribute = attributes.get(TYPE); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } if (result == null) { if (collection) result = COLLECTION_TYPE; else result = ""; } return result; }
/** * Get ETag. * * @param strong If true, the strong ETag will be returned * @return ETag */ public String getETag(boolean strong) { String result = null; if (attributes != null) { Attribute attribute = attributes.get(ETAG); if (attribute != null) { try { result = attribute.get().toString(); } catch (NamingException e) { ; // No value for the attribute } } } if (strong) { // The strong ETag must always be calculated by the resources result = strongETag; } else { // The weakETag is contentLenght + lastModified if (weakETag == null) { weakETag = "W/\"" + getContentLength() + "-" + getLastModified() + "\""; } result = weakETag; } return result; }
private AttributesMapper getAttributeMapper(final Object... baseArgs) { return new AttributesMapper() { @Override public Object mapFromAttributes(Attributes attrs) throws NamingException { LdapEntryVO entry = new LdapEntryVO(); entry.setUsername((String) attrs.get(USERNAME_ATTRIBUTE_ID).get()); DistinguishedName dn = new DistinguishedName(getBase(baseArgs)); dn.add(USERNAME_ATTRIBUTE_ID, entry.getUsername()); entry.setAbsoluteDn(dn.encode()); Map<String, Object> attributes = new LinkedHashMap<String, Object>(); if (searchResultAttributes != null) { for (int i = 0; i < searchResultAttributes.length; i++) { Attribute attr = attrs.get(searchResultAttributes[i]); if (attr != null) { attributes.put(searchResultAttributes[i], attr.get()); } } } entry.setAttributes(attributes); return entry; } }; }
/** * @param dn * @return * @throws NamingException */ public TreeMap getAllAttributesSorted(String dn) throws NamingException { NamingEnumeration enumAll = getAllAttributes(dn); TreeMap<String, Object> tree = new TreeMap<String, Object>(); while (enumAll.hasMore()) { Attribute a = (Attribute)enumAll.next(); tree.put(new String(a.getID()), a.get()); } for (Iterator it = tree.keySet().iterator(); it.hasNext();) { String key = (String)it.next(); Log.logDebug(key+" = "+tree.get(key)); } return tree; }
public static Context getURLContext( String scheme, Hashtable<?,?> environment) throws NamingException { return new DnsContext("", null, new Hashtable<String,String>()) { public Attributes getAttributes(String name, String[] attrIds) throws NamingException { return new BasicAttributes() { public Attribute get(String attrID) { BasicAttribute ba = new BasicAttribute(attrID); ba.add("1 1 99 b.com."); ba.add("0 0 88 a.com."); // 2nd has higher priority return ba; } }; } }; }
@SuppressWarnings("rawtypes") private String formatEmailList(SearchResult sResult) { if (null == sResult) { return ""; } StringBuilder emailList = new StringBuilder(); try { NamingEnumeration namingEnumeration = sResult.getAttributes().getAll(); while (namingEnumeration.hasMoreElements()) { Attribute attr = (Attribute) namingEnumeration.next(); emailList.append(formatEmailInfo(attr)); } } catch (NamingException e) { loggerError("formatEmailList", "", e); } return emailList.toString(); }
@SuppressWarnings("rawtypes") private List<String> formatUserEnName(SearchResult sResult) { if (null == sResult) { return Collections.emptyList(); } List<String> result = new ArrayList<String>(); try { String memberKey = ldapConfig.get("memberKey"); NamingEnumeration namingEnumeration = sResult.getAttributes().getAll(); while (namingEnumeration.hasMoreElements()) { Attribute attr = (Attribute) namingEnumeration.next(); String attrId = attr.getID(); if (memberKey.equals(attrId)) { List<String> userEnNames = formatUserEnName(attr); result.addAll(userEnNames); } } } catch (Exception e) { loggerError("formatUserEnName 619", "", e); } return result; }
/** * 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 {@code attrSet} 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 }
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName, String principalDomain, String... attributeNames) throws NamingException { if (StringUtils.isBlank(userName)) { throw new IllegalArgumentException("Username and password can not be blank."); } if (attributeNames.length == 0) { return Collections.emptyMap(); } Attributes matchAttr = new BasicAttributes(true); BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain); matchAttr.put(basicAttr); NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames); if (ctx != null) { ctx.close(); } Map<String, String> result = new HashMap<>(); if (searchResult.hasMore()) { NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll(); while (attributes.hasMore()) { Attribute attr = attributes.next(); String attrId = attr.getID(); String attrValue = (String) attr.get(); result.put(attrId, attrValue); } } return result; }
@Before public void setupMocksBase() throws NamingException { mockContext = mock(DirContext.class); doReturn(mockContext).when(mappingSpy).getDirContext(); // We only ever call hasMoreElements once for the user NamingEnum, so // we can just have one return value when(mockUserNamingEnum.hasMoreElements()).thenReturn(true); SearchResult mockGroupResult = mock(SearchResult.class); // We're going to have to define the loop here. We want two iterations, // to get both the groups when(mockGroupNamingEnum.hasMoreElements()).thenReturn(true, true, false); when(mockGroupNamingEnum.nextElement()).thenReturn(mockGroupResult); // Define the attribute for the name of the first group Attribute group1Attr = new BasicAttribute("cn"); group1Attr.add(testGroups[0]); Attributes group1Attrs = new BasicAttributes(); group1Attrs.put(group1Attr); // Define the attribute for the name of the second group Attribute group2Attr = new BasicAttribute("cn"); group2Attr.add(testGroups[1]); Attributes group2Attrs = new BasicAttributes(); group2Attrs.put(group2Attr); // This search result gets reused, so return group1, then group2 when(mockGroupResult.getAttributes()).thenReturn(group1Attrs, group2Attrs); }
/** * Put attribute. */ @Override public Attribute put(Attribute attribute) { if (attributes == null) { try { return put(attribute.getID(), attribute.get()); } catch (NamingException e) { return null; } } else { return attributes.put(attribute); } }
private static Attribute doLookup(String hostName) throws NamingException { Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(hostName, new String[]{"MX"}); Attribute attr = attrs.get("MX"); if (attr == null) return (null); return (attr); }