Пример #1
0
 public Operator_Ldap mapFromAttributes(Attributes attrs) throws javax.naming.NamingException {
   Operator_Ldap p = new Operator_Ldap();
   p.setSn(attrs.get("sn").get().toString());
   p.setCn(attrs.get("cn").get().toString());
   p.setUserPassword(attrs.get("userPassword").get().toString());
   return p;
 }
Пример #2
0
  /** Search criteria based on sn(surname) */
  private void searchUsingSubTree() {
    System.out.println("Inside searchUsingSubTree");
    DirContext ctx = LDAPConstants.getLdapContext();
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();
    String[] attributeFilter = {"cn", "givenName"};
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "sn=X*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();

        Attribute attr = attrs.get("cn");
        System.out.print("cn : " + attr.get() + "\n");
        attr = attrs.get("givenName");
        System.out.print("givenName: " + attr.get() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #3
0
    @Override
    public LdapEntry[] groupSearch(DirContext dirContext, LdapEntry entry)
        throws IOException, NamingException {
      Set<LdapEntry> foundEntries = new HashSet<LdapEntry>();
      // Load the list of group.
      Attributes groups =
          dirContext.getAttributes(entry.getDistinguishedName(), new String[] {groupAttribute});
      Attribute groupRef = groups.get(groupAttribute);
      if (groupRef != null && groupRef.size() > 0) {
        NamingEnumeration<String> groupRefValues = (NamingEnumeration<String>) groupRef.getAll();
        while (groupRefValues.hasMore()) {
          String distingushedName = groupRefValues.next();
          SECURITY_LOGGER.tracef("Group found with distinguishedName=%s", distingushedName);
          String simpleName = null;
          if (groupNameAttribute != null) {
            // Load the Name
            Attributes groupNameAttrs =
                dirContext.getAttributes(distingushedName, new String[] {groupNameAttribute});
            Attribute groupNameAttr = groupNameAttrs.get(groupNameAttribute);
            simpleName = (String) groupNameAttr.get();
            SECURITY_LOGGER.tracef(
                "simpleName %s loaded for group with distinguishedName=%s",
                simpleName, distingushedName);
          } else {
            SECURITY_LOGGER.trace("No groupNameAttribute to load simpleName");
          }
          foundEntries.add(new LdapEntry(simpleName, distingushedName));
        }
      } else {
        SECURITY_LOGGER.tracef("No groups found for %s", entry);
      }

      return foundEntries.toArray(new LdapEntry[foundEntries.size()]);
    }
  private User getUserBasicAttributes(String username, LdapContext ctx) {
    User user = null;
    try {

      SearchControls constraints = new SearchControls();
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String[] attrIDs = {"distinguishedName", "sn", "givenname", "mail", "telephonenumber"};
      constraints.setReturningAttributes(attrIDs);
      // First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
      // Second Attribute can be uid=username
      NamingEnumeration answer =
          ctx.search("DC=YourDomain,DC=com", "sAMAccountName=" + username, constraints);
      if (answer.hasMore()) {
        Attributes attrs = ((SearchResult) answer.next()).getAttributes();
        System.out.println("distinguishedName " + attrs.get("distinguishedName"));
        System.out.println("givenname " + attrs.get("givenname"));
        System.out.println("sn " + attrs.get("sn"));
        System.out.println("mail " + attrs.get("mail"));
      } else {
        throw new Exception("Invalid User");
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return user;
  }
Пример #5
0
    private LdapEntry convertToLdapEntry(SearchResult searchResult, Attributes attributes)
        throws NamingException {
      String simpleName = null;
      String distinguishedName = null;

      if (groupNameAttribute != null) {
        SECURITY_LOGGER.tracef("Getting groupNameAttribute=%s", groupNameAttribute);
        Attribute groupNameAttr = attributes.get(groupNameAttribute);
        if (groupNameAttr != null) {
          simpleName = (String) groupNameAttr.get();
        }
      }

      if (groupDnAttribute != null) {
        if ("dn".equals(groupDnAttribute)) {
          SECURITY_LOGGER.trace("Obtaining dn using getNameInNamespace()");
          distinguishedName = searchResult.getNameInNamespace();
        } else {
          SECURITY_LOGGER.tracef("Getting groupDnAttribute=%s", groupDnAttribute);
          Attribute groupDnAttr = attributes.get(groupDnAttribute);
          if (groupDnAttr != null) {
            distinguishedName = (String) groupDnAttr.get();
          }
        }
      }

      return new LdapEntry(simpleName, distinguishedName);
    }
  /**
   * 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, toProviderUrl(fixNull(getServerUrl()), ""));

      DirContext ctx = new InitialDirContext(props);
      Attributes atts = ctx.getAttributes("");
      Attribute a = atts.get("defaultNamingContext");
      if (a != null
          && a.get()
              != null) { // this entry is available on Active Directory. See
                         // http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
        return a.get().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;
    }
  }
Пример #7
0
  public UserDTO doLdapAuthentication(UserDTO dto) throws Exception {
    log.info("INSIDE LDAP AUTHENTICATION 2");
    UserDTO ldapDTO = null;
    String url = "ldap://172.18.20.0:10389";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {
      ldapDTO = new UserDTO();
      DirContext ctx = new InitialDirContext(env);
      Attributes attrs = ctx.getAttributes("cn=" + dto.getUsername() + ",ou=users,ou=system");
      Attribute userPassword = attrs.get("userPassword");
      String ldapPasswordFromDB = new String((byte[]) userPassword.get());
      String md5EncryptedPassword = encryptLdapPassword("md5", dto.getPassword());
      if (md5EncryptedPassword.equalsIgnoreCase(ldapPasswordFromDB)) {
        ldapDTO.setEmployeeId((String) (attrs.get("employeeNumber").get()));
        ldapDTO.setEmployeeType((String) (attrs.get("employeeType").get()));
        ldapDTO.setUsername((String) (attrs.get("cn").get()));
      }
      ctx.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return ldapDTO;
  }
Пример #8
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null) param = "";

    String bar;

    // Simple ? condition that assigns constant to bar on true condition
    int num = 106;

    bar = (7 * 18) + num > 200 ? "This_should_always_happen" : param;

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person))(|(uid=" + bar + ")(street={0}))";
      Object[] filters = new Object[] {"The streetz 4 Ms bar"};

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, filters, sc);
      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  }
 @Override
 protected void loadFrom(Device device, Attributes attrs)
     throws NamingException, CertificateException {
   super.loadFrom(device, attrs);
   if (!(device instanceof ArchiveDevice)) return;
   ArchiveDevice arcdev = (ArchiveDevice) device;
   arcdev.setFuzzyAlgorithmClass(stringValue(attrs.get("dcmFuzzyAlgorithmClass")));
   arcdev.setConfigurationStaleTimeout(intValue(attrs.get("dcmConfigurationStaleTimeout"), 0));
 }
Пример #10
0
  /**
   * Compare this with that only looking at the named attributes. For this method, the dns must be
   * equal and the values of the named attributes must be equal but their names may differ. The two
   * arrays of attrIDs must be non-null and of the same length or an exception is raised.
   *
   * <p>If there are no attributes in both records they are considered equal. If there are no
   * attributes in only one record they are unequal.
   *
   * <p>Zero length attrID lists means only the dn is compared.
   *
   * @param that
   * @param thisAttrIDs
   * @param thatAttrIDs
   * @return boolean
   * @throws Throwable
   */
  public boolean equals(DirRecord that, String[] thisAttrIDs, String[] thatAttrIDs)
      throws Throwable {
    if ((thisAttrIDs == null) || (thatAttrIDs == null)) {
      throw new Exception("DirectoryRecord: null attrID list");
    }

    if (thisAttrIDs.length != thatAttrIDs.length) {
      throw new Exception("DirectoryRecord: unequal length attrID lists");
    }

    if (!dnEquals(that)) {
      return false;
    }

    int n = thisAttrIDs.length;

    if (n == 0) {
      return true;
    }

    Attributes thisAttrs = getAttributes();
    Attributes thatAttrs = that.getAttributes();

    if (thisAttrs == null) {
      if (thatAttrs == null) {
        return true;
      }
      return false;
    }

    if (thatAttrs == null) {
      return false;
    }

    for (int i = 0; i < n; i++) {
      Attribute thisAttr = thisAttrs.get(thisAttrIDs[i]);
      Attribute thatAttr = thatAttrs.get(thatAttrIDs[i]);

      if (thisAttr == null) {
        if (thatAttr == null) {
          return true;
        }
        return false;
      }

      if (thatAttr == null) {
        return false;
      }

      if (!attrEquals(thisAttr, thatAttr)) {
        return false;
      }
    }

    return true;
  }
 private RejectionNote loadRejectionNoteFrom(Attributes attrs) throws NamingException {
   RejectionNote rn =
       new RejectionNote(
           stringValue(attrs.get("dcmCodeValue")),
           stringValue(attrs.get("dcmCodingSchemeDesignator")),
           stringValue(attrs.get("dcmCodingSchemeVersion")),
           stringValue(attrs.get("dcmCodeMeaning")));
   loadRejectionActionsFrom(rn, attrs.get("dcmRejectionAction"));
   return rn;
 }
Пример #12
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getParameter("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person)(uid=" + bar + "))";

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, sc);

      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  } // end doPost
Пример #13
0
 /**
  * Map the properties from LDAP to the {@link UserDetails}
  *
  * @param serverKey the LDAP index so we use the correct {@link LdapUserMapping}
  * @return If no exceptions are thrown, a {@link UserDetails} object containing the values from
  *     LDAP.
  * @throws NamingException In case the communication or mapping to the LDAP server fails.
  */
 private UserDetails mapUserDetails(String serverKey, SearchResult searchResult)
     throws NamingException {
   Attributes attributes = searchResult.getAttributes();
   UserDetails details;
   details = new UserDetails();
   details.setName(
       getAttributeValue(attributes.get(userMappings.get(serverKey).getRealNameAttribute())));
   details.setEmail(
       getAttributeValue(attributes.get(userMappings.get(serverKey).getEmailAttribute())));
   return details;
 }
 private static StorageOptions toStorageOptions(Attributes attrs) throws NamingException {
   Attribute levelOfSupport = attrs.get("dcmStorageConformance");
   Attribute signatureSupport = attrs.get("dcmDigitalSignatureSupport");
   Attribute coercion = attrs.get("dcmDataElementCoercion");
   if (levelOfSupport == null && signatureSupport == null && coercion == null) return null;
   StorageOptions opts = new StorageOptions();
   opts.setLevelOfSupport(StorageOptions.LevelOfSupport.valueOf(intValue(levelOfSupport, 3)));
   opts.setDigitalSignatureSupport(
       StorageOptions.DigitalSignatureSupport.valueOf(intValue(signatureSupport, 0)));
   opts.setElementCoercion(StorageOptions.ElementCoercion.valueOf(intValue(coercion, 2)));
   return opts;
 }
 private static EnumSet<QueryOption> toQueryOptions(Attributes attrs) throws NamingException {
   Attribute relational = attrs.get("dcmRelationalQueries");
   Attribute datetime = attrs.get("dcmCombinedDateTimeMatching");
   Attribute fuzzy = attrs.get("dcmFuzzySemanticMatching");
   Attribute timezone = attrs.get("dcmTimezoneQueryAdjustment");
   if (relational == null && datetime == null && fuzzy == null && timezone == null) return null;
   EnumSet<QueryOption> opts = EnumSet.noneOf(QueryOption.class);
   if (booleanValue(relational, false)) opts.add(QueryOption.RELATIONAL);
   if (booleanValue(datetime, false)) opts.add(QueryOption.DATETIME);
   if (booleanValue(fuzzy, false)) opts.add(QueryOption.FUZZY);
   if (booleanValue(timezone, false)) opts.add(QueryOption.TIMEZONE);
   return opts;
 }
  public Object mapFromAttributes(Attributes attributes) throws NamingException {
    BusinessUnitDTO contactDTO = new BusinessUnitDTO();
    Attribute commonName = attributes.get("cn");
    if (commonName != null) contactDTO.setCommonName((String) commonName.get());
    Attribute description = attributes.get("description");
    if (description != null) contactDTO.setDescription((String) description.get());
    Attribute displayName = attributes.get("displayName");
    if (displayName != null) contactDTO.setDisplayName((String) displayName.get());
    Attribute organization = attributes.get("o");
    if (organization != null) contactDTO.setOrganization((String) organization.get());

    return contactDTO;
  }
 private String getStringAttribute(Attributes user, String name) throws NamingException {
   Attribute a = user.get(name);
   if (a == null) return null;
   Object v = a.get();
   if (v == null) return null;
   return v.toString();
 }
Пример #18
0
  /**
   * Returns the host name and port that the specified XMPP server can be reached at for
   * client-to-server communication. A DNS lookup for a SRV record in the form
   * "_xmpp-client._tcp.example.com" is attempted, according to section 14.4 of RFC 3920. If that
   * lookup fails, a lookup in the older form of "_jabber._tcp.example.com" is attempted since
   * servers that implement an older version of the protocol may be listed using that notation. If
   * that lookup fails as well, it's assumed that the XMPP server lives at the host resolved by a
   * DNS lookup at the specified domain on the default port of 5222.
   *
   * <p>As an example, a lookup for "example.com" may return "im.example.com:5269".
   *
   * <p>Note on SRV record selection. We now check priority and weight, but we still don't do this
   * correctly. The missing behavior is this: if we fail to reach a host based on its SRV record
   * then we need to select another host from the other SRV records. In Smack 3.1.1 we're not going
   * to be able to do the major system redesign to correct this.
   *
   * @param domain the domain.
   * @return a HostAddress, which encompasses the hostname and port that the XMPP server can be
   *     reached at for the specified domain.
   */
  public static HostAddress resolveXMPPDomain(String domain) {
    if (context == null) {
      return new HostAddress(domain, 5222);
    }
    String key = "c" + domain;
    // Return item from cache if it exists.
    if (cache.containsKey(key)) {
      HostAddress address = (HostAddress) cache.get(key);
      if (address != null) {
        return address;
      }
    }
    String bestHost = domain;
    int bestPort = 5222;
    int bestPriority = 0;
    int bestWeight = 0;
    try {
      Attributes dnsLookup =
          context.getAttributes("_xmpp-client._tcp." + domain, new String[] {"SRV"});
      Attribute srvAttribute = dnsLookup.get("SRV");
      NamingEnumeration srvRecords = srvAttribute.getAll();
      while (srvRecords.hasMore()) {
        String srvRecord = (String) srvRecords.next();
        String[] srvRecordEntries = srvRecord.split(" ");
        int priority = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 4]);
        int port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 2]);
        int weight = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 3]);
        String host = srvRecordEntries[srvRecordEntries.length - 1];

        // Randomize the weight.
        weight *= Math.random() * weight;

        if ((bestPriority == 0) || (priority < bestPriority)) {
          // Choose a server with the lowest priority.
          bestPriority = priority;
          bestWeight = weight;
          bestHost = host;
          bestPort = port;
        } else if (priority == bestPriority) {
          // When we have like priorities then randomly choose a server based on its weight
          // The weights were randomized above.
          if (weight > bestWeight) {
            bestWeight = weight;
            bestHost = host;
            bestPort = port;
          }
        }
      }
    } catch (Exception e) {
      // Ignore.
    }
    // Host entries in DNS should end with a ".".
    if (bestHost.endsWith(".")) {
      bestHost = bestHost.substring(0, bestHost.length() - 1);
    }
    HostAddress address = new HostAddress(bestHost, bestPort);
    // Add item to cache.
    cache.put(key, address);
    return address;
  }
 private void loadAttributeFilters(ArchiveDevice device, String deviceDN) throws NamingException {
   NamingEnumeration<SearchResult> ne = search(deviceDN, "(objectclass=dcmAttributeFilter)");
   try {
     while (ne.hasMore()) {
       SearchResult sr = ne.next();
       Attributes attrs = sr.getAttributes();
       AttributeFilter filter = new AttributeFilter(tags(attrs.get("dcmTag")));
       filter.setCustomAttribute1(valueSelector(attrs.get("dcmCustomAttribute1")));
       filter.setCustomAttribute2(valueSelector(attrs.get("dcmCustomAttribute2")));
       filter.setCustomAttribute3(valueSelector(attrs.get("dcmCustomAttribute3")));
       device.setAttributeFilter(Entity.valueOf(stringValue(attrs.get("dcmEntity"))), filter);
     }
   } finally {
     safeClose(ne);
   }
 }
  /**
   * Retrieve the input attributes from the Active Directory for the given search query
   *
   * <p>Method getAttributes.
   *
   * @param searchBase String
   * @return List<User>
   * @throws NamingException
   */
  private final List<User> getAttributes(String searchBase) throws NamingException {
    LOGGER.info(">> getAttributes()");

    NamingEnumeration<SearchResult> results =
        localInitialLdapContext.search(searchBase, searchFilter, searchctls);

    List<User> users = new ArrayList<User>();
    User user = null;

    while (results.hasMoreElements()) {
      user = new User();
      SearchResult searchResult = results.next();
      Attributes attrs = searchResult.getAttributes();

      if (attrs != null && attrs.size() != 0) {
        Attribute attribute = null;

        String[] retrieveAttributes = parameters.getRetrieveAttributes();
        String[] attributesValues = new String[retrieveAttributes.length];
        for (int i = 0; i < retrieveAttributes.length; i++) {
          attribute = attrs.get(retrieveAttributes[i]);
          if (attribute != null && attribute.get() != null) {
            if (!isNullOrEmpty(attribute.get().toString())) {
              attributesValues[i] = attribute.get().toString();
            }
          }
        }
        user.setAttributeValues(attributesValues);
      }
      users.add(user);
    }

    LOGGER.info("<< getAttributes()");
    return users;
  }
  /**
   * @param attributes
   * @return
   * @throws NamingException
   */
  protected final Map<String, List<String>> convertToStringAttributesMap(Attributes attributes)
      throws NamingException {
    Map<String, List<String>> attributesMap = new HashMap<String, List<String>>();

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    while (attributeNames.hasMore()) {
      String attributeName = attributeNames.next();
      if (ldapAttributesKey.getPasswordAttributeName().equalsIgnoreCase(attributeName)) {
        // skip
        continue;
      }
      Attribute attribute = attributes.get(attributeName);
      int numberOfValues = attribute.size();
      for (int i = 0; i < numberOfValues; i++) {
        String value = (String) attribute.get(i);
        if (null != value) {
          value = value.trim();
        }

        List<String> list = safeGetAttributeList(attributesMap, attributeName.toLowerCase());
        list.add(value);
      }
    }
    return attributesMap;
  }
