TraditionalPersonRepoImpl.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package com.primeton.poctag.service.ldap.impl;
  2. import com.primeton.poctag.service.ldap.PersonRepo;
  3. import javax.naming.Context;
  4. import javax.naming.NameNotFoundException;
  5. import javax.naming.NamingEnumeration;
  6. import javax.naming.NamingException;
  7. import javax.naming.directory.Attribute;
  8. import javax.naming.directory.Attributes;
  9. import javax.naming.directory.DirContext;
  10. import javax.naming.directory.InitialDirContext;
  11. import javax.naming.directory.SearchControls;
  12. import javax.naming.directory.SearchResult;
  13. import java.util.Hashtable;
  14. import java.util.LinkedList;
  15. import java.util.List;
  16. /**
  17. * <pre>
  18. *
  19. * Created by zhenqin.
  20. * User: zhenqin
  21. * Date: 2021/9/14
  22. * Time: 16:40
  23. * Vendor: yiidata.com
  24. *
  25. * </pre>
  26. *
  27. * @author zhenqin
  28. */
  29. public class TraditionalPersonRepoImpl implements PersonRepo {
  30. @Override
  31. public List<String> getAllPersonNames() {
  32. Hashtable env = new Hashtable();
  33. env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  34. env.put(Context.PROVIDER_URL, "ldap://localhost:10389/ou=yiidata,dc=yiidata,dc=com");
  35. DirContext ctx;
  36. try {
  37. ctx = new InitialDirContext(env);
  38. } catch (NamingException e) {
  39. throw new RuntimeException(e);
  40. }
  41. List<String> list = new LinkedList<String>();
  42. NamingEnumeration results = null;
  43. try {
  44. SearchControls controls = new SearchControls();
  45. controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  46. results = ctx.search("", "(uid=*)", controls);
  47. System.out.println("-------------------------------");
  48. while (results.hasMore()) {
  49. SearchResult searchResult = (SearchResult) results.next();
  50. Attributes attributes = searchResult.getAttributes();
  51. System.out.println(attributes);
  52. Attribute attr = attributes.get("uid");
  53. String cn = attr.get().toString();
  54. list.add(cn);
  55. }
  56. } catch (NameNotFoundException e) {
  57. // The base context was not found.
  58. e.printStackTrace();
  59. // Just clean up and exit.
  60. } catch (NamingException e) {
  61. throw new RuntimeException(e);
  62. } finally {
  63. if (results != null) {
  64. try {
  65. results.close();
  66. } catch (Exception e) {
  67. // Never mind this.
  68. }
  69. }
  70. if (ctx != null) {
  71. try {
  72. ctx.close();
  73. } catch (Exception e) {
  74. // Never mind this.
  75. }
  76. }
  77. }
  78. return list;
  79. }
  80. public static void main(String[] args) {
  81. final List<String> allPersonNames = new TraditionalPersonRepoImpl().getAllPersonNames();
  82. System.out.println(allPersonNames);
  83. }
  84. }