List of usage examples for javax.naming.directory Attributes getAll
NamingEnumeration<? extends Attribute> getAll();
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Gathers attributes from JNDI storage to the supplied attributes object. * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes) *//*w w w . java 2s.com*/ public void process(String sUserId, IAttributes oAttributes) throws AttributeException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); if (_listGather.size() > 0) { String[] saAttributes = _listGather.toArray(new String[0]); oScope.setReturningAttributes(saAttributes); } String searchFilter = resolveSearchQuery(sUserId); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(sUserId); _logger.error(sbFailed.toString(), e); throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown: " + sUserId); return; } if (oNamingEnumeration.hasMore()) { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oSearchedAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oSearchedAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); String sMappedName = _htMapper.get(sAttributeName); if (sMappedName != null) sAttributeName = sMappedName; if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); oAttributes.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; oAttributes.put(sAttributeName, oValue); } } } } catch (AttributeException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch attributes for user: " + sUserId, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e); } } } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *//*from www. j a v a2 s . c om*/ public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:fr.cls.atoll.motu.web.services.MotuOGCFrontController.java
/** * Method that returns an adapted version of the servlet config returned by the super method. Thus, the * {@link ServletContext#getRealPath(String)} is overriden to allow a nice resolution of a file among * external directories./* w w w . ja v a 2 s . com*/ * * @return the servlet context instance of this servlet. */ private ServletConfig wrapServletConfig(final ServletConfig sc) { return new ServletConfigAdapter(sc) { private ServletContextAdapter ctx = null; @Override public ServletContext getServletContext() { if (ctx == null) { ctx = new ServletContextAdapter(super.getServletContext()) { /** * First try to resolve the given location as a resource (using classpath extensions * if necessary). If this try fails, then let the process go on. */ @Override public String getRealPath(String name) { try { // try the classpath URL url = ConfigLoader.getInstance().get(name); if (url != null) { return url.toString(); } // try the current context naming // TODO: try to see if we can keep independence with the container ApplicationContext appCtx = null; if (ctx.getRootContext() instanceof ApplicationContextFacade) { Field privateStringField = ApplicationContextFacade.class .getDeclaredField("context"); privateStringField.setAccessible(true); Object context = privateStringField.get(ctx.getRootContext()); if ((context != null) && context instanceof ApplicationContext) { DirContext dc = ((ApplicationContext) context).getResources(); Attributes atts = dc.getAttributes(name); for (NamingEnumeration e = atts.getAll(); e.hasMore();) { final Attribute a = (Attribute) e.next(); if ("canonicalPath".equals(a.getID())) { String s = a.get().toString(); File f = new File(s); if (f.exists()) { return f.getAbsolutePath(); } } } } } throw new IllegalStateException("name " + name + " not resolved on classpath. Try default (servlet) resolution."); } catch (Exception e) { return super.getRealPath(name); } } }; } return ctx; } }; }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames) throws SubjectNotFoundException, SubjectNotUniqueException { Attributes attributes = null; Iterator<SearchResult> results = getLdapResults(search, searchValue, attributeNames); if (results == null || !results.hasNext()) { String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter") + " searchValue: " + searchValue; throw new SubjectNotFoundException(errMsg); }//from w ww . ja v a 2s .com SearchResult si = (SearchResult) results.next(); attributes = si.getAttributes(); if (results.hasNext()) { si = (SearchResult) results.next(); if (!multipleResults) { String errMsg = "Search is not unique:" + si.getName() + "\n"; throw new SubjectNotUniqueException(errMsg); } Attributes attr = si.getAttributes(); NamingEnumeration<? extends Attribute> n = attr.getAll(); try { while (n.hasMore()) { Attribute a = n.next(); log.debug("checking attribute " + a.getID()); if (attributes.get(a.getID()) == null) { log.debug("adding " + a.getID()); attributes.put(a); } } } catch (NamingException e) { log.error("ldap excp: " + e); } } return attributes; }
From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java
/** * Loads attributes for the argument subject. * @param subject // w w w. j a v a2 s.c om * @return the map */ protected Map loadAttributes(SubjectImpl subject) { Map<String, Set<String>> attributes1 = new HashMap<String, Set<String>>(); Search search = getSearch("searchSubject"); if (search == null) { log.error("searchType: \"search\" not defined."); return attributes1; } //setting attributeNames to null will cause all attributes for a subject to be returned String[] attributeNames = null; Set attributeNameSet = this.getAttributes(); if (attributeNameSet.size() == 0) { attributeNames = null; } else { attributeNames = new String[attributeNameSet.size()]; int i = 0; for (Iterator it = attributeNameSet.iterator(); it.hasNext(); attributeNames[i++] = (String) it.next()) ; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getId(), attributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String name1 = attr.getID(); Set<String> values = new HashSet<String>(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes1.put(name1, values); } subject.setAttributes(attributes1); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes1; }
From source file:com.openkm.principal.LdapPrincipalAdapter.java
@SuppressWarnings("unchecked") private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) { log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute }); List<String> al = new ArrayList<String>(); DirContext ctx = null;// w w w . j ava 2s.c om Hashtable<String, String> env = getEnvironment(); try { ctx = new InitialDirContext(env); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String searchBase : searchBases) { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attribute.equals("")) { StringBuilder sb = new StringBuilder(); for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.nextElement(); sb.append(attr.toString()); sb.append("\n"); } al.add(sb.toString()); } else { Attribute attrib = attributes.get(attribute); if (attrib != null) { // Handle multi-value attributes for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) { String value = (String) ne.nextElement(); // If FQDN get only main part if (value.startsWith("CN=") || value.startsWith("cn=")) { String cn = value.substring(3, value.indexOf(',')); log.debug("FQDN: {}, CN: {}", value, cn); al.add(cn); } else { al.add(value); } } } } } } } catch (ReferralException e) { log.error("ReferralException: {}", e.getMessage()); log.error("ReferralInfo: {}", e.getReferralInfo()); log.error("ResolvedObj: {}", e.getResolvedObj()); try { log.error("ReferralContext: {}", e.getReferralContext()); } catch (NamingException e1) { log.error("NamingException logging context: {}", e1.getMessage()); } } catch (NamingException e) { log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})", new Object[] { e.getMessage(), searchBases, searchFilter, attribute }); } finally { try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { log.error("NamingException closing context: {}", e.getMessage()); } } log.debug("ldapSearch: {}", al); return al; }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
/** * Try to get more attributes for the argument subject. (from name) *///w w w .j a v a 2 s.c o m protected Map getAllAttributes(LdapSubject subject) { Map attributes = new HashMap(); log.debug("getAllAttributes for " + subject.getName()); Search search = getSearch("searchSubjectAttributes"); if (search == null) { log.error("searchType: \"searchSubjectAttributes\" not defined."); return attributes; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getName(), allAttributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String attrName = attr.getID(); // special case the basic ones if (attrName.equals(subjectIDAttributeName)) continue; // already have if (attrName.equals(nameAttributeName)) continue; // already have if (attrName.equals(descriptionAttributeName)) { subject.setDescription((String) attr.get()); continue; } Set values = new HashSet(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes.put(attrName, values); } subject.setAttributes(attributes); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes; }
From source file:ldap.ActiveLoginImpl.java
/** * This does a light copy of an attributes list (such as a UserAccount, if we need to modify it but * want to keep the original userAccount) * @param oldAtts/* www. j av a 2s.c om*/ * @return a light copy of the original attributes list. */ public Attributes copyAttributes(Attributes oldAtts) { BasicAttributes atts = new BasicAttributes(); NamingEnumeration attList = oldAtts.getAll(); while (attList.hasMoreElements()) // shouldn't throw an exception, so use normal enumeration methods { Attribute att = (Attribute) attList.nextElement(); atts.put(att); } return atts; }
From source file:it.webappcommon.lib.LDAPHelper.java
/** * @param args/*from w ww. ja v a2 s . com*/ * the command line arguments */ // public static void main(String[] args) { private List<UserInfo> search(String filter) throws NamingException { DirContext ctx = null; SearchControls ctls = null; Properties env = new Properties(); List<UserInfo> res = new ArrayList<UserInfo>(); boolean trovatiRisultati = false; env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) { env.put(Context.SECURITY_PRINCIPAL, loginUserName); } else { env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName); } env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { ctx = new InitialDirContext(env); ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // String filter = ""; // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))"; // filter = FILTER_USERS_ACTIVE; // Tutti i membri di un gruppo // (objectCategory=user)(memberOf=CN=QA Users,OU=Help // Desk,DC=dpetri,DC=net) // ESEMPI // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm // Account disabled // (UserAccountControl:1.2.840.113556.1.4.803:=2) NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls); UserInfo userInfo = null; while (answer.hasMoreElements()) { trovatiRisultati = true; SearchResult a = answer.nextElement(); // logger.debug(a.getNameInNamespace()); Attributes result = a.getAttributes(); if (result == null) { // System.out.print("Attributi non presenti"); } else { NamingEnumeration<? extends Attribute> attributi = result.getAll(); userInfo = new UserInfo(); while (attributi.hasMoreElements()) { Attribute att = attributi.nextElement(); // logger.debug(att.getID()); String value = ""; // for (NamingEnumeration vals = att.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())) // ; NamingEnumeration<?> vals = att.getAll(); while (vals.hasMoreElements()) { Object val = vals.nextElement(); // logger.debug("\t" + val); value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString(); } if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) { // userInfo.setFIELD_ACCOUNT_NAME(value); userInfo.setAccount(value); } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) { // userInfo.setFIELD_COGNOME(value); userInfo.setCognome(value); } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) { // userInfo.setFIELD_EMAIL(value); userInfo.setEmail(value); } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) { // userInfo.setFIELD_GROUPS(value); userInfo.setGruppi(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) { // userInfo.setFIELD_NOME(value); userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) { // userInfo.setFIELD_NOME_COMPLETO(value); userInfo.setNomeCompleto(value); } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) { // userInfo.setFIELD_NOME_VISUALIZZATO(value); // userInfo.setNome(value); } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) { // userInfo.setFIELD_TEL(value); userInfo.setTel(value); } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) { // userInfo.setFIELD_UFFICIO(value); userInfo.setUfficio(value); } // res.put(att.getID(), value); } // Attribute attr = result.get("cn"); // if (attr != null) { // logger.debug("cn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("sn"); // if (attr != null) { // logger.debug("sn:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // attr = result.get("mail"); // if (attr != null) { // logger.debug("mail:"); // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // } // // // attr = result.get("uid"); // // if (attr != null) { // // logger.debug("uid:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } // // // // attr = result.get("userPassword"); // // if (attr != null) { // // logger.debug("userPassword:"); // // for (NamingEnumeration vals = attr.getAll(); // vals.hasMoreElements(); logger.debug("\t" + // vals.nextElement())); // // } if (userInfo != null) { res.add(userInfo); } } } } catch (NamingException ne) { // ne.printStackTrace(); logger.error(ne); throw ne; } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { } } // Azzero l'hash map if (!trovatiRisultati) { res = null; } return res; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static void parseData(NamingEnumeration searchResults) { int totalResultLogger = 0; if (searchResults == null) { return;// w w w . j a v a2 s. c om } // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return; } Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } }