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 Remote object storage and retrieval using an LDAP directory.
26 * The RMI object is supplied by a third-party module.
27 */
28
29package test;
30
31import java.io.*;
32import java.net.*;
33import java.rmi.Remote;
34import java.rmi.server.UnicastRemoteObject;
35import java.util.*;
36import javax.naming.*;
37import javax.naming.directory.*;
38
39import org.example.hello.*;
40
41public class StoreRemote {
42
43    // LDAP capture file
44    private static final String LDAP_CAPTURE_FILE =
45        System.getProperty("test.src") + "/src/test/test/StoreRemote.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:   StoreRemote <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 StoreRemote ldap://oasis/o=airius.com");
63            return;
64        }
65
66        /*
67         * Launch the LDAP server with the StoreRemote.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 a Remote object 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        System.out.println("StoreRemote: connecting to " + ldapUri);
101        DirContext ctx = new InitialDirContext(env);
102        String dn = "cn=myremote";
103
104        try {
105            Hello hello = new HelloImpl();
106            ctx.bind(dn, hello);
107            System.out.println("StoreRemote: created entry '" + dn + "'");
108
109            // Explicitly release the RMI object
110            UnicastRemoteObject.unexportObject(hello, true);
111
112        } catch (NameAlreadyBoundException e) {
113            System.err.println("StoreRemote: entry '" + dn +
114                "' already exists");
115            cleanup(ctx, (String)null);
116            return;
117        }
118
119        /*
120         * Retrieve the Remote object from the LDAP directory
121         */
122
123        try {
124            Hello obj = (Hello) ctx.lookup(dn);
125            System.out.println("StoreRemote: retrieved object: " + obj);
126            System.out.println("StoreRemote: calling Hello.sayHello()...\n" +
127                obj.sayHello());
128
129            // Explicitly release the RMI object
130            UnicastRemoteObject.unexportObject(obj, true);
131
132        } catch (NamingException e) {
133            System.err.println("StoreRemote: error retrieving entry '" +
134                dn + "' " + e);
135            e.printStackTrace();
136            cleanup(ctx, dn);
137            return;
138        }
139
140        cleanup(ctx, dn);
141    }
142
143    /*
144     * Remove objects from the LDAP directory
145     */
146    private static void cleanup(DirContext ctx, String... dns)
147        throws NamingException {
148
149        for (String dn : dns) {
150            try {
151                ctx.destroySubcontext(dn);
152                System.out.println("StoreRemote: removed entry '" + dn + "'");
153            } catch (NamingException e) {
154                System.err.println("StoreRemote: error removing entry '" + dn +
155                    "' " + e);
156            }
157        }
158        ctx.close();
159    }
160}
161