Java Code Examples for javax.naming.directory.SearchResult#getName()

The following examples show how to use javax.naming.directory.SearchResult#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ADMRealmImpl.java    From development with Apache License 2.0 6 votes vote down vote up
String retrieveName(Properties ldapProps, SearchResult res) {
    String name = "";
    if (res.isRelative()) {
        name = res.getName();
    } else {
        name = res.getNameInNamespace();
        String urlName = res.getName();
        int index = urlName.lastIndexOf("/");
        if (index > 0) {
            ldapProps
                    .put(Context.PROVIDER_URL, urlName.substring(0, index));
        }

    }
    return name;
}
 
Example 2
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException
{
  final LinkedList<T> list = new LinkedList<T>();
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnit);
  results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
  while (results.hasMore()) {
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    list.add(mapToObject(dn, searchBase, attributes));
  }
  return list;
}
 
Example 3
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public T findById(final DirContext ctx, final Object id, final String... organizationalUnits) throws NamingException
{
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnits);
  final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
  results = ctx.search(searchBase, args, controls);
  if (results.hasMore() == false) {
    return null;
  }
  final SearchResult searchResult = (SearchResult) results.next();
  final String dn = searchResult.getName();
  final Attributes attributes = searchResult.getAttributes();
  if (results.hasMore() == true) {
    log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
  }
  return mapToObject(dn, searchBase, attributes);
}
 
Example 4
Source File: ReadWriteLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private String getGroupName(SearchResult resultedGroup) throws NamingException {

        Attribute attribute = resultedGroup.getAttributes()
                .get(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE));
        if (attribute == null) {
            return resultedGroup.getName();
        } else {
            String groupNameAttributeValue = (String) attribute.get();
            return realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE) +
                    "=" + groupNameAttributeValue;
        }
    }
 
Example 5
Source File: GUISSOLdapClient.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private String formatGroupId(SearchResult sResult) {

        if (null == sResult) {
            return "";
        }

        String groupId = "";
        String userDN = sResult.getName();
        if (userDN.length() <= 0) {
            return "";
        }

        String[] strings = userDN.split(",");

        String loginbaseDN = ldapConfig.get("loginbasedn");
        String rootOU = loginbaseDN.substring(loginbaseDN.indexOf("=") + 1, loginbaseDN.indexOf(","));

        for (int i = 1; i < strings.length; i++) {

            String s = strings[i];
            s = s.substring(s.indexOf("=") + 1);

            if (s.equals(rootOU)) {
                break;
            }
            groupId = s + "/" + groupId;
        }

        groupId = groupId.substring(0, groupId.length() - 1);

        return groupId;
    }
 
Example 6
Source File: LdapUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * @param base
 *            :根节点(在这里是"dc=example,dc=com")
 * @param scope
 *            :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
 * @param filter
 *            :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
 */
public static String getDN(String base, String scope, String filter,
		DirContext dc) {
	String dn = null;
	SearchControls sc = new SearchControls();
	if (scope.equals("base")) {
		sc.setSearchScope(SearchControls.OBJECT_SCOPE);
	} else if (scope.equals("one")) {
		sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	} else {
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
	}
	NamingEnumeration<?> ne = null;
	try {
		ne = dc.search(base, filter, sc);
		while (ne.hasMore()) {
			//System.out.println();
			SearchResult sr = (SearchResult) ne.next();
			String name = sr.getName();
			if (base != null && !base.equals("")) {
				LogUtil.info("entry: " + name + "," + base);
			} else {
				LogUtil.info("entry: " + name);
			}
			dn = name + "," + base;
			break;
		}
	} catch (Exception nex) {
		System.err.println("Error: " + nex.getMessage());
		nex.printStackTrace();
	}
	return dn;
}
 
Example 7
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public List<?> getOtherGroups(Map<String, String> paramsMap, String attributes, String groupId) {
    Map<String, String> fieldNames = new HashMap<String, String>();
    Map<String, String> defaultValues = new HashMap<String, String>();
    for (Iterator<?> it = XMLDocUtil.dataXml2Doc(attributes).getRootElement().elementIterator(); it.hasNext();) {
        Element element = (Element) it.next();
        fieldNames.put(element.getName(), element.getText());
        defaultValues.put(element.getName(), element.attributeValue(DEFAULT_VALUE));
    }
    
    List<GroupDTO> items = new ArrayList<GroupDTO>();
    try {
    	DirContext conn =  getConnection(paramsMap);
        NamingEnumeration<SearchResult> en = ldapSearch(conn, groupId, GROUP_FILTER_STR);         
        while (en != null && en.hasMoreElements()) {
            SearchResult searchResult = en.next();
            String dn = searchResult.getName();

            // 组合全路径
            dn = !EasyUtils.isNullOrEmpty(dn) ? (dn + "," + groupId) : groupId;
            
            if (dn.indexOf(OU_TAG) < 0)  continue;

            GroupDTO group = new GroupDTO();

            // 获得组的属性
            dn = dn.toLowerCase().replaceAll(", ", ",");
            group.setId(getGroupId(dn));
            group.setName(getGroupName(dn));
            group.setParentId(getParentGroupId(dn));
            
            Attributes attrs = searchResult.getAttributes();
            // description
            String value = getValueFromAttribute(attrs, fieldNames.get(DESCRIPTION_GROUP));
group.setDescription(value);
            
            items.add(group);
        }
    } catch (NamingException e) {           
        throw new BusinessException("获取外部用户组失败!",e);
    }
    return items;
}
 
Example 8
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public List<?> getOtherUsers(Map<String, String> paramsMap, String attributes, String groupId, Object...otherParams) {
    String filterString =  otherParams.length > 0 ? (String)otherParams[0] : USER_FILTER_STR;
    
    Document doc = XMLDocUtil.dataXml2Doc(attributes);
    Map<String, String> fieldNames = new HashMap<String, String>();
    Map<String, String> defaultValues = new HashMap<String, String>();
    
    for (Iterator<?> it = doc.getRootElement().elementIterator(); it.hasNext();) {
        Element element = (Element) it.next();
        fieldNames.put(element.getName(), element.getText());
        defaultValues.put(element.getName(), element.attribute(DEFAULT_VALUE).getText());
    }
    
    List<UserDTO> items = new ArrayList<UserDTO>();
    Set<String> loginNameSet = new HashSet<String> ();
    Set<String> dnCache = new HashSet<String> ();
    // 数据查询
    try {
    	DirContext conn =  getConnection(paramsMap);
        NamingEnumeration<SearchResult> en = ldapSearch(conn, groupId, filterString);         
        while (en != null && en.hasMoreElements()) {
            SearchResult sr = en.next();
            String dn = sr.getName();
            
            // 组合全路径
            dn = dn + "," + groupId;
            if(dnCache.contains(dn)) continue;
            
            Attributes attrs = sr.getAttributes();
            
            if (attrs.get(SN_TAG) == null){
                continue;
            }
            
            UserDTO user = new UserDTO();
            user.setId(dn);
            user.setGroupId(getGroupId(dn));                
            user.setUserName( getNameValueFromAttribute( attrs, SN_TAG ) );
            
            // 获得用户的属性              
            // loginName
            String uid_in_ldap = getNameValueFromAttribute(attrs, fieldNames.get(LOGIN_NAME_USER));
            if (uid_in_ldap != null) { // uid简称 有可能重名,重名只导入第一个
                if(loginNameSet.contains(uid_in_ldap)) {
                    continue;
                }
                user.setLoginName(uid_in_ldap);
            } 
            else {
                user.setLoginName(dn);
            }
            
            // email
            String emailName = fieldNames.get(EAMIL_USER);
            String emailValue = getValueFromAttribute(attrs, emailName);
            user.setEmail(emailValue);
 
            // sex
            String sexName = fieldNames.get(SEX_USER);
        	String sexValue = getValueFromAttribute(attrs, sexName);
        	user.setSex(sexValue);


            // telephone
String telephoneName = fieldNames.get(TELE_PHONE);
String telephoneValue = getValueFromAttribute(attrs, telephoneName);
        	user.setTelephone(telephoneValue);

            // employeeNo
String employeeNoName = fieldNames.get(EMPLOYEE_NO_USER);
            user.setEmployeeNo(defaultValues.get(employeeNoName));
            
            // disabled
            String disabled = fieldNames.get(USER_STATUS);
            user.setAuthMethod(defaultValues.get(disabled));
            
            items.add(user);
            dnCache.add(dn);
            loginNameSet.add(user.getLoginName());
        }
    } catch (NamingException e) {           
        throw new BusinessException("获取外部用户失败!",e);
    }
    return items;
}
 
