Example usage for javax.naming.directory InitialDirContext InitialDirContext

List of usage examples for javax.naming.directory InitialDirContext InitialDirContext

Introduction

In this page you can find the example usage for javax.naming.directory InitialDirContext InitialDirContext.

Prototype

public InitialDirContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial DirContext using the supplied environment.

Usage

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 * Connect to the LDAP server and return a context.
 *
 * @return The LDAP context to use when retrieving user information.
 *//*from   ww w . ja  v a2s . c o m*/
private InitialDirContext getContext(String username, String password) throws Exception {
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, Environment.getValue(Environment.PROP_LDAP_FACTORY_CLASS));
    env.put(Context.PROVIDER_URL, Environment.getValue(Environment.PROP_LDAP_URL));
    if (!StringUtils.isBlank(username)) {
        // "simple" "DIGEST-MD5"
        env.put(Context.SECURITY_AUTHENTICATION,
                Environment.getValue(Environment.PROP_LDAP_SECURITY_AUTHENTICATION));
        // cn=login, ou=NewHires, o=JNDITutorial
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    InitialDirContext ctx = new InitialDirContext(env);
    return ctx;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

/**
 * @return Connection context of the LDAP userstore.
 * @throws UserStoreException If an error occurs while connecting to th userstore.
 *//*  w ww . j av  a2s.c o m*/
DirContext getContext() throws UserStoreException {
    DirContext context;
    try {
        context = new InitialDirContext(environment);

    } catch (NamingException e) {
        log.error("Error obtaining connection. " + e.getMessage(), e);
        log.error("Trying again to get connection.");

        try {
            context = new InitialDirContext(environment);
        } catch (Exception e1) {
            log.error("Error obtaining connection for the second time" + e.getMessage(), e);
            throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e);
        }

    }
    return (context);
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public Attributes getAttributes(String dn) throws NamingException {
    InitialDirContext searchContext = new InitialDirContext(searchEnvironment);
    Attributes attributes = searchContext.getAttributes(dn);
    searchContext.close();//ww  w  .  ja v a 2  s .  c o m
    return attributes;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private DirContext initContext() throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, this.connectionURL);
    env.put("java.naming.ldap.version", "3");
    if (this.connectionName != null) {
        env.put(Context.SECURITY_PRINCIPAL, this.connectionName);
        env.put(Context.SECURITY_CREDENTIALS, this.connectionPassword);
    }//from   ww  w.  j a  v a 2s  .c o m
    return new InitialDirContext(env);
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * @see com.alfaariss.oa.api.idmapper.IIDMapper#remap(java.lang.String)
 *///from   w w  w.j ava  2s . co  m
public String remap(String id) throws OAException {
    if (id == null)
        throw new IllegalArgumentException("Could not remap: NULL");

    String sReturn = null;
    DirContext oDirContext = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment, e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        }

        try {
            if (_sMapperAttribute == null) {//must be null, otherwise you can't do the inverse
                Name nameLdap = new LdapName(id);
                if (_sIDAttribute != null)
                    return getAttributes(oDirContext, _sIDAttribute, nameLdap);

                _logger.error("Can't remap: no id attribute name configured");
                throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
            }

            sReturn = searchAttributes(oDirContext, _sMapperAttribute, _sIDAttribute, id);
        } catch (InvalidNameException e) {
            _logger.debug("Supplied id isn't a valid LdapName: " + id);
        }

    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not remap id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for mapped id: " + id, e);
            }
        }
    }
    return sReturn;
}

From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java

protected InitialDirContext getLdapConnection() throws NamingException {
    Properties ldapEnv = new Properties();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, "ldap://" + _host + "/" + _rootContext);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, _rootDN);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, _rootPW);
    return new InitialDirContext(ldapEnv);

}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Starts the JNDI object./*  w ww  .  ja  v  a  2 s.c  o  m*/
 * @see IStorage#start(IConfigurationManager, org.w3c.dom.Element)
 */
public void start(IConfigurationManager oConfigurationManager, Element eConfig) throws UserException {
    InitialDirContext context = null;
    try {
        Element eResource = oConfigurationManager.getSection(eConfig, "resource");
        if (eResource == null) {
            _logger.error("No 'resource' section found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        Element eDN = oConfigurationManager.getSection(eResource, "dn");
        if (eDN == null) {
            _logger.error("No 'dn' section found in 'resource' section in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        _sDNBase = oConfigurationManager.getParam(eDN, "base");
        if (_sDNBase == null) {
            _logger.error("No 'dn' item found in 'base' section in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        _sDNUser = oConfigurationManager.getParam(eDN, "user");
        _sFilter = oConfigurationManager.getParam(eDN, "filter");
        if (_sFilter != null && _sDNUser != null) {
            _logger.error(
                    "Invalid configuration: Both 'user' and 'filter' item found in 'base' section in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        } else if (_sFilter != null) {
            _logger.info("Using search filter: " + _sFilter);
        } else if (_sDNUser != null) {
            _logger.info("Generating search filter with user: " + _sDNUser);
        } else {
            _logger.error("No 'user' or 'filter' item found in 'base' section in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        _htJNDIEnvironment = readJNDIContext(oConfigurationManager, eResource);

        //test connection
        context = new InitialDirContext(_htJNDIEnvironment);

    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create object", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        //Close context
        try {
            if (context != null)
                context.close();
        } catch (NamingException e) {
            _logger.error("Could not close initial context", e);
        }
    }
}

From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

private synchronized boolean connect() {
    Hashtable<String, String> env = this.getBuildEnv();
    env.putAll(properties);/*from   ww w.ja  v a2s  . c o  m*/
    try {
        ctx = new InitialDirContext(env);
        logger.debug("Ldap server connect success.");
        return true;
    } catch (Exception e) {
        logger.error("Ldap server connect failure", e);
    }
    return false;
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Asks the identity provider to provision a new user with the given profile and password.
 *
 * @param user the user to be provisioned
 * @param password the password for the user
 * @throws PortalServiceException for any errors encountered
 *///  w  w  w.  ja v a2  s  .  c  o m
public void provisionUser(CMSUser user, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        List<Attribute> profileAttributes = mapAttributes(user);

        // set type
        Attribute oc = new BasicAttribute("objectClass");
        oc.add("top");
        oc.add("person");
        oc.add("organizationalPerson");
        oc.add("inetOrgPerson");

        // build the entry
        BasicAttributes entry = new BasicAttributes();
        for (Attribute attribute : profileAttributes) {
            entry.put(attribute);
        }

        // initial password
        entry.put(new BasicAttribute("userPassword", hash(password)));
        entry.put(oc);

        ctx.createSubcontext(MessageFormat.format(userDNPattern, user.getUsername()), entry);
        synchRoles(user.getUsername(), user.getRole());
    } catch (NamingException e) {
        throw new PortalServiceException("Error while provisioning user.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {// w ww  .j a  v a 2s  .  com
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}