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:it.doqui.index.ecmengine.client.engine.EcmEngineDirectDelegateImpl.java

protected EcmEngineSecurityBusinessInterface createSecurityService() throws Throwable {
    this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] BEGIN ");

    Properties properties = new Properties();

    // Caricamento del file contenenti le properties su cui fare il binding
    rb = ResourceBundle.getBundle(ECMENGINE_PROPERTIES_FILE);

    // Caricamento delle proprieta' su cui fare il binding all'oggetto di business delle funzionalita'
    // implementate per la ricerca.
    try {/* w  w  w. j  a  v a  2  s .c  om*/
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] P-Delegata di backoffice.");

        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] context factory vale : "
                + rb.getString(ECMENGINE_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] url to connect vale : "
                + rb.getString(ECMENGINE_URL_TO_CONNECT));
        properties.put(Context.PROVIDER_URL, rb.getString(ECMENGINE_URL_TO_CONNECT));

        // Controllo che la property cluster partition sia valorizzata per capire se
        // sto lavorando in una configurazione in cluster oppure no
        String clusterPartition = rb.getString(ECMENGINE_CLUSTER_PARTITION);
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] disable discovery vale : "
                    + rb.getString(ECMENGINE_DISABLE_DISCOVERY));
            properties.put("jnp.disableDiscovery", rb.getString(ECMENGINE_DISABLE_DISCOVERY));
        }

        // Get an initial context
        InitialContext jndiContext = new InitialContext(properties);
        log.debug("[" + getClass().getSimpleName() + "::createSecurityService] context istanziato");

        // Get a reference to the Bean
        Object ref = jndiContext.lookup(ECMENGINE_SECURITY_JNDI_NAME);

        // Get a reference from this to the Bean's Home interface
        EcmEngineSecurityHome home = (EcmEngineSecurityHome) PortableRemoteObject.narrow(ref,
                EcmEngineSecurityHome.class);

        // Create an Adder object from the Home interface
        return home.create();

    } catch (Throwable e) {
        this.log.error("[" + getClass().getSimpleName() + "::createSecurityService] "
                + "Impossibile l'EJB di security: " + e.getMessage());
        throw e;
    } finally {
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] END ");
    }
}

From source file:org.sonatype.security.ldap.realms.DefaultLdapContextFactory.java

@VisibleForTesting
Hashtable<String, String> getSetupEnvironment(String username, final String password,
        final boolean systemContext) {
    Preconditions.checkNotNull(url, "No ldap URL specified (ldap://<hostname>:<port>)");

    if (username != null && principalSuffix != null) {
        username += principalSuffix;//from  www  .  j  a v  a2  s  .  c  o m
    }

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

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

    // if the Authentication scheme is none, and this is not the system ctx we need to set the scheme to 'simple'
    if ("none".equals(authentication) && !systemContext) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
    } else {
        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 && systemContext) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
        // Enable pooling for plain and ssl connections
        env.put(SUN_CONNECTION_POOLING_PROTOCOL_PROPERTY, "plain ssl");
    }

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

From source file:org.jboss.ejb3.locator.client.Ejb3ServiceLocatorImpl.java

private void setNamingContextProviderUrl(Properties props, JndiHost host) {
    // Place into properties
    props.put(Context.PROVIDER_URL, this.constructJnpUrl(host));
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with/*from  w  ww. ja  va2  s  .co  m*/
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:com.springsource.insight.plugin.ldap.LdapOperationCollectionAspectTestSupport.java

protected static final Hashtable<String, Object> createEnvironment() {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_PRINCIPAL, LDAP_USERNAME);
    env.put(Context.SECURITY_CREDENTIALS, LDAP_PASSWORD);
    return env;// ww  w. jav a 2 s  .c  o  m
}

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Connect to LDAP with the User-Name and Password given as parameters Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) LDAP Base = olatextconfig.xml
 * (property=ldapBase) LDAP Attributes Map = olatextconfig.xml (property=userAttrs)
 * //w  w  w.  j  av a 2  s . co  m
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * @return After successful bind Attributes otherwise NULL
 * @throws NamingException
 */
