Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

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

Prototype

String PROVIDER_URL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password) throws NamingException {
    if (searchBase == null) {
        throw new IllegalStateException("A search base must be specified.");
    }/*from   ww  w  .  java 2  s.  co  m*/
    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }

    if (username != null && principalSuffix != null) {
        username += principalSuffix;
    }

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

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);/*w  w w.  jav a2 s. c o  m*/
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

From source file:org.jboss.as.quickstarts.secured.ejb.remote.client.RemoteEJBClient.java

private void initLookupContextProps() {
    props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
    if (this.useSSLOnRemoteEJBProps) {
        initSSLParams();//from w w  w  .ja v  a 2  s.  com
        CommandLineArgumentsParserUtils.printSysProps(props);
    }

    if (!this.setRemoteEJBProps) {
        return;
    }
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");

    String url = "remote://" + this.host + STR_COLON_SEPARATOR + this.port;

    props.put(Context.PROVIDER_URL, url);
    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.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.connection.default.connect.options.org.xnio.Options.SSL_ENABLED", "true");

        props.put("remote.connection.default.connect.options.org.xnio.Options.SSL_STARTTLS", "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.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);
    }
    EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(props);
    ContextSelector<EJBClientContext> sel = new ConfigBasedEJBClientContextSelector(cc);
    EJBClientContext.setSelector(sel);

    CommandLineArgumentsParserUtils.printSysProps(props);
    CommandLineArgumentsParserUtils.printProps(props);
}

From source file:org.mule.providers.ldap.util.DSManager.java

/**
 * Sets the contexts of this class taking into account the extras and
 * overrides properties./*from   www  . j  ava  2 s  . com*/
 * 
 * @param env
 *            an environment to use while setting up the system root.
 * @throws NamingException
 *             if there is a failure of any kind
 */
protected void setContexts(Hashtable env) throws NamingException {
    Hashtable envFinal = new Hashtable(env);
    envFinal.put(Context.PROVIDER_URL, "ou=system");
    sysRoot = new InitialLdapContext(envFinal, null);

    envFinal.put(Context.PROVIDER_URL, "");
    rootDSE = new InitialLdapContext(envFinal, null);
}

From source file:jp.terasoluna.fw.web.jndi.DefaultJndiSupport.java

/**
 * JndiTemplate??// w w  w.  j  a v a2s. co  m
 */
public void initialize() {

    // JNDI???????Weblogic??
    if (jndiEnvironmentMap != null) {

        // jndiEnvironmentMap???
        String factory = jndiEnvironmentMap.get(JNDI_FACTORY_KEY);
        String url = jndiEnvironmentMap.get(JNDI_URL_KEY);
        String username = jndiEnvironmentMap.get(JNDI_USERNAME_KEY);
        String password = jndiEnvironmentMap.get(JNDI_PASSWORD_KEY);

        Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        environment.put(Context.PROVIDER_URL, url);

        if (!"".equals(username) && username != null) {
            environment.put(Context.SECURITY_PRINCIPAL, username);
            if (password == null) {
                password = "";
            }
            environment.put(Context.SECURITY_CREDENTIALS, password);
        }

        // ??
        getJndiTemplate().setEnvironment(environment);

        // 
        if (log.isInfoEnabled()) {
            log.info("Initialize Weblogic JNDI Resource");
            log.info(Context.INITIAL_CONTEXT_FACTORY + " = " + factory);
            log.info(Context.PROVIDER_URL + " = " + url);
            log.info(Context.SECURITY_PRINCIPAL + " = " + username);
            log.info(Context.SECURITY_CREDENTIALS + " = " + password);
        }
    }
}

From source file:org.bedework.selfreg.common.DirMaintImpl.java

private LdapDirectory getLdir() throws SelfregException {
    if (ldir != null) {
        return ldir;
    }/*  w w w  .  j a  v  a2 s .  c om*/

    Properties pr = new Properties();

    pr.put(Context.PROVIDER_URL, config.getLdapUrl());

    ldir = new LdapDirectory(pr, config.getAdminId(), config.getAdminPw(), debug);

    return ldir;
}

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);
    }//  ww w. j  av a 2 s  .com

    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.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:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;//from  w  w  w.j  a v  a 2s  . 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;
}