/**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Returns a
   * <code>java.util.List<String></code> with the Distinguished names of the entries that match. You
   * can specify a match limit
   *
   * @param q DirectoryQuery
   * @param limit An <code>Integer</code> with the limit of matches
   * @return List<String>
   * @exception LDAPException
   */
  public List<String> searchDN(final LDAPDirectoryQuery q, final Integer limit)
      throws LDAPException {
    List<String> results = new ArrayList<String>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      if (limit != null) {
        ctls.setCountLimit(limit.intValue());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        results.add(sr.getNameInNamespace());
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() null pointer");
      throw new LDAPException("search DN null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
Ejemplo n.º 2
0
  /** {@inheritDoc} */
  public LDAPConnection getConnection() throws LDAPException {

    if (M_log.isDebugEnabled()) {
      M_log.debug("getConnection()");
    }
    LDAPConnection conn = newConnection();

    if (config.isAutoBind()) {
      if (M_log.isDebugEnabled()) {
        M_log.debug("getConnection(): auto-binding");
      }
      try {
        bind(conn, config.getLdapUser(), config.getLdapPassword());
      } catch (LDAPException ldape) {
        if (ldape.getResultCode() == LDAPException.INVALID_CREDENTIALS) {
          M_log.warn(
              "Failed to bind against: "
                  + conn.getHost()
                  + " with user: "******" password: "******".", "*"));
        }
        throw ldape;
      }
    }

    return conn;
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions
   *
   * @param q DirectoryQuery
   * @return List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> search(final LDAPDirectoryQuery q) throws LDAPException {
    List<Identity> results = new ArrayList<Identity>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      List<String> _aux = new ArrayList<String>();
      _aux.add("modifyTimestamp");
      _aux.add("*");
      ctls.setReturningAttributes(_aux.toArray(new String[_aux.size()]));
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = null;
        if (sr.getName().isEmpty()) {
          _e = new LDAPDirectoryEntry(baseDN);
        } else {
          _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
          /*
           * _e = new LDAPEntry(sr.getName() + "," + this.baseDN); if(_e.getID().matches(
           * "^(ldap|ldaps)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*[^\\.\\,\\)\\(\\s]$"
           * )) { URL _url = new URL(_e.getID()); _e.setID(_url.getPath()); }
           */
        }
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        results.add(_e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "search() null pointer");
      throw new LDAPException("search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "search() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Results will
   * be order using the values of a specific attribute
   *
   * @param q DirectoryQuery
   * @param attribute Name of the attribute that determines the order
   * @return java.util.List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> sortedSearch(final LDAPDirectoryQuery q, final String attribute)
      throws LDAPException {
    TreeMap<String, Identity> results =
        new TreeMap<String, Identity>(Collator.getInstance(new Locale("es")));
    try {
      LdapContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("Directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());
      ctx.setRequestControls(new Control[] {new SortControl(attribute, Control.NONCRITICAL)});

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        String _value = String.valueOf(_e.getAttribute(attribute)[0]);
        while (results.containsKey(_value)) {
          _value = _value.concat("0");
        }
        results.put(_value, _e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() null pointer");
      throw new LDAPException("sorted search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } catch (IOException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return new ArrayList<Identity>(results.values());
  }
Ejemplo n.º 5
0
  /** {@inheritDoc} */
  @InternalUseOnly()
  public void responseReceived(final LDAPResponse response) throws LDAPException {
    if (!responseReturned.compareAndSet(false, true)) {
      return;
    }

    final long responseTime = System.nanoTime() - createTime;

    final LDAPResult result;
    if (response instanceof ConnectionClosedResponse) {
      final ConnectionClosedResponse ccr = (ConnectionClosedResponse) response;
      final String msg = ccr.getMessage();
      if (msg == null) {
        result =
            new LDAPResult(
                asyncRequestID.getMessageID(),
                ccr.getResultCode(),
                ERR_CONN_CLOSED_WAITING_FOR_ASYNC_RESPONSE.get(),
                null,
                StaticUtils.NO_STRINGS,
                StaticUtils.NO_CONTROLS);
      } else {
        result =
            new LDAPResult(
                asyncRequestID.getMessageID(),
                ccr.getResultCode(),
                ERR_CONN_CLOSED_WAITING_FOR_ASYNC_RESPONSE_WITH_MESSAGE.get(msg),
                null,
                StaticUtils.NO_STRINGS,
                StaticUtils.NO_CONTROLS);
      }
    } else {
      result = (LDAPResult) response;
    }

    switch (operationType) {
      case ADD:
        connection.getConnectionStatistics().incrementNumAddResponses(responseTime);
        break;
      case DELETE:
        connection.getConnectionStatistics().incrementNumDeleteResponses(responseTime);
        break;
      case MODIFY:
        connection.getConnectionStatistics().incrementNumModifyResponses(responseTime);
        break;
      case MODIFY_DN:
        connection.getConnectionStatistics().incrementNumModifyDNResponses(responseTime);
        break;
    }

    resultListener.ldapResultReceived(asyncRequestID, result);
    asyncRequestID.setResult(result);
  }
Ejemplo n.º 6
0
 private static void closeConnection(final LDAPConnection ld) {
   if (LDAPConnectionPool.verbose) {
     System.out.println("Closing connection");
   }
   if (ld == null || !ld.isConnected()) {
     return;
   }
   try {
     ld.disconnect();
   } catch (final LDAPException ldape) {
     System.err.println(" Problem closing connection to LDAP server " + ldape.getMessage());
   }
 }
  /**
   * Check if an entry has specific attribute value. This method is more efficient than getting a
   * complete <code>LDAPDirectoryEntry</code> and check the value
   *
   * @param DN Distinguished Name of the entry
   * @param attribute Attribute name
   * @param value Attribute value
   * @return boolean
   * @exception LDAPException
   */
  public boolean checkEntryAttribute(final String DN, final String attribute, final Object value)
      throws LDAPException {
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }

      Object[] _values;
      StringBuilder _sb = new StringBuilder();
      if (value instanceof Object[]) {
        _values = (Object[]) value;
        if (_values.length > 1) {
          _sb.append("(&");
        }
        for (int i = 0; i < _values.length; i++) {
          _sb.append("(");
          _sb.append(attribute);
          _sb.append("={");
          _sb.append(i);
          _sb.append("})");
        }
        if (_values.length > 1) {
          _sb.append(")");
        }
      } else {
        _sb.append("(");
        _sb.append(attribute);
        _sb.append("={0})");
        _values = new Object[] {value};
      }

      SearchControls ctls = new SearchControls();
      ctls.setReturningAttributes(new String[0]);
      ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

      NamingEnumeration<SearchResult> _answer = ctx.search(DN, _sb.toString(), _values, ctls);
      return _answer.hasMoreElements();
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntryAttribute() null pointer");
      throw new LDAPException("check entry null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntryAttribute() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
  }
Ejemplo n.º 8
0
 /** {@inheritDoc} */
 public void returnConnection(LDAPConnection conn) {
   try {
     if (conn != null) conn.disconnect();
   } catch (LDAPException e) {
     M_log.error("returnConnection(): failed on disconnect: ", e);
   }
 }
 /**
  * Gets an <code>LDAPDirectoryEntry</code> object that represent an entry on directory. You can
  * provide a list of attributes to be ignored when load the entry data. Look for attribute matches
  * using a map of values
  *
  * @param DN Distinguished Name of the entry
  * @param ignore_attributes You can indicate here a list of attribute to be ignored when load all
  *     entry data. this is useful if you have some big data in some attributes and do you want to
  *     ignore that
  * @param attribute_matches Map with attribute names and values to match
  * @return LDAPDirectoryEntry
  * @exception LDAPException
  */
 public LDAPDirectoryEntry getEntry(
     final String DN,
     final List<String> ignore_attributes,
     final Map<String, String> attribute_matches)
     throws LDAPException {
   LDAPDirectoryEntry _e = null;
   try {
     _e = new LDAPDirectoryEntry(DN);
     DirContext ctx = connection.connect();
     if (ctx == null) {
       throw new LDAPException("directory service not available");
     }
     Attributes atts = ctx.getAttributes(DN);
     if (atts == null) {
       return null;
     }
     @SuppressWarnings("unchecked")
     NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) atts.getAll();
     while (ne.hasMore()) {
       Attribute att = ne.next();
       if (ignore_attributes == null || !ignore_attributes.contains(att.getID())) {
         List<Object> _values = new ArrayList<Object>();
         @SuppressWarnings("unchecked")
         NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
         while (nea.hasMore()) {
           Object _value = nea.next();
           if (attribute_matches == null || !attribute_matches.containsKey(att.getID())) {
             _values.add(_value);
           } else if (attribute_matches.get(att.getID()) != null
               && String.valueOf(_value).contains(attribute_matches.get(att.getID()))) {
             _values.add(_value);
           }
         }
         _e.setAttribute(att.getID(), _values.toArray());
       }
     }
   } catch (NullPointerException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() null pointer");
     throw new LDAPException("get entry null pointer");
   } catch (NamingException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() - " + e.getMessage());
     throw new LDAPException(e.getMessage());
   } finally {
     connection.disconnect();
   }
   return _e;
 }
Ejemplo n.º 10
0
  /**
   * Connects the specified <code>LDAPConnection</code> to the currently configured host and port.
   *
   * @param conn an <code>LDAPConnection</code>
   * @throws LDAPConnection if the connect attempt fails
   */
  protected void connect(LDAPConnection conn) throws LDAPException {
    if (M_log.isDebugEnabled()) {
      M_log.debug("connect()");
    }

    conn.connect(config.getLdapHost(), config.getLdapPort());

    try {
      postConnect(conn);
    } catch (LDAPException e) {
      M_log.error(
          "Failed to completely initialize a connection [host = "
              + config.getLdapHost()
              + "][port = "
              + config.getLdapPort()
              + "]",
          e);
      try {
        conn.disconnect();
      } catch (LDAPException ee) {
      }

      throw e;
    } catch (Throwable e) {
      M_log.error(
          "Failed to completely initialize a connection [host = "
              + config.getLdapHost()
              + "][port = "
              + config.getLdapPort()
              + "]",
          e);
      try {
        conn.disconnect();
      } catch (LDAPException ee) {
      }

      if (e instanceof Error) {
        throw (Error) e;
      }
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }

      throw new RuntimeException("LDAPConnection allocation failure", e);
    }
  }
 @Override
 public String toString() {
   return "LdapUserProvider : "
       + baseDn
       + " : "
       + ldapconnexion.getIdentifier()
       + " : "
       + pattern.getIdentifier();
 }
Ejemplo n.º 12
0
  private void bind(LDAPConnection conn, String dn, String pw) throws LDAPException {

    if (M_log.isDebugEnabled()) {
      M_log.debug("bind(): binding [dn = " + dn + "]");
    }

    try {
      conn.bind(LDAPConnection.LDAP_V3, dn, pw.getBytes("UTF8"));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Failed to encode user password", e);
    }
  }
  /**
   * Verify if an entry Distinguished Name already exists on directory
   *
   * @param DN Distinguished Name of the entry
   * @return boolean
   * @exception LDAPException
   */
  public boolean checkEntry(final String DN) throws LDAPException {
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      if (ctx.getAttributes(DN) != null) {
        return true;
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntry() null pointer");
      throw new LDAPException("add entry null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntry() - " + e.getMessage());
      throw new LDAPException(e.getMessage());

    } finally {
      connection.disconnect();
    }
    return false;
  }
  /**
   * Gets values of an entry attribute using a Distinguished Name and the name of the attribute
   *
   * @param DN Distinguished Name of the entry
   * @param attribute name of the attribute
   * @return List<Object>
   * @exception LDAPException
   */
  public List<Object> getEntryAttribute(final String DN, final String attribute)
      throws LDAPException {
    List<Object> _values = new ArrayList<Object>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      Attributes _atts = null;
      if ("modifyTimestamp".equals(attribute)) {
        String[] _attributeName = new String[1];
        _attributeName[0] = attribute;
        _atts = ctx.getAttributes(DN, _attributeName);
      } else {
        _atts = ctx.getAttributes(DN);
        if (_atts == null) {
          throw new LDAPException("entry not found [" + DN + "]");
        }
      }
      Attribute _att = _atts.get(attribute);
      if (_att == null) {
        throw new LDAPException("attribute [" + attribute + "] not found in entry");
      }

      @SuppressWarnings("unchecked")
      NamingEnumeration<Object> _ne = (NamingEnumeration<Object>) _att.getAll();
      while (_ne.hasMore()) {
        _values.add(_ne.next());
      }
      return _values;
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "getEntryAttribute() null pointer");
      throw new LDAPException("get entry attribute null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "getEntryAttribute() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
  }
Ejemplo n.º 15
0
  private static LDAPConnection establishNewConnection() {

    LDAPConnection lc = null;
    try {
      lc = new LDAPConnection();
      lc.connect(LDAPParameters.LDAPURI, LDAPParameters.port);
      if (LDAPConnectionPool.verbose) {
        System.out.println("connected upto the LDAP server");
      }
      lc.authenticate(LDAPParameters.LDAP_CONNECTION_NAME, LDAPParameters.LDAP_CONNECTION_PASSWORD);
      if (LDAPConnectionPool.verbose) {
        System.out.println("authenticated ok on the LDAP server.");
      }
    } catch (final LDAPException le) {
      System.err.println(" Problem getting connection to LDAP server " + le.getMessage());
      lc = null;
    } catch (final Exception e) {
      System.err.println(" Unknown problem getting connection to LDAP server " + e.toString());
      lc = null;
    }
    return lc;
  }
Ejemplo n.º 16
0
  protected void postConnect(LDAPConnection conn) throws LDAPException {

    if (M_log.isDebugEnabled()) {
      M_log.debug("postConnect()");
    }

    if (config.isSecureConnection() && isTlsSocketFactory()) {
      if (M_log.isDebugEnabled()) {
        M_log.debug("postConnect(): starting TLS");
      }
      conn.startTLS();
    }
  }
  /**
   * Check efficiently if some query finally got some results or not
   *
   * @param q DirectoryQuery
   * @return boolean
   * @exception LDAPException
   */
  public boolean checkSearch(final LDAPDirectoryQuery q) throws LDAPException {
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      ctls.setCountLimit(2);
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      return answer.hasMoreElements();
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "checkSearch() null pointer");
      throw new LDAPException("check search nullpointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "checkSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
  }
Ejemplo n.º 18
0
 /**
  * Applies <code>LDAPConstraints</code> to the specified <code>LDAPConnection</code>. Implemented
  * to assign <code>timeLimit</code> and <code>referralFollowing</code> constraint values retrieved
  * from the currently assigned {@link LdapConnectionManagerConfig}.
  *
  * @param conn
  */
 protected void applyConstraints(LDAPConnection conn) {
   int timeout = config.getOperationTimeout();
   boolean followReferrals = config.isFollowReferrals();
   if (M_log.isDebugEnabled()) {
     M_log.debug(
         "applyConstraints(): values [timeout = "
             + timeout
             + "][follow referrals = "
             + followReferrals
             + "]");
   }
   LDAPConstraints constraints = new LDAPConstraints();
   constraints.setTimeLimit(timeout);
   constraints.setReferralFollowing(followReferrals);
   conn.setConstraints(constraints);
 }
Ejemplo n.º 19
0
  public static void main(String[] args) {
    String ldapHost = "192.168.121.130";
    String loginDN = "cn=admin,dc=ucweb,dc=com";
    String password = "******";
    String containerName = "dc=ucweb,dc=com";

    int ldapPort = LDAPConnection.DEFAULT_SSL_PORT;
    int ldapVersion = LDAPConnection.LDAP_V3;

    LDAPJSSESecureSocketFactory ssf =
        new LDAPJSSESecureSocketFactory(TrustManager.createSSLSocketFactory());
    LDAPConnection lc = new LDAPConnection(ssf);

    LDAPAttributeSet attributeSet = new LDAPAttributeSet();

    attributeSet.add(
        new LDAPAttribute("objectclass", new String[] {new String("top"), new String("person")}));
    attributeSet.add(new LDAPAttribute("cn", "17"));
    attributeSet.add(new LDAPAttribute("sn", "17"));
    attributeSet.add(new LDAPAttribute("description", " "));
    //        attributeSet.add(new LDAPAttribute("userPassword", "111111"));
    String dn = "cn=17," + containerName;
    LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);

    try {
      lc.connect(ldapHost, ldapPort);
      lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
      System.out.println("login ldap server successfully.");
      lc.add(newEntry);
      System.out.println("Added object: " + dn + " successfully.");

    } catch (LDAPException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } finally {
      try {
        if (lc.isConnected()) {
          lc.disconnect();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }