Example usage for javax.naming Context REFERRAL

List of usage examples for javax.naming Context REFERRAL

Introduction

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

Prototype

String REFERRAL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying how referrals encountered by the service provider are to be processed.

Usage

From source file:ldap.ActiveLoginImpl.java

/**
 * open the directory connection.//from   ww w. jav a2 s.c o m
 * @param url
 * @param tracing
 * @return
 * @throws NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
     * First, set up a large number of environment variables to sensible default valuse
     */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, 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, "com.sun.jndi.ldap.LdapCtxFactory");  // use default jndi provider
    env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider

    //env.put("java.naming.ldap.deleteRDN", "false");         // usually what we want
    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
     */

    DirContext newContext = new InitialDirContext(env);

    if (newContext == null)
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

    return newContext;

}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

public InitialLdapContext getInitialContext(String url, Map<String, String> properties) throws NamingException {
    Hashtable<String, String> variables = new Hashtable<String, String>(properties);
    variables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    variables.put(Context.PROVIDER_URL, url); // Must use fully qualified hostname

    if (isSslProtcolType()) {
        variables.put("java.naming.ldap.factory.socket", "com.adito.boot.CustomSSLSocketFactory");
        // Add the custom socket factory
    }//from   ww w.j  a va 2 s  .  c  o  m

    if (isFollowReferrals()) {
        variables.put(Context.REFERRAL, "follow");
    }

    variables.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(getTimeout()));
    variables.put("java.naming.ldap.version", "3");
    variables.put("com.sun.jndi.ldap.connect.pool", "true");
    variables.put("javax.security.sasl.qop", "auth-conf,auth-int,auth");
    variables.put(Context.SECURITY_PROTOCOL, getProtocolType());

    InitialLdapContext context = new InitialLdapContext(variables, null);
    String usedUrl = (String) context.getEnvironment().get(Context.PROVIDER_URL);
    setLastContactedActiveDirectoryUrl(usedUrl);
    return context;
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * (non-Javadoc)//from   w w w .ja  va 2  s.  co  m
 *
 * @see com.adito.security.UserDatabase#open(com.adito.core.CoreServlet, com.adito.realms.Realm)
 */
public void open(CoreServlet controllingServlet, Realm realm) throws Exception {
    try {
        super.open(controllingServlet, realm);

        if (logger.isInfoEnabled()) {
            logger.info("User database is being opened...");
        }

        initConfiguration();

        userContainer = new UserContainer(userCacheSize, inMemoryCache, usernamesAreCaseSensitive, baseDn);
        groupContainer = new GroupContainer(groupCacheSize, inMemoryCache);

        ldapContextSource = new LdapContextSource();
        String ldapProtocol = LDAP_PROTOCOL;
        if (useSSL) {
            ldapProtocol = LDAP_PROTOCOL_SSL;
        } else {
            ldapProtocol = LDAP_PROTOCOL;
        }
        ldapContextSource.setUrl(ldapProtocol + controllerHost);

        ldapContextSource.setBase(baseDn);
        ldapContextSource.setUserDn(serviceAccountName);
        ldapContextSource.setPassword(serviceAccountPassword);
        ldapContextSource.afterPropertiesSet();

        Map baseEnvProps = new Hashtable();
        baseEnvProps.put("com.sun.jndi.ldap.connect.timeout", timeOut);

        if (followReferrals) {
            baseEnvProps.put(Context.REFERRAL, "follow");
        }

        ldapContextSource.setBaseEnvironmentProperties(baseEnvProps);

        CoreServlet.getServlet().addCoreListener(this);
        threadRunner = new ThreadRunner("CacheUpdater", getCacheUpdaterJob(), timeToLive);
        threadRunner.start();
    } catch (Exception e) {
        close();
        throw e;
    }
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Protected constructor. Creates an initial default context environment and
 * adds support for referrals, a fix for OpenSSL aliases, and enables SSL as
 * default.//from   ww w .  j a va  2 s. c om
 * @param sessionTicket
 *            The session ticket for this instance, used when logging. May
 *            be <code>null</code> (which is treated as an empty string)
 *            or an empty string.
 * @param timeout
 *            The number of seconds before a connection attempt through this
 *            backend times out.
 * @param ssl
 *            <code>true</code> if SSL is to be used, otherwise
 *            <code>false</code>.
 * @param usernameAttributeName
 *            The name of the attribute holding the username. Cannot be
 *            <code>null</code>.
 * @param guessedAttributeName
 *            If we search but cannot find a user element (for example, if
 *            it is not searchable), we will guess that the (R)DN starts
 *            with the substring
 *            <code><i>guessedAttributeName</i>=<i>usernamePrefix</i></code>,
 *            where <code><i>usernamePrefix</i></code> is the part of the
 *            username preceding the 'at' character. Cannot be
 *            <code>null</code>.
 * @throws IllegalArgumentException
 *             If <code>timeout</code> is less than zero.
 * @throws NullPointerException
 *             If <code>guessedAttributeName</code> or
 *             <code>usernameAttribute</code> is <code>null</code>.
 */
protected JNDIBackend(final String sessionTicket, final int timeout, final boolean ssl,
        final String usernameAttributeName, final String guessedAttributeName)
        throws IllegalArgumentException, NullPointerException {

    // Assignments, with sanity checks.
    if (usernameAttributeName == null)
        throw new NullPointerException("Username attribute name cannot be NULL");
    usernameAttribute = usernameAttributeName;
    if (guessedAttributeName == null)
        throw new NullPointerException("Guessed attribute name cannot be NULL");
    guessedAttribute = guessedAttributeName;
    if (timeout < 0)
        throw new IllegalArgumentException("Timeout must be greater than zero");
    myTimeout = timeout;
    mySessionTicket = sessionTicket;
    if (mySessionTicket == null)
        mySessionTicket = "";

    // Create initial context environment.
    defaultEnv = new Hashtable<String, String>();
    defaultEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // To catch referrals.
    defaultEnv.put(Context.REFERRAL, "throw");

    // Due to OpenSSL problems.
    defaultEnv.put("java.naming.ldap.derefAliases", "never");

    // Use LDAP v3.
    defaultEnv.put("java.naming.ldap.version", "3");

    // Add timeout value for connection attempts (not searches).
    defaultEnv.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(1000 * timeout));

    // Should we enable SSL?
    if (ssl)
        defaultEnv.put(Context.SECURITY_PROTOCOL, "ssl");

}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

/**
 * Helper method to create the LDAP context needed to interact with the Active Directory.
 *
 * @return the relevant LdapContext//from  w  w w  .  ja  v a 2s  .  c  o m
 * @throws KerberosKDCConnectionException       if a connection to the KDC cannot be made
 * @throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate
 * @throws KerberosRealmException               if the realm does not map to a KDC
 * @throws KerberosOperationException           if an unexpected error occurred
 */