Пример #22
0
  @Test
  public void testLdapExample2() throws Exception {
    System.out.println("testLdapExample2");

    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String[] attrIDs = {"cn"};
    constraints.setReturningAttributes(attrIDs);
    Hashtable<String, Object> options = new Hashtable<String, Object>();
    options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    options.put("java.naming.provider.url", "ldap://127.0.0.1:10389/");
    options.put("java.naming.security.authentication", "simple");
    options.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    options.put(Context.SECURITY_CREDENTIALS, "secret");

    LdapContext ctx = new InitialLdapContext(options, null);
    String username = "******";

    NamingEnumeration<SearchResult> answer =
        ctx.search("ou=users,o=jtogaf", "uid=" + username, constraints);
    assertTrue("There is att: ", answer.hasMore());

    if (answer.hasMore()) {
      Attributes attrs = ((SearchResult) answer.next()).getAttributes();
      Attribute attr = (Attribute) attrs.get("cn");
      System.out.print(attr.get(0));
    }
  }
 @Override
 protected void loadFrom(HL7Application hl7App, Attributes attrs) throws NamingException {
   super.loadFrom(hl7App, attrs);
   if (!(hl7App instanceof ArchiveHL7Application)) return;
   ArchiveHL7Application arcHL7App = (ArchiveHL7Application) hl7App;
   arcHL7App.setTemplatesURIs(stringArray(attrs.get("labeledURI")));
 }