Example 9
Source File: LdapUsersLoginModule.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected String bindDNAuthentication(InitialLdapContext ctx, String user, Object credential, String baseDN,
      String filter) throws NamingException
{
   SearchControls constraints = new SearchControls();
   constraints.setSearchScope(searchScope);
   constraints.setTimeLimit(searchTimeLimit);
   String attrList[] = {distinguishedNameAttribute};
   constraints.setReturningAttributes(attrList);

   NamingEnumeration<SearchResult> results = null;

   Object[] filterArgs = {user};
   results = ctx.search(baseDN, filter, filterArgs, constraints);
   if (!results.hasMore())
   {
      results.close();
      throw PicketBoxMessages.MESSAGES.failedToFindBaseContextDN(baseDN);
   }

   SearchResult sr = results.next();
   String name = sr.getName();
   String userDN = null;
   Attributes attrs = sr.getAttributes();
   if (attrs != null)
   {
      Attribute dn = attrs.get(distinguishedNameAttribute);
      if (dn != null)
      {
         userDN = (String) dn.get();
      }
   }
   if (userDN == null)
   {
      if (sr.isRelative())
         userDN = name + ("".equals(baseDN) ? "" : "," + baseDN);
      else
         throw PicketBoxMessages.MESSAGES.unableToFollowReferralForAuth(name);
   }

   results.close();
   results = null;
   // Bind as the user dn to authenticate the user
   InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
   userCtx.close();

   return userDN;
}
 
Example 10
Source File: LdapCallbackHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 @param ctx - the context to search from
 @param user - the input username
 @param credential - the bind credential
 @param baseDN - base DN to search the ctx from
 @param filter - the search filter string
 @return the userDN string for the successful authentication
 @throws NamingException
 */
@SuppressWarnings("rawtypes")
protected String bindDNAuthentication(InitialLdapContext ctx, String user, Object credential, String baseDN,
      String filter) throws NamingException
{
   SearchControls constraints = new SearchControls();
   constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
   constraints.setTimeLimit(searchTimeLimit);
   String attrList[] = {distinguishedNameAttribute};
   constraints.setReturningAttributes(attrList);

   NamingEnumeration results = null;

   Object[] filterArgs = {user};
   results = ctx.search(baseDN, filter, filterArgs, constraints);
   if (results.hasMore() == false)
   {
      results.close();
      throw PicketBoxMessages.MESSAGES.failedToFindBaseContextDN(baseDN);
   }

   SearchResult sr = (SearchResult) results.next();
   String name = sr.getName();
   String userDN = null;
   Attributes attrs = sr.getAttributes();
   if (attrs != null)
   {
       Attribute dn = attrs.get(distinguishedNameAttribute);
       if (dn != null)
       {
               userDN = (String) dn.get();
       }
   }
   if (userDN == null)
   {
       if (sr.isRelative() == true)
           userDN = name + ("".equals(baseDN) ? "" : "," + baseDN);
       else
           throw PicketBoxMessages.MESSAGES.unableToFollowReferralForAuth(name);
   }

   safeClose(results);
   results = null;

   InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
   safeClose(userCtx);

   return userDN;
}
 