protected LdapContext createLdapContext() throws KerberosOperationException {
    KerberosCredential administratorCredentials = getAdministratorCredentials();

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY_CLASS);
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.SECURITY_PRINCIPAL, administratorCredentials.getPrincipal());
    properties.put(Context.SECURITY_CREDENTIALS, administratorCredentials.getPassword());
    properties.put(Context.SECURITY_AUTHENTICATION, "simple");
    properties.put(Context.REFERRAL, "follow");
    properties.put("java.naming.ldap.factory.socket", TrustingSSLSocketFactory.class.getName());

    try {
        return createInitialLdapContext(properties, null);
    } catch (CommunicationException e) {
        String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosKDCConnectionException(message, e);
    } catch (AuthenticationException e) {
        String message = String.format("Failed to authenticate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosAdminAuthenticationException(message, e);
    } catch (NamingException e) {
        String error = e.getMessage();

        if ((error != null) && !error.isEmpty()) {
            String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                    e.getMessage());
            LOG.warn(message, e);

            if (error.startsWith("Cannot parse url:")) {
                throw new KerberosKDCConnectionException(message, e);
            } else {
                throw new KerberosOperationException(message, e);
            }
        } else {
            throw new KerberosOperationException("Unexpected error condition", e);
        }
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Search.//from w w w.  j a va  2s .c  om
 * 
 * @param searchBase the search base
 * @param filter the filter
 * @param searchControls the controls
 * @param aliasesDereferencingMethod the aliases dereferencing method
 * @param referralsHandlingMethod the referrals handling method
 * @param controls the LDAP controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 * 
 * @return the naming enumeration or null if an exception occurs.
 */
public JndiStudioNamingEnumeration search(final String searchBase, final String filter,
        final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod,
        final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls,
        final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    final long requestNum = searchRequestNum++;

    // start
    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            LdapContext searchCtx = context;
            try {
                // create the search context
                searchCtx = context.newInstance(controls);

                // translate alias dereferencing method
                searchCtx.addToEnvironment(JAVA_NAMING_LDAP_DEREF_ALIASES,
                        translateDerefAliasMethod(aliasesDereferencingMethod));

                // use "throw" as we handle referrals manually
                searchCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // perform the search
                NamingEnumeration<SearchResult> result = searchCtx
                        .search(JNDIConnectionWrapper.getSaveJndiName(searchBase), filter, searchControls);
                namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, result, null,
                        searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod,
                        controls, requestNum, monitor, referralsInfo);
            } catch (PartialResultException | ReferralException e) {
                namingEnumeration = new JndiStudioNamingEnumeration(connection, searchCtx, null, e, searchBase,
                        filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls,
                        requestNum, monitor, referralsInfo);
            } catch (NamingException e) {
                namingException = e;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                if (namingEnumeration != null) {
                    logger.logSearchRequest(connection, searchBase, filter, searchControls,
                            aliasesDereferencingMethod, controls, requestNum, namingException);
                } else {
                    logger.logSearchRequest(connection, searchBase, filter, searchControls,
                            aliasesDereferencingMethod, controls, requestNum, namingException);
                    logger.logSearchResultDone(connection, 0, requestNum, namingException);
                }
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
        return null;
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
        return null;
    } else {
        return runnable.getResult();
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Modifies attributes of an entry.//w  ww .  j  av  a2  s.  co m
 * 
 * @param dn the Dn
 * @param modificationItems the modification items
 * @param controls the controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 */
public void modifyEntry(final String dn, final ModificationItem[] modificationItems, final Control[] controls,
        final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    if (connection.isReadOnly()) {
        monitor.reportError(
                new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName())));
        return;
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // create modify context
                LdapContext modCtx = context.newInstance(controls);

                // use "throw" as we handle referrals manually
                modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // perform modification
                modCtx.modifyAttributes(getSaveJndiName(dn), modificationItems);
            } catch (ReferralException re) {
                try {
                    ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo);
                    Referral referral = newReferralsInfo.getNextReferral();

                    if (referral != null) {
                        Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral,
                                monitor, this);
                        if (referralConnection != null) {
                            List<String> urls = new ArrayList<>(referral.getLdapUrls());

                            String referralDn = new LdapUrl(urls.get(0)).getDn().getName();
                            referralConnection.getConnectionWrapper().modifyEntry(referralDn, modificationItems,
                                    controls, monitor, newReferralsInfo);
                        } else {
                            canceled = true;
                        }
                    }

                    return;
                } catch (NamingException ne) {
                    namingException = ne;
                } catch (LdapURLEncodingException e) {
                    namingException = new NamingException(e.getMessage());
                }
            } catch (NamingException ne) {
                namingException = ne;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                logger.logChangetypeModify(connection, dn, modificationItems, controls, namingException);
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Renames an entry.//from  www. j  a  v  a2s  .c o  m
 * 
 * @param oldDn the old Dn
 * @param newDn the new Dn
 * @param deleteOldRdn true to delete the old Rdn
 * @param controls the controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 */
public void renameEntry(final String oldDn, final String newDn, final boolean deleteOldRdn,
        final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    if (connection.isReadOnly()) {
        monitor.reportError(
                new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName())));
        return;
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // create modify context
                LdapContext modCtx = context.newInstance(controls);

                // use "throw" as we handle referrals manually
                modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // delete old Rdn
                if (deleteOldRdn) {
                    modCtx.addToEnvironment(JAVA_NAMING_LDAP_DELETE_RDN, "true"); //$NON-NLS-1$
                } else {
                    modCtx.addToEnvironment(JAVA_NAMING_LDAP_DELETE_RDN, "false"); //$NON-NLS-1$
                }

                // rename entry
                modCtx.rename(getSaveJndiName(oldDn), getSaveJndiName(newDn));
            } catch (ReferralException re) {
                try {
                    ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo);
                    Referral referral = newReferralsInfo.getNextReferral();
                    if (referral != null) {
                        Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral,
                                monitor, this);
                        if (referralConnection != null) {
                            referralConnection.getConnectionWrapper().renameEntry(oldDn, newDn, deleteOldRdn,
                                    controls, monitor, newReferralsInfo);
                        } else {
                            canceled = true;
                        }
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                }
            } catch (NamingException ne) {
                namingException = ne;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                logger.logChangetypeModDn(connection, oldDn, newDn, deleteOldRdn, controls, namingException);
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Creates an entry./*from w ww  .java  2  s  .c  o  m*/
 * 
 * @param dn the entry's Dn
 * @param attributes the entry's attributes
 * @param controls the controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 */
public void createEntry(final String dn, final Attributes attributes, final Control[] controls,
        final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) {
    if (connection.isReadOnly()) {
        monitor.reportError(
                new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName())));
        return;
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // create modify context
                LdapContext modCtx = context.newInstance(controls);

                // use "throw" as we handle referrals manually
                modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // create entry
                modCtx.createSubcontext(getSaveJndiName(dn), attributes);
            } catch (ReferralException re) {
                try {
                    ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo);
                    Referral referral = newReferralsInfo.getNextReferral();

                    if (referral != null) {
                        Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral,
                                monitor, this);

                        if (referralConnection != null) {
                            List<String> urls = new ArrayList<>(referral.getLdapUrls());

                            String referralDn = new LdapUrl(urls.get(0)).getDn().getName();
                            referralConnection.getConnectionWrapper().createEntry(referralDn, attributes,
                                    controls, monitor, newReferralsInfo);
                        } else {
                            canceled = true;
                        }
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                } catch (LdapURLEncodingException e) {
                    namingException = new NamingException(e.getMessage());
                }
            } catch (NamingException ne) {
                namingException = ne;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                logger.logChangetypeAdd(connection, dn, attributes, controls, namingException);
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

/**
 * Deletes an entry./* www  . j  ava 2 s.c om*/
 * 
 * @param dn the Dn of the entry to delete
 * @param controls the controls
 * @param monitor the progress monitor
 * @param referralsInfo the referrals info
 */
public void deleteEntry(final String dn, final Control[] controls, final StudioProgressMonitor monitor,
        final ReferralsInfo referralsInfo) {
    if (connection.isReadOnly()) {
        monitor.reportError(
                new Exception(NLS.bind(Messages.error__connection_is_readonly, connection.getName())));
        return;
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // create modify context
                LdapContext modCtx = context.newInstance(controls);

                // use "throw" as we handle referrals manually
                modCtx.addToEnvironment(Context.REFERRAL, REFERRAL_THROW);

                // delete entry
                modCtx.destroySubcontext(getSaveJndiName(dn));
            } catch (ReferralException re) {
                try {
                    ReferralsInfo newReferralsInfo = handleReferralException(re, referralsInfo);
                    Referral referral = newReferralsInfo.getNextReferral();
                    if (referral != null) {
                        Connection referralConnection = ConnectionWrapperUtils.getReferralConnection(referral,
                                monitor, this);
                        if (referralConnection != null) {
                            List<String> urls = new ArrayList<>(referral.getLdapUrls());

                            String referralDn = new LdapUrl(urls.get(0)).getDn().getName();
                            referralConnection.getConnectionWrapper().deleteEntry(referralDn, controls, monitor,
                                    newReferralsInfo);
                        } else {
                            canceled = true;
                        }
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                } catch (LdapURLEncodingException e) {
                    namingException = new NamingException(e.getMessage());
                }
            } catch (NamingException ne) {
                namingException = ne;
            }

            for (IJndiLogger logger : getJndiLoggers()) {
                logger.logChangetypeDelete(connection, dn, controls, namingException);
            }
        }
    };

    try {
        checkConnectionAndRunAndMonitor(runnable, monitor);
    } catch (NamingException ne) {
        monitor.reportError(ne);
    }

    if (runnable.isCanceled()) {
        monitor.setCanceled(true);
    }
    if (runnable.getException() != null) {
        monitor.reportError(runnable.getException());
    }
}