List of usage examples for javax.naming NamingEnumeration hasMoreElements
boolean hasMoreElements();
From source file:org.viafirma.util.ConfigUtil.java
/** * Recupera el conjunto de propiedades que utiliza la aplicacin. * @param context//from w w w. j av a 2 s . co m * @return */ public String readConfigProperty(String property) { Context initCtx; try { initCtx = new InitialContext(); Context contextInit = (Context) initCtx.lookup("java:comp/env"); // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list(""); while (propiedadesJDNI.hasMoreElements()) { NameClassPair propiedad = propiedadesJDNI.nextElement(); if (property.equalsIgnoreCase(propiedad.getName())) { // propiedad encontrada Object temp = contextInit.lookup(propiedad.getName()); if (temp instanceof String) { String valor = (String) temp; return valor; } } } } catch (Exception e) { throw new ExceptionInInitializerError( "No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible." + e.getMessage()); } log.fatal("No se pueden recuperar el parametro de configuracin " + property + " de configuracin. JNDI parece no estar disponible."); return null; }
From source file:org.viafirma.util.ConfigUtil.java
/** * Recupera el conjunto de propiedades que utiliza la aplicacin. * @param context//from w ww . j a v a 2s.c om * @return */ public Properties readConfigPropertes() { Properties properties = new Properties(); Context initCtx; try { initCtx = new InitialContext(); Context contextInit = (Context) initCtx.lookup("java:comp/env"); // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list(""); while (propiedadesJDNI.hasMoreElements()) { NameClassPair propiedad = propiedadesJDNI.nextElement(); Object temp = contextInit.lookup(propiedad.getName()); if (temp instanceof String) { String valor = (String) temp; System.out.println("\t\t\t" + propiedad.getName() + "=" + valor); properties.put(propiedad.getName(), valor); } } } catch (Exception e) { log.fatal("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible.", e); throw new ExceptionInInitializerError( "No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible." + e.getMessage()); } return properties; }
From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java
protected String getNameInSpaceForUserName(String userName) throws UserStoreException { DirContext dirContext;//from w ww.ja v a2 s . c o m String usernameSearchFilter = realmConfig.getUserStoreProperty("UserNameListFilter"); String userNameProperty = realmConfig.getUserStoreProperty("UserNameAttribute"); String searchFilter = getSearchFilter(usernameSearchFilter, userNameProperty, userName); if (log.isDebugEnabled()) { log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString()); } dirContext = ldapConnectionSource.getContext(); NamingEnumeration answer = null; String userDn; try { String name = null; answer = searchForObject(searchFilter, null, dirContext, realmConfig.getUserStoreProperty("UserSearchBase")); int count = 0; SearchResult userObj; SearchResult sr; for (userObj = null; answer.hasMoreElements(); userObj = sr) { sr = (SearchResult) answer.next(); if (count > 0) { log.error("More than one user exist for the same name"); } count++; } if (userObj != null) { name = userObj.getNameInNamespace(); } userDn = name; } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDn; }
From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java
protected String[] getTenantDomains(String userDN) throws UserStoreException { DirContext dirContext;/*from w w w . j av a2 s .c o m*/ String groupNameSearchFilter = realmConfig.getUserStoreProperty("GroupNameListFilter"); String groupNameProperty = realmConfig.getUserStoreProperty("MembershipAttribute"); String searchFilter = getSearchFilter(groupNameSearchFilter, groupNameProperty, userDN); Set<String> list = new HashSet<String>(); if (log.isDebugEnabled()) { log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString()); } dirContext = ldapConnectionSource.getContext(); NamingEnumeration answer = null; String domainsStrs[]; try { String dn; String domain; answer = searchForObject(searchFilter, null, dirContext, tenantMgtConfig.getTenantStoreProperties().get("RootPartition")); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); dn = sr.getNameInNamespace(); domain = getOrganizationalContextName(dn); if (domain != null) { list.add(domain); } } domainsStrs = list.toArray(new String[list.size()]); } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return domainsStrs; }
From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java
public static String getUserIdFromEmail(String email, LDAPConnectionContext connectionSource, String userSearchBase) throws UserStoreException { // if it is not an email, just return it as the uid. if (!email.contains("@")) { return email; }// www .j a v a 2 s . c o m // check from cache String userId = otUserIdCache.getValueFromCache(email); if (userId != null && !userId.isEmpty()) { return userId; } // check from ldap and update the cache StringBuffer buff = new StringBuffer(); buff.append("(&(objectClass=inetOrgPerson)(mail=").append(email).append("))"); if (log.isDebugEnabled()) { log.debug("Searching for " + buff.toString()); } DirContext dirContext = connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { String name = null; answer = searchForUser(buff.toString(), null, dirContext, userSearchBase); int count = 0; SearchResult userObj = null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (count > 0) { log.error("More than one user exist for the same name"); } count++; userObj = sr; } if (userObj != null) { name = userObj.getName(); if (name != null) { name = name.replaceFirst("uid=", ""); } } otUserIdCache.addToCache(email, name); return name; } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java
public static String getEmailFromUserId(String uid, LDAPConnectionContext connectionSource, String userSearchBase) throws UserStoreException { // check from cache String email = otEmailCache.getValueFromCache(uid); if (email != null && !email.isEmpty()) { return email; }/*w w w.j a v a 2s . c o m*/ // check from ldap and update the cache StringBuffer buff = new StringBuffer(); buff.append("(&(objectClass=inetOrgPerson)(uid=").append(uid).append("))"); if (log.isDebugEnabled()) { log.debug("Searching for " + buff.toString()); } DirContext dirContext = connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { String[] returnedAttributes = { "mail" }; answer = searchForUser(buff.toString(), returnedAttributes, dirContext, userSearchBase); int count = 0; SearchResult userObj = null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (count > 0) { log.error("More than one user exist for the same name"); } count++; userObj = sr; } if (userObj != null) { Attributes attributes = userObj.getAttributes(); Attribute mailAttribute = attributes.get("mail"); if (mailAttribute != null) { email = mailAttribute.getID(); } } otEmailCache.addToCache(uid, email); return email; } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } }
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 w ww. j a v a2 s . co 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:org.wso2.carbon.connector.ldap.SearchEntry.java
private OMElement prepareNode(SearchResult entityResult, OMFactory factory, OMNamespace ns, String returnAttributes[]) throws NamingException { Attributes attributes = entityResult.getAttributes(); Attribute attribute;//w w w. j a va 2 s .c om OMElement entry = factory.createOMElement(LDAPConstants.ENTRY, ns); OMElement dnattr = factory.createOMElement(LDAPConstants.DN, ns); dnattr.setText(entityResult.getNameInNamespace()); entry.addChild(dnattr); for (int i = 0; i < returnAttributes.length; i++) { attribute = attributes.get(returnAttributes[i]); if (attribute != null) { NamingEnumeration ne = null; ne = attribute.getAll(); while (ne.hasMoreElements()) { String value = (String) ne.next(); OMElement attr = factory.createOMElement(returnAttributes[i], ns); attr.setText(value); entry.addChild(attr); } } } return entry; }
From source file:org.wso2.carbon.connector.ldap.SearchEntry.java
private SearchResult makeSureOnlyOneMatch(NamingEnumeration<SearchResult> results) { SearchResult searchResult = null; if (results.hasMoreElements()) { searchResult = (SearchResult) results.nextElement(); // Make sure there is not another item available, there should be only 1 match if (results.hasMoreElements()) { // Here the code has matched multiple objects for the searched target return null; }// w w w . j a v a2s . c o m } return searchResult; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException { ServerPrinciple[] serverNames = null; int maxItemLimit = Integer.parseInt( this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { log.error("Invalid search character " + filter); throw new DirectoryServerManagerException( "Invalid character sequence entered for service principle search. Please enter valid sequence."); }//from w ww .jav a 2 s. c o m StringBuilder searchFilter; searchFilter = new StringBuilder( this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); StringBuilder buff = new StringBuilder(); buff.append("(&").append(searchFilter).append("(") .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter) .append(")").append(getServerPrincipleIncludeString()).append(")"); String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE, LDAPServerManagerConstants.LDAP_COMMON_NAME }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; try { dirContext = connectionSource.getContext(); NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<ServerPrinciple> list = new ArrayList<ServerPrinciple>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { Attribute serverNameAttribute = sr.getAttributes() .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE); Attribute serverDescription = sr.getAttributes() .get(LDAPServerManagerConstants.LDAP_COMMON_NAME); if (serverNameAttribute != null) { ServerPrinciple principle; String serviceName; String serverPrincipleFullName = (String) serverNameAttribute.get(); if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH) .contains(LDAPServerManagerConstants.KERBEROS_TGT)) { continue; } if (serverPrincipleFullName.contains("@")) { serviceName = serverPrincipleFullName.split("@")[0]; } else { serviceName = serverPrincipleFullName; } if (serverDescription != null) { principle = new ServerPrinciple(serviceName, (String) serverDescription.get()); } else { principle = new ServerPrinciple(serviceName); } list.add(principle); i++; } } } serverNames = list.toArray(new ServerPrinciple[list.size()]); Arrays.sort(serverNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } catch (UserStoreException e) { log.error("Unable to retrieve LDAP connection context.", e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return serverNames; }