List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java
/** * Returns single value for an attribute, even if attribute has more values... * * @param attrs collection of attributes * @param attr attribute name//from w w w . ja v a 2 s. c o m */ private String getValue(Attributes attrs, String attrName) throws NamingException { Attribute attribute = attrs.get(attrName); if (attribute == null) { return null; } Object value = attribute.get(); if (value == null) { return null; } // some values like userPassword are returned as byte[], see XX-9328 if (value instanceof byte[]) { return new String((byte[]) value); } return value.toString(); }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Reproduces the problem with/*from www. ja va2 s. c o 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:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java
@Override public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; }/*from ww w .j ava2 s . c o m*/ int givenMax = Integer .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); if (maxItemLimit < 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user serch. Please enter valid sequence."); } StringBuffer searchFilter = null; searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); StringBuffer buff = new StringBuffer(); buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter) .append("))"); String serviceNameAttribute = "sn"; String mailAttribute = "mail"; String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; String[] allUserNames = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<String> list = new ArrayList<String>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(mailAttribute); /* * If this is a service principle, just ignore and iterate rest of the array. * The entity is a service if value of surname is Service */ Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); //append the domain if exist String domain = userRealm.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (domain != null) { domain = domain + "/"; name = domain + name; } list.add(name); i++; } } } userNames = list.toArray(new String[list.size()]); //get secondary user lists UserStoreManager secUserManager = this.getSecondaryUserStoreManager(); if (secUserManager != null) { String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit); allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames); } else { allUserNames = userNames; } Arrays.sort(allUserNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return allUserNames; }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Retrieves an attribute by its name./*from w w w. j av a 2s . c o m*/ * @param attributes the list of attributes to query on * @param attributeName the name of the attribute to return * @return the value of the attribute, or null if not found * @throws NamingException if an exception is thrown * @since 1.4.0 */ public String getAttribute(Attributes attributes, String attributeName) throws NamingException { if (attributes == null || attributes.size() == 0) { return null; } else { final Attribute attribute = attributes.get(attributeName); if (attribute != null) { final Object o = attribute.get(); if (o instanceof String) { return (String) attribute.get(); } } } return null; }
From source file:org.javlo.external.agitos.dkim.DKIMUtil.java
public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); String recordname = selector + "._domainkey." + signingDomain; String value = null;//from ww w .j a v a 2s . c om try { DirContext dnsContext = new InitialDirContext(env); javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname, new String[] { "TXT" }); javax.naming.directory.Attribute txtrecord = attribs.get("txt"); if (txtrecord == null) { throw new DKIMSignerException("There is no TXT record available for " + recordname); } // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..." value = (String) txtrecord.get(); } catch (NamingException ne) { throw new DKIMSignerException("Selector lookup failed", ne); } if (value == null) { throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved"); } // try to read public key from RR String[] tags = value.split(";"); for (String tag : tags) { tag = tag.trim(); if (tag.startsWith("p=")) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // decode public key, FSTODO: convert to DER format PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes()); RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec); } catch (NoSuchAlgorithmException nsae) { throw new DKIMSignerException("RSA algorithm not found by JVM"); } catch (InvalidKeySpecException ikse) { throw new DKIMSignerException( "The public key " + tag + " in RR " + recordname + " couldn't be decoded."); } // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair return true; } } throw new DKIMSignerException("No public key available in " + recordname); }
From source file:info.globalbus.dkim.DKIMUtil.java
public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); String recordname = selector + "._domainkey." + signingDomain; String value = null;/*from w w w . j a v a2 s . co m*/ try { DirContext dnsContext = new InitialDirContext(env); javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname, new String[] { "TXT" }); javax.naming.directory.Attribute txtrecord = attribs.get("txt"); if (txtrecord == null) { throw new DKIMSignerException("There is no TXT record available for " + recordname); } // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..." value = (String) txtrecord.get(); } catch (NamingException ne) { throw new DKIMSignerException("Selector lookup failed", ne); } if (value == null) { throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved"); } // try to read public key from RR String[] tags = value.split(";"); for (String tag : tags) { tag = tag.trim(); if (tag.startsWith("p=")) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // decode public key, FSTODO: convert to DER format PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes()); keyFactory.generatePublic(pubSpec); } catch (NoSuchAlgorithmException nsae) { throw new DKIMSignerException("RSA algorithm not found by JVM"); } catch (InvalidKeySpecException ikse) { throw new DKIMSignerException( "The public key " + tag + " in RR " + recordname + " couldn't be decoded."); } // FSTODO: create test signature with privKey and test // validation with pubKey to check on a valid key pair return true; } } throw new DKIMSignerException("No public key available in " + recordname); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets a personBean from LDAP// www. java 2 s . c om * * @param searchResult * @param loginAttributeName * @param firstNameAttributeName * @param lastNameAttributName * @param emailAttributeName * @param phoneAttributName * @return */ public static TPersonBean getPersonBean(SearchResult searchResult, String loginAttributeName, String firstNameAttributeName, String lastNameAttributName, String emailAttributeName, String phoneAttributName) { Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute loginAttribute = attributes.get(loginAttributeName); if (loginAttribute != null) { String loginName = (String) loginAttribute.get(); LOGGER.debug("Loginname: " + loginName); if (loginName == null || "".equals(loginName)) { LOGGER.info("No value for loginame attribute " + loginAttributeName); return null; } else { // loginname is mandatory for person personBean.setLoginName(loginName); } } else { LOGGER.info("No loginame attribute " + loginAttributeName); return null; } Attribute emailAttribute = attributes.get(emailAttributeName); if (emailAttribute != null) { String email = (String) emailAttribute.get(); LOGGER.debug("E-mail: " + email); if (email == null || "".equals(email)) { LOGGER.info("No value for e-mail attribute " + emailAttributeName); // e-mail is mandatory for person return null; } else { personBean.setEmail(email); } } else { LOGGER.info("No e-mail attribute " + emailAttributeName); return null; } Attribute firstNameAttribute = attributes.get(firstNameAttributeName); if (firstNameAttribute != null) { String firstName = (String) firstNameAttribute.get(); LOGGER.debug("Firstname: " + firstName); personBean.setFirstName(firstName); } Attribute lastNameAttribute = attributes.get(lastNameAttributName); if (lastNameAttribute != null) { String lastName = (String) lastNameAttribute.get(); LOGGER.debug("Lastname: " + lastName); if (lastName == null || "".equals(lastName)) { LOGGER.info("No value for lastname attribute " + lastNameAttributName); // lastname is mandatory for person return null; } else { personBean.setLastName(lastName); } } if (phoneAttributName != null) { Attribute phoneAttribute = attributes.get(phoneAttributName); if (phoneAttribute != null) { String phone = (String) phoneAttribute.get(); LOGGER.debug("Phone: " + phone); personBean.setPhone(phone); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn("This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return personBean; }
From source file:openscim.restful.server.resources.user.ldap.UserAttributesMapper.java
public Object mapFromAttributes(Attributes attributes) throws NamingException { // create a user resource User user = ResourceUtilities.FACTORY.createUser(); // get the uid attribute name String uidAtttributeName = properties.getProperty(UID_ATTRIBUTE, DEFAULT_UID_ATTRIBUTE); // get the uid //Attribute uidAttribute = attributes.get(uidAtttributeName); //if(uidAttribute != null) user.setId((String)uidAttribute.get()); // get the display name attribute name String displayAtttributeName = properties.getProperty(DISPLAYNAME_ATTRIBUTE, DEFAULT_DISPLAYNAME_ATTRIBUTE); // get the display name Attribute displayNameAttribute = attributes.get(displayAtttributeName); if (displayNameAttribute != null) user.setDisplayName((String) displayNameAttribute.get()); // create a user name resource Name name = ResourceUtilities.FACTORY.createName(); // get the surname attribute name String surnameAtttributeName = properties.getProperty(FAMILYNAME_ATTRIBUTE, DEFAULT_FAMILYNAME_ATTRIBUTE); // get the surname name Attribute surnameAttribute = attributes.get(surnameAtttributeName); if (surnameAttribute != null) name.setFamilyName((String) surnameAttribute.get()); // get the given name attribute name String givenAtttributeName = properties.getProperty(GIVENNAME_ATTRIBUTE, DEFAULT_GIVENNAME_ATTRIBUTE); // get the given name Attribute givenAttribute = attributes.get(givenAtttributeName); if (givenAttribute != null) name.setGivenName((String) givenAttribute.get()); // add the name to the user resource user.setName(name);//from w w w .ja va2s.co m // get the email attribute name String mailAtttributeName = properties.getProperty(MAIL_ATTRIBUTE, DEFAULT_MAIL_ATTRIBUTE); // get the mails if (attributes.get(mailAtttributeName) != null) { NamingEnumeration mailEnumeration = attributes.get(mailAtttributeName).getAll(); if (mailEnumeration != null) { // create a emails resource Emails emails = ResourceUtilities.FACTORY.createUserEmails(); while (mailEnumeration.hasMoreElements()) { // get the next email String mailAttribute = (String) mailEnumeration.next(); if (mailAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); pluralAttribute.setValue(mailAttribute); if (emails.getEmail().isEmpty()) pluralAttribute.setPrimary(true); else pluralAttribute.setPrimary(false); emails.getEmail().add(pluralAttribute); } } // add the mails to the user resource user.setEmails(emails); } } // get the telephone attribute name String telephoneAtttributeName = properties.getProperty(TELEPHONE_ATTRIBUTE, DEFAULT_TELEPHONE_ATTRIBUTE); // get the telephones if (attributes.get(telephoneAtttributeName) != null) { NamingEnumeration telephoneEnumeration = attributes.get(telephoneAtttributeName).getAll(); if (telephoneEnumeration != null) { // create a telephones resource PhoneNumbers telephones = ResourceUtilities.FACTORY.createUserPhoneNumbers(); while (telephoneEnumeration.hasMoreElements()) { // get the next telephone String telephoneAttribute = (String) telephoneEnumeration.next(); if (telephoneAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); pluralAttribute.setValue(telephoneAttribute); if (telephones.getPhoneNumber().isEmpty()) pluralAttribute.setPrimary(true); else pluralAttribute.setPrimary(false); telephones.getPhoneNumber().add(pluralAttribute); } } // add the telephones to the user resource user.setPhoneNumbers(telephones); } } // get the password attribute name String passwordAtttributeName = properties.getProperty(PASSWORD_ATTRIBUTE, DEFAULT_PASSWORD_ATTRIBUTE); // get the password Attribute passwordAttribute = attributes.get(passwordAtttributeName); if (passwordAttribute != null) user.setPassword(new String((byte[]) passwordAttribute.get())); // get the memberOf attribute name String memberOfAtttributeName = properties.getProperty(MEMBEROF_ATTRIBUTE, DEFAULT_MEMBEROF_ATTRIBUTE); // get the memberOf if (attributes.get(memberOfAtttributeName) != null) { NamingEnumeration memberOfEnumeration = attributes.get(memberOfAtttributeName).getAll(); if (memberOfEnumeration != null) { // create a memberof resource MemberOf memberof = ResourceUtilities.FACTORY.createUserMemberOf(); while (memberOfEnumeration.hasMoreElements()) { // get the next member String memberOfAttribute = (String) memberOfEnumeration.next(); if (memberOfAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); // check if the member dns need to be concealed if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { Matcher matcher = pattern.matcher(memberOfAttribute); if (matcher.matches()) { memberOfAttribute = matcher.group(1); } } pluralAttribute.setValue(memberOfAttribute); memberof.getGroup().add(pluralAttribute); } } // add the memberOf to the user resource user.setMemberOf(memberof); } } return user; }
From source file:LDAPTest.java
/** * Saves the changes that the user made. *//*w w w . j a va2 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:org.jasig.cas.authentication.principal.CredentialsToLDAPAttributePrincipalResolver.java
private String resolveFromLDAP(final String lookupAttributeValue) { final String searchFilter = LdapUtils.getFilterWithValues(getFilter(), lookupAttributeValue); if (log.isDebugEnabled()) { log.debug("LDAP search with filter \"" + searchFilter + "\""); }/*from w w w. jav a 2 s .c om*/ try { // searching the directory final String idAttribute = getAttributeIds()[0]; final List principalList = getLdapTemplate().search(getSearchBase(), searchFilter, getSearchControls(), new AttributesMapper() { public Object mapFromAttributes(final Attributes attrs) throws NamingException { final Attribute attribute = attrs.get(idAttribute); if (attribute == null) { log.debug("Principal attribute \"" + idAttribute + "\" " + "not found in LDAP search results. Returning null."); return null; } return attribute.get(); } }); if (principalList.isEmpty()) { log.debug("LDAP search returned zero results."); return null; } if (principalList.size() > 1) { log.error("LDAP search returned multiple results " + "for filter \"" + searchFilter + "\", " + "which is not allowed."); return null; } return (String) principalList.get(0); } catch (final Exception e) { log.error(e.getMessage(), e); return null; } }