List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user DN.//from w w w.j ava 2s . c o m * * @param uid the user id * @return the user DN for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException { String dn = null; String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } String uidValue = uidAttr.get().toString(); if (uidValue != null) { dn = sr.getName() + "," + usersCtxDN; if (logger.isDebugEnabled()) logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid + "' DN=" + dn); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + uid + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } return dn; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * attempts to get the users credentials from the users context * <p/>//from ww w . j av a 2 s . co m * NOTE: this is not an user authenticated operation * * @param username * @return * @throws LoginException */ @SuppressWarnings("unchecked") private String getUserCredentials(String username) throws LoginException { String ldapCredential = null; SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { Object[] filterArguments = { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } SearchResult result = findUser(username); Attributes attributes = result.getAttributes(); setDemographicAttributes(attributes); Attribute attribute = attributes.get(_userPasswordAttribute); if (attribute != null) { try { byte[] value = (byte[]) attribute.get(); ldapCredential = new String(value); } catch (NamingException e) { LOG.info("no password available under attribute: " + _userPasswordAttribute); } } } catch (NamingException e) { throw new LoginException("Root context binding failure."); } debug("user cred is present: " + (ldapCredential != null)); return ldapCredential; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected Organisation convertSearchResultToOrganization(final SearchResult sr) throws ExecutionException, NameNotFoundException { if (sr == null) { throw new ExecutionException("SearchResult sr == NULL", new NullPointerException()); }//from w w w . j ava 2s . c om Organisation vOrganisation = null; try { Attributes attributes = sr.getAttributes(); Attribute attr; String vStr; String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null ? String.valueOf(attr.get()) : null); String vName = sr.getName(); String vNameInNamespace = sr.getNameInNamespace(); // --- EntryDN String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null ? String.valueOf(attr.get()) : ""); int idx; // -- Parent node detections: String vParent = null; //vParent = sr.getName(); //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'"); //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'"); // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de' // -- getName() = 'o=99900711,o=00008125,o=00050350' //sr.getName(): 'o=00000116', //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de' vParent = sr.getNameInNamespace(); if ((idx = vParent.indexOf(",ou=")) >= 0) { vParent = vParent.substring(0, idx); } vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", ""); // -- 99900711,00008125,00050350' String[] vParents = vParent.split(","); if (vParents.length >= 2) { vParent = vParents[1]; } else { vParent = null; } LOG.log(Level.INFO, "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'"); /* * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName, * vDescription, vParent); */ if ((vEntryDN != null) && (!vEntryDN.isEmpty())) { vOrganisation = new Organisation(vEntryDN, (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null ? String.valueOf(attr.get()) : null); // Public-ID: (s.o.) // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) : // ""); // Parent (s.o.) vOrganisation.setOrgParent(vParent); // Kurzbeschreibung der Einrichtung vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null ? String.valueOf(attr.get()) : null); // -- Rechtsform try { vOrganisation.setBusinessCategory( (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get())) : null); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage()); vOrganisation.setStatus(null); } // -- Sub-Sectors: if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) { ConstEnumOrgSubSector vSubSector; NamingEnumeration<?> allSubSectors = attr.getAll(); while (allSubSectors.hasMore()) { try { vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next()); vOrganisation.addSubSectors(vSubSector); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage()); } } } // -- Funding Agency vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null ? String.valueOf(attr.get()) : null); // Name der Einrichtung vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null ? String.valueOf(attr.get()) : ""); // E-Mail vOrganisation.setEmail( (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get()) : null); // Telefonnummer vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null ? String.valueOf(attr.get()) : null); // -- FAX vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null ? String.valueOf(attr.get()) : null); // -- PLZ vOrganisation.getAddress() .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null ? String.valueOf(attr.get()) : ""); // -- City/Ortsname [l, localityName] if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) { vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get())); } else if ((attr = attributes.get("l")) != null) { vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get())); } // -- HouseIdentifier vOrganisation.getAddress() .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null ? String.valueOf(attr.get()) : ""); // -- Strasse vOrganisation.getAddress() .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null ? String.valueOf(attr.get()) : ""); // -- Bundesland [stateOrProvinceName, st] if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) { vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get())); } else if ((attr = attributes.get("st")) != null) { vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get())); } // -- Land [countryName, c] if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) { vOrganisation.getAddress().setCountryName(String.valueOf(attr.get())); } // -- AddressSuplement vOrganisation.getAddress() .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null ? String.valueOf(attr.get()) : ""); // -- Geokoordinaten try { vOrganisation.getAddress() .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null ? Double.valueOf(String.valueOf(attr.get())) : 0.0); } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage()); } try { vOrganisation.getAddress() .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null ? Double.valueOf(String.valueOf(attr.get())) : 0.0); } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage()); } vOrganisation.getAddress().setLocationDisplayName( (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null ? String.valueOf(attr.get()) : null); vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null ? String.valueOf(attr.get()) : null); vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null ? String.valueOf(attr.get()) : null); if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) { NamingEnumeration<?> allURLs = attr.getAll(); while (allURLs.hasMore()) { vOrganisation.addURLs((String) allURLs.next()); } } vOrganisation.setLogo( (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get()) : null); // -- org-Status: //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String // .valueOf(attr.get()) : ""); try { vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get())) : ConstEnumOrgStatus.pending); } catch (IllegalArgumentException ex) { LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage()); vOrganisation.setStatus(null); } vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null ? String.valueOf(attr.get()) : ""); try { // createTimestamp-Error: For input string: "20120620142810Z" // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ? // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1)); if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) { vStr = String.valueOf(attr.get()); vOrganisation.setCreated(convertLdapDateToLong(vStr)); } } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage()); } vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null ? String.valueOf(attr.get()) : ""); try { // modifyTimestamp-Error: For input string: "20120620142810Z" // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ? // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1)); if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) { vStr = String.valueOf(attr.get()); vOrganisation.setModified(convertLdapDateToLong(vStr)); } } catch (NumberFormatException ex) { LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage()); } if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) { vOrganisation.setProperties(serializer.deserialize((String) attr.get())); } } else { throw new NameNotFoundException(); } } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); throw new ExecutionException(ex.getMessage(), ex.getCause()); } catch (NameNotFoundException ex) { LOG.log(Level.SEVERE, null, ex); throw ex; } catch (NamingException ne) { LOG.log(Level.SEVERE, null, ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } return vOrganisation; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
protected String getIdForDn(LDAPSession session, String dn) { // the entry id is not based on the rdn, we thus need to // fetch the LDAP entry to grab it String[] attributeIdsToCollect = { session.idAttribute }; Attributes entry;/*w w w .j av a2s .co m*/ try { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getIdForDn(session, %s): LDAP get dn='%s'" + " attribute ids to collect='%s' [%s]", dn, dn, StringUtils.join(attributeIdsToCollect, ", "), this)); } Name name = new CompositeName().add(dn); entry = session.dirContext.getAttributes(name, attributeIdsToCollect); } catch (NamingException e) { return null; } // NXP-2461: check that id field is filled Attribute attr = entry.get(session.idAttribute); if (attr != null) { try { return attr.get().toString(); } catch (NamingException e) { } } return null; }
From source file:org.springframework.ldap.core.DirContextAdapter.java
/** * returns true if the attribute is empty. It is empty if a == null, size == * 0 or get() == null or an exception if thrown when accessing the get * method// w w w .j a v a 2 s . co m */ private boolean isEmptyAttribute(Attribute a) { try { return (a == null || a.size() == 0 || a.get() == null); } catch (NamingException e) { return true; } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private <T> T fromAttributesToIndirections(Class<T> clazz, Attributes attributes) throws NamingException { try {// w ww. j a v a2 s.c om OneMetaData oneMetaData = IndirectionsMetaData.get(clazz).getOne(); Attribute idAttr = attributes.get(oneMetaData.getIdAttr()); Attribute indirectionAttr = attributes.get(oneMetaData.getIndirectionAttr()); T indirections = null; try { indirections = clazz.newInstance(); String dnOfOne = oneMetaData.getIdAttr() + "=" + String.valueOf(idAttr.get()) + "," + oneMetaData.getContext(); // @One won't be multiple. oneMetaData.setter().set(indirections, dnOfOne); // @TheOther is always multiple. TheOtherMetaData theOtherMetaData = IndirectionsMetaData.get(clazz).getTheOther(); if (null != indirectionAttr) { theOtherMetaData.setter().set(indirections, new MoniteredList(AttrUtils.values(indirectionAttr))); } else { theOtherMetaData.setter().set(indirections, new MoniteredList()); } } catch (InstantiationException e) { LogUtils.error(LOG, "cannot instantiate " + clazz, e); } catch (IllegalAccessException e) { LogUtils.error(LOG, "cannot instantiate " + clazz, e); } return IndirectionsProxyFactory.getProxiedIndirections(indirections); } catch (NamingException e) { LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToIndirections"); throw e; } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected DocumentModel ldapResultToDocumentModel(SearchResult result, String entryId, boolean fetchReferences) throws DirectoryException, NamingException { Attributes attributes = result.getAttributes(); String passwordFieldId = getPasswordField(); Map<String, Object> fieldMap = new HashMap<String, Object>(); Attribute attribute = attributes.get(idAttribute); // NXP-2461: check that id field is filled + NXP-2730: make sure that // entry id is the one returned from LDAP if (attribute != null) { Object entry = attribute.get(); if (entry != null) { entryId = entry.toString();//from ww w . jav a2 s.c o m } } // NXP-7136 handle id case entryId = changeEntryIdCase(entryId, idCase); if (entryId == null) { // don't bother return null; } for (String fieldName : schemaFieldMap.keySet()) { List<Reference> references = directory.getReferences(fieldName); if (references != null && references.size() > 0) { if (fetchReferences) { Map<String, List<String>> referencedIdsMap = new HashMap<>(); for (Reference reference : references) { // reference resolution List<String> referencedIds; if (reference instanceof LDAPReference) { // optim: use the current LDAPSession directly to // provide the LDAP reference with the needed backend entries LDAPReference ldapReference = (LDAPReference) reference; referencedIds = ldapReference.getLdapTargetIds(attributes); } else if (reference instanceof LDAPTreeReference) { // TODO: optimize using the current LDAPSession // directly to provide the LDAP reference with the // needed backend entries (needs to implement getLdapTargetIds) LDAPTreeReference ldapReference = (LDAPTreeReference) reference; referencedIds = ldapReference.getTargetIdsForSource(entryId); } else { referencedIds = reference.getTargetIdsForSource(entryId); } referencedIds = new ArrayList<>(referencedIds); Collections.sort(referencedIds); if (referencedIdsMap.containsKey(fieldName)) { referencedIdsMap.get(fieldName).addAll(referencedIds); } else { referencedIdsMap.put(fieldName, referencedIds); } } fieldMap.put(fieldName, referencedIdsMap.get(fieldName)); } } else { // manage directly stored fields String attributeId = getDirectory().getFieldMapper().getBackendField(fieldName); if (attributeId.equals(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY)) { // this is the special DN readonly attribute try { fieldMap.put(fieldName, result.getNameInNamespace()); } catch (UnsupportedOperationException e) { // ignore ApacheDS partial implementation when running // in embedded mode } } else { // this is a regular attribute attribute = attributes.get(attributeId); if (fieldName.equals(passwordFieldId)) { // do not try to fetch the password attribute continue; } else { fieldMap.put(fieldName, getFieldValue(attribute, fieldName, entryId, fetchReferences)); } } } } // check if the idAttribute was returned from the search. If not // set it anyway, maybe changing its case if it's a String instance String fieldId = getDirectory().getFieldMapper().getDirectoryField(idAttribute); Object obj = fieldMap.get(fieldId); if (obj == null) { fieldMap.put(fieldId, changeEntryIdCase(entryId, getDirectory().getDescriptor().getMissingIdFieldCase())); } else if (obj instanceof String) { fieldMap.put(fieldId, changeEntryIdCase((String) obj, idCase)); } return fieldMapToDocumentModel(fieldMap); }
From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java
private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException { final Attributes attrs = sr.getAttributes(); final int size = attrs.size(); final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size); xmlb.openTag("searchresult"); // $NON-NLS-1$ xmlb.tag("dn", sr.getName()); // $NON-NLS-1$ xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$ xmlb.openTag("attributes"); // $NON-NLS-1$ try {/*from w w w . j a v a2 s . co m*/ for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) { final Attribute attr = en.next(); sortedAttrs.add(attr); } sortAttributes(sortedAttrs); for (final Attribute attr : sortedAttrs) { StringBuilder sb = new StringBuilder(); if (attr.size() == 1) { sb.append(getWriteValue(attr.get())); } else { final ArrayList<String> sortedVals = new ArrayList<>(attr.size()); boolean first = true; for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) { final Object value = getWriteValue(ven.next()); sortedVals.add(value.toString()); } Collections.sort(sortedVals); for (final String value : sortedVals) { if (first) { first = false; } else { sb.append(", "); // $NON-NLS-1$ } sb.append(value); } } xmlb.tag(attr.getID(), sb); } } finally { xmlb.closeTag("attributes"); // $NON-NLS-1$ xmlb.closeTag("searchresult"); // $NON-NLS-1$ } }
From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java
/** * Extracts Value out of LDAP Attribute/*from www.ja v a 2 s .c o m*/ * * * @param attribute LDAP Naming Attribute * @return String value of Attribute, null on Exception * * @throws NamingException */ private String getAttributeValue(Attribute attribute) { try { String attrValue = (String) attribute.get(); return attrValue; } catch (NamingException e) { log.error("NamingException when trying to get attribute value for attribute::" + attribute, e); return null; } }
From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java
/** * Ensure correct roles.// w w w. j a v a2 s . c o m */ @SuppressWarnings("unchecked") public void testRoles() throws Exception { // Mocks final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class); final Attributes attributes = this.createMock(Attributes.class); final Attribute attribute = this.createMock(Attribute.class); // Objects final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes); searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net"); // Record obtaining the Credential Entry this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net", "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), searchResult); // Record obtaining the Groups this.recordReturn(this.context, this.context.search("ou=Groups,dc=officefloor,dc=net", "(&(objectClass=groupOfNames)" + "(member=uid=daniel,ou=People,dc=officefloor,dc=net))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=developers", null, attributes)); this.recordReturn(attributes, attributes.get("ou"), attribute); this.recordReturn(attribute, attribute.get(), "developer"); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=founders", null, attributes)); this.recordReturn(attributes, attributes.get("ou"), attribute); this.recordReturn(attribute, attribute.get(), "founder"); this.recordReturn(searchResults, searchResults.hasMore(), false); // Test this.replayMockObjects(); CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM"); Set<String> roles = entry.retrieveRoles(); this.verifyMockObjects(); // Ensure correct roles assertEquals("Incorrect number of roles", 2, roles.size()); assertTrue("Must have developer role", roles.contains("developer")); assertTrue("Must have founder role", roles.contains("founder")); }