Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

In this page you can find the example usage for javax.naming Context INITIAL_CONTEXT_FACTORY.

Prototype

String INITIAL_CONTEXT_FACTORY

To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:org.dcm4che3.tool.dcmldap.DcmLdap.java

private static Hashtable<?, ?> ldapEnv(CommandLine cl) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.ldap.attributes.binary", "dicomVendorData");
    env.put(Context.PROVIDER_URL, cl.getOptionValue("H", DEFAULT_LDAP_URI));
    env.put(Context.SECURITY_PRINCIPAL, cl.getOptionValue("D", DEFAULT_BIND_DN));
    env.put(Context.SECURITY_CREDENTIALS, cl.getOptionValue("w", DEFAULT_PASSWORD));
    return env;/*from  w w  w.  j a  v a  2  s.  c  o m*/
}

From source file:com.att.ajsc.csilogging.common.QueueConnector.java

@PostConstruct
public void init() {

    if (csiEnable && StringUtils.isNotEmpty(initialContextFactoryName)
            && StringUtils.isNotEmpty(connectionFactoryName) && StringUtils.isNotEmpty(providerURL)) {

        if (StringUtils.isNotEmpty(System.getenv(("com_att_aft_config_file")))) {
            System.setProperty("com.att.aft.config.file", System.getenv("com_att_aft_config_file"));
        }/*from ww w. j  a v a  2  s  . c  o  m*/

        if (StringUtils.isEmpty(System.getProperty("com.att.aft.config.file"))) {
            logger.error("Environment or System properties dont have the property com.att.aft.config.file");
            return;
        }

        QueueConnectionFactory queueConnectionFactory;
        InitialContext jndi = null;
        ConnectionFactory connectionFactory = null;
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName);
            env.put(Context.PROVIDER_URL, providerURL);
            jndi = new InitialContext(env);
            connectionFactory = (ConnectionFactory) jndi.lookup(connectionFactoryName);
            queueConnectionFactory = (QueueConnectionFactory) connectionFactory;
            if (StringUtils.isNotEmpty(auditDestinationName)) {
                auditQueueConnection = queueConnectionFactory.createQueueConnection();
                auditQueueSession = auditQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue auditQueue = (Queue) auditQueueSession.createQueue(auditDestinationName);
                auditQueueSender = auditQueueSession.createSender(auditQueue);
                auditQueueConnection.start();
                logger.info("*************CONNECTED :" + auditDestinationName + "*************");

            }

            if (StringUtils.isNotEmpty(perfDestinationName)) {
                pefQueueConnection = queueConnectionFactory.createQueueConnection();
                pefQueueSession = pefQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue perfQueue = (Queue) pefQueueSession.createQueue(perfDestinationName);
                pefQueueSender = pefQueueSession.createSender(perfQueue);
                pefQueueConnection.start();
                logger.info("*************CONNECTED :" + perfDestinationName + "*************");
            }

        } catch (Exception e) {
            logger.error("Error while connecting to the Queue" + e);
        }
    }

}

From source file:org.picketlink.idm.performance.TestBase.java

public LdapContext getLdapContext() throws Exception {
    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_PROVIDER_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, LDAP_PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, LDAP_CREDENTIALS);

    return new InitialLdapContext(env, null);
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void doUnbind(String[] vals) throws NamingException {
    String url = "rmi://localhost:" + vals[1];
    String serviceName = vals[0];
    System.out.println("Unbinding " + url + "/" + serviceName);
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    env.put(Context.PROVIDER_URL, url);

    Context ictx = new InitialContext(env);
    try {//from  w w  w .j  a  v  a 2 s .  co m
        ictx.unbind(serviceName);
        System.out.println("Done");
    } catch (Exception ex) {
        System.err.println(ex.getMessage() + ex.getCause().getMessage());
    }
}

From source file:org.wso2.carbon.bpel.b4p.coordination.db.DatabaseUtil.java

