List of usage examples for javax.naming.directory Attribute getID
String getID();
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen// ww w. j a v a 2s. c om * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }
From source file:org.apereo.services.persondir.support.ldap.AttributeMapAttributesMapper.java
@Override public Object mapFromAttributes(final Attributes attributes) throws NamingException { final int attributeCount = attributes.size(); final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount); for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum .hasMore();) {/*from w ww . ja v a2s .c o m*/ final Attribute attribute = attributesEnum.next(); if (!this.ignoreNull || attribute.size() > 0) { final String attrName = attribute.getID(); final String key = this.getAttributeKey(attrName); final NamingEnumeration<?> valuesEnum = attribute.getAll(); final List<?> values = this.getAttributeValues(valuesEnum); mapOfAttrValues.put(key, values); } } return mapOfAttrValues; }
From source file:org.jasig.services.persondir.support.ldap.AttributeMapAttributesMapper.java
public Object mapFromAttributes(Attributes attributes) throws NamingException { final int attributeCount = attributes.size(); final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount); for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum .hasMore();) {/*from w w w . j a v a 2 s. co m*/ final Attribute attribute = attributesEnum.next(); if (!this.ignoreNull || attribute.size() > 0) { final String attrName = attribute.getID(); final String key = this.getAttributeKey(attrName); final NamingEnumeration<?> valuesEnum = attribute.getAll(); final List<?> values = this.getAttributeValues(valuesEnum); mapOfAttrValues.put(key, values); } } return mapOfAttrValues; }
From source file:se.vgregion.service.innovationsslussen.ldap.LdapService.java
AttributesMapper newAttributesMapper(final Class type) { return new AttributesMapper() { @Override// w ww . j a va 2s. c o m public Object mapFromAttributes(Attributes attributes) throws NamingException { try { return mapFromAttributesImpl(attributes); } catch (Exception e) { throw new RuntimeException(e); } } public Object mapFromAttributesImpl(Attributes attributes) throws NamingException, IllegalAccessException, InstantiationException { Object result = type.newInstance(); BeanMap bm = new BeanMap(result); NamingEnumeration<? extends Attribute> all = attributes.getAll(); while (all.hasMore()) { Attribute attribute = all.next(); String name = toBeanPropertyName(attribute.getID()); if (bm.containsKey(name) && bm.getWriteMethod(name) != null) { bm.put(name, attribute.get()); } } return result; } }; }
From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java
public String searchQueryLDAP() { NamingEnumeration results = null; ObjectMapper mapper = new ObjectMapper(); Response response;//from www.jav a2 s .com String resultOutput = new String(); List<Map<String, String>> attributesList = new LinkedList<>(); String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES)); try { ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL), allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME), allLDAPClientParameters.get(ARG_PASSWORD)); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (attributesToReturn.length > 0) { controls.setReturningAttributes(attributesToReturn); } results = ldapConnection.search( getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_SEARCH_BASE)), allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls); // Iterate through all attributes in the result of search query while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes != null && attributes.size() > 0) { NamingEnumeration ae = attributes.getAll(); Map<String, String> attributesMap = new HashMap<>(); while (ae.hasMore()) { Attribute attribute = (Attribute) ae.next(); attributesMap.put(attribute.getID(), attribute.get().toString()); } attributesList.add(attributesMap); } } response = new LDAPResponse("Ok", attributesList); } catch (Exception e) { response = new ErrorResponse("Error", e.toString()); } finally { if (results != null) { try { results.close(); } catch (Exception e) { e.printStackTrace(); } } if (ldapConnection != null) { try { ldapConnection.close(); } catch (Exception e) { e.printStackTrace(); } } } try { resultOutput = mapper.writeValueAsString(response); } catch (JsonProcessingException e) { e.printStackTrace(); } return resultOutput; }
From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames; roleNames = new LinkedHashSet<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (principalSuffix != null) { userPrincipalName += principalSuffix; }/*from ww w . java 2 s . c o m*/ String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving group names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) { Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr); if (log.isDebugEnabled()) { log.debug("Groups found for user [" + username + "]: " + groupNames); } Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return roleNames; }
From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java
/** * check if client's ip is listed in the Ldap Roles if yes, return true and * update ldapent. if not, return false/*from ww w . j av a 2 s . co m*/ * */ @SuppressWarnings("unchecked") private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException { String ipMember = hdfsIpSchemaStrPrefix + userIp; Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember)); matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr)); matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr)); String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr }; NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs); if (results.hasMore()) { String userId = null; ArrayList<Path> paths = new ArrayList<Path>(); SearchResult sr = results.next(); Attributes attrs = sr.getAttributes(); for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.next(); if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) { userId = (String) attr.get(); } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) { for (NamingEnumeration e = attr.getAll(); e.hasMore();) { String pathStr = (String) e.next(); paths.add(new Path(pathStr)); } } } ldapent.init(userId, paths); if (LOG.isDebugEnabled()) LOG.debug(ldapent); return true; } LOG.info("Ip address " + userIp + " is not authorized to access the proxy server"); return false; }
From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java
/** * DNS????????//from www .j a v a2 s . c om * * @param addressText * @return DNS */ /* * (non-Javadoc) * * @see * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java. * lang.String) */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); String addressStr = address.getHostAddress(); if (address instanceof Inet6Address) { addressStr = "[" + addressStr + "]"; } bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo); props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout)); props.put("com.sun.jndi.dns.timeout.retries", "1"); InitialDirContext idctx = null; String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost"); m_log.debug("The hostname from which to retrieve attributes is " + hostname); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); start = HinemosTime.currentTimeMillis(); idctx = new InitialDirContext(props); Attributes attrs = idctx.getAttributes(hostname); end = HinemosTime.currentTimeMillis(); bufferOrg.append("\n"); NamingEnumeration<? extends Attribute> allAttr = attrs.getAll(); while (allAttr.hasMore()) { Attribute attr = allAttr.next(); bufferOrg.append("Attribute: " + attr.getID() + "\n"); NamingEnumeration<?> values = attr.getAll(); while (values.hasMore()) bufferOrg.append("Value: " + values.next() + "\n"); } bufferOrg.append("\n"); m_response = end - start; if (m_response > 0) { if (m_response < m_timeout) { result = result + ("Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("Response Time = " + m_response + "ms"); } } else { result = result + ("Response Time < 1ms"); } retry = false; isReachable = true; } catch (NamingException e) { result = (e.getMessage() + "[NamingException]"); retry = true; isReachable = false; } catch (Exception e) { result = (e.getMessage() + "[Exception]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); try { if (idctx != null) { idctx.close(); } } catch (NamingException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(DNS/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:LDAPTest.java
/** * Constructs the data panel.// w w w. j ava 2 s .c o m * @param attributes the attributes of the given entry */ public DataPanel(Attributes attrs) throws NamingException { setLayout(new java.awt.GridLayout(0, 2, 3, 1)); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute attr = attrEnum.next(); String id = attr.getID(); NamingEnumeration<?> valueEnum = attr.getAll(); while (valueEnum.hasMore()) { Object value = valueEnum.next(); if (id.equals("userPassword")) value = new String((byte[]) value); JLabel idLabel = new JLabel(id, SwingConstants.RIGHT); JTextField valueField = new JTextField("" + value); if (id.equals("objectClass")) valueField.setEditable(false); if (!id.equals("uid")) { add(idLabel); add(valueField); } } } }
From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException { List<String> userNameList = new ArrayList<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))"; Object[] searchArguments = new Object[] { containString }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]"); }//ww w. j a va2s. c o m Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().toLowerCase().equals("cn")) { userNameList.addAll(LdapUtils.getAllAttributeValues(attr)); } } } } return userNameList; }