1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.forgerock.opendj.examples;
19
20 import java.io.IOException;
21 import java.util.Arrays;
22
23 import org.forgerock.opendj.ldap.Connection;
24 import org.forgerock.opendj.ldap.LdapException;
25 import org.forgerock.opendj.ldap.LDAPConnectionFactory;
26 import org.forgerock.opendj.ldap.ResultCode;
27 import org.forgerock.opendj.ldap.SearchScope;
28 import org.forgerock.opendj.ldap.responses.SearchResultEntry;
29 import org.forgerock.opendj.ldap.responses.SearchResultReference;
30 import org.forgerock.opendj.ldif.ConnectionEntryReader;
31 import org.forgerock.opendj.ldif.LDIFEntryWriter;
32
33
34
35
36
37
38
39
40
41
42 public final class Search {
43
44
45
46
47
48
49
50
51 public static void main(final String[] args) {
52 if (args.length < 7) {
53 System.err.println("Usage: host port username password baseDN scope "
54 + "filter [attribute ...]");
55 System.exit(1);
56 }
57
58
59 final String hostName = args[0];
60 final int port = Integer.parseInt(args[1]);
61 final String userName = args[2];
62 final String password = args[3];
63 final String baseDN = args[4];
64 final String scopeString = args[5];
65 final String filter = args[6];
66 String[] attributes;
67 if (args.length > 7) {
68 attributes = Arrays.copyOfRange(args, 7, args.length);
69 } else {
70 attributes = new String[0];
71 }
72
73 final SearchScope scope = SearchScope.valueOf(scopeString);
74 if (scope == null) {
75 System.err.println("Unknown scope: " + scopeString);
76 System.exit(ResultCode.CLIENT_SIDE_PARAM_ERROR.intValue());
77 return;
78 }
79
80
81
82 final LDIFEntryWriter writer = new LDIFEntryWriter(System.out);
83
84
85 final LDAPConnectionFactory factory = new LDAPConnectionFactory(hostName, port);
86 Connection connection = null;
87
88 try {
89 connection = factory.getConnection();
90 connection.bind(userName, password.toCharArray());
91
92
93 final ConnectionEntryReader reader =
94 connection.search(baseDN, scope, filter, attributes);
95 while (reader.hasNext()) {
96 if (!reader.isReference()) {
97 final SearchResultEntry entry = reader.readEntry();
98 writer.writeComment("Search result entry: " + entry.getName());
99 writer.writeEntry(entry);
100 } else {
101 final SearchResultReference ref = reader.readReference();
102
103
104 writer.writeComment("Search result reference: " + ref.getURIs());
105 }
106 }
107 writer.flush();
108 } catch (final LdapException e) {
109 System.err.println(e.getMessage());
110 System.exit(e.getResult().getResultCode().intValue());
111 } catch (final IOException e) {
112 System.err.println(e.getMessage());
113 System.exit(ResultCode.CLIENT_SIDE_LOCAL_ERROR.intValue());
114 } finally {
115 if (connection != null) {
116 connection.close();
117 }
118 }
119
120 }
121
122 private Search() {
123
124 }
125 }