1 /*
   2  * Copyright (c) 2015, 2018, 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 
  32 package test;
  33 
  34 import java.io.PrintStream;
  35 import java.net.*;
  36 import java.util.*;
  37 import javax.naming.*;
  38 import javax.naming.directory.*;
  39 
  40 import org.example.person.Person;
  41 
  42 public class StorePerson {
  43 
  44     static {
  45         final PrintStream out = new PrintStream(System.out, true);
  46         final PrintStream err = new PrintStream(System.err, true);
  47 
  48         System.setOut(out);
  49         System.setErr(err);
  50     }
  51 
  52     // LDAP capture file
  53     private static final String LDAP_CAPTURE_FILE =
  54         System.getProperty("test.src") + "/src/test/test/StorePerson.ldap";
  55 
  56     public static void main(String[] args) throws Exception {
  57 
  58         /*
  59          * Process arguments
  60          */
  61 
  62         int argc = args.length;
  63         if ((argc < 1) ||
  64             ((argc == 1) && (args[0].equalsIgnoreCase("-help")))) {
  65 
  66             System.err.println("\nUsage:   StorePerson <ldapurl>\n");
  67             System.err.println("        <ldapurl> is the LDAP URL of the parent entry\n");
  68             System.err.println("example:");
  69             System.err.println("        java StorePerson ldap://oasis/o=airius.com");
  70             return;
  71         }
  72 
  73         /*
  74          * Launch the LDAP server with the StorePerson.ldap capture file
  75          */
  76 
  77         try (ServerSocket serverSocket = new ServerSocket()) {
  78             serverSocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
  79             new Thread(new Runnable() {
  80                 @Override
  81                 public void run() {
  82                     try {
  83                         new LDAPServer(serverSocket, LDAP_CAPTURE_FILE);
  84                     } catch (Exception e) {
  85                         System.out.println("ERROR: unable to launch LDAP server");
  86                         e.printStackTrace();
  87                     }
  88                 }
  89             }).start();
  90 
  91             /*
  92              * Store Person objects in the LDAP directory
  93              */
  94 
  95             Hashtable<String,Object> env = new Hashtable<>();
  96             env.put(Context.INITIAL_CONTEXT_FACTORY,
  97                     "com.sun.jndi.ldap.LdapCtxFactory");
  98             URI ldapUri = new URI(args[0]);
  99             if (ldapUri.getPort() == -1) {
 100                 ldapUri = new URI(ldapUri.getScheme(), null, ldapUri.getHost(),
 101                         serverSocket.getLocalPort(), ldapUri.getPath(), null, null);
 102             }
 103             env.put(Context.PROVIDER_URL, ldapUri.toString());
 104             if (args[args.length - 1].equalsIgnoreCase("-trace")) {
 105                 env.put("com.sun.jndi.ldap.trace.ber", System.out);
 106             }
 107 
 108             // Specify the factory classname explicitly
 109             env.put(Context.STATE_FACTORIES, "org.example.person.PersonFactory");
 110             env.put(Context.OBJECT_FACTORIES, "org.example.person.PersonFactory");
 111 
 112             System.out.println("StorePerson: connecting to " + ldapUri);
 113             DirContext ctx = new InitialDirContext(env);
 114             Person person = null;
 115             String name = "John Smith";
 116             String dn = "cn=" + name;
 117 
 118             try {
 119                 person = new Person(name, "Smith");
 120                 person.setMailAddress("jsmith@smith.com");
 121                 ctx.bind(dn, person);
 122                 System.out.println("StorePerson: created entry '" + dn + "'");
 123             } catch (NameAlreadyBoundException e) {
 124                 System.err.println("StorePerson: entry '" + dn +
 125                         "' already exists");
 126                 cleanup(ctx, (String)null);
 127                 return;
 128             }
 129 
 130             name = "Jill Smyth";
 131             String dn2 = "cn=" + name;
 132             Person person2 = new Person(name, "Smyth");
 133             person2.setMailAddress("jsmyth@smith.com");
 134 
 135             try {
 136                 ctx.bind(dn2, person2);
 137                 System.out.println("StorePerson: created entry '" + dn2 + "'");
 138             } catch (NameAlreadyBoundException e) {
 139                 System.err.println("StorePerson: entry '" + dn2 +
 140                         "' already exists");
 141                 cleanup(ctx, dn);
 142                 return;
 143             }
 144 
 145             /*
 146              * Retrieve Person objects from the LDAP directory
 147              */
 148 
 149             try {
 150                 Person person3 = (Person) ctx.lookup(dn);
 151                 System.out.println("StorePerson: retrieved object: " + person3);
 152                 if (person.getAttributes().equals(person3.getAttributes())) {
 153                     System.out.println(
 154                             "StorePerson: retrieved person matches original");
 155                 } else {
 156                     System.out.println(
 157                             "StorePerson: retrieved person does NOT match original");
 158                 }
 159             } catch (NamingException e) {
 160                 System.err.println("StorePerson: error retrieving entry '" +
 161                         dn + "' " + e);
 162                 e.printStackTrace();
 163                 cleanup(ctx, dn, dn2);
 164                 return;
 165             }
 166 
 167             try {
 168                 Person person4 = (Person) ctx.lookup(dn2);
 169                 System.out.println("StorePerson: retrieved object: " + person4);
 170                 if (person2.getAttributes().equals(person4.getAttributes())) {
 171                     System.out.println(
 172                             "StorePerson: retrieved person matches original");
 173                 } else {
 174                     System.out.println(
 175                             "StorePerson: retrieved person does NOT match original");
 176                 }
 177             } catch (NamingException e) {
 178                 System.err.println("StorePerson: error retrieving entry '" +
 179                         dn2 + "' " + e);
 180                 e.printStackTrace();
 181                 cleanup(ctx, dn, dn2);
 182                 return;
 183             }
 184 
 185             cleanup(ctx, dn, dn2);
 186         }
 187     }
 188 
 189     /*
 190      * Remove objects from the LDAP directory
 191      */
 192     private static void cleanup(DirContext ctx, String... dns)
 193         throws NamingException {
 194 
 195         for (String dn : dns) {
 196             try {
 197                 ctx.destroySubcontext(dn);
 198                 System.out.println("StorePerson: removed entry '" + dn + "'");
 199             } catch (NamingException e) {
 200                 System.err.println("StorePerson: error removing entry '" + dn +
 201                     "' " + e);
 202             }
 203         }
 204         ctx.close();
 205     }
 206 }