List of usage examples for javax.naming.directory DirContext close
public void close() throws NamingException;
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
public void updateSchemas() { DirContext dirContext = null; try {/* w ww . j a v a2s . com*/ dirContext = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setCountLimit(1); updateSuffix(dirContext); updateGroups(dirContext, controls); updatePeople(dirContext, controls); updateRootDN(dirContext, controls); updateUsers(dirContext, controls); } finally { if (dirContext != null) { try { dirContext.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the LDAP context", ex); } } } }
From source file:org.wso2.carbon.connector.ldap.SearchEntry.java
@Override public void connect(MessageContext messageContext) throws ConnectException { String objectClass = (String) getParameter(messageContext, LDAPConstants.OBJECT_CLASS); String filter = (String) getParameter(messageContext, LDAPConstants.FILTERS); String dn = (String) getParameter(messageContext, LDAPConstants.DN); String returnAttributes[] = ((String) getParameter(messageContext, LDAPConstants.ATTRIBUTES)).split(","); boolean onlyOneReference = Boolean .valueOf((String) getParameter(messageContext, LDAPConstants.ONLY_ONE_REFERENCE)); OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE); OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns); try {//from w w w.j a v a 2s . c o m DirContext context = LDAPUtils.getDirectoryContext(messageContext); String attrFilter = generateAttrFilter(filter); String searchFilter = generateSearchFilter(objectClass, attrFilter); NamingEnumeration<SearchResult> results = null; try { results = searchInUserBase(dn, searchFilter, returnAttributes, SearchControls.SUBTREE_SCOPE, context); SearchResult entityResult = null; if (!onlyOneReference) { if (results != null && results.hasMore()) { while (results.hasMore()) { entityResult = results.next(); result.addChild(prepareNode(entityResult, factory, ns, returnAttributes)); } } } else { entityResult = makeSureOnlyOneMatch(results); if (entityResult == null) throw new NamingException( "Multiple objects for the searched target have been found. Try to " + "change onlyOneReference option"); result.addChild(prepareNode(entityResult, factory, ns, returnAttributes)); } LDAPUtils.preparePayload(messageContext, result); if (context != null) { context.close(); } } catch (NamingException e) { //LDAP Errors are catched LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.SEARCH_ERROR, e); throw new SynapseException(e); } } catch (NamingException e) { //Authentication failures are catched LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e); throw new SynapseException(e); } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.util.JNDIUtil.java
public static void closeContext(DirContext dirContext) throws UserStoreException { try {/*from ww w.j a va2 s . com*/ if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { String errorMessage = "Error in closing connection context."; log.error(errorMessage, e); } }
From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java
protected void closeContext(DirContext ldapContext) { if (ldapContext != null) { try {/*w ww . j a v a2 s.co m*/ ldapContext.close(); } catch (NamingException e) { logger.error("Error closing sub context.", e); } } }
From source file:ru.runa.wfe.security.logic.LdapLogic.java
public synchronized int synchronizeExecutors() { if (!LdapProperties.isSynchronizationEnabled()) { log.debug("Synchronization is disabled"); return -1; }/*from w ww. j a va 2 s.c om*/ log.info("Synchronizing executors"); try { importGroup = loadGroup(new Group(LdapProperties.getSynchronizationImportGroupName(), LdapProperties.getSynchronizationImportGroupDescription())); wasteGroup = loadGroup(new Group(LdapProperties.getSynchronizationWasteGroupName(), LdapProperties.getSynchronizationWasteGroupDescription())); DirContext dirContext = getContext(); Map<String, Actor> actorsByDistinguishedName = Maps.newHashMap(); int changesCount = synchronizeActors(dirContext, actorsByDistinguishedName); changesCount += synchronizeGroups(dirContext, actorsByDistinguishedName); dirContext.close(); return changesCount; } catch (Exception e) { log.error("", e); // prevent java.io.NotSerializableException: com.sun.jndi.ldap.LdapCtx throw new InternalApplicationException(e.getMessage()); } }
From source file:se.vgregion.service.barium.BariumRestClientIT.java
License:asdf
public static void main(String[] args) { try {//from w ww. ja v a 2s .co m Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "LDAP://my.ldap.server:389"); //replace with your server URL/IP //only DIGEST-MD5 works with our Windows Active Directory env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5"); //No other SALS worked with me env.put(Context.SECURITY_PRINCIPAL, "user1"); // specify the username ONLY to let Microsoft Happy env.put(Context.SECURITY_CREDENTIALS, "secret1"); //the password DirContext ctx = new InitialDirContext(env); ctx.close(); } catch (NamingException ne) { System.out.println("Error authenticating user:"); System.out.println(ne.getMessage()); return; } //if no exception, the user is already authenticated. System.out.println("OK, successfully authenticating user"); }
From source file:security.AuthenticationManager.java
public static void authenticateUser(String userName, String password) throws NamingException, SQLException { if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) { throw new IllegalArgumentException("Username and password can not be blank."); }// w ww . j a va 2 s . com if (UserDAO.authenticate(userName, password)) { UserDAO.insertLoginHistory(userName, "default", "SUCCESS", null); return; } final String contextFactories = Play.application().configuration() .getString(LDAP_CONTEXT_FACTORY_CLASS_KEY); /* three LDAP properties, each is a '|' separated string of same number of tokens. e.g. Url: "ldaps://ldap1.abc.com:1234|ldap://ldap2.abc.com:5678" Principal Domain: "@abc.com|@abc.cn" Search Base: "ou=Staff Users,dc=abc,dc=com|ou=Staff Users,dc=abc,dc=cn" */ final String[] ldapUrls = Play.application().configuration().getString(MASTER_LDAP_URL_KEY) .split("\\s*\\|\\s*"); final String[] principalDomains = Play.application().configuration().getString(MASTER_PRINCIPAL_DOMAIN_KEY) .split("\\s*\\|\\s*"); final String[] ldapSearchBase = Play.application().configuration().getString(LDAP_SEARCH_BASE_KEY) .split("\\s*\\|\\s*"); DirContext ctx = null; int i; for (i = 0; i < ldapUrls.length; i++) { try { Hashtable<String, String> env = buildEnvContext(userName, password, contextFactories, ldapUrls[i], principalDomains[i]); ctx = new InitialDirContext(env); if (!UserDAO.userExist(userName)) { User user = getAttributes(ctx, ldapSearchBase[i], userName, principalDomains[i]); UserDAO.addLdapUser(user); } break; } catch (NamingException e) { // Logger.error("Ldap authentication failed for user " + userName + " - " + principalDomains[i] + " - " + ldapUrls[i], e); // if exhausted all ldap options and can't authenticate user if (i >= ldapUrls.length - 1) { UserDAO.insertLoginHistory(userName, "LDAP", "FAILURE", e.getMessage()); throw e; } } catch (SQLException e) { // Logger.error("Ldap authentication SQL error for user: " + userName, e); UserDAO.insertLoginHistory(userName, "LDAP", "FAILURE", ldapUrls[i] + e.getMessage()); throw e; } finally { if (ctx != null) { ctx.close(); } } } UserDAO.insertLoginHistory(userName, "LDAP", "SUCCESS", ldapUrls[i]); }
From source file:security.AuthenticationManager.java
public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName, String principalDomain, String... attributeNames) throws NamingException { if (StringUtils.isBlank(userName)) { throw new IllegalArgumentException("Username and password can not be blank."); }/*from www . ja v a 2 s .co m*/ if (attributeNames.length == 0) { return Collections.emptyMap(); } Attributes matchAttr = new BasicAttributes(true); BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain); matchAttr.put(basicAttr); NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames); if (ctx != null) { ctx.close(); } Map<String, String> result = new HashMap<>(); if (searchResult.hasMore()) { NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll(); while (attributes.hasMore()) { Attribute attr = attributes.next(); String attrId = attr.getID(); String attrValue = (String) attr.get(); result.put(attrId, attrValue); } } return result; }