Search in sources :

Example 1 with LDAPConnection

use of com.novell.ldap.LDAPConnection in project opennms by OpenNMS.

the class LdapMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to connect the service.
 *
 * Provided that the interface's response is valid we set the service status
 * to SERVICE_AVAILABLE and return.
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
    String reason = null;
    final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // get the parameters
    // 
    final int ldapVersion = ParameterMap.getKeyedInteger(parameters, "version", LDAPConnection.LDAP_V3);
    final int ldapPort = determinePort(parameters);
    final String searchBase = ParameterMap.getKeyedString(parameters, "searchbase", DEFAULT_BASE);
    final String searchFilter = ParameterMap.getKeyedString(parameters, "searchfilter", DEFAULT_FILTER);
    final String password = (String) parameters.get("password");
    final String ldapDn = (String) parameters.get("dn");
    String address = InetAddrUtils.str(svc.getAddress());
    // first just try a connection to the box via socket. Just in case there
    // is
    // a no way to route to the address, don't iterate through the retries,
    // as a
    // NoRouteToHost exception will only be thrown after about 5 minutes,
    // thus tying
    // up the thread
    Double responseTime = null;
    Socket socket = null;
    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(svc.getAddress(), ldapPort), tracker.getConnectionTimeout());
        socket.setSoTimeout(tracker.getSoTimeout());
        LOG.debug("LdapMonitor: connected to host: {} on port: {}", address, ldapPort);
        // We're connected, so upgrade status to unresponsive
        serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
        if (socket != null)
            socket.close();
        // lets detect the service
        LDAPConnection lc = new LDAPConnection(new TimeoutLDAPSocket(tracker.getSoTimeout()));
        for (tracker.reset(); tracker.shouldRetry() && !(serviceStatus == PollStatus.SERVICE_AVAILABLE); tracker.nextAttempt()) {
            LOG.debug("polling LDAP on {}, {}", address, tracker);
            // connect to the ldap server
            tracker.startAttempt();
            try {
                lc.connect(address, ldapPort);
                LOG.debug("connected to LDAP server {} on port {}", address, ldapPort);
            } catch (LDAPException e) {
                LOG.debug("could not connect to LDAP server {} on port {}", address, ldapPort);
                reason = "could not connect to LDAP server " + address + " on port " + ldapPort;
                continue;
            }
            // bind if possible
            if (ldapDn != null && password != null) {
                try {
                    lc.bind(ldapVersion, ldapDn, password.getBytes());
                    LOG.debug("bound to LDAP server version {} with distinguished name {}", ldapVersion, ldapDn);
                    LOG.debug("poll: responseTime= {}ms", tracker.elapsedTimeInMillis());
                } catch (LDAPException e) {
                    try {
                        lc.disconnect();
                    } catch (LDAPException ex) {
                        LOG.debug(ex.getMessage());
                    }
                    LOG.debug("could not bind to LDAP server version {} with distinguished name {}", ldapVersion, ldapDn);
                    reason = "could not bind to LDAP server version " + ldapVersion + " with distinguished name " + ldapDn;
                    continue;
                }
            }
            // do a quick search and see if any results come back
            boolean attributeOnly = true;
            String[] attrs = { LDAPConnection.NO_ATTRS };
            int searchScope = LDAPConnection.SCOPE_ONE;
            LOG.debug("running search {} from {}", searchFilter, searchBase);
            LDAPSearchResults results = null;
            int msLimit = (int) tracker.getTimeoutInMillis();
            int serverLimit = (int) tracker.getTimeoutInSeconds() + 1;
            LDAPSearchConstraints cons = new LDAPSearchConstraints(msLimit, serverLimit, // dereference: default = never
            LDAPSearchConstraints.DEREF_NEVER, // maxResults: default = 1000
            1000, // doReferrals: default = false
            false, // batchSize: default = 1
            1, // handler: default = null
            null, // hop_limit: default = 10
            10);
            try {
                results = lc.search(searchBase, searchScope, searchFilter, attrs, attributeOnly, cons);
                if (results != null && results.hasMore()) {
                    responseTime = tracker.elapsedTimeInMillis();
                    LOG.debug("search yielded {} result(s)", results.getCount());
                    serviceStatus = PollStatus.SERVICE_AVAILABLE;
                } else {
                    LOG.debug("no results found from search");
                    reason = "No results found from search";
                    serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
                }
            } catch (LDAPException e) {
                try {
                    lc.disconnect();
                } catch (LDAPException ex) {
                    LOG.debug(ex.getMessage());
                }
                LOG.debug("could not perform search {} from {}", searchFilter, searchBase);
                reason = "could not perform search " + searchFilter + " from " + searchBase;
                continue;
            }
            try {
                lc.disconnect();
                LOG.debug("disconected from LDAP server {} on port {}", address, ldapPort);
            } catch (LDAPException e) {
                LOG.debug(e.getMessage());
            }
        }
    } catch (ConnectException e) {
        LOG.debug("connection refused to host {}", address, e);
        reason = "connection refused to host " + address;
    } catch (NoRouteToHostException e) {
        LOG.debug("No route to host {}", address, e);
        reason = "No route to host " + address;
    } catch (InterruptedIOException e) {
        LOG.debug("did not connect to host with {}", tracker);
        reason = "did not connect to host with " + tracker;
    } catch (Throwable t) {
        LOG.debug("An undeclared throwable exception caught contacting host {}", address, t);
        reason = "An undeclared throwable exception caught contacting host " + address;
    }
    return PollStatus.get(serviceStatus, reason, responseTime);
}
Also used : InterruptedIOException(java.io.InterruptedIOException) InetSocketAddress(java.net.InetSocketAddress) LDAPSearchConstraints(com.novell.ldap.LDAPSearchConstraints) LDAPConnection(com.novell.ldap.LDAPConnection) NoRouteToHostException(java.net.NoRouteToHostException) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 2 with LDAPConnection

