1 16 17 package com.google.inject.tools.jmx; 18 19 import com.google.inject.Binding; 20 import com.google.inject.Guice; 21 import com.google.inject.Injector; 22 import com.google.inject.Key; 23 import com.google.inject.Module; 24 import java.lang.annotation.Annotation ; 25 import java.lang.management.ManagementFactory ; 26 import javax.management.MBeanServer ; 27 import javax.management.MalformedObjectNameException ; 28 import javax.management.ObjectName ; 29 30 35 public class Manager { 36 37 41 public static void manage( 42 String domain, 43 Injector injector) { 44 manage(ManagementFactory.getPlatformMBeanServer(), domain, injector); 45 } 46 47 51 public static void manage(MBeanServer server, String domain, 52 Injector injector) { 53 for (Binding<?> binding : injector.getBindings().values()) { 55 StringBuilder name = new StringBuilder (); 58 name.append(domain).append(":"); 59 Key<?> key = binding.getKey(); 60 name.append("type=").append(quote(key.getTypeLiteral().toString())); 61 Annotation annotation = key.getAnnotation(); 62 if (annotation != null) { 63 name.append(",annotation=").append(quote(annotation.toString())); 64 } 65 else { 66 Class <? extends Annotation > annotationType = key.getAnnotationType(); 67 if (annotationType != null) { 68 name.append(",annotation=") 69 .append(quote("@" + annotationType.getName())); 70 } 71 } 72 73 try { 74 server.registerMBean(new ManagedBinding(binding), 75 new ObjectName (name.toString())); 76 } 77 catch (MalformedObjectNameException e) { 78 throw new RuntimeException ("Bad object name: " 79 + name.toString(), e); 80 } 81 catch (Exception e) { 82 throw new RuntimeException (e); 83 } 84 } 85 } 86 87 static String quote(String value) { 88 return ObjectName.quote(value).replace(',', ';'); 90 } 91 92 95 public static void main(String [] args) throws Exception { 96 if (args.length != 1) { 97 System.err.println("Usage: java -Dcom.sun.management.jmxremote " 98 + Manager.class.getName() + " [module class name]"); 99 System.err.println("Then run 'jconsole' to connect."); 100 System.exit(1); 101 } 102 103 Module module = (Module) Class.forName(args[0]).newInstance(); 104 Injector injector = Guice.createInjector(module); 105 106 manage(args[0], injector); 107 108 System.out.println("Press Ctrl+C to exit..."); 109 110 Thread.sleep(Long.MAX_VALUE); 112 } 113 } 114 | Popular Tags |