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:com.nridge.core.app.ldap.ADQuery.java

/**
 * Opens a connection to Active Directory by establishing an initial LDAP
 * context.  The security principal and credentials are assigned the
 * account name and password parameters.
 *
 * @param anAcountDN Active Directory account name (DN format).
 * @param anAccountPassword Active Directory account password.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from   w  w w  .  ja va 2 s  .  c  om*/
@SuppressWarnings("unchecked")
public void open(String anAcountDN, String anAccountPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "open");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html

    Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
    environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
    environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
    environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentalVariables.put(Context.SECURITY_PRINCIPAL, anAcountDN);
    environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);

    // Referral options: follow, throw, ignore (default)

    environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));

    // Authentication options: simple, DIGEST-MD5 CRAM-MD5

    environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple"));

    try {
        mLdapContext = new InitialLdapContext(environmentalVariables, null);
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Context Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.redhat.consulting.eapquickstarts.mutualauth.remoting.ejb.client.RemoteEJBClient.java

private void initLookupContextProps() {
    iniCtxProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
    if (this.useSSLOnRemoteEJBProps) {
        initSSLParams();/*from w ww  .  j  a  v  a 2 s . c o  m*/
        CommandLineArgumentsParserUtils.printSysProps(props);
    }

    if (!this.setRemoteEJBProps) {
        return;
    }
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    props.put("remote.connections", "default");
    props.put("remote.connection.default.host", this.host);
    props.put("remote.connection.default.port", this.port);
    props.put("remote.connection.default.timeout", DEFAULT_TIMEOUT);
    props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");

    if (this.useSSLOnRemoteEJBProps) {

        props.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "true");
        props.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_STARTTLS", "true");
        props.put("remote.connection.default.protocol", "https-remoting");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_ENABLED", "true");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS",
                "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS",
                "JBOSS-LOCAL-USER");

    } else {
        props.put("remote.connection.default.protocol", "http-remoting");
        props.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_ENABLED", "false");
        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_STARTTLS", "false");
        props.put("remote.connection.default.username", this.username);
        props.put("remote.connection.default.password", this.password);
    }
    final EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(props);
    final ConfigBasedEJBClientContextSelector sel = new ConfigBasedEJBClientContextSelector(cc);
    EJBClientContext.setSelector(sel);
    CommandLineArgumentsParserUtils.printSysProps(props);
    CommandLineArgumentsParserUtils.printProps(props);
}

From source file:org.alfresco.reporting.test.TestReporting.java

private static InitialContext createContext() throws NamingException {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    env.put(Context.PROVIDER_URL, "rmi://localhost:" + Registry.REGISTRY_PORT);
    InitialContext context = new InitialContext(env);
    return context;
}

From source file:xc.mst.manager.user.DefaultUserService.java

/**
 * Sets up the Properties used to create an LDAP connection
 * //from   w w w . j  ava  2 s.  co  m
 * @return The Properties for an LDAP connection
 */
private static Properties getGenericLDAPProperties(Server loginserver) {

    // Get important values from the configuration file for connecting to the LDAP server.
    String url = loginserver.getUrl();
    int port = loginserver.getPort();

    // Set up the environment for creating the initial context
    Properties ldapProperties = new Properties();
    ldapProperties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapProperties.setProperty(Context.PROVIDER_URL, url + ":" + port);

    return ldapProperties;
}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

/**
 * Sets up the environment parameters for creating a new context.
 *
 * @return the Hashtable describing the base DirContext that will be created, minus the username/password if any.
 *///from  w ww .  j av  a2s  .  c o  m
protected Hashtable getEnvironment() {
    Hashtable env = new Hashtable();

    env.put(Context.SECURITY_AUTHENTICATION, authenticationType);
    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (useConnectionPool) {
        env.put(CONNECTION_POOL_KEY, "true");
    }

    if ((extraEnvVars != null) && (extraEnvVars.size() > 0)) {
        env.putAll(extraEnvVars);
    }

    return env;
}

From source file:org.rhq.enterprise.server.core.CustomJaasDeploymentService.java

