Search in sources :

Example 1 with LDAPSearchResults

use of com.novell.ldap.LDAPSearchResults 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 LDAPSearchResults

use of com.novell.ldap.LDAPSearchResults 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 3 with LDAPSearchResults

use of com.novell.ldap.LDAPSearchResults in project neo4j-apoc-procedures by neo4j-contrib.

the class LoadLdapTest method testLoadLDAP.

@Test
public void testLoadLDAP() throws Exception {
    Map<String, Object> connParms = new HashMap<>();
    connParms.put("ldapHost", "ldap.forumsys.com");
    connParms.put("ldapPort", 389l);
    connParms.put("loginDN", "cn=read-only-admin,dc=example,dc=com");
    connParms.put("loginPW", "password");
    LoadLdap.LDAPManager mgr = new LoadLdap.LDAPManager(LoadLdap.getConnectionMap(connParms));
    Map<String, Object> searchParms = new HashMap<>();
    searchParms.put("searchBase", "dc=example,dc=com");
    searchParms.put("searchScope", "SCOPE_ONE");
    searchParms.put("searchFilter", "(&(objectClass=*)(uid=training))");
    ArrayList<String> ats = new ArrayList<>();
    ats.add("uid");
    searchParms.put("attributes", ats);
    LDAPSearchResults results = mgr.doSearch(searchParms);
    LDAPEntry le = results.next();
    assertEquals("uid=training,dc=example,dc=com", le.getDN());
    assertEquals("training", le.getAttribute("uid").getStringValue());
}
Also used : LDAPEntry(com.novell.ldap.LDAPEntry) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 4 with LDAPSearchResults

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

the class JLDAPProviderImpl method searchImpl.

public Map<String, Map<String, List<String>>> searchImpl(final String baseDN, final SearchHelper searchHelper, final boolean onlyFirstValue) throws ChaiOperationException, ChaiUnavailableException, IllegalStateException {
    activityPreCheck();
    // make a copy so if it changes somewhere else we won't be affected.
    final SearchHelper effectiveSearchHelper = new SearchHelper(searchHelper);
    // replace a null dn with an empty string
    final String effectiveBaseDN = baseDN != null ? baseDN : "";
    final int ldapScope;
    switch(effectiveSearchHelper.getSearchScope()) {
        case ONE:
            ldapScope = LDAPConnection.SCOPE_ONE;
            break;
        case BASE:
            ldapScope = LDAPConnection.SCOPE_BASE;
            break;
        case SUBTREE:
            ldapScope = LDAPConnection.SCOPE_SUB;
            break;
        default:
            ldapScope = -1;
    }
    final Map<String, Map<String, List<String>>> returnMap = new LinkedHashMap<>();
    final LDAPSearchConstraints constraints = new LDAPSearchConstraints();
    constraints.setMaxResults(effectiveSearchHelper.getMaxResults());
    constraints.setTimeLimit(effectiveSearchHelper.getTimeLimit());
    final String[] returnAttributes = effectiveSearchHelper.getAttributes() == null ? null : effectiveSearchHelper.getAttributes().toArray(new String[effectiveSearchHelper.getAttributes().size()]);
    final LDAPSearchResults results;
    try {
        results = ldapConnection.search(effectiveBaseDN, ldapScope, effectiveSearchHelper.getFilter(), returnAttributes, false, constraints);
        while (results.hasMore()) {
            final LDAPEntry loopEntry = results.next();
            final String loopDN = loopEntry.getDN();
            final Map<String, List<String>> loopAttributes = new LinkedHashMap<>();
            final LDAPAttributeSet attrSet = loopEntry.getAttributeSet();
            for (final Object anAttrSet : attrSet) {
                final LDAPAttribute loopAttr = (LDAPAttribute) anAttrSet;
                if (onlyFirstValue) {
                    loopAttributes.put(loopAttr.getName(), Collections.singletonList(loopAttr.getStringValue()));
                } else {
                    loopAttributes.put(loopAttr.getName(), Arrays.asList(loopAttr.getStringValueArray()));
                }
            }
            returnMap.put(loopDN, loopAttributes);
        }
    } catch (LDAPException e) {
        if (!returnMap.isEmpty()) {
            return Collections.unmodifiableMap(returnMap);
        }
        throw ChaiOperationException.forErrorMessage(e.getLDAPErrorMessage());
    }
    return Collections.unmodifiableMap(returnMap);
}
Also used : LDAPAttribute(com.novell.ldap.LDAPAttribute) LDAPSearchConstraints(com.novell.ldap.LDAPSearchConstraints) LDAPAttributeSet(com.novell.ldap.LDAPAttributeSet) SearchHelper(com.novell.ldapchai.util.SearchHelper) LinkedHashMap(java.util.LinkedHashMap) LDAPEntry(com.novell.ldap.LDAPEntry) LDAPSearchResults(com.novell.ldap.LDAPSearchResults) LDAPException(com.novell.ldap.LDAPException) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

LDAPSearchResults (com.novell.ldap.LDAPSearchResults)4 LDAPEntry (com.novell.ldap.LDAPEntry)3 LDAPException (com.novell.ldap.LDAPException)3 LDAPSearchConstraints (com.novell.ldap.LDAPSearchConstraints)3 LDAPConnection (com.novell.ldap.LDAPConnection)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 LDAPAttribute (com.novell.ldap.LDAPAttribute)1 LDAPAttributeSet (com.novell.ldap.LDAPAttributeSet)1 SearchHelper (com.novell.ldapchai.util.SearchHelper)1 ICaller (de.janrufmonitor.framework.ICaller)1 ICallerList (de.janrufmonitor.framework.ICallerList)1 IMultiPhoneCaller (de.janrufmonitor.framework.IMultiPhoneCaller)1 IPhonenumber (de.janrufmonitor.framework.IPhonenumber)1 InterruptedIOException (java.io.InterruptedIOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ConnectException (java.net.ConnectException)1 InetSocketAddress (java.net.InetSocketAddress)1 NoRouteToHostException (java.net.NoRouteToHostException)1 Socket (java.net.Socket)1