List of usage examples for javax.naming NamingEnumeration hasMoreElements
boolean hasMoreElements();
From source file:org.lsc.jndi.JndiServices.java
/** * Retrieve a specific attribute from an object * //from w w w . ja va 2 s . c om * @param objectDn * @param attribute * @return * @throws LscServiceException */ public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException { List<String> values = null; try { // Setup search SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { attribute }); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningObjFlag(true); // Retrieve attribute values SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE); Attribute attr = res.getAttributes().get(attribute); if (attr != null) { values = new ArrayList<String>(); NamingEnumeration<?> enu = attr.getAll(); while (enu.hasMoreElements()) { Object val = enu.next(); values.add(val.toString()); } } } catch (NamingException e) { throw new LscServiceException(e); } return values; }
From source file:org.lsc.jndi.JndiServices.java
public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope, final List<String> attrsNames) throws NamingException { // sanity checks String searchBase = base == null ? "" : rewriteBase(base); String searchFilter = filter == null ? DEFAULT_FILTER : filter; Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>(); if (attrsNames == null || attrsNames.size() == 0) { LOGGER.error("No attribute names to read! Check configuration."); return res; }/* ww w . ja v a 2 s . com*/ String[] attributes = new String[attrsNames.size()]; attributes = attrsNames.toArray(attributes); SearchControls constraints = new SearchControls(); constraints.setDerefLinkFlag(false); constraints.setReturningAttributes(attributes); constraints.setSearchScope(scope); constraints.setReturningObjFlag(true); try { boolean requestPagedResults = false; List<Control> extControls = new ArrayList<Control>(); if (pageSize > 0) { requestPagedResults = true; LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize); } if (requestPagedResults) { extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL)); } if (sortedBy != null) { extControls.add(new SortControl(sortedBy, Control.CRITICAL)); } if (extControls.size() > 0) { ctx.setRequestControls(extControls.toArray(new Control[extControls.size()])); } byte[] pagedResultsResponse = null; do { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints); if (results != null) { Map<String, Object> attrsValues = null; while (results.hasMoreElements()) { attrsValues = new HashMap<String, Object>(); SearchResult ldapResult = (SearchResult) results.next(); // get the value for each attribute requested for (String attributeName : attrsNames) { Attribute attr = ldapResult.getAttributes().get(attributeName); if (attr != null && attr.get() != null) { attrsValues.put(attributeName, attr.get()); } } res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues)); } } Control[] respCtls = ctx.getResponseControls(); if (respCtls != null) { for (Control respCtl : respCtls) { if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) { pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie(); } } } if (requestPagedResults && pagedResultsResponse != null) { ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) }); } } while (pagedResultsResponse != null); // clear requestControls for future use of the JNDI context if (requestPagedResults) { ctx.setRequestControls(null); } } catch (CommunicationException e) { // Avoid handling the communication exception as a generic one throw e; } catch (ServiceUnavailableException e) { // Avoid handling the service unavailable exception as a generic one throw e; } catch (NamingException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } catch (IOException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } return res; }
From source file:org.netoprise.neo4j.ConnectorTest.java
@Test @Ignore/*from w w w .ja va2 s.c o m*/ @OperateOnDeployment("test") public void listJNDI() { try { Context context = new InitialContext(); System.out.println("Context namespace: " + context.getNameInNamespace()); NamingEnumeration<NameClassPair> content = context.list("comp"); while (content.hasMoreElements()) { NameClassPair nameClassPair = (NameClassPair) content.nextElement(); System.out .println("Name :" + nameClassPair.getName() + " with type:" + nameClassPair.getClassName()); } } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java
private boolean isInDirectory(String ldapName, ManagedSystemObjectMatch matchObj, LdapContext ldapctx) { int indx = ldapName.indexOf(","); String rdn = null;/*from w w w . j a v a2 s. c om*/ if (indx > 0) { rdn = ldapName.substring(0, ldapName.indexOf(",")); } else { rdn = ldapName; } String[] attrAry = { "uid", "cn", "fn" }; NamingEnumeration results = null; try { results = search(matchObj, ldapctx, rdn, attrAry); if (results != null && results.hasMoreElements()) { return true; } return false; } catch (NamingException ne) { log.error(ne); return false; } }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private void serialize(List results, Config config, ContentHandler ch) { try {//from w ww . ja v a 2s .com ch.startDocument(); ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES); for (Iterator i = results.iterator(); i.hasNext();) { SearchResult sr = (SearchResult) i.next(); ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", sr.getName()); try { addElement(ch, "fullname", sr.getNameInNamespace()); } catch (UnsupportedOperationException e) { // This seems to be the only way to know if sr contains a name! } Attributes attr = sr.getAttributes(); NamingEnumeration attrEn = attr.getAll(); while (attrEn.hasMoreElements()) { Attribute a = (Attribute) attrEn.next(); if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) { ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES); addElement(ch, "name", a.getID()); NamingEnumeration aEn = a.getAll(); while (aEn.hasMoreElements()) { Object o = aEn.next(); addElement(ch, "value", o.toString()); } ch.endElement("", "attribute", "attribute"); } } ch.endElement("", "result", "result"); } ch.endElement("", "results", "results"); ch.endDocument(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java
/** * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String) *//*from www. j av a 2 s . c om*/ protected boolean validatePassword(String inputPassword, String expectedPassword) { // Load our LDAP specific properties Properties env = getProperties(); // Load the BaseDN String baseDN = (String) options.get("BaseDN"); if (baseDN == null) { // If the BaseDN is not specified, log an error and refuse the login attempt log.info("BaseDN is not set, refusing login"); return false; } // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords if ((inputPassword == null) || inputPassword.equals("")) { log.debug("Empty password, refusing login"); return false; } // Load the LoginProperty String loginProperty = (String) options.get("LoginProperty"); if (loginProperty == null) { // Use the default loginProperty = "cn"; } // Load any search filter String searchFilter = (String) options.get("Filter"); // Find the user that is calling us String userName = getUsername(); // Load any information we may need to bind String bindDN = (String) options.get("BindDN"); String bindPW = (String) options.get("BindPW"); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter=" + filter); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration answer = ctx.search(baseDNs[x], filter, searchControls); boolean ldapApiNpeFound = false; if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = (SearchResult) answer.next(); // Construct the UserDN String userDN = si.getName() + "," + baseDNs[x]; ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword); ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); //if successful then verified that user and pw are valid ldap credentials ctx.reconnect(null); return true; } // If we try all the BaseDN's and have not found a match, return false return false; } catch (Exception e) { log.info("Failed to validate password: " + e.getMessage()); return false; } }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
public Map<String, String> findLdapUserDetails(String userName) { Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord()); HashMap<String, String> userDetails = new HashMap<String, String>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; }//from w w w. j a v a 2 s . co m // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); // Load any search filter String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = answer.next(); //generate the DN String userDN = null; try { userDN = si.getNameInNamespace(); } catch (UnsupportedOperationException use) { userDN = si.getName(); if (userDN.startsWith("\"")) { userDN = userDN.substring(1, userDN.length()); } if (userDN.endsWith("\"")) { userDN = userDN.substring(0, userDN.length() - 1); } userDN = userDN + "," + baseDNs[x]; } userDetails.put("dn", userDN); // Construct the UserDN NamingEnumeration<String> keys = si.getAttributes().getIDs(); while (keys.hasMore()) { String key = keys.next(); Attribute value = si.getAttributes().get(key); if ((value != null) && (value.get() != null)) { userDetails.put(key, value.get().toString()); } } return userDetails; } return userDetails; } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
/** * @throws NamingException//from ww w. j ava 2 s . c om * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String) */ protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) { Set<Map<String, String>> ret = new HashSet<Map<String, String>>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; } // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/ // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); boolean ldapApiEnumerationBugEncountered = false; while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change // We use the first match SearchResult si = null; try { si = answer.next(); } catch (NullPointerException npe) { ldapApiEnumerationBugEncountered = true; break; } Map<String, String> entry = new HashMap<String, String>(); String name = (String) si.getAttributes().get("cn").get(); name = name.trim(); Attribute desc = si.getAttributes().get("description"); String description = desc != null ? (String) desc.get() : ""; description = description.trim(); entry.put("id", name); entry.put("name", name); entry.put("description", description); ret.add(entry); } } } catch (NamingException e) { if (e instanceof InvalidSearchFilterException) { InvalidSearchFilterException fException = (InvalidSearchFilterException) e; String message = "The ldap group filter defined is invalid "; log.error(message, fException); throw new LdapFilterException(message + " " + fException.getMessage()); } //TODO: check for ldap connection/unavailable/etc. exceptions. else { log.error("LDAP communication error: " + e.getMessage(), e); throw new LdapCommunicationException(e); } } return ret; }
From source file:org.saiku.reporting.backend.server.SaikuJndiDatasourceConnectionProvider.java
public void showJndiContext(Context ctx, String name, String space) { if (null == name) name = ""; if (null == space) space = ""; try {//from w ww .j a va 2 s. com NamingEnumeration<NameClassPair> en = ctx.list(name); while (en != null && en.hasMoreElements()) { String delim = (name.length() > 0) ? "/" : ""; NameClassPair ncp = en.next(); log.debug(space + name + delim + ncp); if (space.length() < 40) showJndiContext(ctx, ncp.getName(), " " + space); } } catch (javax.naming.NamingException ex) { // Normalerweise zu ignorieren } }
From source file:org.viafirma.cliente.util.ConfigUtil.java
/** * Recupera el conjunto de propiedades que utiliza la aplicacin. * @param context/*from w ww. j av a 2 s.co m*/ * @return */ public Properties readConfigPropertes() { Properties properties = new Properties(); Context initCtx; try { // carcamos la configuracin por defecto properties.load(getClass().getResourceAsStream("/viafirmaConfig.properties")); // recuperamos la configuracin almacenada en el contexto de aplicacin initCtx = new InitialContext(); Context contextInit = (Context) initCtx.lookup("java:comp/env"); // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list(""); while (propiedadesJDNI.hasMoreElements()) { NameClassPair propiedad = propiedadesJDNI.nextElement(); Object temp = contextInit.lookup(propiedad.getName()); if (temp instanceof String) { if (propiedad.getName().startsWith("SYSTEM_")) { String valor = (String) temp; String nombre = StringUtils.substringAfter(propiedad.getName(), "SYSTEM_"); System.getProperties().put(nombre, valor); properties.put(nombre, valor); } else { String valor = (String) temp; properties.put(propiedad.getName(), valor); } } } for (Object key : properties.keySet()) { if (((String) key).contains("PASSWORD")) { System.out.println("\t\t\t" + key + "=***"); } else { System.out.println("\t\t\t" + key + "=" + properties.get(key)); } } } catch (Exception e) { log.error("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible. " + e.getMessage()); //Permitimos el arranque de la aplicacin utilizando la configuracin de los properties. //throw new ExceptionInInitializerError("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible."+e.getMessage()); } return properties; }