View Javadoc
1   /*
2    * The contents of this file are subject to the terms of the Common Development and
3    * Distribution License (the License). You may not use this file except in compliance with the
4    * License.
5    *
6    * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
7    * specific language governing permission and limitations under the License.
8    *
9    * When distributing Covered Software, include this CDDL Header Notice in each file and include
10   * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
11   * Header, with the fields enclosed by brackets [] replaced by your own identifying
12   * information: "Portions Copyright [year] [name of copyright owner]".
13   *
14   * Copyright 2012-2014 ForgeRock AS.
15   */
16  
17  package org.forgerock.opendj.examples;
18  
19  import java.io.IOException;
20  import java.util.Calendar;
21  import java.util.Set;
22  
23  import org.forgerock.opendj.ldap.AttributeDescription;
24  import org.forgerock.opendj.ldap.Connection;
25  import org.forgerock.opendj.ldap.DN;
26  import org.forgerock.opendj.ldap.Entry;
27  import org.forgerock.opendj.ldap.LdapException;
28  import org.forgerock.opendj.ldap.LDAPConnectionFactory;
29  import org.forgerock.opendj.ldap.LinkedHashMapEntry;
30  import org.forgerock.opendj.ldap.ModificationType;
31  import org.forgerock.opendj.ldap.ResultCode;
32  import org.forgerock.opendj.ldap.requests.ModifyRequest;
33  import org.forgerock.opendj.ldap.requests.Requests;
34  import org.forgerock.opendj.ldap.responses.SearchResultEntry;
35  import org.forgerock.opendj.ldap.schema.Schema;
36  import org.forgerock.opendj.ldif.LDIFEntryWriter;
37  
38  /**
39   * This command-line client demonstrates parsing entry attribute values to
40   * objects. The client takes as arguments the host and port for the directory
41   * server, and expects to find the entries and access control instructions as
42   * defined in <a
43   * href="http://opendj.forgerock.org/Example.ldif">Example.ldif</a>.
44   */
45  public final class ParseAttributes {
46  
47      /**
48       * Connect to the server, and then try to use some LDAP controls.
49       *
50       * @param args
51       *            The command line arguments: host, port
52       */
53      public static void main(final String[] args) {
54          if (args.length != 2) {
55              System.err.println("Usage: host port");
56              System.err.println("For example: localhost 1389");
57              System.exit(1);
58          }
59          final String host = args[0];
60          final int port = Integer.parseInt(args[1]);
61  
62          // --- JCite ---
63          final LDAPConnectionFactory factory = new LDAPConnectionFactory(host, port);
64          Connection connection = null;
65          try {
66              connection = factory.getConnection();
67  
68              // Use Kirsten Vaughan's credentials and her entry.
69              String name = "uid=kvaughan,ou=People,dc=example,dc=com";
70              char[] password = "bribery".toCharArray();
71              connection.bind(name, password);
72  
73              // Make sure we have a timestamp to play with.
74              updateEntry(connection, name, "description");
75  
76              // Read Kirsten's entry.
77              final SearchResultEntry entry = connection.readEntry(name,
78                      "cn", "objectClass", "hasSubordinates", "numSubordinates",
79                      "isMemberOf", "modifyTimestamp");
80  
81              // Get the entry DN and some attribute values as objects.
82              DN dn = entry.getName();
83  
84              Set<String> cn = entry.parseAttribute("cn").asSetOfString("");
85              Set<AttributeDescription> objectClasses =
86                      entry.parseAttribute("objectClass").asSetOfAttributeDescription();
87              boolean hasChildren = entry.parseAttribute("hasSubordinates").asBoolean();
88              int numChildren = entry.parseAttribute("numSubordinates").asInteger(0);
89              Set<DN> groups = entry
90                      .parseAttribute("isMemberOf")
91                      .usingSchema(Schema.getDefaultSchema()).asSetOfDN();
92              Calendar timestamp = entry
93                      .parseAttribute("modifyTimestamp")
94                      .asGeneralizedTime().toCalendar();
95  
96              // Do something with the objects.
97              // ...
98  
99              // This example simply dumps what was obtained.
100             entry.setName(dn);
101             Entry newEntry = new LinkedHashMapEntry(name)
102                 .addAttribute("cn", cn.toArray())
103                 .addAttribute("objectClass", objectClasses.toArray())
104                 .addAttribute("hasChildren", hasChildren)
105                 .addAttribute("numChildren", numChildren)
106                 .addAttribute("groups", groups.toArray())
107                 .addAttribute("timestamp", timestamp.getTimeInMillis());
108 
109             final LDIFEntryWriter writer = new LDIFEntryWriter(System.out);
110             writer.writeEntry(newEntry);
111             writer.close();
112         } catch (final LdapException e) {
113             System.err.println(e.getMessage());
114             System.exit(e.getResult().getResultCode().intValue());
115             return;
116         } catch (IOException e) {
117             System.err.println(e.getMessage());
118             System.exit(ResultCode.CLIENT_SIDE_LOCAL_ERROR.intValue());
119         } finally {
120             if (connection != null) {
121                 connection.close();
122             }
123         }
124         // --- JCite ---
125     }
126 
127     /**
128      * Update and entry to generate a time stamp.
129      *
130      * @param connection
131      *            Connection to the directory server with rights to perform a
132      *            modification on the entry.
133      * @param name
134      *            DN of the entry to modify.
135      * @param attributeDescription
136      *            Attribute to modify. Must take a String value.
137      * @throws LdapException
138      *             Modify failed.
139      */
140     private static void updateEntry(final Connection connection, final String name,
141             final String attributeDescription) throws LdapException {
142         ModifyRequest request = Requests.newModifyRequest(name)
143                 .addModification(ModificationType.REPLACE, attributeDescription, "This is a String.");
144         connection.modify(request);
145     }
146 
147     /**
148      * Constructor not used.
149      */
150     private ParseAttributes() {
151         // Not used.
152     }
153 }