List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;//w ww .ja v a 2s .c o m NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:LDAPTest.java
/** * Saves the changes that the user made. *///from w w w .j a v a2 s .c o m public void saveEntry() { try { if (dataPanel == null) return; if (context == null) context = getContext(); if (uidField.getText().equals(uid)) // update existing entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; Attributes editedAttrs = dataPanel.getEditedAttributes(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute attr = attrEnum.next(); String id = attr.getID(); Attribute editedAttr = editedAttrs.get(id); if (editedAttr != null && !attr.get().equals(editedAttr.get())) context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, new BasicAttributes(id, editedAttr.get())); } } else // create new entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; attrs = dataPanel.getEditedAttributes(); Attribute objclass = new BasicAttribute("objectClass"); objclass.add("uidObject"); objclass.add("person"); attrs.put(objclass); attrs.put("uid", uidField.getText()); context.createSubcontext(dn, attrs); } findEntry(); } catch (NamingException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the LDAP users//from ww w. j a v a2s . c om * * @param ctx * @param loginAttributeName * @param searchStrs * @return */ static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) { List<TPersonBean> personBeans = new LinkedList<TPersonBean>(); if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return personBeans; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); for (String searchStr : searchStrs) { LOGGER.debug("Searching by filter " + searchStr); SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { LOGGER.debug("Search successful " + searchStr); personBeans.add(personBean); } } } catch (NamingException e) { LOGGER.warn("Search failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } return personBeans; }
From source file:com.ritchey.naming.InitialContextFactory.java
/** * Get Context that has access to default Namespace. This method won't be * called if a name URL beginning with java: is passed to an InitialContext. * * @see org.mortbay.naming.java.javaURLContextFactory * @param env a <code>Hashtable</code> value * @return a <code>Context</code> value *///from w w w . j a va 2s. c o m public Context getInitialContext(Hashtable env) { Log.debug("InitialContext loaded"); Context ctx = new localContextRoot(env); Properties properties = new Properties(); try { properties.load(new FileInputStream("build.properties")); } catch (Exception e1) { e1.printStackTrace(); } Context jdbc = null; try { jdbc = ctx.createSubcontext("jdbc"); } catch (NamingException e) { try { jdbc = (Context) ctx.lookup("jdbc"); } catch (NamingException e1) { e1.printStackTrace(); } } Context ldap = null; try { ldap = ctx.createSubcontext("ldap"); } catch (NamingException e) { try { ldap = (Context) ctx.lookup("ldap"); } catch (NamingException e1) { e1.printStackTrace(); } } Log.debug("getInitialContext"); String databaseNames = properties.getProperty("database.jndi.names"); if (databaseNames == null) { Log.warn(new RuntimeException("database.jndi.names is not defined" + " in build.properties as a comma separated list in " + "build.properties")); return ctx; } for (String database : databaseNames.split(" *, *")) { Log.debug("create " + database); try { createDs(database, properties, jdbc); } catch (NamingException e) { e.printStackTrace(); } } try { createLdapStrings(properties, ldap); } catch (NamingException e1) { e1.printStackTrace(); } String url = getValue(false, "picture", null, properties); try { ctx.bind("picture", url); } catch (NamingException ex) { Logger.getLogger(InitialContextFactory.class.getName()).log(Level.SEVERE, null, ex); } try { Log.debug("jdbc initial context = " + ctx.listBindings("jdbc")); NamingEnumeration<Binding> ldapBindings = ctx.listBindings("ldap"); Log.debug("ldap initial context = " + ctx.listBindings("ldap")); while (ldapBindings.hasMore()) { Binding binding = ldapBindings.next(); Log.debug("binding: " + binding.getName()); } } catch (NamingException e) { e.printStackTrace(); } return ctx; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static List<Organization> getOrgList(String country) { List<Organization> OrgList = new ArrayList<Organization>(); NamingEnumeration resultCountries = null; DirContext ctx = null;/*from w w w. j a va2s . c o m*/ try { ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); String filter; if (country == null) { filter = "(objectclass=country)"; } else { filter = "(&(objectclass=country)(c=" + country + "))"; } resultCountries = ctx.search(rb.getString("organisationsRoot"), filter, controls); while (resultCountries.hasMore()) { SearchResult searchResult = (SearchResult) resultCountries.next(); Attributes attributes = searchResult.getAttributes(); String countryCode = (String) attributes.get("c").get(); String countryName = (String) attributes.get("co").get(); NamingEnumeration resultsOrgs = ctx.search( "c=" + countryCode + "," + rb.getString("organisationsRoot"), "(objectclass=organization)", controls); while (resultsOrgs.hasMore()) { SearchResult srOrg = (SearchResult) resultsOrgs.next(); Attributes orgAttrs = srOrg.getAttributes(); String description = ""; if ((orgAttrs.get("description")) != null) { description = (String) orgAttrs.get("description").get(); } OrgList.add(new Organization((String) orgAttrs.get("o").get(), countryName, countryCode, description, srOrg.getNameInNamespace())); } resultsOrgs.close(); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (resultCountries != null) { try { resultCountries.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } Collections.sort(OrgList, new Comparator<Organization>() { public int compare(Organization o1, Organization o2) { return o1.getKey().compareTo(o2.getKey()); } }); return OrgList; }
From source file:edu.vt.middleware.ldap.ssl.DefaultHostnameVerifier.java
/** * Returns the CNs from the supplied certificate. * * @param cert to get CNs from/* w ww. java2 s . co m*/ * * @return CNs */ private String[] getCNs(final X509Certificate cert) { final List<String> names = new ArrayList<String>(); final String subjectPrincipal = cert.getSubjectX500Principal().toString(); if (subjectPrincipal != null) { try { final LdapName subjectDn = new LdapName(subjectPrincipal); for (Rdn rdn : subjectDn.getRdns()) { final Attributes attrs = rdn.toAttributes(); final NamingEnumeration<String> ids = attrs.getIDs(); while (ids.hasMore()) { final String id = ids.next(); if (id.toLowerCase().equals("cn") || id.toLowerCase().equals("commonname") || id.toLowerCase().equals("2.5.4.3")) { final Object value = attrs.get(id).get(); if (value != null) { if (value instanceof String) { names.add((String) value); } else if (value instanceof Attribute) { // for multi value RDNs the first value is used final Object multiValue = ((Attribute) value).get(); if (multiValue != null && multiValue instanceof String) { names.add((String) multiValue); } } } } } } } catch (NamingException e) { if (this.logger.isWarnEnabled()) { this.logger.warn("Could not get distinguished name from subject " + subjectPrincipal, e); } } } return names.toArray(new String[names.size()]); }
From source file:org.gbif.portal.registration.LDAPUtils.java
/** * Log attribute values for debug./*from w w w.ja v a2s . com*/ * @param attributes * @throws NamingException */ private void debugAttributes(Attributes attributes) throws NamingException { if (logger.isDebugEnabled()) { // useful for debug NamingEnumeration attributesEnum = attributes.getAll(); while (attributesEnum != null && attributesEnum.hasMore()) { logger.debug("Attribute:" + attributesEnum.next()); } } }
From source file:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java
/** * Extract from LDAP all configured attributes. * /*from ww w . ja va 2 s . co m*/ * @param id user id * @param environment LDAP environment * @return list of principal attributes */ public List<PrincipalAttribute> search(String id, Hashtable<String, String> environment) { // checks if attributes are set if (attributes != null && attributes.length > 0) { ctls.setReturningAttributes(attributes); } // if no attributes, uses UID by default if (ctls.getReturningAttributes() == null) { ctls.setReturningAttributes(new String[] { UID }); } // uses useDN for searching String userDn = super.getUserDnTemplate(); String ldapUserContext = StringUtils.substringAfter(userDn, ","); try { // gets initial context InitialDirContext ctx = new InitialDirContext(environment); // creates search string String filter = MessageFormat.format("(uid={0})", new Object[] { id }); // searchs! Object obj = ctx.search(ldapUserContext, filter, ctls); // scans all attributes and load into a Principal Attribute @SuppressWarnings("rawtypes") NamingEnumeration userEnum = (NamingEnumeration) obj; if (userEnum != null && userEnum.hasMore()) { SearchResult result = (SearchResult) userEnum.next(); return loadAttributes(id, result.getAttributes()); } } catch (NamingException ne) { LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, ne, id); } return new ArrayList<PrincipalAttribute>(); }
From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java
private void extractGroupsFromAttribute(User user, String groupNameAttribName, Attribute groupNameAttrib, SiteFeed siteFeed) throws NamingException { if (groupNameAttrib != null && groupNameAttrib.size() > 0) { NamingEnumeration groupAttribValues = groupNameAttrib.getAll(); while (groupAttribValues.hasMore()) { Object groupNameObj = groupAttribValues.next(); if (groupNameObj != null) { String groupName = extractGroupNameFromAttributeValue(groupNameObj.toString()); if (StringUtils.isNotEmpty(groupName)) { addGroupToUser(user, groupName, siteFeed); }//from www. ja va2 s .c om } } } else { logger.debug("No LDAP attribute " + groupNameAttribName + " found for username " + user.getUsername()); } }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;/*from ww w.j av a 2 s .c om*/ String firstName = null; String lastName = null; String employeenumber = null; String email = null; try { DirContext ctx = new InitialDirContext(env); // Setup subtree scope to tell LDAP to recursively descend directory structure // during searches. SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // We want the user's id, first name and last name ... searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" }); // Execute the search, starting at the directory level of Users NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls); while (results.hasMore()) { SearchResult result = (SearchResult) results.next(); String dn = result.getName().toString() + "," + getBasePath(); Attributes attrs = ctx.getAttributes(dn); id = attrs.get("uid").get().toString(); String cn = attrs.get("cn").get().toString(); firstName = cn.substring(0, cn.indexOf(" ")); lastName = cn.substring(cn.indexOf(" ")); email = attrs.get("mail").get().toString(); } results.close(); ctx.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } edit.setId(id); edit.setFirstName(firstName); edit.setLastName(lastName); edit.setEmail(email); return true; }