Command Line Parser: GNUCommandLine
import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.MissingOptionException; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; public class GNUCommandLine { private Options options = new Options(); private String[] cmdlineArgs = null; private CommandLine cmdLine = null; private boolean isParsed = false; public GNUCommandLine(String cmdLineArgs[]) { this.cmdlineArgs = cmdLineArgs; this.addOption("help", "print this help message", false, false); } /** * Adds an option into the command line parser * @param optionName - the option name * @param description - option description * @param hasArg - if set to true, the option will accept argument: --optionName=value, otherwise, --optionName is a boolean * @param isMandatory - if set to true, the option must be provided. */ public Option addOption(String optionName, String description, boolean hasArg, boolean isMandatory) { return addOption(optionName, null, description, hasArg, isMandatory); } /** * Adds an option into the command line parser * @param optionName - the option name * @param argName - the name for the argument * @param description - option description * @param hasArg - if set to true, the option will accept argument: --optionName=value, otherwise, --optionName is a boolean * @param isMandatory - if set to true, the option must be provided. */ @SuppressWarnings("static-access") public Option addOption(String optionName, String argName, String description, boolean hasArg, boolean isMandatory) { OptionBuilder opt = OptionBuilder.withLongOpt(optionName); opt = opt.withDescription(description); if (hasArg) { opt = opt.hasArg(); } if (isMandatory) { opt = opt.isRequired(); } if (argName != null) { opt = opt.withArgName(argName); } Option option = opt.create(); options.addOption(option); return option; } /** * Two options form a mutually exclusive option group * @param option1 * @param option2 * @return */ public OptionGroup addOptionGroup(Option option1, Option option2) { OptionGroup optionGroup = new OptionGroup(); optionGroup.addOption(option1); optionGroup.addOption(option2); options.addOptionGroup(optionGroup); return optionGroup; } /** * Several options form a mutually exclusive option group * @param optionList * @return */ public OptionGroup addOptionGroup(List<Option> optionList) { OptionGroup optionGroup = new OptionGroup(); for (Option option : optionList) { optionGroup.addOption(option); } options.addOptionGroup(optionGroup); return optionGroup; } /** * Return all options * @return */ public Options getOptions() { return this.options; } private void parse() throws Exception { CommandLineParser parser = new GnuParser(); try { this.cmdLine = parser.parse(this.options, this.cmdlineArgs); } catch (MissingOptionException e) { printUsage(); } this.isParsed = true; if (this.cmdLine.hasOption("help")) { printUsage(); } } public void printUsage() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("options ", options); System.exit(1); } public String getString(String optionName) throws Exception { if (!this.isParsed) { this.parse(); } return this.cmdLine.getOptionValue(optionName); } public Integer getInteger(String optionName) throws Exception { return Integer.parseInt(this.getString(optionName)); } public Double getDouble(String optionName) throws Exception { return Double.parseDouble(this.getString(optionName)); } public List<String> getList(String optionName, String delimiter) throws Exception { List<String> arrayList = new ArrayList<String>(); StringTokenizer tkn = new StringTokenizer(this.getString(optionName), delimiter); while (tkn.hasMoreTokens()) { arrayList.add(tkn.nextToken()); } return arrayList; } public boolean hasOption(String optionName) throws Exception { if (!this.isParsed) { this.parse(); } return this.cmdLine.hasOption(optionName); } }
JMXClient:
public class JmxClient { private static final String OPTION_HOSTNAME = "host-name"; private static final String OPTION_PORT = "port"; private static final String OPTION_USER_NAME = "user-name"; private static final String OPTION_PASSWORD = "password"; private static final String OPTION_MBEAN_DOMAIN = "mbean-domain"; private static final String OPTION_MBEAN_NAME = "mbean-name"; private static final String OPTION_MBEAN_OPERATION = "mbean-operation"; public static void main(String[] args) { GNUCommandLine cli = new GNUCommandLine(args); cli.addOption(OPTION_HOSTNAME, "host name of remote mbean server", true, true); cli.addOption(OPTION_PORT, "port number of remote mbean server", true, true); cli.addOption(OPTION_USER_NAME, "user name for remote jmx connection", true, true); cli.addOption(OPTION_PASSWORD, "password for remote jmx connection", true, true); cli.addOption(OPTION_MBEAN_DOMAIN, "mbean domain to lookup from remote mbean server", true, true); cli.addOption(OPTION_MBEAN_NAME, "mbean name to lookup from remote mbean server", true, true); cli.addOption(OPTION_MBEAN_OPERATION, "mbean operation to lookup from remote mbean server", true, true); String hostName = null; Integer port = null; String userName = null; String password = null; String mBeanDomain = null; String mBeanName = null; String mBeanOperation = null; try { hostName = cli.getString(OPTION_HOSTNAME); port = cli.getInteger(OPTION_PORT); userName = cli.getString(OPTION_USER_NAME); password = cli.getString(OPTION_PASSWORD); mBeanDomain = cli.getString(OPTION_MBEAN_DOMAIN); mBeanName = cli.getString(OPTION_MBEAN_NAME); mBeanOperation = cli.getString(OPTION_MBEAN_OPERATION); } catch (NumberFormatException e) { System.err.println("Number format error. " + e.getMessage()); System.exit(1); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } JmxClientWorker worker = new JmxClientWorker(); worker.execute(hostName, port, userName, password, mBeanDomain, mBeanName, mBeanOperation); } }
JMXClientWorker:
import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.MBeanFeatureInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class JmxClientWorker { public void execute(String hostName, Integer port, String userName, String password, String mBeanDomain, String mBeanName, String mBeanOperation) { JMXConnector jmxc = null; try { JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostName + ":" + port + "/jmxrmi"); Hashtable<String, Object[]> env = new Hashtable<String, Object[]>(); String[] credentials = new String[]{userName, password}; env.put(JMXConnector.CREDENTIALS, credentials); System.out.println("Connecting to server: [" + url + "]"); jmxc = JMXConnectorFactory.connect(url, env); MBeanServerConnection mbs = jmxc.getMBeanServerConnection(); System.out.println("Invoking operation: [" + mBeanDomain + ":" + mBeanName + " -> " + mBeanOperation + "]"); ObjectName objectName = new ObjectName(mBeanDomain + ":name=" + mBeanName); Set<?> beans = mbs.queryMBeans(objectName, null); if (beans.size() == 0) { exit("Not a registered bean -> " + "[" + objectName.getCanonicalName() + "]"); } else if (beans.size() > 1) { listOptions(beans); exit("More than one beans are found. Please be more specific"); } else { ObjectInstance instance = (ObjectInstance) beans.iterator().next(); MBeanOperationInfo[] operationInfos = mbs.getMBeanInfo(instance.getObjectName()).getOperations(); MBeanOperationInfo operationInfo = (MBeanOperationInfo) getFeatureInfo(operationInfos, mBeanOperation); if (operationInfo != null) { MBeanParameterInfo[] paramInfos = operationInfo.getSignature(); String[] params = getParameters(mBeanOperation); int paramInfosLength = paramInfos != null ? paramInfos.length : 0; int paramsLength = params != null ? params.length : 0; if (paramInfosLength != paramsLength) { exit("Parameters count passed doesn't match signature count"); } else { Object[] paramObjects = paramInfosLength != 0 ? new Object[paramInfosLength] : null; String[] signatures = paramInfosLength != 0 ? new String[paramInfosLength] : null; for (int i = 0; i < paramInfos.length; i++) { MBeanParameterInfo paramInfo = paramInfos[i]; Constructor<?> c = Class.forName(paramInfo.getType()).getConstructor(new Class[] { java.lang.String.class }); paramObjects[i] = c.newInstance(new Object[]{params[i] }); signatures[i] = paramInfos[i].getType(); } Object result = mbs.invoke(instance.getObjectName(), operationInfo.getName(), paramObjects, signatures); System.out.println("Result: [" + result + "]"); } } else { exit("Operation not found: [" + mBeanOperation + "]"); } } } catch (InstanceNotFoundException e) { exit("Failed to find mbean", e); } catch (MalformedObjectNameException e) { exit("Invalid object name", e); } catch (ReflectionException e) { exit("No operation found", e); } catch (IOException e) { exit("Failed to connect to mbean server", e); } catch (SecurityException e) { exit("Authentication failed", e); } catch (IntrospectionException e) { exit("Failed to get mbean info", e); } catch (NoSuchMethodException e) { exit("Method is not found", e); } catch (ClassNotFoundException e) { exit("Parameter type is not found", e); } catch (IllegalArgumentException e) { exit("Invalid argument", e); } catch (InstantiationException e) { exit("Failed to initialize type", e); } catch (IllegalAccessException e) { exit("Invalid access", e); } catch (InvocationTargetException e) { exit("Failed to invoke target", e); } catch (MBeanException e) { exit("MBean exception", e); } finally { if (jmxc != null) { try { jmxc.close(); } catch (IOException e) { exit("Failed to close JMXConnectorFactory" + e.getMessage()); } } } System.out.println("Executed: [" + mBeanOperation + "]"); } private void exit (String message) { System.err.println(message); System.exit(1); } private void exit (String message, Throwable e) { while (e.getCause() != null) { e = e.getCause(); } System.err.println("Failed to execute operation, reason: [" + message + " -> " + e.getMessage() + "]"); System.exit(1); } private MBeanFeatureInfo getFeatureInfo(MBeanFeatureInfo infos[], String mBeanOperation) { int index = mBeanOperation.indexOf('='); String name = index <= 0 ? mBeanOperation : mBeanOperation.substring(0, index); for(int i = 0; i < infos.length; i++) { if(infos[i].getName().equals(name)) { return infos[i]; } } return null; } private String[] getParameters (String mBeanOperation) { int index = mBeanOperation.indexOf('='); if (index <=0) { return null; } else { return mBeanOperation.substring(index).split(","); } } private void listOptions(Set<?> beans) { for (Iterator<?> iter = beans.iterator(); iter.hasNext();) { Object obj = iter.next(); if (obj instanceof ObjectName) { System.out.println(((ObjectName) obj).getCanonicalName()); } else if (obj instanceof ObjectInstance) { System.out.println(((ObjectInstance) obj).getObjectName().getCanonicalName()); } else { System.err.println("Unexpected object type: " + obj.toString()); } } } }
相关推荐
catalina-jmx-remote.jar,jmxcmd.jar,cmdline-jmxclient-0.10.3.jar这三个jar包打包合集。因为下载网站已经被墙,所以下载下来放在这里供有需要的同学使用
本文将深入探讨如何使用Zabbix监控Tomcat应用服务器,特别关注"cmdline-jmxclient-0.10.3.jar"工具以及相关的自定义模板。 首先,`cmdline-jmxclient-0.10.3.jar`是一个Java管理扩展(JMX)客户端,它允许通过...
标题“cmdline-jmxclient.zip”指的是一个包含命令行界面的Java管理扩展(JMX)客户端工具,这个工具主要用于远程连接并监控Java虚拟机(JVM)以及运行在其中的应用,比如Tomcat服务器。JMX是一种Java平台提供的标准...
本文将详细讲解如何利用`cmdline-jmxclient-0.10.3.jar`工具与Zabbix集成,实现对Tomcat应用服务器的高效监控。 首先,`cmdline-jmxclient-0.10.3.jar`是一个命令行Java Management Extensions (JMX)客户端,它允许...
`cmdline-jmxclient-0.10.3.jar.zip` 是一个用于Tomcat性能监控的工具包,其中包含 `cmdline-jmxclient-0.10.3.jar` 文件,这是一个Java档案(JAR)文件,专门设计用于通过命令行界面与Java管理扩展(JMX)接口交互...
标题中的"cmdline-jmxclient-0.10.3.jar"和"KafkaOffsetMonitor-assembly-0.2.0.jar"是两个在Java环境中使用的工具,它们与Apache Kafka的管理和监控紧密相关。让我们详细了解一下这两个工具及其背后的原理。 JMX ...
标题“cmdline-jmxclient-0.10.3”指的是一个特定版本的命令行JMX客户端工具,这个工具主要用于与Java Management Extensions (JMX)接口进行交互,从而获取JMX相关的各种信息。JMX是一种Java平台的标准,它提供了一...
标题 "sycdtk-cmdline-jmxclient-master_java_" 暗示这是一个关于Java的项目,特别是涉及命令行界面(cmdline)和Java管理扩展(JMX)客户端的实现。JMX是一种在Java应用程序中管理和监控管理资源的标准机制。这个...
在这个场景中,我们关注的是`jmxclient`,这是一个命令行工具,用于通过JMX协议执行GET和SET操作。这使得用户可以在不编写复杂代码的情况下,远程或者本地地对支持JMX的应用进行交互。 ### JMX简介 JMX是一种服务,...
catalina-jmx-remote.jar放到tomcat/lib目录下 如果是windows版本,编辑TOMCAT_HOME/bin/catalina....java -jar cmdline-jmxclient-0.10.3.jar - 192.168.16.64:11111 java.lang:type=OperatingSystem ProcessCpuLoad
在`jmx_client-master`这个项目中,可能包含了一个命令行工具或脚本示例,供你参考和学习如何利用JMX从远程JVM获取统计信息。通过研究源代码,你可以更深入地理解JMX的工作原理以及如何在实际项目中应用。
标签"测试"表明这个压缩包包含的`cmdline-jmxclient-0.10.3.jar`可能是一个命令行工具,用于测试Zabbix与目标Java应用之间的JMX连接和数据交换。`cmdline-jmxclient`可能是一个轻量级的JMX客户端,允许用户从命令行...
JMX实战 书中不仅有对于基础知识的介绍,还有对于JMX开发中重大的体系架构问题的深入探讨,总结了大量JMX开发中的设计模式,并讨论了框架、安全性与性能等等。书中提供了几个典型的例子,兼顾各种开发平台,这些...
Java Management Extensions(JMX)是Java平台中用于管理和监控应用程序、操作系统、网络设备等资源的一种标准框架。通过JMX,开发者可以创建管理代理(MBeans),这些代理暴露了各种管理特性,使得系统管理员可以...
jmx监控ActiveMQ监控 jmx(Java Management Extensions)是一种Java技术,为Java应用程序提供了管理和监控的功能。ActiveMQ是Apache软件基金会下的一个开源消息队列系统,提供了高效、可靠的消息传递服务。在生产...