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:com.ccc.ccm.client.activemq.StoreablePooledConnectionFactory.java

public void buildFromProperties(Properties properties) {

    if (properties == null) {
        properties = new Properties();
    }/*from   w  w w.j  av a  2  s .com*/

    String temp = properties.getProperty(Context.PROVIDER_URL);
    if (temp == null || temp.length() == 0) {
        temp = properties.getProperty("brokerURL");
    }
    if (temp != null && temp.length() > 0) {
        setBrokerURL(temp);
    }

    buildFromMap(properties);
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the initial context//w w w  .  j  ava  2  s  . co m
 * 
 * @param providerUrl
 * @param bindDN
 * @param bindPassword
 * @return
 */
public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) {
    List<String> trace = new ArrayList<String>();
    LOGGER.debug("providerURL: " + providerUrl);
    trace.add("Attempting to connect to the LDAP server...");
    if (providerUrl != null && providerUrl.startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
        trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE);
        File ks = new File(PATH_TO_KEY_STORE);
        if (!ks.exists()) {
            trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE);
        }
    }
    if (providerUrl == null) {
        LOGGER.warn("LDAP provider URL should not be null.");
        return null;
    }
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    if (LOGGER.isDebugEnabled()) {
        env.put("com.sun.jndi.ldape.trace.ber", System.err);
    }
    env.put("java.naming.ldap.version", "3");
    env.put("com.sun.jndi.ldap.connect.timeout", "10000");
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    env.put("com.sun.jndi.dns.timeout.retries", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    if ((bindDN != null) && !bindDN.equals("")) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, bindDN);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);
        LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*"));
        trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****");
    } else {
        LOGGER.debug("bind anonymous");
        trace.add("Preparing to bind anonymously to the LDAP server");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.error(msg);
        }
        LOGGER.error("Getting the initial ldap context failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        try {
            new InitialDirContext(env);
        } catch (NamingException e1) {
            LOGGER.error("Getting the initial dir context failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

/**
 * Gets and returns the entries from the server.
 * /*from   ww  w.  j ava  2  s. c  o m*/
 * @throws ToolCommandException
 * @throws NamingException
 */
public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException {
    // Connecting to the LDAP Server
    if (isDebugEnabled()) {
        notifyOutputListener("Connecting to LDAP server");
        notifyOutputListener("Host: " + host);
        notifyOutputListener("Port: " + port);
        notifyOutputListener("User DN: " + user);
        notifyOutputListener("Base DN: " + baseDN);
        notifyOutputListener("Authentication: " + auth);
    }
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    DirContext ctx;
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage());
    }

    // Setting up search scope
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(scope);

    // Fetching entries
    try {
        return ctx.search(exportPoint, "(objectClass=*)", ctls);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not retreive entries");
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Returns <i>true</i> if the Active Directory account and password are
 * valid (e.g. a context can be successfully established) or <i>false</i>
 * otherwise./*  w ww. j  av  a  2 s  . c om*/
 *
 * @param anAccountName An Active Directory account name.
 * @param anAccountPassword An Active Directory account passowrd.
 *
 * @return <i>true</i> or <i>false</i>
 */
@SuppressWarnings("unchecked")
public boolean isAccountValid(String anAccountName, String anAccountPassword) {
    boolean isValid = false;
    Logger appLogger = mAppMgr.getLogger(this, "isAccountValid");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    DataBag userBag = schemaUserBag();
    userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName);

    try {
        loadUserByAccountName(userBag);
        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,
                userBag.getValueAsString(LDAP_DISTINGUISHED_NAME));
        environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);
        environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));
        environmentalVariables.put(Context.SECURITY_AUTHENTICATION,
                getPropertyValue("authentication", "simple"));

        LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null);
        ldapContext.close();

        isValid = true;
    } catch (Exception ignored) {
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return isValid;
}

From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java

/**
 * Convenience method for getting an environment suitable for acquiring
 * an {@link LdapContext} for the client.
 * /*ww w.ja  v a 2  s  . co  m*/
 * @param session The current session.
 * @return An environment suitable for acquiring an {@link LdapContext} for the client.
 */
protected Hashtable<String, Object> getEnvironment(IoSession session) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, session.getAttribute("baseDn"));
    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.core.jndi.CoreContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN);
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, AuthenticationLevel.SIMPLE.toString());

    return env;
}

From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java

