List of usage examples for javax.naming.directory Attributes get
Attribute get(String attrID);
From source file:com.haulmont.cuba.security.app.LdapLoginWorker.java
protected Map<String, String> ldapAuthenticate(String login, String password, Locale locale) throws LoginException { if (!ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, buildPersonFilter(login), password, new LookupAttemptingCallback())) { throw new LoginException(getInvalidCredentialsMessage(login, locale)); }//from www . j a v a 2s .co m List result = ldapTemplate.search(DistinguishedName.EMPTY_PATH, buildPersonFilter(login), (Attributes attributes) -> { Map<String, String> map = new HashMap<>(); if (attributes.get("givenname") != null) { map.put("firstName", (String) attributes.get("givenname").get()); } if (attributes.get("sn") != null) { map.put("lastName", (String) attributes.get("sn").get()); } if (attributes.get("mail") != null) { map.put("email", (String) attributes.get("mail").get()); } return map; }); if (result.size() != 1) { throw new LoginException(getInvalidCredentialsMessage(login, locale)); } //noinspection unchecked return (Map<String, String>) result.get(0); }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Convert a Attributes to a EmailInformation object. *///from www . ja va2s . c om static EmailInformation getUserEmailInfo(String p_userId, Attributes p_entry) throws NamingException { StringBuffer sb = new StringBuffer(); Attribute attr = p_entry.get(LDAP_ATTR_FIRST_NAME); sb.append(getSingleAttributeValue(attr)); sb.append(BLANK); attr = p_entry.get(LDAP_ATTR_LAST_NAME); sb.append(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_EMAIL); String email = getSingleAttributeValue(attr); attr = p_entry.get(LDAP_ATTR_CC_EMAIL); String ccEmail = getSingleAttributeValue(attr); attr = p_entry.get(LDAP_ATTR_BCC_EMAIL); String bccEmail = getSingleAttributeValue(attr); attr = p_entry.get(LDAP_ATTR_DEFAULT_UI_LOCALE); String uiLocale = getSingleAttributeValue(attr); attr = p_entry.get(LDAP_ATTR_COMPANY); String companyName = getSingleAttributeValue(attr); // return new EmailInformation(p_userId, sb.toString(), email, // uiLocale, getUserTimeZone(p_userId)); EmailInformation eInfor = new EmailInformation(p_userId, sb.toString(), email, uiLocale, getUserTimeZone(p_userId)); eInfor.setCCEmailAddress(ccEmail); eInfor.setBCCEmailAddress(bccEmail); eInfor.setCompanyName(companyName); return eInfor; }
From source file:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java
/** * Encode some attributes as JSON./*from w w w .j a va 2 s . c om*/ * @param json The JSON object to insert into * @param attributes Collection of attributes */ public void toJson(final JSONObject json, final Attributes attributes) { Attribute attribute = attributes.get(attributeLabel); if (attribute == null) { LOGGER.debug("Missing attribute: " + attributeLabel); // just put an empty entry into the JSON try { if (allowMultiples) { json.put(jsonLabel, new JSONArray()); } else { json.put(jsonLabel, ""); } } catch (JSONException e) { logException(Level.ERROR, e); } return; } int numValues = attribute.size(); if (numValues == 0) { LOGGER.error("Attribute " + attributeLabel + " contains no values"); return; } try { if (allowMultiples) { JSONArray values = new JSONArray(); NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } values.put(value); } json.put(jsonLabel, values); } else { // expecting only one value if (numValues != 1) { LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues); return; } String value = attribute.get().toString(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } json.put(jsonLabel, value); } } catch (NamingException e) { logException(Level.ERROR, e); return; } catch (JSONException e) { logException(Level.ERROR, e); return; } }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
private MetricValue getMetric(Metric metric, String tree, String attr) throws MetricNotFoundException, NamingException { NamingEnumeration enumer = null; try {/* w ww. j a v a2 s . c o m*/ String[] a = { attr }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons); while (enumer.hasMore()) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); Attribute val; if (null != (val = attrs.get(attr))) { return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis()); } } throw new MetricNotFoundException(""); } finally { if (enumer != null) { enumer.close(); } } }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Convert a Attributes to a User object. *///from ww w .j a v a 2s. co m static User getUserFromLDAPEntry(Attributes p_entry) throws NamingException { User user = new UserImpl(); Attribute attr = p_entry.get(LDAP_ATTR_USERID); user.setUserId(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_TITLE); user.setTitle(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_FIRST_NAME); user.setFirstName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_PASSWORD); user.setPassword(getSinglePasswordAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_LAST_NAME); user.setLastName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_USER_NAME); user.setUserName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_STATUS); String status = getSingleAttributeValue(attr); user.setState(getStateAsInt(status)); attr = p_entry.get(LDAP_ATTR_ADDRESS); user.setAddress(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_COMPANY); user.setCompanyName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_EMAIL); user.setEmail(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_CC_EMAIL); user.setCCEmail(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_BCC_EMAIL); user.setBCCEmail(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_HOME_PHONE); user.setHomePhoneNumber(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_OFFICE_PHONE); user.setOfficePhoneNumber(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_FAX_NUMBER); user.setFaxPhoneNumber(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_CELL_NUMBER); user.setCellPhoneNumber(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_DEFAULT_UI_LOCALE); user.setDefaultUILocale(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_INALLPROJECTS); if (attr != null && getSingleAttributeValue(attr).equalsIgnoreCase(LDAP_ATTR_TRUE)) { // set to "false" as default - so only need to set to true // if value is "true" user.isInAllProjects(true); } attr = p_entry.get(LDAP_ATTR_TYPE); if (attr != null && getSingleAttributeValue(attr).equalsIgnoreCase(LDAP_ANONYMOUS_USER_TYPE)) { user.setType(User.UserType.ANONYMOUS); } else { user.setType(User.UserType.GLOBALSIGHT); } return user; }
From source file:py.una.pol.karaku.security.KarakuUserService.java
private List<KarakuPermission> loadAuthoritiesByDn(String uid) { List<KarakuPermission> listaRoles = new ArrayList<KarakuPermission>(); try {// w w w. ja v a 2 s . c o m DirContext ctx = getInitialDirContext(propertiesUtil.get(LDAP_ADMIN_KEY), propertiesUtil.get(LDAP_ADMIN_PASS_KEY)); Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute("member", getRealUsername(uid))); NamingEnumeration<SearchResult> answer = ctx.search("ou=permissions", matchAttrs); while (answer.hasMore()) { SearchResult searchResult = answer.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get("cn"); String rol = (String) attr.get(); KarakuPermission grantedAuthority = new KarakuPermission(rol); listaRoles.add(grantedAuthority); } return listaRoles; } catch (NamingException e) { LOG.warn("Can't create Ldap Context", e); return Collections.emptyList(); } }
From source file:com.surevine.ldap2alfresco.ProfileUpdater.java
/** * Update Alfresco user profile fields from LDAP user attributes. If any users * cannot be updated they are logged and skipped. * @param ldap To connect to LDAP//from w w w .j a v a2s .co m * @param alfresco To connect to Alfresco * @param allUsers Set to true to update all records, not just records changed since the last run * @param lastRun Timestamp of the last run (string representation as returned by LDAP server) * @throws LdapException On any LDAP errors * @throws AlfrescoException On any fatal Alfresco errors */ public void updateFromLdapToAlfresco(final LdapConnector ldap, final AlfrescoConnector alfresco, final boolean allUsers, final String lastRun) throws LdapException, AlfrescoException { // get groups Collection<Attributes> users = null; if (allUsers) { users = ldap.getAllUsers(); } else { users = ldap.getModifiedUsers(lastRun); } LOGGER.info("Found " + users.size() + " users to synchronise"); Iterator<Attributes> userIter = users.iterator(); while (userIter.hasNext()) { // get the user Attributes userAttributes = userIter.next(); Attribute cn = userAttributes.get("cn"); if (cn != null) { String username; try { username = cn.get().toString(); } catch (NamingException e1) { username = null; } if (username != null) { LOGGER.info("Synchronising " + username); JSONObject fields = new JSONObject(); // encode each profile field in turn Iterator<ProfileFieldConverter> fieldIter = profileFields.iterator(); while (fieldIter.hasNext()) { ProfileFieldConverter converter = fieldIter.next(); converter.toJson(fields, userAttributes); } try { alfresco.updateProfile(username, fields); } catch (AlfrescoException e) { recoverFromExceptionUser(ldap, e, username); } } } } }
From source file:org.apache.zeppelin.rest.GetUserList.java
/** * function to extract users from LDAP// ww w . j av a 2s . com */ 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.ktds.ldap.populator.AttributeCheckAttributesMapper.java
public Object mapFromAttributes(Attributes attributes) throws NamingException { Assert.assertEquals("Values and attributes need to have the same length ", expectedAttributes.length, expectedValues.length);// w w w . j a v a 2s . com for (int i = 0; i < expectedAttributes.length; i++) { Attribute attribute = attributes.get(expectedAttributes[i]); Assert.assertNotNull("Attribute " + expectedAttributes[i] + " was not present", attribute); Assert.assertEquals(expectedValues[i], attribute.get()); } for (String absentAttribute : absentAttributes) { Assert.assertNull(attributes.get(absentAttribute)); } return null; }
From source file:org.nuxeo.ecm.directory.ldap.dns.DNSServiceResolverImpl.java
/** * Returns the host name and port that a server providing the specified service can be reached at. A DNS lookup for * a SRV record in the form "_service.example.com" is attempted. * <p>//from w w w .jav a 2s . c om * As an example, a lookup for "example.com" for the service _gc._tcp may return "dc01.example.com:3268". * * @param service the service. * @param domain the domain. * @return a List of DNSServiceEntrys, which encompasses the hostname and port that the server can be reached at for * the specified domain. * @throws NamingException if the DNS server is unreachable */ protected List<DNSServiceEntry> resolveDnsServiceRecord(final String service, final String domain) throws NamingException { List<DNSServiceEntry> addresses = new ArrayList<>(); if (context == null) { return addresses; } final String key = service + "." + domain; /* * Return item from cache if it exists. */ if (System.currentTimeMillis() - lastCacheUpdate > maxDelay) { cache.clear(); } if (cache.containsKey(key)) { List<DNSServiceEntry> cachedAddresses = cache.get(key); if (cachedAddresses != null) { return cachedAddresses; } } Attributes dnsLookup = context.getAttributes(service + "." + domain, new String[] { SRV_RECORD }); Attribute attribute = dnsLookup.get(SRV_RECORD); for (int i = 0; i < attribute.size(); i++) { /* * Get the current resource record */ String entry = (String) attribute.get(i); String[] records = entry.split(" "); String host = records[records.length - 1]; int port = Integer.parseInt(records[records.length - 2]); int weight = Integer.parseInt(records[records.length - 3]); int priority = Integer.parseInt(records[records.length - 4]); /* * possible to get TTL? */ /* * Host entries in DNS should end with a "." */ if (host.endsWith(".")) { host = host.substring(0, host.length() - 1); } addresses.add(new DNSServiceEntry(host, port, priority, weight)); } /* * Sort the addresses by DNS priority and weight settings */ Collections.sort(addresses); /* * Add item to cache. */ if (cache.size() > 100) { cache.clear(); } cache.put(key, addresses); lastCacheUpdate = System.currentTimeMillis(); return addresses; }