Пример #24
0
  public static String[] getAttributeStringArray(Attributes attributes, String id)
      throws NamingException {

    if (Validator.isNull(id)) {
      return null;
    }

    Attribute attribute = attributes.get(id);

    if (attribute == null) {
      return new String[0];
    }

    int size = attribute.size();

    if (size == 0) {
      return null;
    }

    String[] array = new String[size];

    for (int i = 0; i < size; i++) {
      Object object = attribute.get(i);

      if (object == null) {
        array[i] = StringPool.BLANK;
      } else {
        array[i] = object.toString();
      }
    }

    return array;
  }
  /** Returns the name of the specified header field. */
  @Override
  public String getHeaderField(String name) {

    if (!connected) {
      // Try to connect (silently)
      try {
        connect();
      } catch (IOException e) {
        // Ignore
      }
    }

    if (attributes == null) return (null);

    NamingEnumeration<String> attributeEnum = attributes.getIDs();
    try {
      while (attributeEnum.hasMore()) {
        String attributeID = attributeEnum.next();
        if (attributeID.equalsIgnoreCase(name)) {
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) return null;
          Object attrValue = attribute.get(attribute.size() - 1);
          return getHeaderValueAsString(attrValue);
        }
      }
    } catch (NamingException ne) {
      // Shouldn't happen
    }

    return (null);
  }
  /** Return the last modified date. */
  @Override
  public long getLastModified() {

    if (!connected) {
      // Try to connect (silently)
      try {
        connect();
      } catch (IOException e) {
        // Ignore
      }
    }

    if (attributes == null) return 0;

    Attribute lastModified = attributes.get(ResourceAttributes.LAST_MODIFIED);
    if (lastModified != null) {
      try {
        Date lmDate = (Date) lastModified.get();
        return lmDate.getTime();
      } catch (Exception e) {
        // Ignore
      }
    }

    return 0;
  }
  protected Attribute getUsers(
      long ldapServerId,
      long companyId,
      LdapContext ldapContext,
      Attributes attributes,
      UserGroup userGroup,
      Properties groupMappings)
      throws Exception {

    Attribute attribute = attributes.get(groupMappings.getProperty("user"));

    if (attribute == null) {
      return null;
    }

    String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

    String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix);

    StringBundler sb = new StringBundler(7);

    sb.append("(&");
    sb.append(
        PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_IMPORT_GROUP_SEARCH_FILTER + postfix));
    sb.append("(");
    sb.append(groupMappings.getProperty("groupName"));
    sb.append("=");
    sb.append(escapeValue(userGroup.getName()));
    sb.append("))");

    return PortalLDAPUtil.getMultivaluedAttribute(
        companyId, ldapContext, baseDN, sb.toString(), attribute);
  }
 public static String getIfNotNull(Attributes attrs, String attrID) throws NamingException {
   Attribute attr = attrs.get(attrID);
   if (attr != null) {
     return (String) attr.get();
   } else {
     return "";
   }
 }
Пример #29
0
 // 得到属性
 private String getAttribute(Attributes attrs, String attrName) throws NamingException {
   Attribute attr = attrs.get(attrName);
   if (attr == null) {
     return "";
   } else {
     return (String) attr.get();
   }
 }
Пример #30
0
  /** Test that the partition has been correctly created */
  public void testPartition() throws NamingException {

    // We should be able to read it
    DirContext appRoot = createContext("o=sevenSeas");
    assertNotNull(appRoot);

    // Let's get the entry associated to the top level
    Attributes attributes = appRoot.getAttributes("");
    assertNotNull(attributes);
    assertEquals("sevenseas", attributes.get("o").get());

    Attribute attribute = attributes.get("objectClass");
    assertNotNull(attribute);
    assertTrue(attribute.contains("top"));
    assertTrue(attribute.contains("organization"));
    // Ok, everything is fine
  }