1 /*
   2  * Copyright (c) 2013, 2017, 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 import sun.management.ManagementFactoryHelper;
  25 
  26 import com.sun.management.DiagnosticCommandMBean;
  27 
  28 public class DcmdUtil
  29 {
  30     public static String executeDcmd(String cmd, String ... args) {
  31         DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
  32         Object[] dcmdArgs = {args};
  33         String[] signature = {String[].class.getName()};
  34 
  35         try {
  36             System.out.print("> " + cmd + " ");
  37             for (String s : args) {
  38                 System.out.print(s + " ");
  39             }
  40             System.out.println(":");
  41             String result = (String) dcmd.invoke(transform(cmd), dcmdArgs, signature);
  42             System.out.println(result);
  43             return result;
  44         } catch(Exception ex) {
  45             ex.printStackTrace();
  46         }
  47         return null;
  48     }
  49 
  50     private static String transform(String name) {
  51         StringBuilder sb = new StringBuilder();
  52         boolean toLower = true;
  53         boolean toUpper = false;
  54         for (int i = 0; i < name.length(); i++) {
  55             char c = name.charAt(i);
  56             if (c == '.' || c == '_') {
  57                 toLower = false;
  58                 toUpper = true;
  59             } else {
  60                 if (toUpper) {
  61                     toUpper = false;
  62                     sb.append(Character.toUpperCase(c));
  63                 } else if(toLower) {
  64                     sb.append(Character.toLowerCase(c));
  65                 } else {
  66                     sb.append(c);
  67                 }
  68             }
  69         }
  70         return sb.toString();
  71     }
  72 
  73 }