Search in sources :

Example 56 with NamingException

use of javax.naming.NamingException in project hudson-2.x by hudson.

the class LDAPSecurityRealm method inferRootDN.

/**
     * Infer the root DN.
     *
     * @return null if not found.
     */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, getServerUrl() + '/');
        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (// this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
        a != null)
            return a.toString();
        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 57 with NamingException

use of javax.naming.NamingException in project javaee7-samples by javaee-samples.

the class EmployeeBean method postConstruct.

@PostConstruct
public void postConstruct() {
    try {
        Context context = new InitialContext();
        em = (EntityManager) context.lookup("java:comp/env/persistence/myJNDI");
    } catch (NamingException ex) {
        Logger.getLogger(EmployeeBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) PersistenceContext(javax.persistence.PersistenceContext) NamingException(javax.naming.NamingException) InitialContext(javax.naming.InitialContext) PostConstruct(javax.annotation.PostConstruct)

Example 58 with NamingException

use of javax.naming.NamingException in project Openfire by igniterealtime.

the class LdapUserTester method getSample.

/**
     * Returns a list of usernames with a sample of the users found in LDAP.
     *
     * @param maxSample the max size of the sample to return.
     * @return a list of usernames with a sample of the users found in LDAP.
     * @throws NamingException if something goes wrong....
     */
public List<String> getSample(int maxSample) throws NamingException {
    List<String> usernames = new ArrayList<>();
    LdapContext ctx = null;
    try {
        ctx = manager.getContext();
        // Sort on username field.
        Control[] searchControl;
        try {
            searchControl = new Control[] { new SortControl(new String[] { manager.getUsernameField() }, Control.NONCRITICAL) };
        } catch (IOException e) {
            Log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
        ctx.setRequestControls(searchControl);
        // Search for the dn based on the username.
        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (manager.isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(new String[] { manager.getUsernameField() });
        // Limit results to those we'll need to process
        searchControls.setCountLimit(maxSample);
        String filter = MessageFormat.format(manager.getSearchFilter(), "*");
        NamingEnumeration answer = ctx.search("", filter, searchControls);
        while (answer.hasMoreElements()) {
            // Get the next userID.
            String username = (String) ((SearchResult) answer.next()).getAttributes().get(manager.getUsernameField()).get();
            // Escape username and add to results.
            usernames.add(JID.escapeNode(username));
        }
        // Close the enumeration.
        answer.close();
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        } catch (Exception ignored) {
        // Ignore.
        }
    }
    return usernames;
}
Also used : SortControl(javax.naming.ldap.SortControl) Control(javax.naming.ldap.Control) SortControl(javax.naming.ldap.SortControl) NamingEnumeration(javax.naming.NamingEnumeration) IOException(java.io.IOException) LdapContext(javax.naming.ldap.LdapContext) IOException(java.io.IOException) NamingException(javax.naming.NamingException)

Example 59 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class DNS method getHosts.

/**
   * Returns all the host names associated by the provided nameserver with the
   * address bound to the specified network interface
   *
   * @param strInterface
   *            The name of the network interface or subinterface to query
   *            (e.g. eth0 or eth0:0)
   * @param nameserver
   *            The DNS host name
   * @param tryfallbackResolution
   *            if true and if reverse DNS resolution fails then attempt to
   *            resolve the hostname with
   *            {@link InetAddress#getCanonicalHostName()} which includes
   *            hosts file resolution.
   * @return A string vector of all host names associated with the IPs tied to
   *         the specified interface
   * @throws UnknownHostException if the given interface is invalid
   */
public static String[] getHosts(String strInterface, @Nullable String nameserver, boolean tryfallbackResolution) throws UnknownHostException {
    final List<String> hosts = new Vector<String>();
    final List<InetAddress> addresses = getIPsAsInetAddressList(strInterface, true);
    for (InetAddress address : addresses) {
        try {
            hosts.add(reverseDns(address, nameserver));
        } catch (NamingException ignored) {
        }
    }
    if (hosts.isEmpty() && tryfallbackResolution) {
        for (InetAddress address : addresses) {
            final String canonicalHostName = address.getCanonicalHostName();
            // Don't use the result if it looks like an IP address.
            if (!InetAddresses.isInetAddress(canonicalHostName)) {
                hosts.add(canonicalHostName);
            }
        }
    }
    if (hosts.isEmpty()) {
        LOG.warn("Unable to determine hostname for interface " + strInterface);
        hosts.add(cachedHostname);
    }
    return hosts.toArray(new String[hosts.size()]);
}
Also used : NamingException(javax.naming.NamingException) Vector(java.util.Vector) InetAddress(java.net.InetAddress)

Example 60 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class LdapGroupsMapping method getRelativeDistinguishedName.

/**
   * A helper method to get the Relative Distinguished Name (RDN) from
   * Distinguished name (DN). According to Active Directory documentation,
   * a group object's RDN is a CN.
   *
   * @param distinguishedName A string representing a distinguished name.
   * @throws NamingException if the DN is malformed.
   * @return a string which represents the RDN
   */
private String getRelativeDistinguishedName(String distinguishedName) throws NamingException {
    LdapName ldn = new LdapName(distinguishedName);
    List<Rdn> rdns = ldn.getRdns();
    if (rdns.isEmpty()) {
        throw new NamingException("DN is empty");
    }
    Rdn rdn = rdns.get(rdns.size() - 1);
    if (rdn.getType().equalsIgnoreCase(groupNameAttr)) {
        String groupName = (String) rdn.getValue();
        return groupName;
    }
    throw new NamingException("Unable to find RDN: The DN " + distinguishedName + " is malformed.");
}
Also used : NamingException(javax.naming.NamingException) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Aggregations

NamingException (javax.naming.NamingException)698 InitialContext (javax.naming.InitialContext)234 Context (javax.naming.Context)169 IOException (java.io.IOException)82 NameNotFoundException (javax.naming.NameNotFoundException)67 SQLException (java.sql.SQLException)58 Reference (javax.naming.Reference)53 DataSource (javax.sql.DataSource)52 Test (org.junit.Test)51 Attribute (javax.naming.directory.Attribute)49 DirContext (javax.naming.directory.DirContext)48 Properties (java.util.Properties)45 ArrayList (java.util.ArrayList)41 Name (javax.naming.Name)36 SearchResult (javax.naming.directory.SearchResult)35 Hashtable (java.util.Hashtable)34 InitialDirContext (javax.naming.directory.InitialDirContext)34 Connection (java.sql.Connection)33 NameAlreadyBoundException (javax.naming.NameAlreadyBoundException)32 Attributes (javax.naming.directory.Attributes)30