private void validateLdapOptions(Map<String, String> options) throws NamingException {
    Properties env = new Properties();

    String factory = options.get(Context.INITIAL_CONTEXT_FACTORY);
    if (factory == null) {
        throw new NamingException("No initial context factory");
    }//from www . j a  v  a2 s .  co m

    String url = options.get(Context.PROVIDER_URL);
    if (url == null) {
        throw new NamingException("Naming provider url not set");
    }

    String protocol = options.get(Context.SECURITY_PROTOCOL);
    if ("ssl".equals(protocol)) {
        String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket");
        if (ldapSocketFactory == null) {
            env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName());
        }
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.setProperty(Context.PROVIDER_URL, url);

    // Load any information we may need to bind
    String bindDN = options.get("BindDN");
    String bindPW = options.get("BindPW");
    if ((bindDN != null) && (bindDN.length() != 0) && (bindPW != null) && (bindPW.length() != 0)) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    log.debug("Validating LDAP properties. Initializing context...");
    new InitialLdapContext(env, null).close();

    return;
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;// ww  w  .ja v a2 s  .c o m
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:org.pentaho.platform.repository.hibernate.HibernateUtil.java

protected static boolean initialize() {
    IApplicationContext applicationContext = PentahoSystem.getApplicationContext();
    // Add to entry/exit points list
    HibernateUtil hUtil = new HibernateUtil();
    applicationContext.addEntryPointHandler(hUtil);
    applicationContext.addExitPointHandler(hUtil);

    // Look for some hibernate-specific properties...

    String hibernateConfigurationFile = lookupSetting(applicationContext, "hibernateConfigPath", //$NON-NLS-1$
            "settings/config-file", //$NON-NLS-1$
            "hibernate/hibernateConfigPath"); //$NON-NLS-1$

    String hibernateManagedString = lookupSetting(applicationContext, "hibernateManaged", //$NON-NLS-1$
            "settings/managed", //$NON-NLS-1$
            "hibernate/hibernateManaged"); //$NON-NLS-1$

    if (hibernateManagedString != null) {
        hibernateManaged = Boolean.parseBoolean(hibernateManagedString);
    }//from  w  w  w.ja v a 2  s  .  c  om

    try {
        HibernateUtil.configuration = new Configuration();
        HibernateUtil.configuration.setEntityResolver(new PentahoEntityResolver());
        HibernateUtil.configuration.setListener("load", new HibernateLoadEventListener()); //$NON-NLS-1$

        if (hibernateConfigurationFile != null) {
            String configPath = applicationContext.getSolutionPath(hibernateConfigurationFile);
            File cfgFile = new File(configPath);
            if (cfgFile.exists()) {
                HibernateUtil.configuration.configure(cfgFile);
            } else {
                HibernateUtil.log.error(Messages.getInstance()
                        .getErrorString("HIBUTIL.ERROR_0012_CONFIG_NOT_FOUND", configPath)); //$NON-NLS-1$
                return false;
            }
        } else {
            // Assume defaults which means we hope Hibernate finds a configuration
            // file in a file named hibernate.cfg.xml
            HibernateUtil.log.error(Messages.getInstance()
                    .getErrorString("HIBUTIL.ERROR_0420_CONFIGURATION_ERROR_NO_HIB_CFG_FILE_SETTING")); //$NON-NLS-1$
            HibernateUtil.configuration.configure();
        }
        String dsName = HibernateUtil.configuration.getProperty("connection.datasource"); //$NON-NLS-1$
        if ((dsName != null) && dsName.toUpperCase().endsWith("HIBERNATE")) { //$NON-NLS-1$
            // IDBDatasourceService datasourceService =  (IDBDatasourceService) PentahoSystem.getObjectFactory().getObject("IDBDatasourceService",null);     //$NON-NLS-1$
            IDBDatasourceService datasourceService = getDatasourceService();
            String actualDSName = datasourceService.getDSBoundName("Hibernate"); //$NON-NLS-1$
            HibernateUtil.configuration.setProperty("hibernate.connection.datasource", actualDSName); //$NON-NLS-1$
        }

        HibernateUtil.dialect = HibernateUtil.configuration.getProperty("dialect"); //$NON-NLS-1$

        /*
         * configuration.addResource("org/pentaho/platform/repository/runtime/RuntimeElement.hbm.xml"); //$NON-NLS-1$
         * configuration.addResource("org/pentaho/platform/repository/content/ContentLocation.hbm.xml"); //$NON-NLS-1$
         * configuration.addResource("org/pentaho/platform/repository/content/ContentItem.hbm.xml"); //$NON-NLS-1$
         * configuration.addResource("org/pentaho/platform/repository/content/ContentItemFile.hbm.xml"); //$NON-NLS-1$
         */
        if (!HibernateUtil.hibernateManaged) {
            HibernateUtil.log.info(Messages.getInstance().getString("HIBUTIL.USER_HIBERNATEUNMANAGED")); //$NON-NLS-1$
            HibernateUtil.sessionFactory = HibernateUtil.configuration.buildSessionFactory();
        } else {
            HibernateUtil.factoryJndiName = HibernateUtil.configuration
                    .getProperty(Environment.SESSION_FACTORY_NAME);
            if (HibernateUtil.factoryJndiName == null) {
                HibernateUtil.log
                        .error(Messages.getInstance().getErrorString("HIBUTIL.ERROR_0013_NO_SESSION_FACTORY"));
                return false;
            }
            HibernateUtil.log.info(Messages.getInstance().getString("HIBUTIL.USER_HIBERNATEMANAGED")); //$NON-NLS-1$
            HibernateUtil.configuration.buildSessionFactory(); // Let hibernate Bind it
            // to JNDI...

            // BISERVER-2006: Below content is a community contribution see the JIRA case for more info
            // -------- Begin Contribution --------
            // Build the initial context to use when looking up the session
            Properties contextProperties = new Properties();
            if (configuration.getProperty("hibernate.jndi.url") != null) { //$NON-NLS-1$
                contextProperties.put(Context.PROVIDER_URL, configuration.getProperty("hibernate.jndi.url")); //$NON-NLS-1$
            }

            if (configuration.getProperty("hibernate.jndi.class") != null) { //$NON-NLS-1$
                contextProperties.put(Context.INITIAL_CONTEXT_FACTORY,
                        configuration.getProperty("hibernate.jndi.class")); //$NON-NLS-1$
            }
            iniCtx = new InitialContext(contextProperties);
            // --------- End Contribution ---------

        }
        Dialect.getDialect(HibernateUtil.configuration.getProperties());
        return true;
    } catch (Throwable ex) {
        HibernateUtil.log
                .error(Messages.getInstance().getErrorString("HIBUTIL.ERROR_0006_BUILD_SESSION_FACTORY"), ex); //$NON-NLS-1$
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java

public void shutdownLdapServer() {

    Hashtable<String, Object> env = new Hashtable<>(new ShutdownConfiguration().toJndiEnvironment());
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, BASE_DN);

    try {//from   w w  w  .  j av  a2 s  .  c  o m
        new InitialLdapContext(env, null);
    } catch (Exception e) {
        throw new ServerSystemPreferenceException("Failed to shutdown ldap server.", e);
    }
}