@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {/* www . j a  v  a2s  .  c o m*/
        InitialContext ctx = null;
        try {
            if (bpelServerConfiguration.getDataSourceJNDIRepoInitialContextFactory() != null
                    && bpelServerConfiguration.getDataSourceJNDIRepoProviderURL() != null) {
                Properties jndiProps = new Properties();

                jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                        bpelServerConfiguration.getDataSourceJNDIRepoInitialContextFactory());
                jndiProps.setProperty(Context.PROVIDER_URL,
                        bpelServerConfiguration.getDataSourceJNDIRepoProviderURL());
                ctx = new InitialContext(jndiProps);
            } else {
                ctx = new InitialContext();
            }
            return (T) ctx.lookup(objName);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception ex1) {
                    log.error("Error closing JNDI connection.", ex1);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected DirContext open() throws NamingException {
    if (context == null) {
        try {//ww w  .  j  a  v  a2s.  c o  m
            // Set up the environment for creating the initial context
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
            if (StringUtils.isNotEmpty(username)) {
                env.put(Context.SECURITY_PRINCIPAL, username);
            }
            if (StringUtils.isNotEmpty(password)) {
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
            env.put(Context.PROVIDER_URL, url);
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
            context = new InitialDirContext(env);
        } catch (NamingException e) {
            throw e;
        }
    }
    return context;
}

From source file:com.konakart.bl.LDAPMgrCore.java

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>/*  w ww  . jav a 2s .c  om*/
 * <li>A negative number in order for the login attempt to fail. The KonaKart login() method
 * will return a null sessionId</li>
 * <li>Zero to signal that this method is not implemented. The KonaKart login() method will
 * perform the credential check.</li>
 * <li>A positive number for the login attempt to pass. The KonaKart login() will not check
 * credentials, and will log in the customer, returning a valid session id.</li>
 * </ul>
 * This method may need to be modified slightly depending on the structure of your LDAP. The
 * example works when importing the exampleData.ldif file in the LDAP module jar:
 * 
 * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/>
 * objectclass: inetOrgPerson<br/>
 * cn: Robert Smith<br/>
 * cn: Robert J Smith<br/>
 * cn: bob smith<br/>
 * sn: smith<br/>
 * uid: rjsmith<br/>
 * userpassword: rJsmitH<br/>
 * carlicense: HISCAR 123<br/>
 * homephone: 555-111-2222<br/>
 * mail: r.smith@example.com<br/>
 * mail: rsmith@example.com<br/>
 * mail: bob.smith@example.com<br/>
 * description: swell guy<br/>
 * 
 * The code attempts to connect to LDAP using the username, password and URL in the
 * configuration variables set when the module was installed through the admin app.<br/>
 * 
 * After having connected, the person object is searched for using the email address of the
 * user. If found we use the "cn" attribute and the password of the user to attempt to bind to
 * LDAP. If the bind is successful, we return a positive number which means that authentication
 * was successful.
 * 
 * @param emailAddr
 *            The user name required to log in
 * @param password
 *            The log in password
 * @return Returns an integer
 * @throws Exception
 */
public int checkCredentials(String emailAddr, String password) throws Exception {
    DirContext ctx = null;

    try {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        if (log.isDebugEnabled()) {
            log.debug("LDAP connection URL                          =   " + url);
            log.debug("LDAP user name                               =   " + ldapUserName);
            log.debug("LDAP person object distinguished name (DN)   =   " + personDN);
        }

        if (ldapUserName == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set.");
        }
        if (ldapPassword == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set.");
        }
        if (url == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set.");
        }
        if (personDN == null) {
            throw new KKException(
                    "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set.");
        }

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.PROVIDER_URL, url);
        environment.put(Context.SECURITY_PRINCIPAL, ldapUserName);
        environment.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        /*
         * connect to LDAP using the credentials and connection string from the configuration
         * variables
         */
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            log.error("Cannot connect to LDAP", e);
            return -1;
        }

        /* Specify the search filter on the eMail address */
        String filter = "(mail=" + emailAddr + ")";

        /*
         * limit returned attributes to those we care about. In this case we only require the
         * "cn" attribute which we will use to attempt to bind the user in order to validate his
         * password
         */
        String[] attrIDs = { "cn" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /* Search for objects using filter and controls */
        NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls);

        /* close the connection */
        ctx.close();

        if (answer == null || !answer.hasMore()) {
            return -1;
        }

        SearchResult sr = answer.next();
        Attributes attrs = sr.getAttributes();
        String cn = attrs.get("cn").toString();
        if (log.isDebugEnabled()) {
            log.debug("cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /*
         * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture
         * just the first entry
         */
        if (cn != null) {
            if (cn.contains(",")) {
                cn = cn.split(",")[0];
                if (cn.contains(":")) {
                    cn = cn.split(":")[1];
                }
            } else if (cn.contains(":")) {
                cn = cn.split(":")[1];
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /* Now we try to bind as the user */
        String userName = "cn=" + cn + "," + personDN;

        if (log.isDebugEnabled()) {
            log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName);
        }

        /* Bind as the user */
        environment.put(Context.SECURITY_PRINCIPAL, userName);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not bind user " + userName);
            }
            return -1;
        }
        ctx.close();
        if (log.isDebugEnabled()) {
            log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP");
        }
        return 1;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.error("Received an exception while closing the LDAP DirContext", e);
            }
        }
    }
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!//from   w w  w  .j  a v  a2 s .  c  o m
 *
 * @param request DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