private Hashtable getEnvironment(String userid, String password) {
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getEnvironment() ";
    Hashtable env = null;/* w  w w .j  av a 2  s .c  o  m*/

    try {
        env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

        if (VERSION != null && !"".equals(VERSION)) {
            log.debug(m + "ldap explicit version==" + VERSION);
            env.put(CONTEXT_VERSION_KEY, VERSION);
        }
        log.debug(m + "ldap version==" + env.get(CONTEXT_VERSION_KEY));

        env.put(Context.PROVIDER_URL, URL);
        log.debug(m + "ldap url==" + env.get(Context.PROVIDER_URL));

        if (!bindRequired()) {
            log.debug(m + "\"binding\" anonymously");
        } else {
            env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);

            String userForBind = null;
            String passwordForBind = null;
            if (!individualUserBind()) {
                userForBind = SECURITY_PRINCIPAL;
                passwordForBind = SECURITY_CREDENTIALS;
                log.debug(m + "binding to protected directory");
            } else {
                passwordForBind = password;
                if (SECURITY_PRINCIPAL == null || "".equals(SECURITY_PRINCIPAL)) {
                    userForBind = userid;
                    log.debug(m + "binding for real user");
                } else {
                    //simulate test against user-bind at directory server
                    userForBind = SECURITY_PRINCIPAL;
                    log.debug(m + "binding for --test-- user");
                }
            }
            env.put(Context.SECURITY_CREDENTIALS, passwordForBind);
            String[] parms = { userForBind };
            String userFormattedForBind = applyFilter(BIND_FILTER, parms);
            env.put(Context.SECURITY_PRINCIPAL, userFormattedForBind);
        }
        log.debug(m + "bind w " + env.get(Context.SECURITY_AUTHENTICATION));
        log.debug(m + "user== " + env.get(Context.SECURITY_PRINCIPAL));
        log.debug(m + "passwd==" + env.get(Context.SECURITY_CREDENTIALS));
    } catch (Throwable th) {
        if (LOG_STACK_TRACES) {
            log.error(m + "couldn't set up env for DirContext", th);
        } else {
            log.error(m + "couldn't set up env for DirContext" + th.getMessage());
        }
    } finally {
        log.debug(m + "< " + env);
    }
    return env;
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithoutTlsExtension(String userDN, String password) throws AuthenticationException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {//from   w w w .  j  a  v a  2 s.c  o m
        // Create initial context
        Context ctx = new InitialDirContext(env);
        ctx.close();
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException e) {
        throw new AuthenticationException("Error validating LDAP user", e);
    }
}

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

/**
 * /*  ww  w  . j a  v  a2  s  . c o m*/
 * Connect to LDAP with the User-Name and Password given as parameters
 * 
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) LDAP Base =
 * ldapContext.xml (property=ldapBase) LDAP Attributes Map =
 * ldapContext.xml (property=userAttrs)
 * 
 * 
 * @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
 */
@Override
public Attributes bindUser(String uid, String pwd, LDAPError errors) {
    // get user name, password and attributes
    String ldapUrl = ldapLoginModule.getLdapUrl();
    String[] userAttr = syncConfiguration.getUserAttributes();

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

    LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    String userDN = ldapDao.searchUserDN(uid, ctx);
    if (userDN == null) {
        log.info("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
    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.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        Control[] connectCtls = new Control[] {};
        LdapContext userBind = new InitialLdapContext(env, connectCtls);
        Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (AuthenticationException e) {
        log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (NamingException e) {
        log.error("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.tolven.ldapmgr.LDAPMgrPlugin.java

private DirContext getContext() {
    char[] rootPassword = getPassword(getTolvenConfigWrapper().getLDAPServerRootPasswordId());
    if (rootPassword == null) {
        throw new RuntimeException(
                "LDAP password is null for alias: " + getTolvenConfigWrapper().getLDAPServerRootPasswordId());
    }/*from w w w  .  ja  v  a2s  .c o m*/
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getProviderURL());
    env.put(Context.SECURITY_PRINCIPAL, getTolvenConfigWrapper().getLDAPServerRootUser());
    env.put(Context.SECURITY_CREDENTIALS, new String(rootPassword));
    try {
        return new InitialDirContext(env);
    } catch (NamingException ex) {
        throw new RuntimeException("Could not create an IntialDirContext", ex);
    }
}

From source file:org.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {/*from w ww. jav  a  2s  .  com*/

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}