KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > admin > TCStop


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.admin;
5
6 import org.apache.commons.cli.CommandLine;
7 import org.apache.commons.cli.GnuParser;
8 import org.apache.commons.cli.HelpFormatter;
9 import org.apache.commons.cli.Option;
10 import org.apache.commons.cli.Options;
11 import org.apache.commons.cli.UnrecognizedOptionException;
12 import org.apache.commons.lang.ArrayUtils;
13
14 import com.tc.config.schema.NewCommonL2Config;
15 import com.tc.config.schema.setup.FatalIllegalConfigurationChangeHandler;
16 import com.tc.config.schema.setup.L2TVSConfigurationSetupManager;
17 import com.tc.config.schema.setup.StandardTVSConfigurationSetupManagerFactory;
18 import com.tc.config.schema.setup.TVSConfigurationSetupManagerFactory;
19 import com.tc.management.TerracottaManagement;
20 import com.tc.management.beans.L2MBeanNames;
21 import com.tc.management.beans.TCServerInfoMBean;
22
23 import java.io.File JavaDoc;
24 import java.lang.reflect.Method JavaDoc;
25 import java.net.ConnectException JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Arrays JavaDoc;
28 import java.util.HashMap JavaDoc;
29
30 import javax.management.MBeanServerConnection JavaDoc;
31 import javax.management.remote.JMXConnector JavaDoc;
32 import javax.management.remote.JMXConnectorFactory JavaDoc;
33 import javax.management.remote.JMXServiceURL JavaDoc;
34
35 public class TCStop {
36
37   private String JavaDoc m_host;
38   private int m_port;
39   private String JavaDoc m_userName;
40
41   public static final String JavaDoc DEFAULT_HOST = "localhost";
42   public static final int DEFAULT_PORT = 9520;
43   
44   public static final void main(String JavaDoc[] args) throws Exception JavaDoc {
45     Options options = StandardTVSConfigurationSetupManagerFactory.createOptions(true);
46     CommandLine commandLine = null;
47     
48     Option userNameOption = new Option("u", "username", true, "user name");
49     userNameOption.setType(String JavaDoc.class);
50     userNameOption.setRequired(false);
51     options.addOption(userNameOption);
52
53     Option helpOption = new Option("h", "help");
54     helpOption.setType(String JavaDoc.class);
55     helpOption.setRequired(false);
56     options.addOption(helpOption);
57     
58     try {
59       commandLine = new GnuParser().parse(options, args);
60     } catch(UnrecognizedOptionException e) {
61       System.err.println(e.getMessage());
62       usageAndDie(options);
63     }
64
65     if(commandLine == null || commandLine.getArgs().length > 2) {
66       usageAndDie(options);
67     }
68     
69     String JavaDoc host = null;
70     int port = -1;
71
72     if (commandLine.hasOption("h")) {
73       new HelpFormatter().printHelp("java " + TCStop.class.getName(), options);
74       System.exit(1);
75     }
76     
77     String JavaDoc defaultName = StandardTVSConfigurationSetupManagerFactory.DEFAULT_CONFIG_SPEC;
78     File JavaDoc configFile = new File JavaDoc(System.getProperty("user.dir"), defaultName);
79     boolean configSpecified = commandLine.hasOption('f');
80     boolean nameSpecified = commandLine.hasOption('n');
81     boolean userNameSpecified = commandLine.hasOption('u');
82     
83     String JavaDoc userName = null;
84     if(userNameSpecified) {
85       userName = commandLine.getOptionValue('u');
86     }
87     
88     if (configSpecified || System.getProperty("tc.config") != null || configFile.exists()) {
89       if (!configSpecified && System.getProperty("tc.config") == null) {
90         ArrayList JavaDoc tmpArgs = new ArrayList JavaDoc(Arrays.asList(args));
91
92         tmpArgs.add("-f");
93         tmpArgs.add(configFile.getAbsolutePath());
94         args = (String JavaDoc[])tmpArgs.toArray(new String JavaDoc[tmpArgs.size()]);
95       }
96       
97       FatalIllegalConfigurationChangeHandler changeHandler = new FatalIllegalConfigurationChangeHandler();
98       TVSConfigurationSetupManagerFactory factory = new StandardTVSConfigurationSetupManagerFactory(args, true, changeHandler);
99       
100       String JavaDoc name = null;
101       if (nameSpecified) {
102         name = commandLine.getOptionValue('n');
103       }
104
105       L2TVSConfigurationSetupManager manager = factory.createL2TVSConfigurationSetupManager(name);
106       String JavaDoc[] servers = manager.allCurrentlyKnownServers();
107       
108       if (nameSpecified && !Arrays.asList(servers).contains(name)) {
109         System.err.println("The specified Terracotta server configuration '"+name+"' does not exist; exiting.");
110         System.exit(1);
111       }
112       
113       if (name == null && servers != null && servers.length == 1) {
114         name = servers[0];
115         System.err.println("There is only one Terracotta server in this configuration file ("+name+"); stopping it.");
116       } else if (name == null && servers != null && servers.length > 1) {
117         System.err.println("There are multiple Terracotta servers defined in this configuration file; please specify "
118                            + "which one you want to stop, using the '-n' command-line option. Available servers are:\n"
119                            + " " + ArrayUtils.toString(servers));
120         System.exit(1);
121       }
122
123       NewCommonL2Config serverConfig = manager.commonL2ConfigFor(name);
124
125       host = serverConfig.host().getString();
126       if (host == null) host = name;
127       if (host == null) host = DEFAULT_HOST;
128       port = serverConfig.jmxPort().getInt();
129       System.err.println("Host: " + host + ", port: " + port);
130     } else {
131       if (commandLine.getArgs().length == 0) {
132         host = DEFAULT_HOST;
133         port = DEFAULT_PORT;
134         System.err
135             .println("No host or port provided. Stopping the Terracotta server at '" + host + "', port " + port + " by default.");
136       } else if (commandLine.getArgs().length == 1) {
137         host = DEFAULT_HOST;
138         port = Integer.parseInt(commandLine.getArgs()[0]);
139       } else {
140         host = commandLine.getArgs()[0];
141         port = Integer.parseInt(commandLine.getArgs()[1]);
142       }
143     }
144
145     try {
146       new TCStop(host, port, userName).stop();
147     } catch (ConnectException JavaDoc ce) {
148       System.err.println("Unable to connect to host '" + host + "', port " + port
149                          + ". Are you sure there is a Terracotta server running there?");
150     } catch(Exception JavaDoc e) {
151       System.err.println(e.getMessage());
152     }
153   }
154
155   private static void usageAndDie(Options options) throws Exception JavaDoc {
156     new HelpFormatter().printHelp("java " + TCStop.class.getName(), options);
157     System.exit(1);
158   }
159
160   public TCStop(String JavaDoc host, int port) {
161     m_host = host;
162     m_port = port;
163   }
164
165   public TCStop(String JavaDoc host, int port, String JavaDoc userName) {
166     this(host, port);
167     m_userName = userName;
168   }
169
170   public void stop() throws Exception JavaDoc {
171     JMXConnector JavaDoc jmxc = getJMXConnector();
172     MBeanServerConnection JavaDoc mbsc = jmxc.getMBeanServerConnection();
173
174     if (mbsc != null) {
175       TCServerInfoMBean tcServerInfo = (TCServerInfoMBean) TerracottaManagement.findMBean(L2MBeanNames.TC_SERVER_INFO,
176                                                                                 TCServerInfoMBean.class, mbsc);
177       try {
178         tcServerInfo.shutdown();
179       } catch (Exception JavaDoc e) {
180         jmxc.close();
181         throw e;
182       } finally {
183         jmxc.close();
184       }
185     }
186   }
187
188   private static String JavaDoc getPassword() {
189     try {
190       Method JavaDoc m = System JavaDoc.class.getMethod("console", new Class JavaDoc[]{});
191       Object JavaDoc console = m.invoke(null, null);
192       if(console != null) {
193         m = console.getClass().getMethod("readPassword", new Class JavaDoc[] {String JavaDoc.class, Object JavaDoc[].class});
194         if(m != null) {
195           byte[] pw = (byte[])m.invoke(console, new Object JavaDoc[] {"[%s]", "[console] Enter Password: "});
196           return new String JavaDoc(pw);
197         }
198       }
199     } catch(Exception JavaDoc e) {/**/}
200     
201     try {
202       System.out.print("Enter password: ");
203       return new jline.ConsoleReader().readLine(new Character JavaDoc('*'));
204     } catch(Exception JavaDoc e) {/**/}
205     
206     return null;
207   }
208   
209   private JMXConnector JavaDoc getJMXConnector() throws Exception JavaDoc {
210     String JavaDoc uri = "service:jmx:rmi:///jndi/rmi://" + m_host + ":" + m_port + "/jmxrmi";
211     JMXServiceURL JavaDoc url = new JMXServiceURL JavaDoc(uri);
212     HashMap JavaDoc env = new HashMap JavaDoc();
213     
214     if(m_userName != null) {
215       String JavaDoc[] creds = {m_userName, getPassword()};
216       env.put("jmx.remote.credentials", creds);
217     }
218
219     return JMXConnectorFactory.connect(url, env);
220   }
221 }
222
Popular Tags