List of usage examples for javax.naming.directory DirContext close
public void close() throws NamingException;
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private String performRoleSearch(String location, String roleName) { String val = null; try {// w ww . ja va 2 s . c o m DirContext dc = new InitialDirContext(env); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); //String filter = "(" + filterPrefix + roleName + ")"; NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc); if (ne.hasMore()) { val = getAttrValue("memberOf", ne.next()); } ne.close(); dc.close(); } catch (NamingException ne) { log.warn("Failed LDAP lookup getAttr", ne); log.warn("roleName:", roleName); log.warn("location:", location); } return val; }
From source file:org.apache.archiva.redback.rbac.ldap.LdapRbacManager.java
protected void closeContext(DirContext context) { if (context != null) { try {//from ww w. j a va2 s . c o m context.close(); } catch (NamingException e) { log.warn("skip issue closing context: {}", e.getMessage()); } } }
From source file:ru.efo.security.ADUserDetailsService.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final String username = authentication.getName(); final String password = authentication.getCredentials().toString(); logger.log(Level.FINE, "Performing logon into '" + ldapUrl + "' with credentials '" + username + "'/'" + password.replaceAll(".", "*") + "'"); DirContext context = null; try {/*ww w .ja v a 2 s . c om*/ context = getDirContext(username + userSuffix, password); logger.log(Level.FINE, "User '" + username + "' has been successfully logged on"); final ADUserDetails details = loadUserByUsername(context, username, password); return new UsernamePasswordAuthenticationToken(details, password, details.getAuthorities()); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not login into '" + ldapUrl + "'", ex); throw new BadCredentialsException(ex.getMessage()); } finally { if (context != null) { try { context.close(); } catch (NamingException ex) { logger.log(Level.WARNING, "Could not close DirContext", ex); } } } }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
protected boolean userExists(String id) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try {/*from w w w. j a v a 2s . c o m*/ DirContext ctx = new InitialDirContext(env); /* * Setup subtree scope to tell LDAP to recursively descend directory structure during searches. */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* * Setup the directory entry attributes we want to search for. In this case it is the user's ID. */ String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))"; /* Execute the search, starting at the directory level of Users */ NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls); /* All we need to know is if there were any hits at all. */ if (hits.hasMore()) { hits.close(); ctx.close(); return true; } else { hits.close(); ctx.close(); return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Set next free uidNumber.//from www. j a v a 2 s . com */ private void setNextUidNumber() { Hashtable<String, String> env = getLdapConnectionSettings(); env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); DirContext ctx; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId")); Attribute la = attrs.get("uidNumber"); String oldValue = (String) la.get(0); int bla = Integer.parseInt(oldValue) + 1; BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla)); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu); ctx.modifyAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"), mods); ctx.close(); } catch (NamingException e) { logger.error(e); } }
From source file:edu.lafayette.metadb.model.userman.UserManDAO.java
/** * Get the LDAP DN for a user./* ww w .j av a 2s. c o m*/ * @param searchUser * @param searchPassword * @param userName * @return */ @SuppressWarnings("unchecked") private static String getDN(String searchUser, String searchPassword, String userName) { // The resultant DN String result; // Set up environment for creating initial context Hashtable env = new Hashtable(11); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL); // Use admin credencials for search// Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser); env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword); DirContext ctx = null; try { // Create initial context ctx = new InitialDirContext(env); //MetaDbHelper.note("Created LDAP context"); Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName)); //MetaDbHelper.note("Created attributes"); // look up attributes try { //MetaDbHelper.note("Setting up query"); SearchControls ctrls = new SearchControls(); ctrls.setSearchScope(Global.LDAP_SCOPE); NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT, "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls); //MetaDbHelper.note("NamingEnumeration retrieved"); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) { result = sr.getName(); } else { result = (sr.getName() + "," + Global.LDAP_CONTEXT); } //MetaDbHelper.note("Got DN: "+result); return result; } } catch (NamingException e) { MetaDbHelper.logEvent(e); //MetaDbHelper.note("LDAP Error: Failed Search"); } } catch (NamingException e) { MetaDbHelper.logEvent(e); //MetaDbHelper.note("LDAP Error: Failed authentication"); } finally { // Close the context when we're done try { if (ctx != null) ctx.close(); } catch (NamingException e) { } } // No DN match found return null; }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;/* ww w .ja v a 2s .co m*/ String firstName = null; String lastName = null; String employeenumber = null; String email = null; try { DirContext ctx = new InitialDirContext(env); // Setup subtree scope to tell LDAP to recursively descend directory structure // during searches. SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // We want the user's id, first name and last name ... searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" }); // Execute the search, starting at the directory level of Users NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls); while (results.hasMore()) { SearchResult result = (SearchResult) results.next(); String dn = result.getName().toString() + "," + getBasePath(); Attributes attrs = ctx.getAttributes(dn); id = attrs.get("uid").get().toString(); String cn = attrs.get("cn").get().toString(); firstName = cn.substring(0, cn.indexOf(" ")); lastName = cn.substring(cn.indexOf(" ")); email = attrs.get("mail").get().toString(); } results.close(); ctx.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } edit.setId(id); edit.setFirstName(firstName); edit.setLastName(lastName); edit.setEmail(email); return true; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns the CN (common name) for a given login name * /*w w w. j a va 2s.com*/ * @param loginName * the loginName of the user * @return CN as a String(if found), or null (else) */ private static String getCn(TSiteBean siteBean, String loginName) throws NamingException { String keyDn = null; DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(), siteBean.getLdapBindPassword()); if (ctx != null) { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for the user-id String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")"; NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls); if (answer.hasMore()) { // retrieve the CN SearchResult sr = answer.next(); keyDn = sr.getName();// + "," + ctx.getNameInNamespace(); LOGGER.debug("Name = " + keyDn); String nameInNamespace = ctx.getNameInNamespace(); LOGGER.debug("Name in namespace " + nameInNamespace); if (nameInNamespace != null && nameInNamespace.trim().length() > 0) { keyDn += "," + ctx.getNameInNamespace(); } LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!"); answer.close(); // wo don't need more answers } else { LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!"); } ctx.close(); } return keyDn; }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will return the LDAP schema associated with the supplied dn. The * resulting <code>Iterator</code> is a deep copy of the original search * results. See {@link javax.naming.DirContext#getSchema(String)}. * * @param dn <code>String</code> named object in the LDAP * * @return <code>Iterator</code> - LDAP search result * * @throws NamingException if the LDAP returns an error *///from www .jav a 2 s .c o m protected Iterator<SearchResult> getSchema(final String dn) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("Schema search with the following parameters:"); this.logger.debug(" dn = " + dn); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; DirContext schema = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); schema = ctx.getSchema(dn); en = schema.search("", null); results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (schema != null) { schema.close(); } if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }