1/*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 * Demonstrate Java object storage and retrieval using an LDAP directory.
26 * The Person object and its associated object and state factory is supplied by
27 * a third-party module. As the Person object does not implement
28 * javax.naming.Referenceable, the classname of its state and object factory
29 * must be specified to the JNDI initial context.
30 */
31
32package test;
33
34import java.net.*;
35import java.util.*;
36import javax.naming.*;
37import javax.naming.directory.*;
38
39import org.example.person.Person;
40
41public class StorePerson {
42
43    // LDAP capture file
44    private static final String LDAP_CAPTURE_FILE =
45        System.getProperty("test.src") + "/src/test/test/StorePerson.ldap";
46    // LDAPServer socket
47    private static ServerSocket serverSocket;
48
49    public static void main(String[] args) throws Exception {
50
51        /*
52         * Process arguments
53         */
54
55        int argc = args.length;
56        if ((argc < 1) ||
57            ((argc == 1) && (args[0].equalsIgnoreCase("-help")))) {
58
59            System.err.println("\nUsage:   StorePerson <ldapurl>\n");
60            System.err.println("        <ldapurl> is the LDAP URL of the parent entry\n");
61            System.err.println("example:");
62            System.err.println("        java StorePerson ldap://oasis/o=airius.com");
63            return;
64        }
65
66        /*
67         * Launch the LDAP server with the StorePerson.ldap capture file
68         */
69
70        serverSocket = new ServerSocket(0);
71        new Thread(new Runnable() {
72            @Override
73            public void run() {
74                try {
75                    new LDAPServer(serverSocket, LDAP_CAPTURE_FILE);
76               } catch (Exception e) {
77                   System.out.println("ERROR: unable to launch LDAP server");
78                   e.printStackTrace();
79               }
80            }
81        }).start();
82
83        /*
84         * Store Person objects in the LDAP directory
85         */
86
87        Hashtable<String,Object> env = new Hashtable<>();
88        env.put(Context.INITIAL_CONTEXT_FACTORY,
89    "com.sun.jndi.ldap.LdapCtxFactory");
90        URI ldapUri = new URI(args[0]);
91        if (ldapUri.getPort() == -1) {
92            ldapUri = new URI(ldapUri.getScheme(), null, ldapUri.getHost(),
93                serverSocket.getLocalPort(), ldapUri.getPath(), null, null);
94        }
95        env.put(Context.PROVIDER_URL, ldapUri.toString());
96        if (args[args.length - 1].equalsIgnoreCase("-trace")) {
97            env.put("com.sun.jndi.ldap.trace.ber", System.out);
98        }
99
100        // Specify the factory classname explicitly
101        env.put(Context.STATE_FACTORIES, "org.example.person.PersonFactory");
102        env.put(Context.OBJECT_FACTORIES, "org.example.person.PersonFactory");
103
104        System.out.println("StorePerson: connecting to " + ldapUri);
105        DirContext ctx = new InitialDirContext(env);
106        Person person = null;
107        String name = "John Smith";
108        String dn = "cn=" + name;
109
110        try {
111            person = new Person(name, "Smith");
112            person.setMailAddress("jsmith@smith.com");
113            ctx.bind(dn, person);
114            System.out.println("StorePerson: created entry '" + dn + "'");
115        } catch (NameAlreadyBoundException e) {
116            System.err.println("StorePerson: entry '" + dn +
117                "' already exists");
118            cleanup(ctx, (String)null);
119            return;
120        }
121
122        name = "Jill Smyth";
123        String dn2 = "cn=" + name;
124        Person person2 = new Person(name, "Smyth");
125        person2.setMailAddress("jsmyth@smith.com");
126
127        try {
128            ctx.bind(dn2, person2);
129            System.out.println("StorePerson: created entry '" + dn2 + "'");
130        } catch (NameAlreadyBoundException e) {
131            System.err.println("StorePerson: entry '" + dn2 +
132                "' already exists");
133            cleanup(ctx, dn);
134            return;
135        }
136
137        /*
138         * Retrieve Person objects from the LDAP directory
139         */
140
141        try {
142            Person person3 = (Person) ctx.lookup(dn);
143            System.out.println("StorePerson: retrieved object: " + person3);
144            if (person.getAttributes().equals(person3.getAttributes())) {
145                System.out.println(
146                    "StorePerson: retrieved person matches original");
147            } else {
148                System.out.println(
149                    "StorePerson: retrieved person does NOT match original");
150            }
151        } catch (NamingException e) {
152            System.err.println("StorePerson: error retrieving entry '" +
153                dn + "' " + e);
154            e.printStackTrace();
155            cleanup(ctx, dn, dn2);
156            return;
157        }
158
159        try {
160            Person person4 = (Person) ctx.lookup(dn2);
161            System.out.println("StorePerson: retrieved object: " + person4);
162            if (person2.getAttributes().equals(person4.getAttributes())) {
163                System.out.println(
164                    "StorePerson: retrieved person matches original");
165            } else {
166                System.out.println(
167                    "StorePerson: retrieved person does NOT match original");
168            }
169        } catch (NamingException e) {
170            System.err.println("StorePerson: error retrieving entry '" +
171                dn2 + "' " + e);
172            e.printStackTrace();
173            cleanup(ctx, dn, dn2);
174            return;
175        }
176
177        cleanup(ctx, dn, dn2);
178        return;
179    }
180
181    /*
182     * Remove objects from the LDAP directory
183     */
184    private static void cleanup(DirContext ctx, String... dns)
185        throws NamingException {
186
187        for (String dn : dns) {
188            try {
189                ctx.destroySubcontext(dn);
190                System.out.println("StorePerson: removed entry '" + dn + "'");
191            } catch (NamingException e) {
192                System.err.println("StorePerson: error removing entry '" + dn +
193                    "' " + e);
194            }
195        }
196        ctx.close();
197    }
198}
199