List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.apache.nifi.processors.enrich.QueryDNS.java
@Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { if (!initialized.get()) { initializeResolver(context);//from w w w.j a v a 2s. c o m getLogger().warn("Resolver was initialized at onTrigger instead of onScheduled"); } FlowFile flowFile = session.get(); if (flowFile == null) { return; } final String queryType = context.getProperty(DNS_QUERY_TYPE).getValue(); final String queryInput = context.getProperty(QUERY_INPUT).evaluateAttributeExpressions(flowFile) .getValue(); final String queryParser = context.getProperty(QUERY_PARSER).getValue(); final String queryRegex = context.getProperty(QUERY_PARSER_INPUT).getValue(); boolean found = false; try { Attributes results = doLookup(queryInput, queryType); // NOERROR & NODATA seem to return empty Attributes handled bellow // but defaulting to not found in any case if (results.size() < 1) { found = false; } else { int recordNumber = 0; NamingEnumeration<?> dnsEntryIterator = results.get(queryType).getAll(); while (dnsEntryIterator.hasMoreElements()) { String dnsRecord = dnsEntryIterator.next().toString(); // While NXDOMAIN is being generated by doLookup catch if (dnsRecord != "NXDOMAIN") { // Map<String, String> parsedResults = parseResponse(recordNumber, dnsRecord, queryParser, queryRegex, "dns"); Map<String, String> parsedResults = parseResponse(String.valueOf(recordNumber), dnsRecord, queryParser, queryRegex, "dns"); flowFile = session.putAllAttributes(flowFile, parsedResults); found = true; } else { // Otherwise treat as not found found = false; } // Increase the counter and iterate over next record.... recordNumber++; } } } catch (NamingException e) { context.yield(); throw new ProcessException( "Unexpected NamingException while processing records. Please review your configuration.", e); } // Finally prepare to send the data down the pipeline if (found) { // Sending the resulting flowfile (with attributes) to REL_FOUND session.transfer(flowFile, REL_FOUND); } else { // NXDOMAIN received, accepting the fate but forwarding // to REL_NOT_FOUND session.transfer(flowFile, REL_NOT_FOUND); } }
From source file:eu.uqasar.util.ldap.LdapManager.java
public List<LdapUser> getUsersFromGroup(int maximum, LdapGroup group) throws NamingException { List<LdapUser> users = new ArrayList<>(); final String mapping = settings.getGroupMemberMapping(); javax.naming.directory.Attribute members = group.getMappedAttribute(mapping); if (members == null) { return users; }/*from w ww . j av a2 s. c om*/ NamingEnumeration<?> results = members.getAll(); while (results.hasMoreElements() && users.size() < maximum) { try { final String userDN = (String) results.next(); LdapUser user = getUserByDNAndFilter(userDN, settings.getUserFilter()); if (user != null) { users.add(user); } } catch (LdapReferralException ex) { logger.warn(ex.getMessage(), ex); } } Collections.sort(users, new LdapUserComparator()); return users; }
From source file:com.teklabs.throng.integration.ldap.Ldap.java
private String getPrincipal(String login) throws NamingException { if (baseDN == null) { throw new IllegalArgumentException("LDAP BaseDN is not set"); }//ww w . j a v a 2s . c o m InitialDirContext context = null; String principal; try { if (LdapHelper.LOG.isDebugEnabled()) { LdapHelper.LOG.debug("Search principal: " + login); } context = ldapContextFactory.getInitialDirContext(); String request = "(&(objectClass=" + userObjectClass + ")(" + loginAttribute + "={0}))"; if (LdapHelper.LOG.isDebugEnabled()) { LdapHelper.LOG.debug("LDAP request: " + request); } SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setReturningAttributes(new String[] {}); controls.setReturningObjFlag(true); NamingEnumeration result = context.search(baseDN, request, new String[] { login }, controls); String found = null; if (result.hasMore()) { SearchResult obj = (SearchResult) result.next(); found = obj.getNameInNamespace(); if (found != null && result.hasMore()) { found = null; LdapHelper.LOG.error( "Login \'" + login + "\' is not unique in LDAP (see attribute " + loginAttribute + ")"); } } principal = found; } finally { LdapHelper.closeContext(context); } return principal; }
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 w w w . j av a 2 s .c o 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:edu.vt.middleware.ldap.dsml.Dsmlv1.java
/** * This will take a DSML <code>Element</code> containing an entry of type * <dsml:entry name="name"/> and convert it to a LDAP search result. * * @param entryElement <code>Element</code> of DSML content * * @return <code>SearchResult</code> *//* w ww . java 2s . co m*/ protected SearchResult createSearchResult(final Element entryElement) { String name = ""; final Attributes entryAttributes = new BasicAttributes(true); SearchResult attrResults = null; if (entryElement != null) { name = entryElement.attributeValue("dn"); if (name == null) { name = ""; } if (entryElement.hasContent()) { final Iterator<?> ocIterator = entryElement.elementIterator("objectclass"); while (ocIterator.hasNext()) { final Element ocElement = (Element) ocIterator.next(); if (ocElement != null && ocElement.hasContent()) { final String ocName = "objectClass"; final Attribute entryAttribute = new BasicAttribute(ocName); final Iterator<?> valueIterator = ocElement.elementIterator("oc-value"); while (valueIterator.hasNext()) { final Element valueElement = (Element) valueIterator.next(); if (valueElement != null) { final String value = valueElement.getText(); if (value != null) { entryAttribute.add(value); } } } entryAttributes.put(entryAttribute); } } attrResults = super.createSearchResult(entryElement); } } if (attrResults != null) { final Attributes attrs = attrResults.getAttributes(); if (attrs != null) { final NamingEnumeration<? extends Attribute> ae = attrs.getAll(); if (ae != null) { try { while (ae.hasMore()) { entryAttributes.put(ae.next()); } } catch (NamingException e) { if (LOG.isDebugEnabled()) { LOG.debug("Could not read attribute in SearchResult from parent"); } } } } } return new SearchResult(name, null, entryAttributes); }
From source file:org.apache.zeppelin.rest.GetUserList.java
/** * function to extract users from LDAP//from ww w .j a v a2s . c o m */ public List<String> getUserList(JndiLdapRealm r, String searchText) { List<String> userList = new ArrayList<>(); String userDnTemplate = r.getUserDnTemplate(); String userDn[] = userDnTemplate.split(",", 2); String userDnPrefix = userDn[0].split("=")[0]; String userDnSuffix = userDn[1]; JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory(); try { LdapContext ctx = CF.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { userDnPrefix }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userDnPrefix) != null) { String currentUser = attrs.get(userDnPrefix).toString(); userList.add(currentUser.split(":")[1].trim()); } } } catch (Exception e) { LOG.error("Error retrieving User list from Ldap Realm", e); } LOG.info("UserList: " + userList); return userList; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns the CN (common name) for a given login name * /* www . java2 s . c om*/ * @param loginName * the loginName of the user * @return CN as a String(if found), or null (else) */ private static String getCn(TSiteBean siteBean, String loginName) throws NamingException { String keyDn = null; DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(), siteBean.getLdapBindPassword()); if (ctx != null) { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for the user-id String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")"; NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls); if (answer.hasMore()) { // retrieve the CN SearchResult sr = answer.next(); keyDn = sr.getName();// + "," + ctx.getNameInNamespace(); LOGGER.debug("Name = " + keyDn); String nameInNamespace = ctx.getNameInNamespace(); LOGGER.debug("Name in namespace " + nameInNamespace); if (nameInNamespace != null && nameInNamespace.trim().length() > 0) { keyDn += "," + ctx.getNameInNamespace(); } LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!"); answer.close(); // wo don't need more answers } else { LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!"); } ctx.close(); } return keyDn; }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Reproduces the problem with// w ww . j a va 2s. co m * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>. * * @throws Exception if anything goes wrong */ @Test public void testAdminAccessBug() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous final Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); Attributes attributes = new BasicAttributes(true); Attribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("organizationalUnit"); attributes.put(objectClass); attributes.put("ou", "blah"); InitialDirContext ctx = new InitialDirContext(env); ctx.createSubcontext("ou=blah,ou=system", attributes); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.OBJECT_SCOPE); controls.setReturningAttributes(new String[] { "+" }); NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls); SearchResult result = list.next(); list.close(); Attribute creatorsName = result.getAttributes().get("creatorsName"); assertEquals("", creatorsName.get()); ctx.destroySubcontext("ou=blah,ou=system"); }
From source file:LDAPTest.java
/** * Saves the changes that the user made. *//*www. j a v a 2s . c om*/ 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:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getUser(String cn) { LDAPUser user = null;/*from w ww . j a v a2 s . c o m*/ NamingEnumeration results = null; DirContext ctx = null; try { ctx = getContext(); 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; }