View Javadoc
1   /*
2    * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
3    *
4    * Redistribution and use in source and binary forms, with or without
5    * modification, are permitted provided that the following conditions
6    * are met:
7    *
8    *   - Redistributions of source code must retain the above copyright
9    *     notice, this list of conditions and the following disclaimer.
10   *
11   *   - Redistributions in binary form must reproduce the above copyright
12   *     notice, this list of conditions and the following disclaimer in the
13   *     documentation and/or other materials provided with the distribution.
14   *
15   *   - Neither the name of Oracle nor the names of its
16   *     contributors may be used to endorse or promote products derived
17   *     from this software without specific prior written permission.
18   *
19   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21   * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22   * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30   */
31  
32  /*
33   * This source code is provided to illustrate the usage of a given feature
34   * or technique and has been deliberately simplified. Additional steps
35   * required for a production-quality application, such as security checks,
36   * input validation and proper error handling, might not be present in
37   * this sample code.
38   */
39  
40  
41  package com.sun.jmx.examples.scandir;
42  
43  import java.net.InetAddress;
44  import java.net.UnknownHostException;
45  import java.util.HashMap;
46  import java.util.Map;
47  import javax.management.MBeanServerConnection;
48  import javax.management.remote.JMXConnector;
49  import javax.management.remote.JMXConnectorFactory;
50  import javax.management.remote.JMXServiceURL;
51  import javax.rmi.ssl.SslRMIClientSocketFactory;
52  
53  /**
54   * The ScanDirClient class is a very simple programmatic client example
55   * which is able to connect to a secured JMX <i>scandir</i> application.
56   * <p>The program initialize the connection environment map with the
57   * appropriate properties and credentials, and then connects to the
58   * secure JMX <i>scandir</i> daemon.</p>
59   * <p>It gets the application's current configuration and prints it on
60   * its <code>System.out</code>.</p>
61   * <p>The {@link #main main} method takes two arguments: the host on which
62   * the server is running (localhost), and the port number
63   * that was configured to start the server RMI Connector (4545).
64   * </p>
65   * @author Sun Microsystems, 2006 - All rights reserved.
66   **/
67  public class ScanDirClient {
68  
69      // This class has only a main.
70      private ScanDirClient() { }
71  
72      /**
73       * The usage string for the ScanDirClient.
74       */
75      public static final String USAGE = ScanDirClient.class.getSimpleName() +
76              " <server-host> <rmi-port-number>";
77  
78      /**
79       * Connects to a secured JMX <i>scandir</i> application.
80       * @param args The {@code main} method takes two parameters:
81       *        <ul>
82       *        <li>args[0] must be the server's host</li>
83       *        <li>args[1] must be the rmi port number at which the
84       *        JMX <i>scandir</i> daemon is listening for connections
85       *        - that is, the port number of its JMX RMI Connector which
86       *        was configured in {@code management.properties}
87       *        </li>
88       *        <ul>
89       **/
90      public static void main(String[] args) {
91          try {
92              // Check args
93              //
94              if (args==null || args.length!=2) {
95                  System.err.println("Bad number of arguments: usage is: \n\t" +
96                          USAGE);
97                  System.exit(1);
98              }
99              try {
100                 InetAddress.getByName(args[0]);
101             } catch (UnknownHostException x) {
102                 System.err.println("No such host: " + args[0]+
103                             "\n usage is: \n\t" + USAGE);
104                 System.exit(2);
105             } catch (Exception x) {
106                 System.err.println("Bad address: " + args[0]+
107                             "\n usage is: \n\t" + USAGE);
108                 System.exit(2);
109             }
110             try {
111                 if (Integer.parseInt(args[1]) <= 0) {
112                     System.err.println("Bad port value: " + args[1]+
113                             "\n usage is: \n\t" + USAGE);
114                     System.exit(2);
115                 }
116             } catch (Exception x) {
117                 System.err.println("Bad argument: " + args[1]+
118                         "\n usage is: \n\t" + USAGE);
119                 System.exit(2);
120             }
121 
122             // Create an environment map to hold connection properties
123             // like credentials etc... We will later pass this map
124             // to the JMX Connector.
125             //
126             System.out.println("\nInitialize the environment map");
127             final Map<String,Object> env = new HashMap<String,Object>();
128 
129             // Provide the credentials required by the server
130             // to successfully perform user authentication
131             //
132             final String[] credentials = new String[] { "guest" , "guestpasswd" };
133             env.put("jmx.remote.credentials", credentials);
134 
135             // Provide the SSL/TLS-based RMI Client Socket Factory required
136             // by the JNDI/RMI Registry Service Provider to communicate with
137             // the SSL/TLS-protected RMI Registry
138             //
139             env.put("com.sun.jndi.rmi.factory.socket",
140                     new SslRMIClientSocketFactory());
141 
142             // Create the RMI connector client and
143             // connect it to the RMI connector server
144             // args[0] is the server's host - localhost
145             // args[1] is the secure server port - 4545
146             //
147             System.out.println("\nCreate the RMI connector client and " +
148                     "connect it to the RMI connector server");
149             final JMXServiceURL url = new JMXServiceURL(
150                     "service:jmx:rmi:///jndi/rmi://"+args[0]+":"+args[1] +
151                     "/jmxrmi");
152 
153             System.out.println("Connecting to: "+url);
154             final JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
155 
156             // Get an MBeanServerConnection
157             //
158             System.out.println("\nGet the MBeanServerConnection");
159             final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
160 
161             // Create a proxy for the ScanManager MXBean
162             //
163             final ScanManagerMXBean proxy =
164                     ScanManager.newSingletonProxy(mbsc);
165 
166             // Get the ScanDirConfig MXBean from the scan manager
167             //
168             System.out.println(
169                     "\nGet ScanDirConfigMXBean from ScanManagerMXBean");
170             final ScanDirConfigMXBean configMBean =
171                     proxy.getConfigurationMBean();
172 
173             // Print the scan dir configuration
174             //
175             System.out.println(
176                     "\nGet 'Configuration' attribute on ScanDirConfigMXBean");
177             System.out.println("\nConfiguration:\n" +
178                     configMBean.getConfiguration());
179 
180             // Try to invoke the "close" method on the ScanManager MXBean.
181             //
182             // Should get a SecurityException as the user "guest" doesn't
183             // have readwrite access.
184             //
185             System.out.println("\nInvoke 'close' on ScanManagerMXBean");
186             try {
187                 proxy.close();
188             } catch (SecurityException e) {
189                 System.out.println("\nGot expected security exception: " + e);
190             }
191 
192             // Close MBeanServer connection
193             //
194             System.out.println("\nClose the connection to the server");
195             jmxc.close();
196             System.out.println("\nBye! Bye!");
197         } catch (Exception e) {
198             System.out.println("\nGot unexpected exception: " + e);
199             e.printStackTrace();
200             System.exit(3);
201         }
202     }
203 }