Example 11
Source File: LegacyLDAPSecuritySettingPlugin.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void processSearchResult(Map<String, Set<Role>> securityRoles,
                                 SearchResult searchResult) throws NamingException {
   LdapName searchResultLdapName = new LdapName(searchResult.getName());
   Attributes attrs = searchResult.getAttributes();
   if (attrs == null || attrs.size() == 0) {
      if (logger.isDebugEnabled()) {
         logger.debug("Skipping LDAP search result \"" + searchResultLdapName + "\" with " + (attrs == null ? "null" : attrs.size()) + " attributes");
      }
      return;
   }
   List<Rdn> rdns = searchResultLdapName.getRdns();
   if (rdns.size() < 3) {
      if (logger.isDebugEnabled()) {
         logger.debug("\tSkipping LDAP search result \"" + searchResultLdapName + "\" with " + rdns.size() + " RDNs.");
      }
      return;
   }
   StringBuilder logMessage = new StringBuilder();
   if (logger.isDebugEnabled()) {
      logMessage.append("LDAP search result: ").append(searchResultLdapName);
   }
   // we can count on the RDNs being in order from right to left
   Rdn rdn = rdns.get(rdns.size() - 3);
   String rawDestinationType = rdn.getValue().toString();
   String destinationType = "unknown";
   if (rawDestinationType.toLowerCase().contains("queue")) {
      destinationType = "queue";
   } else if (rawDestinationType.toLowerCase().contains("topic")) {
      destinationType = "topic";
   }
   if (logger.isDebugEnabled()) {
      logMessage.append("\n\tDestination type: ").append(destinationType);
   }

   rdn = rdns.get(rdns.size() - 2);
   if (logger.isDebugEnabled()) {
      logMessage.append("\n\tDestination name: ").append(rdn.getValue());
   }
   String destination = rdn.getValue().toString();

   rdn = rdns.get(rdns.size() - 1);
   if (logger.isDebugEnabled()) {
      logMessage.append("\n\tPermission type: ").append(rdn.getValue());
   }
   String permissionType = rdn.getValue().toString();

   if (logger.isDebugEnabled()) {
      logMessage.append("\n\tAttributes: ").append(attrs);
   }
   Attribute attr = attrs.get(roleAttribute);
   NamingEnumeration<?> e = attr.getAll();
   Set<Role> roles = securityRoles.get(destination);
   boolean exists = false;
   if (roles == null) {
      roles = new HashSet<>();
   } else {
      exists = true;
   }

   while (e.hasMore()) {
      String value = (String) e.next();
      LdapName ldapname = new LdapName(value);
      rdn = ldapname.getRdn(ldapname.size() - 1);
      String roleName = rdn.getValue().toString();
      if (logger.isDebugEnabled()) {
         logMessage.append("\n\tRole name: ").append(roleName);
      }
      Role role = new Role(roleName,
                           permissionType.equalsIgnoreCase(writePermissionValue), // send
                           permissionType.equalsIgnoreCase(readPermissionValue),  // consume
                           permissionType.equalsIgnoreCase(adminPermissionValue), // createDurableQueue
                           permissionType.equalsIgnoreCase(adminPermissionValue), // deleteDurableQueue
                           permissionType.equalsIgnoreCase(adminPermissionValue), // createNonDurableQueue
                           permissionType.equalsIgnoreCase(adminPermissionValue), // deleteNonDurableQueue
                           mapAdminToManage ? permissionType.equalsIgnoreCase(adminPermissionValue) : false, // manage - map to admin based on configuration
                           permissionType.equalsIgnoreCase(readPermissionValue),  // browse
                           permissionType.equalsIgnoreCase(adminPermissionValue), // createAddress
                           permissionType.equalsIgnoreCase(adminPermissionValue)  // deleteAddress
                           );
      roles.add(role);
   }

   if (logger.isDebugEnabled()) {
      logger.debug(logMessage);
   }

   if (!exists) {
      securityRoles.put(destination, roles);
   }
}
 
Example 12
Source File: LdapUtil.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * @param base
 *            :根节点(在这里是"dc=example,dc=com")
 * @param scope
 *            :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
 * @param filter
 *            :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
 */
public void searchInformation(String base, String scope, String filter,
		DirContext dc) {
	SearchControls sc = new SearchControls();
	if (scope.equals("base")) {
		sc.setSearchScope(SearchControls.OBJECT_SCOPE);
	} else if (scope.equals("one")) {
		sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	} else {
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
	}
	NamingEnumeration<?> ne = null;
	try {
		ne = dc.search(base, filter, sc);
		// Use the NamingEnumeration object to cycle through
		// the result set.
		while (ne.hasMore()) {
			//System.out.println();
			SearchResult sr = (SearchResult) ne.next();
			String name = sr.getName();
			if (base != null && !base.equals("")) {
				LogUtil.info("entry: " + name + "," + base);
			} else {
				LogUtil.info("entry: " + name);
			}

			Attributes at = sr.getAttributes();
			NamingEnumeration<?> ane = at.getAll();
			while (ane.hasMore()) {
				Attribute attr = (Attribute) ane.next();
				String attrType = attr.getID();
				NamingEnumeration<?> values = attr.getAll();
				// Another NamingEnumeration object, this time
				// to iterate through attribute values.
				while (values.hasMore()) {
					Object oneVal = values.nextElement();
					if (oneVal instanceof String) {
						LogUtil.info(attrType + ": "+ (String) oneVal);
					} else {
						LogUtil.info(attrType + ": "+ new String((byte[]) oneVal));
					}
				}
			}
		}
	} catch (Exception nex) {
		System.err.println("Error: " + nex.getMessage());
		nex.printStackTrace();
	}
}