protected Hashtable getContextProperties(HttpServletRequest request) {
    Hashtable props = (Hashtable) SessionManager.getObject(Constants.CONTEXT_PROPERTIES, request);

    if (props == null) {
        props = new Hashtable();

        props.put(Context.INITIAL_CONTEXT_FACTORY,
                Configuration.properties.getProperty(Configuration.JNDI_INITIAL_CONTEXT_FACTORY));
        props.put(Context.URL_PKG_PREFIXES,
                Configuration.properties.getProperty(Configuration.JNDI_URL_PKG_PREFIXES));
        props.put(Context.PROVIDER_URL, Configuration.properties.getProperty(Configuration.JNDI_PROVIDER_URL));

        Principal principal = request.getUserPrincipal();
        props.put(Context.SECURITY_PRINCIPAL, principal.getName());
        props.put(Context.SECURITY_CREDENTIALS, SessionManager.getObject(Constants.JAAS_PASSWORD, request));

        props.put(Context.SECURITY_PROTOCOL,
                Configuration.properties.getProperty(Configuration.SECURITY_PROTOCOL));

        SessionManager.setObject(Constants.CONTEXT_PROPERTIES, props, request);
    }

    return props;
}

From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 *//*w w  w.  j  a  v  a2  s  .c o m*/
public Map<String, String> bind(String loginName, String password) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    LdapContext ctx = null;
    if (activeDirectoryDomain != null) { // we are using Active Directory            
        Control[] controls = new Control[] { control };
        ctx = new InitialLdapContext(env, controls);
        logger.debug("Active Directory LDAP context initialized");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        // javax.naming.AuthenticationException
        ctx.reconnect(controls);
        logger.debug("Active Directory LDAP bind successful");
    } else { // standard LDAP            
        env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase);
        env.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialLdapContext(env, null);
        logger.debug("Standard LDAP bind successful");
    }
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(returningAttributes);
    NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc);
    while (results.hasMoreElements()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();
        logger.debug("attributes: " + attrs);
        Map<String, String> map = new HashMap<String, String>(returningAttributes.length);
        for (String key : returningAttributes) {
            Attribute attr = attrs.get(key);
            if (attr != null) {
                map.put(key, (String) attr.get());
            }
        }
        return map; // there should be only one anyway            
    }
    // if we reached here, there was no search result
    throw new Exception("no results returned from ldap");
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer/*  www .  j av  a  2s. c om*/
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}