use of com.novell.ldap.LDAPConnection in project opennms by OpenNMS.

the class LdapDetectorClient method connect.

/**
 * {@inheritDoc}
 */
@Override
public void connect(final InetAddress address, final int port, final int timeout) throws IOException, Exception {
    super.connect(address, port, timeout);
    final LDAPConnection lc = new LDAPConnection(new TimeoutLDAPSocket(timeout));
    lc.connect(InetAddressUtils.str(address), port);
}
Also used : LDAPConnection(com.novell.ldap.LDAPConnection)

Example 3 with LDAPConnection

use of com.novell.ldap.LDAPConnection in project janrufmonitor by tbrandt77.

the class LdapContactsProxy method getContacts.

public synchronized ICallerList getContacts(String category) throws LdapContactsException {
    ICallerList cl = getRuntime().getCallerFactory().createCallerList(getMaxResults());
    String query = "(objectclass=*)";
    if (category != null) {
        String ldapAttrib = LdapMappingManager.getInstance().getLdapAttribute(IJAMConst.ATTRIBUTE_NAME_CATEGORY);
        if (ldapAttrib != null && ldapAttrib.trim().length() > 0) {
            query = "(" + ldapAttrib + "=" + category + ")";
        }
    }
    LDAPConnection lc = new LDAPConnection();
    try {
        lc.connect(getServer(), getPort());
        lc.bind(LDAPConnection.LDAP_V3, getLoginUser(), getLoginPassword().getBytes("UTF-8"));
        LDAPSearchConstraints cons = lc.getSearchConstraints();
        cons.setMaxResults(getMaxResults());
        String baseDN = this.getBaseDN();
        String[] bases = null;
        if (baseDN.indexOf("|") > 0) {
            bases = baseDN.split("\\|");
        } else {
            bases = new String[] { baseDN };
        }
        for (int i = 0; i < bases.length; i++) {
            LDAPSearchResults searchResults = lc.search(bases[i], getScope(), query, // return all attributes
            null, // return attrs and values
            false, cons);
            ICaller c = null;
            while (searchResults.hasMore()) {
                LDAPEntry nextEntry = null;
                try {
                    nextEntry = searchResults.next();
                } catch (LDAPException e) {
                    if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
                        break;
                    else
                        continue;
                }
                c = LdapMappingManager.getInstance().mapToJamCaller(nextEntry);
                if (c != null) {
                    cl.add(c);
                }
            }
        }
        // disconnect from the server
        lc.disconnect();
        LdapMappingManager.invalidate();
    } catch (LDAPException e) {
        this.m_logger.log(Level.SEVERE, e.toString(), e);
        throw new LdapContactsException(e.toString(), e);
    } catch (UnsupportedEncodingException e) {
        this.m_logger.log(Level.SEVERE, e.toString(), e);
    }
    if (this.m_dbh != null) {
        try {
            this.m_dbh.deleteAll();
            ICaller c = null;
            for (int i = 0, j = cl.size(); i < j; i++) {
                c = cl.get(i);
                if (c instanceof IMultiPhoneCaller) {
                    List phones = ((IMultiPhoneCaller) c).getPhonenumbers();
                    IPhonenumber pn = null;
                    for (int k = 0; k < phones.size(); k++) {
                        pn = (IPhonenumber) phones.get(k);
                        this.m_dbh.insert(c.getUUID(), pn.getIntAreaCode(), pn.getAreaCode(), pn.getCallNumber());
                    }
                } else {
                    IPhonenumber pn = c.getPhoneNumber();
                    this.m_dbh.insert(c.getUUID(), pn.getIntAreaCode(), pn.getAreaCode(), pn.getCallNumber());
                }
            }
        } catch (SQLException e) {
            throw new LdapContactsException(e.getMessage(), e);
        }
    } else {
        this.m_logger.warning("GoogleContacts proxy datahandler not initialized. Could not insert google contacts...");
    }
    return cl;
}
Also used : SQLException(java.sql.SQLException) LDAPSearchConstraints(com.novell.ldap.LDAPSearchConstraints) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LDAPConnection(com.novell.ldap.LDAPConnection) ICaller(de.janrufmonitor.framework.ICaller) LDAPEntry(com.novell.ldap.LDAPEntry) ICallerList(de.janrufmonitor.framework.ICallerList) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) IMultiPhoneCaller(de.janrufmonitor.framework.IMultiPhoneCaller) ICallerList(de.janrufmonitor.framework.ICallerList) List(java.util.List) IPhonenumber(de.janrufmonitor.framework.IPhonenumber)