public Attributes bindUser(final String uid, final String pwd, final LDAPError errors) {
    // get user name, password and attributes
    final String ldapUrl = LDAPLoginModule.getLdapUrl();
    final String[] userAttr = LDAPLoginModule.getUserAttrs();

    if (uid == null || pwd == null) {
        if (isLogDebugEnabled()) {
            logDebug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::"
                    + pwd);
        }
        errors.insert("Username and password must be selected");
        return null;
    }

    final LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    final String userDN = searchUserDN(uid, ctx);
    if (userDN == null) {
        logInfo("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (LDAPLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        final Control[] connectCtls = new Control[] {};
        final LdapContext userBind = new InitialLdapContext(env, connectCtls);
        final Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (final AuthenticationException e) {
        logInfo("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (final NamingException e) {
        logError("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Set JNDI properties and any other connection factory parameters to the connection factory
 * passed in, looing at the parameter in axis2.xml
 * @param param the axis parameter that holds the connection factory settings
 * @param jmsConFactory the JMS connection factory to which the parameters should be applied
 *///from  ww w. jav a  2  s.com
public static void setConnectionFactoryParameters(Parameter param, JMSConnectionFactory jmsConFactory) {

    ParameterIncludeImpl pi = new ParameterIncludeImpl();
    try {
        pi.deserializeParameters((OMElement) param.getValue());
    } catch (AxisFault axisFault) {
        log.error("Error reading parameters for JMS connection factory" + jmsConFactory.getName(), axisFault);
    }

    Iterator params = pi.getParameters().iterator();
    while (params.hasNext()) {

        Parameter p = (Parameter) params.next();

        if (JMSConstants.CONFAC_TYPE.equals(p.getName())) {
            String connectionFactoryType = (String) p.getValue();
            jmsConFactory.setConnectionFactoryType(connectionFactoryType);

        } else if (JMSConstants.RECONNECT_TIMEOUT.equals(p.getName())) {
            String strTimeout = (String) p.getValue();
            int reconnectTimeoutSeconds = Integer.parseInt(strTimeout);
            long reconnectTimeoutMillis = reconnectTimeoutSeconds * 1000;
            jmsConFactory.setReconnectTimeout(reconnectTimeoutMillis);

        } else if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue());
        } else if (Context.PROVIDER_URL.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.PROVIDER_URL, (String) p.getValue());
        } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.SECURITY_PRINCIPAL, (String) p.getValue());
        } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.SECURITY_CREDENTIALS, (String) p.getValue());
        } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) {
            jmsConFactory.setConnFactoryJNDIName((String) p.getValue());
            jmsConFactory.addJNDIContextProperty(JMSConstants.CONFAC_JNDI_NAME_PARAM, (String) p.getValue());
        }
    }
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn// w  w  w .  j a va  2s  . c o m
 * @param password
 * @return
 * @throws LDAPException
 */
private Hashtable<String, String> buildEnvironment(String dn, String password) throws LDAPException {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.REFERRAL, getReferral());
    env.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (!isNoAuthentication()) {
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (isConnectionPoolEnabled()) {
        env.put(POOL_ENABLED_ENV_PARAM, "true");

        env.put(AUTHENTICATION_ENV_PARAM, getAuthentication());

        if (getMaxPoolConnections() > 0) {
            env.put(MAX_POOL_SIZE_ENV_PARAM, String.valueOf(getMaxPoolConnections()));
        }

        if (getInitialPoolSizeConnections() > 0) {
            env.put(INIT_POOL_SIZE_ENV_PARAM, String.valueOf(getInitialPoolSizeConnections()));
        }

        if (getPoolTimeout() > 0) {
            env.put(TIME_OUT_ENV_PARAM, String.valueOf(getPoolTimeout()));
        }
    } else {
        env.put(POOL_ENABLED_ENV_PARAM, "false");
    }

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

    return env;

}

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

public void login(String userid, String password) throws AuthenticationException {
    try {/*from   w w w.  j ava2  s. c  om*/
        LDAPAccount user = (LDAPAccount) getUser(userid);
        if (user == null) {
            throw new AuthenticationException(userid + " is not found.");
        }
        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");
        env.put(Context.SECURITY_PRINCIPAL, user.getDn());
        env.put(Context.SECURITY_CREDENTIALS, password);

        new InitialDirContext(env);

    } catch (NamingException e) {
        throw new AuthenticationException(e);
    }
}

From source file:ldap.LdapApi.java

/**
 * open the directory connection./*from w  ww  .j  a v  a 2  s. c om*/
 * @param url
 * @param dn
 * @param password
 * @param tracing
 * @return DirContext - context
 * @throws NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    *  setup  environment variables to sensible default valuse
    */
    Hashtable env = new Hashtable();
    // sanity check
    if (url == null) {
        throw new LdapException("URL not specified in openContext()!");
    }

    // tracing on/off, since it can't be set once the connection is open.
    if (tracing) {
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output
    }

    //env.put("java.naming.ldap.version", "3");               // always use ldap v3 - v2 too limited
    env.put(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider
    env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want
    //env.put(Context.REFERRAL, "ignore");                    //could be: follow, ignore, throw
    env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw
    // env.put("java.naming.ldap.derefAliases", "finding");    // could be: finding, searching, etc.
    env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc.

    //env.put(Context.SECURITY_AUTHENTICATION, "simple");         // 'simple' = username + password
    env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // 'simple' = username + password

    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
     *  Open the actual LDAP session using the above environment variables
     */
    context = new InitialDirContext(env);
    if (context == null) {
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");
    } else {
        logger.info("context is not null");
    }
    return context;
}