List of usage examples for javax.naming.ldap Control CRITICAL
boolean CRITICAL
To view the source code for javax.naming.ldap Control CRITICAL.
Click Source Link
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// w w w . ja va 2s .co m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); 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 groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } 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"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } return ldapGroupsMap; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in * the directory und the DN configured in the Genji server configuration. * /* w w w . j a v a2 s. co m*/ * @return Map with <login name, TPersonBean> */ public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter) throws Exception { if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = siteBean.getLdapAttributeLoginName() + "=*"; } if (!(filter.startsWith("(") && filter.endsWith(")"))) { filter = "(" + filter + ")"; } LOGGER.debug("User filter expression " + filter); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>(); LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword); if (context == null) { return ldapPersonsMap; } int recordCount = 0; // Create initial context // Control the search SearchControls ctls = null; try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return null; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); String loginAttributeName = siteBean.getLdapAttributeLoginName(); do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", filter, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { ldapPersonsMap.put(personBean.getLoginName(), personBean); } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (context != null) { context.close(); } } return ldapPersonsMap; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group//from w w w. j ava 2s . co m * * @param groups * @param siteBean * @param filter * @return * @throws Exception */ static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String filter) throws Exception { List<TPersonBean> personBeans = new ArrayList<TPersonBean>(); if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = loginAttributeName + "=*"; } int recordCount = 0; SearchControls ctls = null; LdapContext ctx = null; try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { return personBeans; } // Activate paged results int pageSize = 5; // TODO replace for GROOVY ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; String searchStr = "(" + filter + ")"; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return personBeans; } String firstNameAttributeName = ldapMap.get("firstName"); String lastNameAttributName = ldapMap.get("lastName"); String emailAttributeName = ldapMap.get("email"); String phoneAttributName = ldapMap.get("phone"); byte[] cookie = null; // TODO replace for GROOVY cookie = new byte[] {}; // cookie = [] as byte[]; while (cookie != null) { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { personBeans.add(personBean); ++recordCount; } } // Examine the paged results control response Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results // TODO replace for GROOVY ctx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (ctx != null) { ctx.close(); } } return personBeans; }
From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java
private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize, AuthenticationDiagnostic diagnostic) throws AuthenticationException { String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL); String providerURL = env.get(Context.PROVIDER_URL); if (isSSLSocketFactoryRequired()) { KeyStore trustStore = initTrustStore(); AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName()); }/*from ww w . j a va 2s . co m*/ if (diagnostic == null) { diagnostic = new AuthenticationDiagnostic(); } try { // If a page size has been requested, use LDAP v3 paging if (pageSize > 0) { InitialLdapContext ctx = new InitialLdapContext(env, null); ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) }); return ctx; } else { InitialDirContext ret = new InitialDirContext(env); Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); return ret; } } catch (javax.naming.AuthenticationException ax) { Object[] args1 = { securityPrincipal }; Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1); // wrong user/password - if we get this far the connection is O.K Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax); } catch (CommunicationException ce) { Object[] args1 = { providerURL }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1); StringBuffer message = new StringBuffer(); message.append(ce.getClass().getName() + ", " + ce.getMessage()); Throwable cause = ce.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect Object[] args = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause); } catch (NamingException nx) { Object[] args = { providerURL }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args); StringBuffer message = new StringBuffer(); message.append(nx.getClass().getName() + ", " + nx.getMessage()); Throwable cause = nx.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect Object[] args1 = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx); } catch (IOException e) { Object[] args = { providerURL, securityPrincipal }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); throw new AuthenticationException("Unable to encode LDAP v3 request controls", e); } }
From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java
public boolean hasNextPage(DirContext ctx, int pageSize) { if (pageSize > 0) { try {// w w w.ja v a2 s . c om LdapContext ldapContext = (LdapContext) ctx; Control[] controls = ldapContext.getResponseControls(); // Retrieve the paged result cookie if there is one if (controls != null) { for (Control control : controls) { if (control instanceof PagedResultsResponseControl) { byte[] cookie = ((PagedResultsResponseControl) control).getCookie(); if (cookie != null) { // Prepare for next page ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); return true; } } } } } catch (NamingException nx) { throw new AuthenticationException("Unable to connect to LDAP Server; check LDAP configuration", nx); } catch (IOException e) { throw new AuthenticationException( "Unable to encode LDAP v3 request controls; check LDAP configuration", e); } } return false; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }//w ww.ja va 2 s. c om byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result)); } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java
@Override public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }//from w w w. ja va 2 s . c o m byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); if (!isUserDisabled(result)) { users.add(createUser(result)); } } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:org.apache.ranger.ldapconfigcheck.LdapConfigCheckMain.java
public static void main(String[] args) { CommandLineOptions cli = new CommandLineOptions(args); cli.parse();//from w ww . j a v a 2 s. c om String inFileName = cli.getInput(); String outputDir = cli.getOutput(); if (!outputDir.endsWith("/")) { outputDir = outputDir.concat("/"); } LdapConfig config = new LdapConfig(inFileName, cli.getBindPassword()); if (cli.getLdapUrl() != null && !cli.getLdapUrl().isEmpty()) { config.updateInputPropFile(cli.getLdapUrl(), cli.getBindDn(), cli.getBindPassword(), cli.getUserSearchBase(), cli.getUserSearchFilter(), cli.getAuthUser(), cli.getAuthPass()); } PrintStream logFile = null; PrintStream ambariProps = null; PrintStream installProps = null; LdapContext ldapContext = null; try { logFile = new PrintStream(new File(outputDir + LOG_FILE)); ambariProps = new PrintStream(new File(outputDir + AMBARI_PROPERTIES)); installProps = new PrintStream(new File(outputDir + INSTALL_PROPERTIES)); UserSync userSyncObj = new UserSync(config, logFile, ambariProps, installProps); String bindDn = config.getLdapBindDn(); Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, config.getLdapUrl()); env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, cli.getBindPassword()); env.put(Context.SECURITY_AUTHENTICATION, config.getLdapAuthenticationMechanism()); env.put(Context.REFERRAL, "follow"); ldapContext = new InitialLdapContext(env, null); if (config.isPagedResultsEnabled()) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(config.getPagedResultsSize(), Control.CRITICAL) }); } String retrieveValues = "all"; if (cli.getDiscoverProperties() != null) { retrieveValues = cli.getDiscoverProperties(); if (cli.getDiscoverProperties().equalsIgnoreCase("users")) { userSyncObj.findUserProperties(ldapContext); } else if (cli.getDiscoverProperties().equalsIgnoreCase("groups")) { userSyncObj.findGroupProperties(ldapContext); } else { findAllUserSyncProperties(ldapContext, userSyncObj); } } else if (cli.getRetrieveValues() != null) { retrieveValues = cli.getRetrieveValues(); } else { cli.help(); } if (cli.isAuthEnabled()) { authenticate(userSyncObj, config, logFile, ambariProps, installProps); } retrieveUsersGroups(ldapContext, userSyncObj, retrieveValues); if (ldapContext != null) { ldapContext.close(); } } catch (FileNotFoundException fe) { System.out.println(fe.getMessage()); } catch (IOException ioe) { logFile.println("ERROR: Failed while setting the paged results controls\n" + ioe); } catch (NamingException ne) { System.out.println("ERROR: Failed to perfom ldap bind. Please verify values for " + "ranger.usersync.ldap.binddn and ranger.usersync.ldap.ldapbindpassword\n" + ne); } catch (Throwable t) { if (logFile != null) { logFile.println("ERROR: Connection failed: " + t.getMessage()); } else { System.out.println("ERROR: Connection failed: " + t.getMessage()); } } finally { if (logFile != null) { logFile.close(); } if (ambariProps != null) { ambariProps.close(); } if (installProps != null) { installProps.close(); } try { if (ldapContext != null) { ldapContext.close(); } } catch (NamingException ne) { System.out.println("Failed to close LdapContext!"); } } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getUsers(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> userSearchResultEnum = null; NamingEnumeration<SearchResult> groupSearchResultEnum = null; try {//from w w w . j a v a2s . c o m createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))"; if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) { String customFilter = userSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")"; } else { extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")"; } LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter); long highestdeltaSyncUserTime = deltaSyncUserTime; // When multiple OUs are configured, go through each OU as the user search base to search for users. for (int ou = 0; ou < userSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter, userSearchControls); while (userSearchResultEnum.hasMore()) { // searchResults contains all the user entries final SearchResult userEntry = userSearchResultEnum.next(); if (userEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("userEntry null, skipping sync for the entry"); } continue; } //System.out.println("userEntry = " + userEntry); Attributes attributes = userEntry.getAttributes(); if (attributes == null) { if (LOG.isInfoEnabled()) { LOG.info("attributes missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute userNameAttr = attributes.get(userNameAttribute); if (userNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } String userFullName = (userEntry.getNameInNamespace()).toLowerCase(); String userName = (String) userNameAttr.get(); if (userName == null || userName.trim().isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " empty for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute timeStampAttr = attributes.get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; } } else { timeStampAttr = attributes.get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; deltaSyncUserTimeStamp = timeStampVal; } } } if (!groupSearchFirstEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName); userNameMap.put(userFullName, transformUserName); Set<String> groups = new HashSet<String>(); // Get all the groups from the group name attribute of the user only when group search is not enabled. if (!groupSearchEnabled) { for (String useGroupNameAttribute : userGroupNameAttributeSet) { Attribute userGroupfAttribute = userEntry.getAttributes() .get(useGroupNameAttribute); if (userGroupfAttribute != null) { NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll(); while (groupEnum.hasMore()) { String gName = getShortGroupName((String) groupEnum.next()); String transformGroupName = groupNameTransform(gName); groups.add(transformGroupName); } } } } List<String> groupList = new ArrayList<String>(groups); try { sink.addOrUpdateUser(transformUserName, groupList); } catch (Throwable t) { LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage() + ", for user: " + transformUserName + " and groups: " + groupList); } counter++; if (counter <= 2000) { if (LOG.isInfoEnabled()) { LOG.info("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } if (counter == 2000) { LOG.info( "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <==="); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } else { if (counter % 100 == 0) { LOG.info("Synced " + counter + " users till now"); } } } } else { // If the user from the search result is present in the group user table, // then addorupdate user to ranger admin. LOG.debug("Chekcing if the user " + userFullName + " is part of the retrieved groups"); if (groupUserTable.containsColumn(userFullName) || groupUserTable.containsColumn(userName)) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(userFullName, transformUserName); //Also update the username in the groupUserTable with the one from username attribute. Map<String, String> userMap = groupUserTable.column(userFullName); for (Map.Entry<String, String> entry : userMap.entrySet()) { LOG.debug("Updating groupUserTable " + entry.getValue() + " with: " + transformUserName + " for " + entry.getKey()); groupUserTable.put(entry.getKey(), userFullName, transformUserName); } } } } // Examine the paged results control response Control[] controls = ldapContext.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter); } } if (deltaSyncUserTime < highestdeltaSyncUserTime) { // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncUserTime = highestdeltaSyncUserTime + 1; // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle. deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l)); } } finally { if (userSearchResultEnum != null) { userSearchResultEnum.close(); } if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getGroups(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> groupSearchResultEnum = null; DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); long highestdeltaSyncGroupTime = deltaSyncGroupTime; try {//from www .j av a 2s . c om createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter; } extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>=" + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))"; LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], extendedAllGroupsSearchFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } String gName = (String) groupNameAttr.get(); String transformGroupName = groupNameTransform(gName); // If group based search is enabled, then // update the group name to ranger admin // check for group members and populate userInfo object with user's full name and group mapping if (groupSearchFirstEnabled) { LOG.debug("Update Ranger admin with " + transformGroupName); sink.addOrUpdateGroup(transformGroupName); } Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; } } else { timeStampAttr = groupEntry.getAttributes().get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; deltaSyncGroupTimeStamp = timeStampVal; } } } Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; String userName = getShortUserName(originalUserFullName); originalUserFullName = originalUserFullName.toLowerCase(); if (groupSearchFirstEnabled && !userSearchEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(originalUserFullName, transformUserName); } //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // Examine the paged results control response Control[] controls = ldapContext.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter); } } } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } if (groupHierarchyLevels > 0) { LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime); if (deltaSyncGroupTime > 0) { LOG.info( "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync"); goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1); } } if (deltaSyncGroupTime < highestdeltaSyncGroupTime) { // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncGroupTime = highestdeltaSyncGroupTime + 1; // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle. deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l)); } }