Example 4 with LDAPConnection

use of com.novell.ldap.LDAPConnection in project janrufmonitor by tbrandt77.

the class LdapContactsProxy method identifyByUUID.

private ICaller identifyByUUID(String uuid) throws LdapContactsException {
    LDAPConnection lc = new LDAPConnection();
    try {
        lc.connect(getServer(), getPort());
        lc.bind(LDAPConnection.LDAP_V3, getLoginUser(), getLoginPassword().getBytes("UTF8"));
        lc.read(uuid);
        // return attrs and values
        LDAPEntry entry = lc.read(uuid);
        if (entry != null) {
            ICaller c = LdapMappingManager.getInstance().mapToJamCaller(entry);
            if (c != null) {
                return c;
            }
        }
    } catch (LDAPException e) {
        throw new LdapContactsException(e.toString(), e);
    } catch (UnsupportedEncodingException e) {
        throw new LdapContactsException(e.toString(), e);
    } finally {
        LdapMappingManager.invalidate();
        try {
            lc.disconnect();
        } catch (LDAPException e) {
            throw new LdapContactsException(e.toString(), e);
        }
    }
    return null;
}
Also used : ICaller(de.janrufmonitor.framework.ICaller) LDAPEntry(com.novell.ldap.LDAPEntry) LDAPException(com.novell.ldap.LDAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LDAPConnection(com.novell.ldap.LDAPConnection)

Example 5 with LDAPConnection

use of com.novell.ldap.LDAPConnection in project ldapchai by ldapchai.

the class JLDAPProviderImpl method init.

public void init(final ChaiConfiguration chaiConfig, final ChaiProviderFactory providerFactory) throws ChaiUnavailableException, IllegalStateException {
    super.init(chaiConfig, providerFactory);
    try {
        // grab the first URL from the list.
        final URI ldapURL = URI.create(chaiConfig.bindURLsAsList().get(0));
        if (ldapURL.getScheme().equalsIgnoreCase("ldaps")) {
            final boolean usePromiscuousSSL = Boolean.parseBoolean(chaiConfig.getSetting(ChaiSetting.PROMISCUOUS_SSL));
            if (usePromiscuousSSL) {
                try {
                    final SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, new X509TrustManager[] { new PromiscuousTrustManager() }, new java.security.SecureRandom());
                    ldapConnection = new LDAPConnection(new LDAPJSSESecureSocketFactory(sc.getSocketFactory()));
                } catch (Exception e) {
                    LOGGER.error("error creating promiscuous ssl ldap socket factory: " + e.getMessage());
                }
            } else if (chaiConfig.getTrustManager() != null) {
                try {
                    final SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, chaiConfig.getTrustManager(), new java.security.SecureRandom());
                    ldapConnection = new LDAPConnection(new LDAPJSSESecureSocketFactory(sc.getSocketFactory()));
                } catch (Exception e) {
                    LOGGER.error("error creating configured ssl ldap socket factory: " + e.getMessage());
                }
            } else {
                ldapConnection = new LDAPConnection(new LDAPJSSESecureSocketFactory());
            }
        } else {
            ldapConnection = new LDAPConnection();
        }
        ldapConnection.connect(ldapURL.getHost(), ldapURL.getPort());
        if (chaiConfig.getBooleanSetting(ChaiSetting.LDAP_FOLLOW_REFERRALS)) {
            final LDAPConstraints ldapConstraints = new LDAPConstraints();
            ldapConstraints.setReferralFollowing(true);
            ldapConnection.setConstraints(ldapConstraints);
        }
        final String characterEncoding = chaiConfig.getSetting(ChaiSetting.LDAP_CHARACTER_ENCODING);
        final byte[] bindPassword = chaiConfig.getSetting(ChaiSetting.BIND_PASSWORD).getBytes(Charset.forName(characterEncoding));
        final String bindDN = chaiConfig.getSetting(ChaiSetting.BIND_DN);
        ldapConnection.bind(LDAPConnection.LDAP_V3, bindDN, bindPassword);
    } catch (LDAPException e) {
        final String message = e.getMessage();
        if (message.contains("Connect Error")) {
            throw new ChaiUnavailableException(message, ChaiError.COMMUNICATION, false, false);
        }
        throw ChaiUnavailableException.forErrorMessage(message);
    }
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) SSLContext(javax.net.ssl.SSLContext) LDAPConnection(com.novell.ldap.LDAPConnection) URI(java.net.URI) LDAPException(com.novell.ldap.LDAPException) NamingException(javax.naming.NamingException) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) LDAPException(com.novell.ldap.LDAPException) LDAPConstraints(com.novell.ldap.LDAPConstraints) LDAPJSSESecureSocketFactory(com.novell.ldap.LDAPJSSESecureSocketFactory)

Aggregations

LDAPConnection (com.novell.ldap.LDAPConnection)5 LDAPException (com.novell.ldap.LDAPException)4 LDAPEntry (com.novell.ldap.LDAPEntry)2 LDAPSearchConstraints (com.novell.ldap.LDAPSearchConstraints)2 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)2 ICaller (de.janrufmonitor.framework.ICaller)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 LDAPConstraints (com.novell.ldap.LDAPConstraints)1 LDAPJSSESecureSocketFactory (com.novell.ldap.LDAPJSSESecureSocketFactory)1 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)1 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)1 ICallerList (de.janrufmonitor.framework.ICallerList)1 IMultiPhoneCaller (de.janrufmonitor.framework.IMultiPhoneCaller)1 IPhonenumber (de.janrufmonitor.framework.IPhonenumber)1 InterruptedIOException (java.io.InterruptedIOException)1 ConnectException (java.net.ConnectException)1 InetSocketAddress (java.net.InetSocketAddress)1 NoRouteToHostException (java.net.NoRouteToHostException)1 Socket (java.net.Socket)1 URI (java.net.URI)1