mx4j-3.0.2/build/ 40755 0 0 0 10513545721 10532 5ustar 0 0 mx4j-3.0.2/lib/ 40755 0 0 0 10513545721 10201 5ustar 0 0 mx4j-3.0.2/src/ 40755 0 0 0 10513545721 10222 5ustar 0 0 mx4j-3.0.2/src/core/ 40755 0 0 0 10513545721 11152 5ustar 0 0 mx4j-3.0.2/src/core/javax/ 40755 0 0 0 10513545721 12263 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/ 40755 0 0 0 10513545721 14377 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/loading/ 40755 0 0 0 10513545721 16014 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/modelmbean/ 40755 0 0 0 10513545721 16502 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/monitor/ 40755 0 0 0 10513545721 16066 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/openmbean/ 40755 0 0 0 10513545721 16343 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/relation/ 40755 0 0 0 10513545721 16214 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/remote/ 40755 0 0 0 10513545721 15672 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/remote/rmi/ 40755 0 0 0 10513545721 16461 5ustar 0 0 mx4j-3.0.2/src/core/javax/management/timer/ 40755 0 0 0 10513545721 15517 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/ 40755 0 0 0 10513545721 12034 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/loading/ 40755 0 0 0 10513545721 13451 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/log/ 40755 0 0 0 10513545721 12615 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/monitor/ 40755 0 0 0 10513545721 13523 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/persist/ 40755 0 0 0 10513545721 13525 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/ 40755 0 0 0 10513545721 13327 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/ 40755 0 0 0 10513545721 15161 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/iiop/ 40755 0 0 0 10513545721 16121 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/rmi/ 40755 0 0 0 10513545721 15750 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/ 40755 0 0 0 10513545721 15170 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/iiop/ 40755 0 0 0 10513545721 16130 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/rmi/ 40755 0 0 0 10513545721 15757 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/rmi/ 40755 0 0 0 10513545721 14116 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/server/ 40755 0 0 0 10513545721 13342 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/server/interceptor/ 40755 0 0 0 10513545721 15700 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/timer/ 40755 0 0 0 10513545721 13154 5ustar 0 0 mx4j-3.0.2/src/core/mx4j/util/ 40755 0 0 0 10513545721 13011 5ustar 0 0 mx4j-3.0.2/src/docs/ 40755 0 0 0 10513545721 11152 5ustar 0 0 mx4j-3.0.2/src/docs/english/ 40755 0 0 0 10513545721 12603 5ustar 0 0 mx4j-3.0.2/src/docs/images/ 40755 0 0 0 10513545721 12417 5ustar 0 0 mx4j-3.0.2/src/docs/xsl/ 40755 0 0 0 10513545721 11760 5ustar 0 0 mx4j-3.0.2/src/etc/ 40755 0 0 0 10513545721 10775 5ustar 0 0 mx4j-3.0.2/src/examples/ 40755 0 0 0 10513545721 12040 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/ 40755 0 0 0 10513545721 12722 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/ 40755 0 0 0 10513545721 14540 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/ 40755 0 0 0 10513545721 16005 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/dynamic/ 40755 0 0 0 10513545721 17431 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/helloworld/ 40755 0 0 0 10513545721 20160 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/ 40755 0 0 0 10513545721 16745 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/legacy/ 40755 0 0 0 10513545721 17251 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/ 40755 0 0 0 10513545721 16574 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/ 40755 0 0 0 10513545721 16033 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/interception/ 40755 0 0 0 10513545721 20536 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/notification/ 40755 0 0 0 10513545721 20521 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ 40755 0 0 0 10513545721 16622 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/iiop/ 40755 0 0 0 10513545721 17562 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ssl/ 40755 0 0 0 10513545721 17423 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/security/ 40755 0 0 0 10513545721 17702 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/simple/ 40755 0 0 0 10513545721 17324 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/ 40755 0 0 0 10513545721 16363 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/loading/ 40755 0 0 0 10513545721 20000 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/relation/ 40755 0 0 0 10513545721 20200 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/ 40755 0 0 0 10513545721 15700 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/ 40755 0 0 0 10513545721 17332 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/ 40755 0 0 0 10513545721 20311 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/config/ 40755 0 0 0 10513545721 17145 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/jython/ 40755 0 0 0 10513545721 17213 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/mail/ 40755 0 0 0 10513545721 16622 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/persister/ 40755 0 0 0 10513545721 17720 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/ 40755 0 0 0 10513545721 17173 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ 40755 0 0 0 10513545721 20625 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ssl/ 40755 0 0 0 10513545721 21426 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/soap/ 40755 0 0 0 10513545721 20135 5ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/xdoclet/ 40755 0 0 0 10513545721 17342 5ustar 0 0 mx4j-3.0.2/src/test/ 40755 0 0 0 10513545721 11201 5ustar 0 0 mx4j-3.0.2/src/test/test/ 40755 0 0 0 10513545721 12160 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/ 40755 0 0 0 10513545721 13271 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/ 40755 0 0 0 10513545721 15405 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/ 40755 0 0 0 10513545721 17517 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/ 40755 0 0 0 10513545721 22374 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/ 40755 0 0 0 10513545721 24110 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/ 40755 0 0 0 10513545721 21520 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/ 40755 0 0 0 10513545721 23234 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/loading/ 40755 0 0 0 10513545721 17022 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/modelmbean/ 40755 0 0 0 10513545721 17510 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/modelmbean/support/ 40755 0 0 0 10513545721 21224 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/monitor/ 40755 0 0 0 10513545721 17074 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/openmbean/ 40755 0 0 0 10513545721 17351 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/relation/ 40755 0 0 0 10513545721 17222 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/ 40755 0 0 0 10513545721 16700 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/ 40755 0 0 0 10513545721 21012 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/ 40755 0 0 0 10513545721 23667 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/ 40755 0 0 0 10513545721 25403 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/ 40755 0 0 0 10513545721 23013 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/rmi/ 40755 0 0 0 10513545721 17467 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/support/ 40755 0 0 0 10513545721 20414 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/support/ 40755 0 0 0 10513545721 17121 5ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/timer/ 40755 0 0 0 10513545721 16525 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/ 40755 0 0 0 10513545721 13042 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/log/ 40755 0 0 0 10513545721 13623 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/remote/ 40755 0 0 0 10513545721 14335 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/server/ 40755 0 0 0 10513545721 14350 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/timer/ 40755 0 0 0 10513545721 14162 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/ 40755 0 0 0 10513545721 14202 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/ 40755 0 0 0 10513545721 15634 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/http/ 40755 0 0 0 10513545721 16613 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/config/ 40755 0 0 0 10513545721 15447 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/ 40755 0 0 0 10513545721 14761 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/jython/ 40755 0 0 0 10513545721 15515 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/ 40755 0 0 0 10513545721 15475 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/ 40755 0 0 0 10513545721 16762 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/ 40755 0 0 0 10513545721 17127 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/local/ 40755 0 0 0 10513545721 16567 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/proxy/ 40755 0 0 0 10513545721 16656 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/ 40755 0 0 0 10513545721 16437 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/stats/ 40755 0 0 0 10513545721 15340 5ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/util/ 40755 0 0 0 10513545721 14017 5ustar 0 0 mx4j-3.0.2/src/tools/ 40755 0 0 0 10513545721 11362 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/ 40755 0 0 0 10513545721 12244 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/ 40755 0 0 0 10513545721 13404 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ 40755 0 0 0 10513545721 15036 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ 40755 0 0 0 10513545721 16015 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/ 40755 0 0 0 10513545721 16623 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/ 40755 0 0 0 10513545721 15637 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/config/ 40755 0 0 0 10513545721 14651 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/i18n/ 40755 0 0 0 10513545721 14163 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/jython/ 40755 0 0 0 10513545721 14717 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/mail/ 40755 0 0 0 10513545721 14326 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/naming/ 40755 0 0 0 10513545721 14655 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/ 40755 0 0 0 10513545721 14677 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/ 40755 0 0 0 10513545721 16141 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/ 40755 0 0 0 10513545721 17426 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/ 40755 0 0 0 10513545721 17573 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/serialization/ 40755 0 0 0 10513545721 21016 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/http/ 40755 0 0 0 10513545721 15656 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/http/jetty/ 40755 0 0 0 10513545721 17015 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/local/ 40755 0 0 0 10513545721 15771 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/ 40755 0 0 0 10513545721 16531 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ 40755 0 0 0 10513545721 20016 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ssl/ 40755 0 0 0 10513545721 20617 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ 40755 0 0 0 10513545721 20163 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ssl/ 40755 0 0 0 10513545721 20764 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/local/ 40755 0 0 0 10513545721 17623 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ 40755 0 0 0 10513545721 17473 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ssl/ 40755 0 0 0 10513545721 20274 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/proxy/ 40755 0 0 0 10513545721 16060 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/ 40755 0 0 0 10513545721 16540 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/ 40755 0 0 0 10513545721 20025 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/ssl/ 40755 0 0 0 10513545721 20626 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/ 40755 0 0 0 10513545721 20172 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/ssl/ 40755 0 0 0 10513545721 20773 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/local/ 40755 0 0 0 10513545721 17632 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ 40755 0 0 0 10513545721 17502 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/ 40755 0 0 0 10513545721 20303 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/rmi/ 40755 0 0 0 10513545721 15466 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/ 40755 0 0 0 10513545721 15641 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ 40755 0 0 0 10513545721 16605 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ 40755 0 0 0 10513545721 17376 5ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/stats/ 40755 0 0 0 10513545721 14542 5ustar 0 0 mx4j-3.0.2/Apache-LICENSE.txt100644 0 0 5156 10513545712 12541 0ustar 0 0 /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ mx4j-3.0.2/BUILD-HOWTO.txt100644 0 0 7400 10513545712 12027 0ustar 0 0 Welcome to MX4J, an open source implementation of the Java(TM) Management Extensions (JMX) (JSR 3) and of the Java(TM) Management Extensions (JMX) remote API (JSR 160). For further information about JMX and JSR 3, see http://java.sun.com/jmx and http://jcp.org/en/jsr/detail?id=3 For further information about JMX remote and JSR 160, see http://java.sun.com/jmx and http://jcp.org/en/jsr/detail?id=160 Refer to the MX4J home page (http://mx4j.sourceforge.net) for new releases and further information about the MX4J project. For up-to-date documentation see http://mx4j.sourceforge.net/docs. Building MX4J from the sources ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To build an MX4J binary distribution from an MX4J source distribution, you must have a J2SE(TM) version 1.3 or later installed (see http://java.sun.com/j2se). Unpack the MX4J source distribution into a directory that will be referred to as $MX4J, and follow the instructions below. Building JSR 3 (Java Management Extensions) classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Download and install Ant version 1.5 or later from http://ant.apache.org The directory where Ant is installed will be referred to as $ANT_HOME * Download BCEL version 5.0 or later from http://jakarta.apache.org/bcel Put bcel.jar into $MX4J/lib * Download Commons-Logging version 1.0 or later from http://jakarta.apache.org/commons Put commons-logging.jar into $MX4J/lib * Download Log4J version 1.2 or later from http://jakarta.apache.org/log4j Put log4j-*.jar into $MX4J/lib + Issue the command $ANT_HOME/bin/ant compile.jmx from the $MX4J/build directory Building JSR 160 (Java Management Extensions Remote API) classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Follow the instruction given for building the JSR 3 classes, and do the following: * [J2SE 1.3 only] Download JAAS version 1.0 or later from http://java.sun.com/products/jaas Unpack jaas.jar into $MX4J/lib. This step is needed to workaround a bug in the rmic compiler that is unable to load classes from jars when compiling with the -iiop flag. After this operation, there should be the directories $MX4J/lib/javax/security/auth and subdirectories, and $MX4J/lib/com/sun/security/auth and subdirectories, containing the JAAS classes. + Issue the command $ANT_HOME/bin/ant compile.rjmx from the $MX4J/build directory Building MX4J Tools classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Warning: some MX4J tools depend on JDK 1.4, since they depend on 3rd party libraries that depend on JDK 1.4. Follow the instruction given for building the JSR 160 classes, and do the following: * Download Axis version 1.1 or later from http://ws.apache.org/axis Put axis.jar, commons-discovery.jar, jaxrpc.jar, saaj.jar and wsdl4j.jar into $MX4J/lib * Download the servlet API classes version 2.3 or later from http://java.sun.com/products/servlet/reference/api/index.html Most likely, you have to rename the downloaded file from servlet-2_3-fcs-classfiles.zip to servlet.jar and put it under $MX4J/lib * Download Jetty version 4.2 or later from http://jetty.mortbay.org Put org.mortbay.jetty.jar into $MX4J/lib * [Optional] Download JavaMail and the JavaBean Activation Framework from http://java.sun.com/products/javamail http://java.sun.com/beans/glasgow Put mail.jar and activation.jar into $MX4J/lib * [Optional] Download Jython from http://www.jython.org Put jython.jar into $MX4J/lib * [Requires J2SE 1.4] Download Hessian from http://www.caucho.com Put hessian-*.jar into $MX4J/lib * [J2SE 1.3 only] Download JSSE version 1.0 or later from http://java.sun.com/products/jsse Put jcert.jar, jnet.jar and jsse.jar into $MX4J/lib + Issue the command $ANT_HOME/bin/ant compile.tools from the $MX4J/build directory mx4j-3.0.2/Jetty-LICENSE.txt100644 0 0 26136 10513545712 12500 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. mx4j-3.0.2/Jython-LICENSE.txt100644 0 0 15520 10513545712 12647 0ustar 0 0 HISTORY OF THE SOFTWARE ======================= JPython was created in late 1997 by Jim Hugunin. Jim was also the primary developer while he was at CNRI. In February 1999 Barry Warsaw took over as primary developer and released JPython version 1.1. In October 2000 Barry helped move the software to SourceForge where it was renamed to Jython. Jython 2.0 is developed by a group of volunteers. The standard library is covered by the BeOpen / CNRI license. See the Lib/LICENSE file for details. The oro regular expresion matcher is covered by the apache license. See the org/apache/LICENSE file for details. The zxJDBC package was written by Brian Zimmer and originally licensed under the GNU Public License. The package is now covered by the Jython Software License. Jython changes Software License. ================================ Copyright (c) 2000, Jython Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Jython Developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. JPython Software License. ========================= ______________________________________________________________________ IMPORTANT: PLEASE READ THE FOLLOWING AGREEMENT CAREFULLY. BY CLICKING ON THE "ACCEPT" BUTTON WHERE INDICATED, OR BY INSTALLING, COPYING OR OTHERWISE USING THE SOFTWARE, YOU ARE DEEMED TO HAVE AGREED TO THE TERMS AND CONDITIONS OF THIS AGREEMENT. ______________________________________________________________________ JPython version 1.1.x 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and using JPython version 1.1.x in source or binary form and its associated documentation as provided herein ("Software"). 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a non-exclusive, non-transferable, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright ©1996-1999 Corporation for National Research Initiatives; All Rights Reserved" are both retained in the Software, alone or in any derivative version prepared by Licensee. Alternatively, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes), provided, however, that such text is displayed prominently in the Software alone or in any derivative version prepared by Licensee: "JPython (Version 1.1.x) is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1006. The License may also be obtained from a proxy server on the Web using the following URL: http://hdl.handle.net/1895.22/1006." 3. In the event Licensee prepares a derivative work that is based on or incorporates the Software or any part thereof, and wants to make the derivative work available to the public as provided herein, then Licensee hereby agrees to indicate in any such work, in a prominently visible way, the nature of the modifications made to CNRI's Software. 4. Licensee may not use CNRI trademarks or trade name, including JPython or CNRI, in a trademark sense to endorse or promote products or services of Licensee, or any third party. Licensee may use the mark JPython in connection with Licensee's derivative versions that are based on or incorporate the Software, but only in the form "JPython-based ___________________," or equivalent. 5. CNRI is making the Software available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 6. CNRI SHALL NOT BE LIABLE TO LICENSEE OR OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. SOME STATES DO NOT ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY SO THE ABOVE DISCLAIMER MAY NOT APPLY TO LICENSEE. 7. This License Agreement may be terminated by CNRI (i) immediately upon written notice from CNRI of any material breach by the Licensee, if the nature of the breach is such that it cannot be promptly remedied; or (ii) sixty (60) days following notice from CNRI to Licensee of a material remediable breach, if Licensee has not remedied such breach within that sixty-day period. 8. This License Agreement shall be governed by and interpreted in all respects by the law of the State of Virginia, excluding conflict of law provisions. Nothing in this Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. 9. By clicking on the "ACCEPT" button where indicated, or by installing, copying or otherwise using the Software, Licensee agrees to be bound by the terms and conditions of this License Agreement. mx4j-3.0.2/LICENSE.txt100644 0 0 4713 10513545712 11360 0ustar 0 0 /* ==================================================================== * The MX4J License, Version 1.0 * * Copyright (c) 2001-2004 by the MX4J contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * MX4J project (http://mx4j.sourceforge.net)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The name "MX4J" must not be used to endorse or promote * products derived from this software without prior written * permission. * For written permission, please contact biorn_steedom@users.sourceforge.net * * 5. Products derived from this software may not be called "MX4J", * nor may "MX4J" appear in their name, without prior written * permission of Simone Bordet. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE MX4J CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the MX4J project. For more information on * MX4J, please see * . */ mx4j-3.0.2/README.txt100644 0 0 14237 10513545712 11255 0ustar 0 0 Welcome to MX4J, an open source implementation of the Java(TM) Management Extensions (JMX) (JSR 3) and of the Java(TM) Management Extensions (JMX) remote API (JSR 160). For further information about JMX and JSR 3, see http://java.sun.com/jmx and http://jcp.org/en/jsr/detail?id=3 For further information about JMX remote and JSR 160, see http://java.sun.com/jmx and http://jcp.org/en/jsr/detail?id=160 Refer to the MX4J home page (http://mx4j.sourceforge.net) for new releases and further information about the MX4J project. For up-to-date documentation see http://mx4j.sourceforge.net/docs. The MX4J distribution ~~~~~~~~~~~~~~~~~~~~~ MX4J's binary distribution is bundled in a compressed file, that contains documentation, examples, libraries. The structure of binary distribution is as follows, where ${release} indicates the MX4J release of the distribution: /mx4j-${release}/ docs/ contains the documentation examples/ contains examples on how to use JMX lib/ contains the MX4J implementation, tools and examples jars MX4J's source distribution is bundled in a compressed file, that contains the source code and an Ant build file, but no libraries. Refer to the BUILD-HOWTO file for further information on how to build MX4J from sources. The structure of source distribution is as follows, where ${release} indicates the MX4J release of the distribution: /mx4j-${release}/ build/ contains the Ant build file lib/ put here the libraries needed to build MX4J src/ contains the source files Installing MX4J ~~~~~~~~~~~~~~~ MX4J does not need to be installed. It simply provides libraries in form of jars that can be used to develop JMX applications. Running MX4J examples ~~~~~~~~~~~~~~~~~~~~~ MX4J examples source files are present in the /examples/ directory, while compiled example classes are packaged in the /lib/mx4j-examples.jar file of the binary distribution (see below). MX4J examples include JSR 160 examples, under the mx4j.examples.remote package. To run JSR 160 examples with J2SE 1.3, you need to download JAAS from http://java.sun.com/products/jaas and put jaas.jar in the classpath. MX4J examples run out of the box when using J2SE 1.4, since JAAS classes are already included in standard Java Runtime. Since J2SE 5.0 (JDK 1.5), JMX and JSR 160 classes are included in the standard Java Runtime, so running the examples will pick up JDK classes, not MX4J's. To pick up MX4J classes, you should put relevant MX4J jars in the boot classpath with the /p option (normally this is done using: java -Xbootclasspath/p:). MX4J jars ~~~~~~~~~ Under the /lib/ directory of the binary distribution there are the following jars: + mx4j-jmx.jar --> contains the JSR 3 javax.management.* classes + mx4j-impl.jar --> contains the mx4j.* classes that implements JSR 3 functionalities + mx4j.jar --> The mx4j-jmx.jar and mx4j-impl.jar packed together + mx4j-rjmx.jar --> contains the JSR 160 javax.management.remote.* classes + mx4j-rimpl.jar --> contains the mx4j.* classes that implements JSR 160 functionalities + mx4j-remote.jar --> The mx4j-rjmx.jar and mx4j-rimpl.jar packed together + mx4j-tools.jar --> contains the MX4J tools + mx4j-soap.war --> contains a sample web application that deploys a JSR 160 connector server over the soap protocol + mx4j-examples.jar --> contains the MX4J examples MX4J's Tools ~~~~~~~~~~~~ + HTTP adaptor, shows the MBeanServer's status in XML. By transforming with XSLT the XML, can be used to see the HTML view of an MBeanServer in a browser + Configuration loader, an XML file format and loader to startup and shutdown a JMX application + Naming MBeans, wrapping the rmiregistry and tnameserv + Statistics MBeans, to gather and show statistics about MBean's attributes + Mail MBean, to send email via the JavaMail API + Jython MBean, to run Python scripts + I18N StandardMBean, to show MBean metadata description in several languages + JSR 160 utilities such as: * PasswordAuthenticator, to authenticate users over JSR 160 connectors * A 'local' JSR 160 connector and connector server * A 'soap' JSR 160 connector and connector server * A 'hessian' JSR 160 connector and connector server * A 'burlap' JSR 160 connector and connector server * RemoteMBeanProxy, to proxy MBeans that reside on a remote MBeanServer * RMI [Client|Server] SocketFactories over SSL * Base classes to develop custom JSR 160 protocol connector and connector servers MX4J's Deprecated Tools ~~~~~~~~~~~~~~~~~~~~~~~ + The JRMPAdaptor and the IIOPAdaptor were tools that allowed connection with a remote MBeanServer via plain RMI and via CORBA's IIOP protocol. Since MX4J 2.x now implements the standard JMX Remote API (JSR 160), these tools are not mantained anymore and they're not shipped with the binary distribution, to protote use of the standard JMX Remote API. They're still present in the source distribution and can be compiled using the provided build file if needed. Their usage is strongly discouraged, though, and they will not be supported any longer. + The HeartBeat tool, which was dependent on the above JRMPAdaptor, is also deprecated and not mantained nor supported anymore. MX4J's Documentation ~~~~~~~~~~~~~~~~~~~~ Refer to the included documentation under the /docs/ directory of the binary distribution for further details on how to use MX4J, and to the online, nightly updated, documentation for the latest changes. MX4J Development ~~~~~~~~~~~~~~~~ MX4J includes software that has been developed using libraries from the following projects: + The Apache Software Foundation (http://www.apache.org) * The Commons Logging project (http://jakarta.apache.org/commons) * The Log4J project (http://jakarta.apache.org/log4j) * The Byte Code Engineering Library project (http://jakarta.apache.org/bcel) * The Axis project (http://ws.apache.org/axis) + The Jetty project (http://jetty.mortbay.org) + The Jython project (http://www.jython.org) + The Caucho project (http://www.caucho.com) mx4j-3.0.2/RELEASE-NOTES-3.0.2.txt100644 0 0 14142 10513545712 12717 0ustar 0 0 MX4J 3.0.2 is a bug fix release over 3.0.1, and fixes few bugs related to JMX monitors, JMX remote connector over IIOP, and registration/deregistration of JMX listeners. Below you can find the release notes for MX4J 3.0.0, reported here since there have been important changes. NOTICE OF INCOMPATIBLE CHANGES ------------------------------ MX4J was chosen as the JMX implementation for Apache Geronimo, the open source J2EE application server of the Apache Software Foundation. As part of the J2EE certification effort for Apache Geronimo, MX4J was run through the Compatibility Test Suite (CTS) for JMX. During this process a number of tests cases failed; some of these were cases where MX4J deviated from the JMX specification, some were differences in interpretation between MX4J, the JMX RI (now included in J2SE 5), and the test suite. To reduce inconsistency between MX4J and the Java platform, several changes were made to MX4J that may cause backward compatibility issues with versions prior to 3.0.0. Below you can find a list of the major changes and an evaluation of the impacts these may have on existing MX4J applications. + Change in MBeanServer's default domain. Prior to MX4J 3.0.0, if a null value was passed to MBeanServerFactory.createMBeanServer(String) or to MBeanServerFactory.newMBeanServer(String) then the default domain of the newly created MBeanServer was the empty string "". The specification, however, says that the default domain must be the string "DefaultDomain". MX4J now uses the value from the specification. This change should not impact applications that did not specify the string "DefaultDomain" as domain when creating ObjectName instances. MBeanServer server = MBeanServerFactory.newMBeanServer(null); ObjectName name = ObjectName.getInstance("DefaultDomain:type=mymbean"); server.registerMBean(mbean, name); // Returned false in MX4J 2.x, returns true in MX4J 3.x server.isRegistered(ObjectName.getInstance(":type=mymbean")); + Change in default ObjectName for an MLet. If no ObjectName is supplied when registering an MLet, then MLet.preRegister() returns a default ObjectName ":type=MLet". MX4J 2.x erroneously returned new ":service=:MLet". This change will impact applications that registered MLet without providing an ObjectName at the moment of registration: MBeanServer server = MBeanServerFactory.newMBeanServer(null); MLet mlet = new MLet(); server.registerMBean(mlet, null); + Parsing of MLet files. The syntax rules used to parse MLet files have been relaxed to conform with laxer rules in the specification. This change should not impact applications that used MX4J to parse MLet files. + Change in default MBeanPermission with 4-arg constructor. MBeanPermission has a 4-arguments constructor that allows class, method, and ObjectName patterns to be specified directly. If a null value is supplied, then the specification defines the behaviour to be that of a nilcard. MX4J 2.x incorrectly treated this as a wildcard. This change should have no impact as the 4-arg constructor is intended for internal use by JMX implementations when performing security checks. + Stricter parameter checking for JMX APIs. Many methods of the JMX API now have additional checks for illegal values. This change should not impact working applications that passed in correct values. + Changes in CounterMonitor behaviour. Since the specification was vague in defining the exact behaviour in certain cases, the MX4J team preferred to mimic the behaviour of the Reference Implementation. Specifically: * Counter values can now be set to negative values, and a THRESHOLD_ERROR event if no longer emitted in that case. * A modulus value is now only applied when the counter value rolls over (i.e. if V[t] < V[t-1]). If the counter value only increases and the offset > 0 then the threshold will continually increase until the counter is actually rolled over. * Once a THRESHOLD_VALUE_EXCEEDED notification has been sent, no futher THRESHOLD_VALUE_EXCEEDED notifications are sent until the counter value falls beneath the threshold. Previously the notification was resent if the counter value increased. * Notification status is now reset if the Monitor is stopped; as a result, notifications may be sent at the end of the first interval after a restart. Previously the notification status was maintained across a restart. + Failures in preRegister() and preDeregister() methods. To conform with the MBean lifecycle, if the invocation of preRegister() or preDeregister() terminates abnormally, then the (de)registration immedaitely fails and the appropriate postRegister() or postDeregister() method is not invoked. Previously the postRegister() method was erroneously invoked with a failure status. USAGE OF MX4J UNDER J2SE 5 -------------------------- + Since J2SE 5 already includes an implementation of JSR 3 (JMX) and JSR 160 (JMX Remote), you don't need mx4j.jar nor mx4j-remote.jar. If you really want to use the MX4J implementation under J2SE 5, you must put them in the boot classpath: %JAVA_HOME/bin/java -Xbootclasspath/p:mx4j.jar;mx4j-remote.jar ... + Running the SOAP connector under J2SE 5 requires setting up the XML provider, since the default XML provider bundled with J2SE 5 may throw a NullPointerException. You should include Xerces in the classpath (xml-apis.jar and xercesImpl.jar) and set this system property: -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl + There is no need anymore to put in the environment Map the provider packages to load MX4J connectors (by specifying the properties JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES or JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES). MX4J 3.0.0 specifies the service providers under META-INF/services in mx4j-tools.jar, so creating an MX4J connector requires nothing more than putting mx4j-tools.jar in the classpath. LIST OF CLOSED BUGS ------------------- The list of closed bugs is available here: http://sourceforge.net/tracker/?group_id=47745&atid=450647&_group=475150 by choosing the "Closed" status.mx4j-3.0.2/build/build.xml100644 0 0 73000 10513545721 12470 0ustar 0 0 Copyright © 2001-2005 The MX4J Contributors. All Rights Reserved.]]> "); doc.write(""); doc.write("

Properties of " + name + "

"); doc.write(""); doc.write(""); doc.write(""); for (prop in TestCases[name]) { doc.write(""); } doc.write("
NameValue
" + prop + "" + TestCases[name][prop] + "
"); doc.write(""); doc.close(); win.focus(); } ]]>

Class .

Tests

cur = TestCases['.'] = new Array(); cur[''] = '';

Classes

Classes

/ .html

Home

Packages

open('allclasses-frame.html','classListFrame')

Summary

Error Failure Pass
Tests Failures Errors Success rate Time
Note: failures are anticipated and checked for with assertions while errors are unanticipated.

Packages

Error Failure Pass
open('package-frame.html','classListFrame')

Package

Classes

../ ../ stylesheet.css

Unit Test Results

version on
JDK from
version ,
Generated on
Designed for use with JUnit and Ant.

Name Tests Errors Failures Time(s) Name Status Type Time(s) Error Failure Pass Error Failure TableRowColor Failure Error Success N/A

\' \\
mx4j-3.0.2/src/etc/key.store100644 0 0 2433 10513545721 12742 0ustar 0 0 þíþímykeyø»þÉY0‚‹0 +*‚w8Ç<,L&Ÿ=;O ºäسìe£‰n «,"|–æCb‡½4¤ÍtMƒÂ|üð–ëŒx8•R3’v²³ƒGÚ ÁSw·Î%XêÛ‘°À“FXâÖZãkW¢{æðXt…U†©tz3¾Ø ‚ª4P–ZÝkA [bîÔÒæß*ptЀ "ÉÃv’å^É2ò­‰GVA+qSß)ÿRn›§‡ƒ?ý>V]h*´4Q 5M§Ï& C"¹û µ)d|ìâzÆ8žÍ„7ŒR®º-~¸…e£{s§¥hÑ•Èl,§%^68I@mjLŒ“.`ky»/u_N톉?çLɽ^£iñÔõzä³£#TüÏ:еæ¨ó·.iR/gO‹2­w—×Ïd —õX¸#Š5³ñ>^áñà0¼ö$.=áĈ§[yf#–ÖnßWxÍJ¨U§g Èû5À ¿¢ëzI“X @AÉò³# òì6sKX.509F0‚B0‚?­0 *†HÎ80†1 0 UUS1 0 UNY10U New York City10U The MX4J Project10U MX4J Development Team10UAnonymous Geek0 031108153844Z 040206153844Z0†1 0 UUS1 0 UNY10U New York City10U The MX4J Project10U MX4J Development Team10UAnonymous Geek0‚·0‚,*†HÎ80‚ýSu)RßJœ.ìäçö·R<ïDÃ?€¶Q&iE]@"QûY=Xú¿Åõº0öË›Ul×;€4oòf`·k™P¥¤ŸŸè{"ÂO»©×þ·Æø;WçÆ¨¦ûƒöÓÅÃ5TZ‘2öuó®+a×*ïò"ÑHÇ—`P# ̲’¹‚¢ë„ ðXõ÷á …Ö›=Þ˼«\6¸W¹y”¯»ú:ê‚ùWL =‚gQYWŽºÔYOæq€´Iq#èL(·Ï 2ŒÈ¦á<z‹T|(࣮+³¦u‘n£ ú!5bñûbz$;̤ñ¾¨Q‰¨ƒßáZ埒‹f^€{U%dL;þÏI*„€Z’@.4ºIâyòÊ“'GÝ.]S«$¬¡÷üº¹ù7"3÷SyNPI13kµ_b³EuÂM·b;–¨Ý Ö¨7¨D=yÊIž%<P Äzƒ£å «´3·á}„ùÄ#z>ö£ ûŠ£wÞ‰EB;äW>ú .¡ód ŸA>ï=íû#0 *†HÎ8/0,î;:W ”—UV¯Tx²„0‰d]v» o¹’ÿe@¨ AšùþúóçEºŽb]-B­SÄïÉ_iDpDmx4j-3.0.2/src/etc/log4j.xml100644 0 0 1205 10513545721 12631 0ustar 0 0 mx4j-3.0.2/src/etc/trust.store100644 0 0 1604 10513545721 13332 0ustar 0 0 þíþímykeyø»ÿCÊX.509F0‚B0‚?­0 *†HÎ80†1 0 UUS1 0 UNY10U New York City10U The MX4J Project10U MX4J Development Team10UAnonymous Geek0 031108153844Z 040206153844Z0†1 0 UUS1 0 UNY10U New York City10U The MX4J Project10U MX4J Development Team10UAnonymous Geek0‚·0‚,*†HÎ80‚ýSu)RßJœ.ìäçö·R<ïDÃ?€¶Q&iE]@"QûY=Xú¿Åõº0öË›Ul×;€4oòf`·k™P¥¤ŸŸè{"ÂO»©×þ·Æø;WçÆ¨¦ûƒöÓÅÃ5TZ‘2öuó®+a×*ïò"ÑHÇ—`P# ̲’¹‚¢ë„ ðXõ÷á …Ö›=Þ˼«\6¸W¹y”¯»ú:ê‚ùWL =‚gQYWŽºÔYOæq€´Iq#èL(·Ï 2ŒÈ¦á<z‹T|(࣮+³¦u‘n£ ú!5bñûbz$;̤ñ¾¨Q‰¨ƒßáZ埒‹f^€{U%dL;þÏI*„€Z’@.4ºIâyòÊ“'GÝ.]S«$¬¡÷üº¹ù7"3÷SyNPI13kµ_b³EuÂM·b;–¨Ý Ö¨7¨D=yÊIž%<P Äzƒ£å «´3·á}„ùÄ#z>ö£ ûŠ£wÞ‰EB;äW>ú .¡ód ŸA>ï=íû#0 *†HÎ8/0,î;:W ”—UV¯Tx²„0‰d]v» o¹’ÿe@¨ Ašùþúا¸#mÃî3³b^©õÆ*¿¦qmx4j-3.0.2/src/etc/web.xml100644 0 0 1562 10513545721 12375 0ustar 0 0 MX4J SOAPConnectorServer axis org.apache.axis.transport.http.AxisServlet axis /servlet/AxisServlet axis *.jws axis /services/* index.jsp mx4j-3.0.2/src/examples/mx4j/examples/mbeans/dynamic/DynamicMBeanExample.java100644 0 0 5255 10513545721 24203 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.dynamic; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.monitor.GaugeMonitor; /** * Purpose of this example is to show how to use DynamicMBean in general, with the help * of the {@link mx4j.AbstractDynamicMBean AbstractDynamicMBean} class, see * {@link DynamicService}. * It also shows usage of the Monitor classes. * * @version $Revision: 1.4 $ */ public class DynamicMBeanExample { public static void main(String[] args) throws Exception { // Let's create the MBeanServer MBeanServer server = MBeanServerFactory.newMBeanServer(); // Let's create a dynamic MBean and register it DynamicService serviceMBean = new DynamicService(); ObjectName serviceName = new ObjectName("examples", "mbean", "dynamic"); server.registerMBean(serviceMBean, serviceName); // Now let's register a Monitor // We would like to know if we have peaks in activity, so we can use JMX's // GaugeMonitor GaugeMonitor monitorMBean = new GaugeMonitor(); ObjectName monitorName = new ObjectName("examples", "monitor", "gauge"); server.registerMBean(monitorMBean, monitorName); // Setup the monitor: we want to be notified if we have too many clients or too less monitorMBean.setThresholds(new Integer(8), new Integer(4)); // Setup the monitor: we want to know if a threshold is exceeded monitorMBean.setNotifyHigh(true); monitorMBean.setNotifyLow(true); // Setup the monitor: we're interested in absolute values of the number of clients monitorMBean.setDifferenceMode(false); // Setup the monitor: link to the service MBean monitorMBean.addObservedObject(serviceName); monitorMBean.setObservedAttribute("ConcurrentClients"); // Setup the monitor: a short granularity period monitorMBean.setGranularityPeriod(50L); // Setup the monitor: register a listener monitorMBean.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println(notification); } }, null, null); // Setup the monitor: start it monitorMBean.start(); // Now start also the service serviceMBean.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/dynamic/DynamicService.java100644 0 0 7536 10513545721 23311 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.dynamic; import javax.management.MBeanAttributeInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import mx4j.AbstractDynamicMBean; /** * This is a DynamicMBean. Note how the usage of the {@link AbstractDynamicMBean} * class simplifies a lot the coding of DynamicMBeans. * The code itself is divided in two parts: the implementation part and the JMX part. * * @version $Revision: 1.4 $ */ public class DynamicService extends AbstractDynamicMBean { // // Implementation part. // This part gives the MBean the service functionality. // private boolean running; private int concurrent; public void start() { // Simulate the accept on incoming client requests // We will track how many requests we have, and if we pass a certain threshold, // we issue a notification. synchronized (this) { running = true; } Thread thread = new Thread(new Runnable() { public void run() { simulateClientRequests(); } }); thread.start(); } public void stop() { synchronized (this) { running = false; } } private void simulateClientRequests() { while (isRunning()) { // Pick a time in ms to simulate the interval between incoming client requests long interval = Math.round(Math.random() * 1000L) + 1; try { Thread.sleep(interval); } catch (InterruptedException ignored) { } // Spawn a new Thread to accept the client request Thread thread = new Thread(new Runnable() { public void run() { // Increase the number of concurrent clients synchronized (DynamicService.this) { ++concurrent; System.out.println("--DynamicService--" + Thread.currentThread() + "-- Incoming client request -- concurrent clients: " + concurrent); } // Pick a time in ms to simulate the processing of the client request long processing = Math.round(Math.random() * 5000L) + 1; try { Thread.sleep(processing); } catch (InterruptedException ignored) { } // We're done with this client, decrease the number of concurrent clients synchronized (DynamicService.this) { --concurrent; } } }); thread.start(); } } public synchronized boolean isRunning() { return running; } public synchronized int getConcurrentClients() { return concurrent; } // // JMX part. // Note how short is :) // protected MBeanAttributeInfo[] createMBeanAttributeInfo() { return new MBeanAttributeInfo[] { new MBeanAttributeInfo("Running", "boolean", "The running status of the DynamicService", true, false, true), new MBeanAttributeInfo("ConcurrentClients", "int", "The number of concurrent clients", true, false, false) }; } protected MBeanOperationInfo[] createMBeanOperationInfo() { return new MBeanOperationInfo[] { new MBeanOperationInfo("start", "Starts the DynamicService", new MBeanParameterInfo[0], "void", MBeanOperationInfo.ACTION), new MBeanOperationInfo("stop", "Stops the DynamicService", new MBeanParameterInfo[0], "void", MBeanOperationInfo.ACTION) }; } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/helloworld/HelloWorld.java100644 0 0 4057 10513545721 23201 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.helloworld; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Service class that reads a configuration file and returns information about the configuration.

* Its purpose is to show the difference between management methods and service methods.
* This class has 3 methods, but only 2 belong to the management interface, therefore only these 2 * are accessible from the MBeanServer, so they're the management methods.
* The third method can be used by any other class but it is not accessible from the MBeanServer so * it's a service method (since it gives a service to callers), and not a management method. * * @version $Revision: 1.3 $ */ public class HelloWorld implements HelloWorldMBean { private int m_times; private Properties m_configuration; public String getInfoFromConfiguration(String key) { // Be sure to use the configuration while it is not changed. synchronized (this) { return m_configuration.getProperty(key); } } public void reloadConfiguration() throws IOException { // Lookup the configuration file in the classpath String configuration = "jndi.properties"; InputStream is = getClass().getClassLoader().getResourceAsStream(configuration); if (is == null) { throw new FileNotFoundException("Cannot find " + configuration + " file in classpath"); } // Load the new configuration from the file Properties p = new Properties(); p.load(is); // Avoid that someone reads the configuration while we are changing it synchronized (this) { m_configuration = p; ++m_times; } } public int getHowManyTimes() { return m_times; } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/helloworld/HelloWorldExample.java100644 0 0 4106 10513545721 24510 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.helloworld; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; /** * JMX HelloWorld example.

* Instead of saying "Hello", this simple class shows how is possible to create services, * register them in the JMX Agent, and invoke methods on them without * having a reference to them.
* One can create a service that can reload its configuration at runtime, and be queried * on how many times the configuration is reloaded, and expose it as standard MBean.
* This class shows in code what is possible to do via a management interface: once the * service is registered, one can connect via (for example) the HTTP adaptor and * invoke methods on the MBean.
* The service (the MBean) can be registered in one host, while the system administrator * can connect to the HTTP adaptor from another host using a browser and ask the service * to reload its configuration, without stopping it nor being forced to login to the * remote host. * * @version $Revision: 1.3 $ */ public class HelloWorldExample { public static void main(String[] args) throws Exception { // Create an instance of MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Create an ObjectName for the MBean ObjectName name = new ObjectName(":mbean=helloworld"); // Create and register the MBean in the MBeanServer server.createMBean("mx4j.examples.mbeans.helloworld.HelloWorld", name, null); // Invoke a method on it server.invoke(name, "reloadConfiguration", new Object[0], new String[0]); // Invoke an attribute on it Integer times = (Integer)server.getAttribute(name, "HowManyTimes"); System.out.println("The configuration was reloaded " + times + " times."); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/helloworld/HelloWorldMBean.java100644 0 0 1023 10513545721 24072 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.helloworld; import java.io.IOException; /** * Management interface for the HelloWorld MBean * * @version $Revision: 1.3 $ */ public interface HelloWorldMBean { public void reloadConfiguration() throws IOException; public int getHowManyTimes(); } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/Hello.java100644 0 0 1157 10513545721 20754 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.iiop; import java.rmi.Remote; import java.rmi.RemoteException; /** * The RMI Remote interface exposed by the Hello service. * * @version $Revision: 1.4 $ */ public interface Hello extends Remote { public static final String IIOP_JNDI_NAME = "iiop://localhost:1900/iiop_service"; public void sayHello(String name) throws RemoteException; } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/HelloImpl.java100644 0 0 3566 10513545721 21604 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.iiop; import java.rmi.RemoteException; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; /** * The Hello service implementation.
* It exposes two interfaces: the RMI Remote interface, invocable from remote clients - * represented by the {@link Hello} interface, and * the management interface - represented by the {@link HelloImplMBean} interface, * invocable from management applications that wants to manage the features of this * service. * * @version $Revision: 1.4 $ */ public class HelloImpl implements Hello, HelloImplMBean { private boolean m_isRunning; public HelloImpl() throws RemoteException { } public void sayHello(String name) throws RemoteException { String hello = "Hello"; System.out.println(hello + " " + name); } public void start() throws Exception { if (!m_isRunning) { // export the remote object PortableRemoteObject.exportObject(this); // set up the initialContext Context ctx = new InitialContext(); ctx.rebind(IIOP_JNDI_NAME, this); System.out.println("My Service servant started successfully"); m_isRunning = true; } } public void stop() throws Exception { if (m_isRunning) { PortableRemoteObject.unexportObject(this); Context ctx = new InitialContext(); ctx.unbind(IIOP_JNDI_NAME); m_isRunning = false; System.out.println("My Service Servant stopped successfully"); } } public boolean isRunning() { return m_isRunning; } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/HelloImplMBean.java100644 0 0 2101 10513545721 22467 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.iiop; /** * The management interface exposed by the service. * As you can see, the management operations consist of * starting and stopping the service along with seeing if the server is running. * Note that it does not contain the {@link Hello#sayHello} method, which is * considered in this example a business method and not a management method. * * @version $Revision: 1.4 $ */ public interface HelloImplMBean { /** * Starts the service, allowing RMI clients to connect * * @see #stop */ public void start() throws Exception; /** * Stops the service so that RMI clients cannot connect anymore * * @see #start */ public void stop() throws Exception; /** * Returns if the service is running * * @see #start */ public boolean isRunning(); } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/IIOPClient.java100644 0 0 1533 10513545721 21606 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.iiop; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; /** * This example connects to an RMI over IIOP server and invoke the services it exposes, * in this simple example it just calls {@link Hello#sayHello}. * * @version $Revision: 1.4 $ */ public class IIOPClient { public static void main(String[] args) throws Exception { InitialContext ctx = new InitialContext(); Hello remoteInterface = (Hello)PortableRemoteObject.narrow(ctx.lookup(Hello.IIOP_JNDI_NAME), Hello.class); remoteInterface.sayHello("from the MX4J Team"); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/IIOPServer.java100644 0 0 2445 10513545721 21641 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.iiop; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; /** * This example starts a RMI over IIOP server that listens for RMI clients to connect * and exposes its functionalities via JMX. * To be run, be sure to have started the tnameserv or the orbd utility on the port * specified by {@link Hello#IIOP_JNDI_NAME}, with the following command: *

 * $JAVA_HOME/bin/orbd -ORBInitialPort 1900
 * 
* * @version $Revision: 1.5 $ */ public class IIOPServer { public static void main(String[] args) throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("examples:type=iiop-remote"); HelloImpl remote = new HelloImpl(); server.registerMBean(remote, name); HelloImplMBean managed = (HelloImplMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, HelloImplMBean.class, false); managed.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/legacy/DynamicLegacyService.java100644 0 0 14300 10513545721 24261 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.legacy; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.management.ListenerNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.Notification; import javax.management.NotificationBroadcaster; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationFilter; import javax.management.NotificationListener; import mx4j.AbstractDynamicMBean; /** * The wrapper DynamicMBean for exposing the legacy service in a non-invasive way.
* This MBean emits notifications when the legacy service starts its activity and when it stops it. * Furthermore, when the legacy service is running, it displays the number of threads that the * legacy service is using to perform its activity.
* Note how the {@link LegacyService} is completely unaware of JMX, and even if it has private fields * and methods (the legacy service was designed without knowledge of JMX), it is possible to * expose them (via reflection) in JMX.
* This MBean is divided in two parts, the implementation one and the JMX one. Note how the JMX * part, thanks to {@link AbstractDynamicMBean}, is very simple even if it is a DynamicMBean. * * @version $Revision: 1.4 $ */ public class DynamicLegacyService extends AbstractDynamicMBean implements NotificationBroadcaster { // // Implementation Part // private LegacyService service; private Thread statusThread; public DynamicLegacyService(LegacyService service) { this.service = service; statusThread = new Thread(new Runnable() { public void run() { monitorStatus(); } }); } /** * Starts monitoring the legacy service, and starts as well the legacy service * * @see #isRunning */ public void start() { // Start the thread that monitors the status of the service statusThread.start(); // We remap the 'start' method as defined by JMX to the 'execute' method of the legacy service service.execute(); } /** * Returns whether the legacy service has woken up and it is running or not. */ public boolean isRunning() { // The method 'isRunning' is private in the legacy service, so here we use reflection tricks try { Class cls = service.getClass(); Method method = cls.getDeclaredMethod("isRunning", new Class[0]); method.setAccessible(true); Boolean result = (Boolean)method.invoke(service, new Object[0]); return result.booleanValue(); } catch (Exception ignored) { ignored.printStackTrace(); return false; } } /** * Returns the number of threads that the legacy service is using to perform its job when it * wakes up. */ public int getThreadCount() { // There is no a direct mapping of the thread count in the legacy service // We use again reflection tricks, calling LegacyService.group.activeCount() try { Class cls = service.getClass(); Field field = cls.getDeclaredField("group"); field.setAccessible(true); ThreadGroup group = (ThreadGroup)field.get(service); return group.activeCount(); } catch (Exception ignored) { ignored.printStackTrace(); return 0; } } /** * Monitors the status of the legacy service, every 50 ms, to see if it has woken up * and it is running.
* When the legacy service starts and stops its job, a notification is emitted. */ private void monitorStatus() { boolean wasRunning = false; while (true) { boolean isRunning = isRunning(); if (wasRunning ^ isRunning) { Notification notification = new Notification("legacy.status.running." + isRunning, this, 0, "Legacy Service Status: " + isRunning); broadcaster.sendNotification(notification); wasRunning = isRunning; } else { if (isRunning) System.out.println("Threads: " + getThreadCount()); } // Monitor every 50 ms try { Thread.sleep(50); } catch (InterruptedException ignored) { } } } // // JMX Part // private NotificationBroadcasterSupport broadcaster = new NotificationBroadcasterSupport(); protected MBeanAttributeInfo[] createMBeanAttributeInfo() { return new MBeanAttributeInfo[] { new MBeanAttributeInfo("Running", "boolean", "The running status of the Legacy Service", true, false, true), new MBeanAttributeInfo("ThreadCount", "int", "The number of running threads", true, false, false) }; } protected MBeanOperationInfo[] createMBeanOperationInfo() { return new MBeanOperationInfo[] { new MBeanOperationInfo("start", "Start the Legacy Service", new MBeanParameterInfo[0], "void", MBeanOperationInfo.ACTION) }; } protected MBeanNotificationInfo[] createMBeanNotificationInfo() { return getNotificationInfo(); } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { broadcaster.addNotificationListener(listener, filter, handback); } public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[] { new MBeanNotificationInfo (new String[]{"legacy.status.running.true", "legacy.status.running.false"}, Notification.class.getName(), "Notifications on the status of the Legacy Service") }; } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/legacy/LegacyExample.java100644 0 0 4266 10513545721 22741 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.legacy; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; /** * This example aims to show how it is possible, with JMX, to write a non-invasive * wrapper for an existing legacy service in order to expose the functionality * of the legacy service with JMX. * * @version $Revision: 1.3 $ */ public class LegacyExample { public static void main(String[] args) throws Exception { // Create the service LegacyService legacyService = new LegacyService(); // Create the JMX MBeanServer and register the service wrapper MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName serviceName = new ObjectName("examples", "mbean", "legacy"); DynamicLegacyService dynamicService = new DynamicLegacyService(legacyService); server.registerMBean(dynamicService, serviceName); // Now register a listener: we want to be able to know when the service starts and stops server.addNotificationListener(serviceName, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println(notification); } }, null, null); // Now start the service, using the new method name: 'start' instead of 'execute' server.invoke(serviceName, "start", null, null); } /** * This is the old main routine that started the service. * In this example we had the possibility to modify the starter of the service * by renaming the main method and by writing a new one that uses JMX. * However, it is also possible to write another starter leaving the legacy part * totally unchanged. */ public static void oldMain(String[] args) { LegacyService service = new LegacyService(); service.execute(); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/legacy/LegacyService.java100644 0 0 6074 10513545721 22745 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.legacy; /** * This service wakes up every once in a while, and does an intensive job * spawning many threads to perform the given operation.
* We would like to be informed of this activity, and would like to expose functionality of * this service via JMX. To achieve these goals, we wrap it by means of a DynamicMBean, * {@link DynamicLegacyService}. * * @version $Revision: 1.3 $ */ public class LegacyService { private boolean running; private ThreadGroup group = new ThreadGroup("Legacy Thread Group"); /** * This method is called 'execute', but we want to expose it in JMX with the name 'start'. * The magic is done in the DynamicMBean that wraps this service to expose it via JMX. */ public void execute() { while (true) { // Wait for a while long wait = Math.round(Math.random() * 10000L) + 1; try { System.out.println("Waiting " + wait + " ms..."); Thread.sleep(wait); } catch (InterruptedException ignored) { } // Ok, we've slept enough, time to do some job synchronized (this) { running = true; } Thread thread = new Thread(new Runnable() { public void run() { spawnThreads(); // We're done now, not running anymore synchronized (this) { running = false; } } }); thread.start(); try { thread.join(); } catch (InterruptedException ignored) { } } } /** * This method is private in the legacy service. However, we want to expose it via JMX * without modifying this service. The magic is done in the DynamicMBean that wraps this * service to expose it via JMX. */ private synchronized boolean isRunning() { return running; } private void spawnThreads() { Thread[] threads = new Thread[20]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(group, new Runnable() { public void run() { // Simulate a job: sleep for a while :D long sleep = Math.round(Math.random() * 5000L) + 1; try { Thread.sleep(sleep); } catch (InterruptedException ignored) { } } }); threads[i].start(); } // Now wait for everyone to complete: for (int i = 0; i < threads.length; ++i) { try { threads[i].join(); } catch (InterruptedException ignored) { } } } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/Client.java100644 0 0 1150 10513545721 20747 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.rmi; import javax.naming.InitialContext; /** * @version $Revision: 1.3 $ */ public class Client { public static void main(String[] args) throws Exception { InitialContext ctx = new InitialContext(); MyRemoteService service = (MyRemoteService)ctx.lookup(MyRemoteService.JNDI_NAME); service.sayHello("Simon"); } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/MyRemoteService.java100644 0 0 1143 10513545721 22615 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.rmi; import java.rmi.Remote; import java.rmi.RemoteException; /** * The RMI Remote interface of the service. * * @version $Revision: 1.4 $ */ public interface MyRemoteService extends Remote { public static final String JNDI_NAME = "rmi://localhost:1099/my-service"; public void sayHello(String name) throws RemoteException; } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/MyRemoteServiceObject.java100644 0 0 3546 10513545721 23755 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.rmi; import java.rmi.RemoteException; import java.rmi.server.RemoteServer; import java.rmi.server.UnicastRemoteObject; import javax.naming.InitialContext; /** * The service implementation.
* It exposes two interfaces: the RMI Remote interface, invocable from remote clients - * represented by the {@link MyRemoteService} interface, and * the management interface - represented by the {@link MyRemoteServiceObjectMBean} interface, * invocable from management applications that wants to manage the features of this * service. * * @version $Revision: 1.4 $ */ public class MyRemoteServiceObject extends RemoteServer implements MyRemoteService, MyRemoteServiceObjectMBean { private boolean m_running; public MyRemoteServiceObject() throws RemoteException { } public void sayHello(String name) throws RemoteException { System.out.println("Hello, " + name); } public void start() throws Exception { if (!m_running) { UnicastRemoteObject.exportObject(this); InitialContext ctx = new InitialContext(); ctx.rebind(JNDI_NAME, this); m_running = true; System.out.println("My remote service started successfully"); } } public void stop() throws Exception { if (m_running) { InitialContext ctx = new InitialContext(); ctx.unbind(JNDI_NAME); UnicastRemoteObject.unexportObject(this, false); m_running = false; System.out.println("My remote service stopped successfully"); } } public boolean isRunning() { return m_running; } } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/MyRemoteServiceObjectMBean.java100644 0 0 1501 10513545721 24645 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.rmi; /** * The management interface exposed by the service. * As you can see, the management operations consist of * starting and stopping the service along with seeing if the server is running. * Note that it does not contain the {@link MyRemoteService#sayHello} method, which is * considered in this example a business method and not a management method. * * @version $Revision: 1.4 $ */ public interface MyRemoteServiceObjectMBean { public void start() throws Exception; public void stop() throws Exception; public boolean isRunning(); } mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/Server.java100644 0 0 2515 10513545721 21005 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.mbeans.rmi; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; /** * This example starts a RMI over IIOP server that listens for RMI clients to connect * and exposes its functionalities via JMX. * To be run, be sure to have started the rmiregistry utility on the port * specified by {@link MyRemoteService#JNDI_NAME}, with the following command: *
 * $JAVA_HOME/bin/rmiregistry 1099
 * 
* * @version $Revision: 1.4 $ */ public class Server { public static void main(String[] args) throws Exception { MBeanServer server = MBeanServerFactory.createMBeanServer(); ObjectName name = new ObjectName("examples:type=remote"); MyRemoteServiceObject remote = new MyRemoteServiceObject(); server.registerMBean(remote, name); MyRemoteServiceObjectMBean managed = (MyRemoteServiceObjectMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, MyRemoteServiceObjectMBean.class, false); managed.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/interception/Client.java100644 0 0 2766 10513545721 22727 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.interception; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to setup a JSR 160 connector client that connects to * a JSR 160 connector server that intercepts calls directed to it. * * @version $Revision: 1.3 $ * @see Server */ public class Client { public static void main(String[] args) throws Exception { // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // The credentials are passed via the environment Map Map environment = new HashMap(); String[] credentials = new String[]{"guest", "guest"}; environment.put(JMXConnector.CREDENTIALS, credentials); // Connect to the server JMXConnector cntor = JMXConnectorFactory.connect(url, environment); MBeanServerConnection connection = cntor.getMBeanServerConnection(); // On the server's console, this call will be intercepted String domain = connection.getDefaultDomain(); System.out.println("Default domain = " + domain); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/interception/Server.java100644 0 0 7362 10513545721 22754 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.interception; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.tools.naming.NamingService; import mx4j.tools.remote.PasswordAuthenticator; /** * This example shows how to setup a JSR 160 connector server that intercepts calls to its target MBeanServer. * It will be shown how to intercept and print on the console the Subject of the current call. * It is very similar to the {@link mx4j.examples.remote.security.Server security example}, because it needs * an authenticated Subject to be present in order to log the Subject of the current invocation. * * @version $Revision: 1.3 $ * @see Client */ public class Server { private static final String PASSWORD_FILE = "users.properties"; public static void main(String[] args) throws Exception { prepareUsersFile(); // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // Specify the authenticator in the environment Map, using the // standard property JMXConnector.AUTHENTICATOR Map environment = new HashMap(); JMXAuthenticator authenticator = new PasswordAuthenticator(new File(PASSWORD_FILE)); environment.put(JMXConnectorServer.AUTHENTICATOR, authenticator); // Create and register the connector server JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, null); ObjectName cntorServerName = ObjectName.getInstance(":service=" + JMXConnectorServer.class.getName() + ",protocol=" + url.getProtocol()); MBeanServer server = MBeanServerFactory.createMBeanServer("remote.security.example"); server.registerMBean(cntorServer, cntorServerName); // Setup the rmiregistry to bind in JNDI the RMIConnectorServer stub. NamingService naming = new NamingService(); ObjectName namingName = ObjectName.getInstance(":service=" + NamingService.class.getName()); server.registerMBean(naming, namingName); naming.start(); // Setup the interception SubjectTrackingMBeanServer interceptor = new SubjectTrackingMBeanServer(); cntorServer.setMBeanServerForwarder(interceptor); // Start the connector server cntorServer.start(); System.out.println("Server up and running"); } /** * Writes a user/password file in the filesystem, with two hardcoded users: * 'admin' and 'guest'. * Normally this file is provided externally, not created by a program. * Purpose of this method is to show how to obfuscate passwords using * {@link PasswordAuthenticator}. */ private static void prepareUsersFile() throws IOException { Properties properties = new Properties(); String user = "admin"; String password = PasswordAuthenticator.obfuscatePassword("admin"); properties.setProperty(user, password); user = "guest"; password = PasswordAuthenticator.obfuscatePassword("guest"); properties.setProperty(user, password); FileOutputStream fos = new FileOutputStream(new File(PASSWORD_FILE)); properties.store(fos, null); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/interception/SubjectTrackingMBeanServer.java100644 0 0 25600 10513545721 26675 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.interception; import java.io.ObjectInputStream; import java.security.AccessController; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.OperationsException; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.management.loading.ClassLoaderRepository; import javax.management.remote.MBeanServerForwarder; import javax.security.auth.Subject; /** * This class tracks the Subject of the current invocation, and prints it to System.out. * It should be better implemented as JDK 1.3 dynamic proxy, but this is left as a simple * exercise to the reader ;) * * @version $Revision: 1.3 $ */ public class SubjectTrackingMBeanServer implements MBeanServerForwarder { private MBeanServer server; public synchronized MBeanServer getMBeanServer() { return server; } public synchronized void setMBeanServer(MBeanServer server) throws IllegalArgumentException { if (server == null) throw new IllegalArgumentException("Cannot forward to a null MBeanServer"); this.server = server; } private void trackSubject() { Subject subject = Subject.getSubject(AccessController.getContext()); System.out.println("Subject = " + subject); } public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { trackSubject(); getMBeanServer().addNotificationListener(observed, listener, filter, handback); } public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { trackSubject(); getMBeanServer().addNotificationListener(observed, listener, filter, handback); } public void removeNotificationListener(ObjectName observed, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException { trackSubject(); getMBeanServer().removeNotificationListener(observed, listener); } public void removeNotificationListener(ObjectName observed, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException { trackSubject(); getMBeanServer().removeNotificationListener(observed, listener); } public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { trackSubject(); getMBeanServer().removeNotificationListener(observed, listener, filter, handback); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { trackSubject(); getMBeanServer().removeNotificationListener(observed, listener, filter, handback); } public MBeanInfo getMBeanInfo(ObjectName objectName) throws InstanceNotFoundException, IntrospectionException, ReflectionException { trackSubject(); return getMBeanServer().getMBeanInfo(objectName); } public boolean isInstanceOf(ObjectName objectName, String className) throws InstanceNotFoundException { trackSubject(); return getMBeanServer().isInstanceOf(objectName, className); } public String[] getDomains() { trackSubject(); return getMBeanServer().getDomains(); } public String getDefaultDomain() { trackSubject(); return getMBeanServer().getDefaultDomain(); } public ObjectInstance createMBean(String className, ObjectName objectName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { trackSubject(); return getMBeanServer().createMBean(className, objectName); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { trackSubject(); return getMBeanServer().createMBean(className, objectName, loaderName); } public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { trackSubject(); return getMBeanServer().createMBean(className, objectName, args, parameters); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { trackSubject(); return getMBeanServer().createMBean(className, objectName, loaderName, args, parameters); } public void unregisterMBean(ObjectName objectName) throws InstanceNotFoundException, MBeanRegistrationException { trackSubject(); getMBeanServer().unregisterMBean(objectName); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { trackSubject(); return getMBeanServer().getAttribute(objectName, attribute); } public void setAttribute(ObjectName objectName, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { trackSubject(); getMBeanServer().setAttribute(objectName, attribute); } public AttributeList getAttributes(ObjectName objectName, String[] attributes) throws InstanceNotFoundException, ReflectionException { trackSubject(); return getMBeanServer().getAttributes(objectName, attributes); } public AttributeList setAttributes(ObjectName objectName, AttributeList attributes) throws InstanceNotFoundException, ReflectionException { trackSubject(); return getMBeanServer().setAttributes(objectName, attributes); } public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters) throws InstanceNotFoundException, MBeanException, ReflectionException { trackSubject(); return getMBeanServer().invoke(objectName, methodName, args, parameters); } public Integer getMBeanCount() { trackSubject(); return getMBeanServer().getMBeanCount(); } public boolean isRegistered(ObjectName objectname) { trackSubject(); return getMBeanServer().isRegistered(objectname); } public ObjectInstance getObjectInstance(ObjectName objectName) throws InstanceNotFoundException { trackSubject(); return getMBeanServer().getObjectInstance(objectName); } public Set queryMBeans(ObjectName patternName, QueryExp filter) { trackSubject(); return getMBeanServer().queryMBeans(patternName, filter); } public Set queryNames(ObjectName patternName, QueryExp filter) { trackSubject(); return getMBeanServer().queryNames(patternName, filter); } public Object instantiate(String className) throws ReflectionException, MBeanException { trackSubject(); return getMBeanServer().instantiate(className); } public Object instantiate(String className, ObjectName loaderName) throws ReflectionException, MBeanException, InstanceNotFoundException { trackSubject(); return getMBeanServer().instantiate(className, loaderName); } public Object instantiate(String className, Object[] args, String[] parameters) throws ReflectionException, MBeanException { trackSubject(); return getMBeanServer().instantiate(className, args, parameters); } public Object instantiate(String className, ObjectName loaderName, Object[] args, String[] parameters) throws ReflectionException, MBeanException, InstanceNotFoundException { trackSubject(); return getMBeanServer().instantiate(className, loaderName, args, parameters); } public ObjectInstance registerMBean(Object mbean, ObjectName objectName) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { trackSubject(); return registerMBean(mbean, objectName); } public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] bytes) throws InstanceNotFoundException, OperationsException, ReflectionException { trackSubject(); return getMBeanServer().deserialize(className, loaderName, bytes); } public ObjectInputStream deserialize(String className, byte[] bytes) throws OperationsException, ReflectionException { trackSubject(); return getMBeanServer().deserialize(className, bytes); } public ObjectInputStream deserialize(ObjectName objectName, byte[] bytes) throws InstanceNotFoundException, OperationsException { trackSubject(); return getMBeanServer().deserialize(objectName, bytes); } public ClassLoader getClassLoaderFor(ObjectName mbeanName) throws InstanceNotFoundException { trackSubject(); return getMBeanServer().getClassLoaderFor(mbeanName); } public ClassLoader getClassLoader(ObjectName loaderName) throws InstanceNotFoundException { trackSubject(); return getMBeanServer().getClassLoader(loaderName); } public ClassLoaderRepository getClassLoaderRepository() { trackSubject(); return getMBeanServer().getClassLoaderRepository(); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/notification/Client.java100644 0 0 4515 10513545721 22704 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.notification; import javax.management.MBeanServerConnection; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.loading.MLet; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to setup a JSR 160 connector client, and how it is * possible to receive notifications emitted by a remote connector server. * * @version $Revision: 1.4 $ * @see Server */ public class Client { public static void main(String[] args) throws Exception { // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // Create and connect the connector client JMXConnector cntor = JMXConnectorFactory.connect(url, null); // The connection represent, on client-side, the remote MBeanServer MBeanServerConnection connection = cntor.getMBeanServerConnection(); // The listener that will receive notifications from a remote MBean NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println(notification); } }; // The MBeanServerDelegate emits notifications about registration/unregistration of MBeans ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); connection.addNotificationListener(delegateName, listener, null, null); // Give chance to the notification machinery to setup Thread.sleep(1000); // Now register a remote MBean, for example an MLet, so that the MBeanServerDelegate // will emit notifications for its registration ObjectName name = ObjectName.getInstance("examples:mbean=mlet"); // First notification connection.createMBean(MLet.class.getName(), name, null); // Second notification connection.unregisterMBean(name); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/notification/Server.java100644 0 0 4515 10513545721 22734 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.notification; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.tools.naming.NamingService; /** * This example shows how to setup a JSR 160 connector server. * The client counterpart of this example will register a remote NotificationListener * and receive notifications over the wire. * Nothing special is needed in the server side, if not registering an MBean * that implements {@link javax.management.NotificationEmitter}. * Every JMX implementation already has such an MBean registered, the MBeanServerDelegate. * The client will register a NotificationListener to the MBeanServerDelegate MBean, * that emits notifications when other MBeans are registered or unregistered. * * @version $Revision: 1.4 $ * @see Client */ public class Server { public static void main(String[] args) throws Exception { // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // No need of environment variables or the MBeanServer at this point JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, null); ObjectName cntorServerName = ObjectName.getInstance(":service=" + JMXConnectorServer.class.getName() + ",protocol=" + url.getProtocol()); MBeanServer server = MBeanServerFactory.createMBeanServer("remote.notification.example"); // Register the connector server as MBean server.registerMBean(cntorServer, cntorServerName); // The rmiregistry needed to bind the RMI stub NamingService naming = new NamingService(); ObjectName namingName = ObjectName.getInstance(":service=" + NamingService.class.getName()); server.registerMBean(naming, namingName); naming.start(); // Start the connector server cntorServer.start(); System.out.println("Server up and running"); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/iiop/Client.java100644 0 0 5117 10513545721 21744 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.rmi.iiop; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to connect to a JSR 160 connector server over IIOP. * It is very similar to the simple example also present in these examples, except * that it uses the IIOP protocol instead of native RMI's one, called JRMP. * * @version $Revision: 1.4 $ */ public class Client { public static void main(String[] args) throws Exception { // The JMXConnectorServer protocol, in this case is IIOP String serverProtocol = "iiop"; // The RMI server's host: this is actually ignored by JSR 160 // since this information is stored in the RMI stub. String serverHost = "host"; // The host and port where the COSNaming service runs and the path under which the stub is registered. String namingHost = "localhost"; int namingPort = 1199; String jndiPath = "/jmxconnector"; // The address of the connector server JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/iiop://" + namingHost + ":" + namingPort + jndiPath); // Connect a JSR 160 JMXConnector to the server side JMXConnector connector = JMXConnectorFactory.connect(url); // Retrieve an MBeanServerConnection that represent the MBeanServer the remote // connector server is bound to MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side as if it is a local MBeanServer ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; // The magic of JDK 1.3 dynamic proxy and JSR 160: // delegate.getImplementationVendor() is actually a remote JMX call, // but it looks like a local, old-style, java call. System.out.println(delegate.getImplementationVendor() + " is cool !"); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/iiop/Server.java100644 0 0 4647 10513545721 22003 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.rmi.iiop; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; /** * This example shows the how to setup a JSR 160 connector server over IIOP, the CORBA * protocol. * It is very similar to the simple example also present in these examples, except * that it uses the IIOP protocol instead of native RMI's one, called JRMP. * * @version $Revision: 1.3 $ */ public class Server { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Register and start the tnameserv MBean, needed by JSR 160 RMIConnectorServer over IIOP // You can also start the new JDK 1.4 'orbd' daemon, but you should do so externally // as there are no MBeans that wrap it. ObjectName namingName = ObjectName.getInstance("naming:type=tnameserv"); server.createMBean("mx4j.tools.naming.CosNamingService", namingName, null); // Standard port for the COS naming service is 900, but that's a restricted port on Unix/Linux systems int namingPort = 1199; server.setAttribute(namingName, new Attribute("Port", new Integer(namingPort))); server.invoke(namingName, "start", null, null); String jndiPath = "/jmxconnector"; // Note how the JMXServiceURL specifies 'iiop' as protocol for both the // JMXConnectorServer (the first), to indicate the protocol of the JMXConnectorServer, // and for the naming server (the second), to indicate that this is not the rmiregistry // but the COS naming service. JMXServiceURL url = new JMXServiceURL("service:jmx:iiop://localhost/jndi/iiop://localhost:" + namingPort + jndiPath); // Create and start the RMIConnectorServer over IIOP JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); connectorServer.start(); System.out.println("Server up and running"); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ssl/Client.java100644 0 0 6327 10513545721 21611 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.rmi.ssl; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to connect to a JSR 160 RMIConnectorServer over SSL.
* An RMI client that has been setup to use SSL must know the X509 certificate * corrispondent to the private key used by the server to encrypt the communication. * This X509 certificate is usually distributed by the server to the clients, that should * import it into a 'trust store'. * This trust store can be the JDK's one ($JRE_HOME/lib/security/cacerts) or a custom one. * In both cases the import operation can be achieved by using JDK's keytool utility. * Here is the command to create a custom trust store containing the X509 certificate * from a certificate file 'myserver.cer' distributed by the server: *
 * keytool -import -v -file myserver.cer -storepass storepwd -keystore trust.store -noprompt
 * 
* When using a custom trust store, the system property javax.net.ssl.trustStore * must point to the file path of the trust store.
* If instead the X509 certificate has been imported into the JDK's default trust store, * then it is not necessary to specify the javax.net.ssl.trustStore system * property.

* This example is meant to show the usage of the JSR 160 API: it is not an example of how to * setup a secure environment.
* Please refer to the JDK documentation about usage of keytool, to the JCE and JSSE documentation * and to a good book on Java security before porting these examples to a real environment that * must be secured. * You know what I mean :-) * * @version $Revision: 1.4 $ */ public class Client { public static void main(String[] args) throws Exception { // The RMI server's host: this is actually ignored by JSR 160 // since this information is stored in the RMI stub. String serverHost = "localhost"; // The host where the rmiregistry runs. String namingHost = "localhost"; String jndiPath = "/ssljmxconnector"; JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + serverHost + "/jndi/rmi://" + namingHost + jndiPath); JMXConnector connector = JMXConnectorFactory.connect(url); MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; System.out.println(delegate.getImplementationVendor() + " is cool !"); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ssl/Server.java100644 0 0 11754 10513545721 21661 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.rmi.ssl; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import mx4j.tools.remote.rmi.SSLRMIClientSocketFactory; import mx4j.tools.remote.rmi.SSLRMIServerSocketFactory; /** * This example shows how to setup a JSR 160 RMIConnectorServer over SSL.
* An RMI server that has been setup to use SSL uses a private key to encrypt the * communication with the client. The client must know the server's public key in order * to be able to decrypt the communication; public keys are stored in X509 certificates. * This X509 certificate is generated by the server and should be made available to * clients (for example by distributing it).
* The private and public key are normally stored in a server-side key store that can * be created by using the JDK's keytool utility; here is a sample command that can * be invoked to generate a keystore: *
 * keytool -genkey -v -keystore key.store -storepass storepwd -dname "CN=Anonymous Geek, OU=MX4J Development Team, O=The MX4J Project, L=New York City, S=NY, C=US"
 * 
* It creates a 'key.store' file that must be present in the classpath when running this example.
* The next step is to export the X509 certificate for the clients, with the following command: *
 * keytool -export -v -storepass storepwd -keystore key.store -file myserver.cer
 * 
* It is also possible to generate a trust store containing the X509 certificate that * can be used directly by the client with the following command: *
 * keytool -export -v -storepass storepwd -keystore key.store | keytool -import -v -storepass storepwd -keystore trust.store -noprompt
 * 
* Once you have exported the X509 certificate, follow the instructions on how to setup * the client {@link Client here}. * * @version $Revision: 1.4 $ */ public class Server { public static void main(String[] args) throws Exception { MBeanServer server = MBeanServerFactory.createMBeanServer(); // Register and start the rmiregistry MBean ObjectName namingName = ObjectName.getInstance("naming:type=rmiregistry"); server.createMBean("mx4j.tools.naming.NamingService", namingName, null); server.invoke(namingName, "start", null, null); int namingPort = ((Integer)server.getAttribute(namingName, "Port")).intValue(); String jndiPath = "/ssljmxconnector"; JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:" + namingPort + jndiPath); // Create the rmi socket factories for SSL Map environment = new HashMap(); SSLContext context = createSSLContext(); environment.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SSLRMIClientSocketFactory()); environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, new SSLRMIServerSocketFactory(context)); // Create and start the RMIConnectorServer JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, null); ObjectName connectorServerName = ObjectName.getInstance("connectors:protocol=" + url.getProtocol()); server.registerMBean(connectorServer, connectorServerName); connectorServer.start(); System.out.println("Server up and running"); } /** * Creates and returns an SSLContext by reading information from a keystore.
* Change the hardcoded options to match your configuration and your environment. */ private static SSLContext createSSLContext() throws Exception { String keystoreName = "key.store"; String keystorePassword = "storepwd"; KeyStore keystore = KeyStore.getInstance("JKS"); InputStream keystoreStream = Server.class.getClassLoader().getResourceAsStream(keystoreName); // Must check for nullity, otherwise a new empty keystore is created by KeyStore.load if (keystoreStream == null) throw new IOException("Cannot find KeyStore " + keystoreName + " in classpath"); keystore.load(keystoreStream, keystorePassword.toCharArray()); KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("SunX509"); keyFactory.init(keystore, keystorePassword.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyFactory.getKeyManagers(), null, null); return context; } } mx4j-3.0.2/src/examples/mx4j/examples/remote/security/Client.java100644 0 0 6165 10513545721 22070 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.security; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXPrincipal; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; /** * This example shows how to setup a JSR 160 connector client that connects to * a secured JSR 160 connector server, and that uses the subject delegation features * defined by JSR 160. * Refer to the MX4J documentation on how to run this example and on how it * works: this example is described in details. * * @version $Revision: 1.4 $ * @see Server */ public class Client { public static void main(String[] args) throws Exception { // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // The credentials are passed via the environment Map Map environment = new HashMap(); String[] credentials = new String[]{"guest", "guest"}; environment.put(JMXConnector.CREDENTIALS, credentials); // Connect to the server JMXConnector cntor = JMXConnectorFactory.connect(url, environment); // Create a subject to delegate to JMXPrincipal principal = new JMXPrincipal("anotherGuest"); Set principals = new HashSet(); principals.add(principal); Subject delegate = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); // Get two MBeanServerConnection: one that uses the 'guest' principal directly, // the second that uses the 'guest' user but delegates to another principal. MBeanServerConnection connection = cntor.getMBeanServerConnection(); MBeanServerConnection delegateConnection = cntor.getMBeanServerConnection(delegate); // The example policy file provided allows both MBeanServerConnections to call // MBeanServerConnection.queryNames Set mbeans = connection.queryNames(null, null); System.out.println("MBeans retrieved by a connection without delegate subject:"); System.out.println(mbeans); System.out.println(); mbeans = delegateConnection.queryNames(null, null); System.out.println("MBeans retrieved by a connection with a delegate subject:"); System.out.println(mbeans); System.out.println(); // The example policy file forbids to call MBeanServerConnection.getObjectInstance try { connection.getObjectInstance(ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate")); throw new Error(); } catch (SecurityException x) { System.out.println("No permission to call getObjectInstance for the MBeanServerDelegate"); } } } mx4j-3.0.2/src/examples/mx4j/examples/remote/security/Server.java100644 0 0 6707 10513545721 22122 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.security; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.tools.naming.NamingService; import mx4j.tools.remote.PasswordAuthenticator; /** * This example shows how to setup a JSR 160 connector server that runs under * security manager and that forbids access to non-authorized users. * Refer to the MX4J documentation on how to run this example and on how to tune * the policy files: this example is described in details. * * @version $Revision: 1.5 $ * @see Client */ public class Server { private static final String PASSWORD_FILE = "users.properties"; public static void main(String[] args) throws Exception { prepareUsersFile(); // The address of the connector server JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx"); // Specify the authenticator in the environment Map, using the // standard property JMXConnector.AUTHENTICATOR Map environment = new HashMap(); JMXAuthenticator authenticator = new PasswordAuthenticator(new File(PASSWORD_FILE)); environment.put(JMXConnectorServer.AUTHENTICATOR, authenticator); // Create and register the connector server JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, null); ObjectName cntorServerName = ObjectName.getInstance(":service=" + JMXConnectorServer.class.getName() + ",protocol=" + url.getProtocol()); MBeanServer server = MBeanServerFactory.createMBeanServer("remote.security.example"); server.registerMBean(cntorServer, cntorServerName); // Setup the rmiregistry to bind in JNDI the RMIConnectorServer stub. NamingService naming = new NamingService(); ObjectName namingName = ObjectName.getInstance(":service=" + NamingService.class.getName()); server.registerMBean(naming, namingName); naming.start(); // Start the connector server cntorServer.start(); System.out.println("Server up and running"); } /** * Writes a user/password file in the filesystem, with two hardcoded users: * 'admin' and 'guest'. * Normally this file is provided externally, not created by a program. * Purpose of this method is to show how to obfuscate passwords using * {@link PasswordAuthenticator}. */ private static void prepareUsersFile() throws IOException { Properties properties = new Properties(); String user = "admin"; String password = PasswordAuthenticator.obfuscatePassword("admin"); properties.setProperty(user, password); user = "guest"; password = PasswordAuthenticator.obfuscatePassword("guest"); properties.setProperty(user, password); FileOutputStream fos = new FileOutputStream(new File(PASSWORD_FILE)); properties.store(fos, null); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/security/server.policy100644 0 0 3371 10513545721 22532 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ /* * This is an example policy file for a JMXConnectorServer that uses RMI/JRMP, * working with JDK 1.4+. * Refer to the bundled example class mx4j.examples.remote.security.Server and to the * MX4J documentation for more details. */ grant codebase "file:${user.dir}/dist/lib/mx4j-remote.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/dist/lib/mx4j.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/dist/lib/mx4j-impl.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/dist/lib/mx4j-jmx.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/dist/lib/mx4j-tools.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/dist/examples/mx4j-examples.jar" { permission java.security.AllPermission; }; grant codebase "file:${user.dir}/lib/bcel.jar" { permission java.security.AllPermission; }; grant { permission javax.security.auth.AuthPermission "doAsPrivileged"; permission java.net.SocketPermission "localhost:1024-", "listen,resolve"; permission java.net.SocketPermission "*", "accept,resolve"; }; grant principal javax.management.remote.JMXPrincipal "admin" { permission java.security.AllPermission; }; grant principal javax.management.remote.JMXPrincipal "guest" { permission javax.management.MBeanPermission "*", "queryNames"; permission javax.management.remote.SubjectDelegationPermission "javax.management.remote.JMXPrincipal.*"; }; mx4j-3.0.2/src/examples/mx4j/examples/remote/simple/Client.java100644 0 0 5524 10513545721 21510 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.simple; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** * This example shows the simplest way to connect to a JSR 160 connector server.
* To do so, the most important information is the JMXServiceURL, which is the address * of the remote connector server. This url is generated by the server, and * must be known to the client. * When using JSR 160's RMI connector server, this information is often in form of a * JNDI name where the RMI stub has been registered; in this case the client needs * to know the host and port of the JNDI server and the JNDI path where the stub is * registered. * * @version $Revision: 1.3 $ */ public class Client { public static void main(String[] args) throws Exception { // The JMXConnectorServer protocol, in this case is RMI. String serverProtocol = "rmi"; // The RMI server's host: this is actually ignored by JSR 160 // since this information is stored in the RMI stub. String serverHost = "host"; // The host, port and path where the rmiregistry runs. String namingHost = "localhost"; int namingPort = 1099; String jndiPath = "/jmxconnector"; // The address of the connector server JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/rmi://" + namingHost + ":" + namingPort + jndiPath); // Connect a JSR 160 JMXConnector to the server side JMXConnector connector = JMXConnectorFactory.connect(url); // Retrieve an MBeanServerConnection that represent the MBeanServer the remote // connector server is bound to MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side as if it is a local MBeanServer ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; // The magic of JDK 1.3 dynamic proxy and JSR 160: // delegate.getImplementationVendor() is actually a remote JMX call, // but it looks like a local, old-style, java call. System.out.println(delegate.getImplementationVendor() + " is cool !"); } } mx4j-3.0.2/src/examples/mx4j/examples/remote/simple/Server.java100644 0 0 3530 10513545721 21533 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.remote.simple; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; /** * This example shows the simplest way to setup a JSR 160 connector server. * It uses the standard JSR 160 RMIConnectorServer, and if you're familiar with * RMI, you'll know that a JNDI server like the rmiregistry is needed * in order to register the server stub that will be looked up by the client. * * @version $Revision: 1.3 $ */ public class Server { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Register and start the rmiregistry MBean, needed by JSR 160 RMIConnectorServer ObjectName namingName = ObjectName.getInstance("naming:type=rmiregistry"); server.createMBean("mx4j.tools.naming.NamingService", namingName, null); server.invoke(namingName, "start", null, null); int namingPort = ((Integer)server.getAttribute(namingName, "Port")).intValue(); String jndiPath = "/jmxconnector"; JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:" + namingPort + jndiPath); // Create and start the RMIConnectorServer JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); connectorServer.start(); System.out.println("Server up and running"); } } mx4j-3.0.2/src/examples/mx4j/examples/services/loading/Main.java100644 0 0 11540 10513545721 21645 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.services.loading; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.ServiceNotFoundException; import javax.management.loading.MLet; /** * The starter class for loading MBeans via an MLET file.
* Modify at your wish. * * @version $Revision: 1.3 $ */ public class Main { public static void main(String[] args) throws Exception { // Create the MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Register the MLet in the MBeanServer MLet mlet = new MLet(); ObjectName mletName = new ObjectName("system:mbean=loader"); server.registerMBean(mlet, mletName); // Set the MLet as context classloader // Can be useful for the loaded services that want to access this classloader. Thread.currentThread().setContextClassLoader(mlet); // Resolve the file to load MBeans from // If we got a program argument, we load it from there, otherwise // we assume we have a 'mbeans.mlet' file in this example's directory URL mbeansURL = null; if (args.length == 1) { String file = args[0]; mbeansURL = new File(file).toURL(); } else { mbeansURL = mlet.getResource("examples/services/loading/mbeans.mlet"); } // If the URL is still null, abort if (mbeansURL == null) throw new ServiceNotFoundException("Could not find MBeans to load"); // Load the MBeans Set mbeans = mlet.getMBeansFromURL(mbeansURL); System.out.println("MLet has now the following classpath: " + Arrays.asList(mlet.getURLs())); // Now let's check everything is ok. checkMBeansLoadedSuccessfully(mbeans); // Now the system is loaded, but maybe we should initialize and start them initializeMBeans(server, mbeans); startMBeans(server, mbeans); // Now the system is up and running System.out.println("System up and running !"); // The program exits because none of the loaded MBeans in this example started a non-daemon thread. } private static void checkMBeansLoadedSuccessfully(Set mbeans) throws ServiceNotFoundException { // MLet.getMBeansFromURL returns a Set containing exceptions if an MBean could not be loaded boolean allLoaded = true; for (Iterator i = mbeans.iterator(); i.hasNext();) { Object mbean = i.next(); if (mbean instanceof Throwable) { ((Throwable)mbean).printStackTrace(); allLoaded = false; // And go on with the next } else { // Ok, the MBean was registered successfully System.out.println("Registered MBean: " + mbean); } } if (!allLoaded) throw new ServiceNotFoundException("Some MBean could not be loaded"); } private static void initializeMBeans(MBeanServer server, Set mbeans) { for (Iterator i = mbeans.iterator(); i.hasNext();) { try { ObjectInstance instance = (ObjectInstance)i.next(); if (server.isInstanceOf(instance.getObjectName(), "org.apache.avalon.framework.activity.Initializable")) { try { server.invoke(instance.getObjectName(), "initialize", null, null); } catch (ReflectionException ignored) { // The initialize method is not part of the management interface, ignore } } } catch (Exception x) { x.printStackTrace(); } } } private static void startMBeans(MBeanServer server, Set mbeans) { for (Iterator i = mbeans.iterator(); i.hasNext();) { try { ObjectInstance instance = (ObjectInstance)i.next(); if (server.isInstanceOf(instance.getObjectName(), "org.apache.avalon.framework.activity.Startable")) { try { server.invoke(instance.getObjectName(), "start", null, null); } catch (ReflectionException ignored) { // The start method is not part of the management interface, ignore } } } catch (Exception x) { x.printStackTrace(); } } } } mx4j-3.0.2/src/examples/mx4j/examples/services/loading/mbeans.mlet100644 0 0 464 10513545721 22211 0ustar 0 0 CODEBASE="lib" ARCHIVE="mx4j-tools.jar"> mx4j-3.0.2/src/examples/mx4j/examples/services/relation/RelationServiceExample.java100644 0 0 33624 10513545721 25602 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.services.relation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.Query; import javax.management.relation.RelationServiceMBean; import javax.management.relation.Role; import javax.management.relation.RoleList; import javax.management.relation.RoleResult; import mx4j.log.Log; import mx4j.log.Logger; /** * @version $Revision: 1.4 $ */ /** * This class will demonstrate the use-case scenarios described in the docs, under chapter "examples" and sub-section RelationService * Some methods will also use the MBeanServerInvocationHandler. */ public class RelationServiceExample { private MBeanServer m_server = null; private RelationServiceMBean m_proxy = null; private String m_relationServiceClass = "javax.management.relation.RelationService"; private String m_libraryClassName = "mx4j.examples.services.relation.SimplePersonalLibrary"; private ObjectName m_libraryObjectName = null; private ObjectName m_relationObjectName = null; private SimplePersonalLibrary m_library = null; public RelationServiceExample() { m_server = MBeanServerFactory.createMBeanServer("RelationExample"); } public void setUpRelations() { // build the object name and register the relationService try { System.out.println("Creating RelationService in the MBeanServer"); Object[] params = {new Boolean(true)}; String[] signature = {"boolean"}; m_relationObjectName = new ObjectName("relations:class=" + m_relationServiceClass); m_server.createMBean(m_relationServiceClass, m_relationObjectName, null, params, signature); // we will create the proxy now so we can make some simple calls through the proxy m_proxy = (RelationServiceMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, m_relationObjectName, RelationServiceMBean.class, false); System.out.println("----------------------- done ----------------------------"); System.out.println("create the relationType"); String libraryTypeName = "personal_library"; m_library = new SimplePersonalLibrary(libraryTypeName); // add it to the relationService addRelationType(); printRelationTypeInfo(); System.out.println("----------------------- done ----------------------------"); System.out.println("create RelationId for the relationType"); String personalLibraryId = libraryTypeName + "_internal"; //....Done.... System.out.println("----------------------- done ----------------------------"); // we now need to build the Roles and MBeans that will represent those relations String ownerClassName = "mx4j.examples.services.relation.SimpleOwner"; // create 2 instance of this String bookClassName = "mx4j.examples.services.relation.SimpleBooks"; // create 5 instances of this System.out.println("Creating MBeans to represent our relations"); ObjectName ownerName1 = new ObjectName("library:name=" + ownerClassName + "1"); ObjectName ownerName2 = new ObjectName("library:name=" + ownerClassName + "2"); ObjectName bookName1 = new ObjectName("library:name=" + bookClassName + "1"); ObjectName bookName2 = new ObjectName("library:name=" + bookClassName + "2"); ObjectName bookName3 = new ObjectName("library:name=" + bookClassName + "3"); ObjectName bookName4 = new ObjectName("library:name=" + bookClassName + "4"); ObjectName bookName5 = new ObjectName("library:name=" + bookClassName + "5"); m_server.createMBean(bookClassName, bookName1, null, new Object[]{"Lord of the rings"}, new String[]{"java.lang.String"}); m_server.createMBean(bookClassName, bookName2, null, new Object[]{"The Hobbit"}, new String[]{"java.lang.String"}); m_server.createMBean(bookClassName, bookName3, null, new Object[]{"Harry Potter"}, new String[]{"java.lang.String"}); m_server.createMBean(bookClassName, bookName4, null, new Object[]{"UML Distilled"}, new String[]{"java.lang.String"}); m_server.createMBean(bookClassName, bookName5, null, new Object[]{"Applying UML"}, new String[]{"java.lang.String"}); m_server.createMBean(ownerClassName, ownerName1, null, new Object[]{"Fred"}, new String[]{"java.lang.String"}); m_server.createMBean(ownerClassName, ownerName2, null, new Object[]{"Humpty Dumpty"}, new String[]{"java.lang.String"}); System.out.println("----------------------- done ----------------------------"); System.out.println("Build the roles"); // build our Lists of values for our first use case an owner registers and takes out one book ArrayList ownerList = new ArrayList(); ownerList.add(ownerName1); // can only add owner to an owner role can only be 1 Role ownerRole = new Role("owner", ownerList); System.out.println("created owner Role"); ArrayList bookList = new ArrayList(); // we can have between 1 and 4 books more than 4 invalidates out relation and less than 1 invalidates it bookList.add(bookName1); bookList.add(bookName2); bookList.add(bookName3); Role bookRole = new Role("books", bookList); System.out.println("Created book role"); System.out.println("----------------------- done ----------------------------"); System.out.println("Creating the relation"); // add our roles to the RoleList RoleList libraryList = new RoleList(); libraryList.add(ownerRole); libraryList.add(bookRole); // now to create the relation createLibraryRelation(personalLibraryId, libraryTypeName, libraryList); System.out.println("Getting all the related info"); printAllRelationInfo(); System.out.println("----------------------- done ----------------------------"); // borrow one book still within our stated quota System.out.println("borrow a book we have 3 one more does not invalidate our relation"); borrowBooks(personalLibraryId, "books", bookName4); ArrayList newBookList4 = getRoleValue(personalLibraryId, "books"); System.out.println("we now have 4 books: " + newBookList4.toString()); System.out.println("----------------------- done ----------------------------"); // remove 2 books from the MBeanServer an see if our owner has only 2 left System.out.println("2 MBeans removed from the MBeanServer - no problem we still have a valid relation."); m_server.unregisterMBean(bookName1); m_server.unregisterMBean(bookName2); ArrayList newBookList = getRoleValue(personalLibraryId, "books"); System.out.println("After removing the 2 MBeans we have only 2 Book MBeans left " + newBookList.toString()); System.out.println("----------------------- done ----------------------------"); // we will now demonstrate the unhappy scenarios. //invalidate the relation and borrow too many books throws InvalidRoleValueException // note we cannot add bookName1 or bookName2 as they have been unregistered from the MBeanServer // register System.out.println("Deregistering the last of our books from the MBeanServer"); m_server.unregisterMBean(bookName3); m_server.unregisterMBean(bookName4); System.out.println("----------------------- done ----------------------------"); System.out.println("Testing access by running queries: "); System.out.println("The relation should have been removed and an exception of RelationNotFoundException returned"); testAllAccessQueries(personalLibraryId); System.out.println("----------------------- done ----------------------------"); } catch (Exception ex) { System.out.println("Could Not create the RelationService: " + ex); ex.printStackTrace(); } } public void borrowBooks(String relationId, String roleName, ObjectName bookToAdd) { Logger logger = getLogger(); try { // get the old values ArrayList oldRoleValue = getRoleValue(relationId, roleName); ArrayList newRoleValue = (ArrayList)oldRoleValue.clone(); newRoleValue.add(bookToAdd); // now we update the values Role role = new Role(roleName, newRoleValue); Object[] params1 = {relationId, role}; String[] signature1 = {"java.lang.String", "javax.management.relation.Role"}; m_server.invoke(m_relationObjectName, "setRole", params1, signature1); } catch (Exception ex) { logger.error("Unable to add a book"); ex.printStackTrace(); } } private void printList(List list) { for (Iterator i = list.iterator(); i.hasNext();) { System.out.println(">>>> Names representing roles: " + i.next()); } } private ArrayList getRoleValue(String relationId, String roleName) { Logger logger = getLogger(); try { Object[] params = {relationId, roleName}; String[] signature = {"java.lang.String", "java.lang.String"}; return ((ArrayList)(m_server.invoke(m_relationObjectName, "getRole", params, signature))); } catch (Exception ex) { logger.error("Unable to get the list of roles for ID: " + relationId); return null; } } public void endExample() { try { System.out.println("Cleaning up......"); // this query will return the set of mbeans which have a class attribute of "management*" which is our MBeans Set mbeanSet = m_server.queryMBeans(null, Query.initialSubString(Query.classattr(), Query.value("management*"))); for (Iterator i = mbeanSet.iterator(); i.hasNext();) { m_server.unregisterMBean(((ObjectInstance)i.next()).getObjectName()); } // release the relationService m_server.unregisterMBean(m_relationObjectName); // release the MBeanServer MBeanServerFactory.releaseMBeanServer(m_server); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private void addRelationType() { try { Object[] params = {m_library}; String[] signature = {"javax.management.relation.RelationType"}; m_server.invoke(m_relationObjectName, "addRelationType", params, signature); } catch (Exception ex) { ex.printStackTrace(); } } private void printRelationTypeInfo() { try { ArrayList relTypeNameList = (ArrayList)(m_server.getAttribute(m_relationObjectName, "AllRelationTypeNames")); System.out.println("The RelationType Names found in the RelationService: " + relTypeNameList.toString()); } catch (Exception ex) { ex.printStackTrace(); } } private void createLibraryRelation(String personalLibraryId, String libraryTypeName, RoleList libraryList) { Logger logger = getLogger(); try { Object[] params = {personalLibraryId, libraryTypeName, libraryList}; String[] signature = {"java.lang.String", "java.lang.String", "javax.management.relation.RoleList"}; m_server.invoke(m_relationObjectName, "createRelation", params, signature); } catch (Exception ex) { logger.error("Exception creating Library Relation: " + ex.getMessage()); ex.printStackTrace(); } } private void printAllRelationInfo() { Logger logger = getLogger(); try { ArrayList allRelationIds = (ArrayList)m_server.getAttribute(m_relationObjectName, "AllRelationIds"); for (Iterator i = allRelationIds.iterator(); i.hasNext();) { String currentRelationId = (String)i.next(); System.out.println("All RelationIds: " + currentRelationId); testAllAccessQueries(currentRelationId); } } catch (Exception ex) { logger.error("Unable to print the relations"); ex.printStackTrace(); } } private void testAllAccessQueries(String relationId) { Logger logger = getLogger(); // retrieve all roles try { Object[] params = {relationId}; String[] signature = {"java.lang.String"}; RoleResult roleResult = (RoleResult)(m_server.invoke(m_relationObjectName, "getAllRoles", params, signature)); RoleList roleList = roleResult.getRoles(); for (Iterator i = roleList.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); System.out.println(">>>> role name: " + currentRole.getRoleName()); System.out.println(">>>> role values: " + currentRole.getRoleValue().toString()); } System.out.println("No unresolved Roles roleUnresolved size: " + roleResult.getRolesUnresolved().size()); } catch (Exception ex) { logger.error("Exception printing the results from relationId: " + relationId); System.out.println("Printing the Exception message to validate exception: " + ex.getMessage()); } } private Logger getLogger() { return Log.getLogger(getClass().getName()); } public static void main(String[] args) { RelationServiceExample example = new RelationServiceExample(); example.setUpRelations(); example.endExample(); } }mx4j-3.0.2/src/examples/mx4j/examples/services/relation/SimpleBooks.java100644 0 0 1323 10513545721 23366 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.services.relation; /** * @version $Revision: 1.3 $ */ interface SimpleBooksMBean { public void setBook(String bookName); public String getBook(); } public class SimpleBooks implements SimpleBooksMBean { private String m_name = null; public SimpleBooks(String bookName) { m_name = bookName; } public void setBook(String bookName) { m_name = bookName; } public String getBook() { return m_name; } }mx4j-3.0.2/src/examples/mx4j/examples/services/relation/SimpleOwner.java100644 0 0 1330 10513545721 23401 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.services.relation; /** * @version $Revision: 1.3 $ */ interface SimpleOwnerMBean { public void setOwnerName(String ownerName); public String getOwnerName(); } public class SimpleOwner implements SimpleOwnerMBean { private String m_name = null; public SimpleOwner(String name) { m_name = name; } public void setOwnerName(String name) { m_name = name; } public String getOwnerName() { return m_name; } }mx4j-3.0.2/src/examples/mx4j/examples/services/relation/SimplePersonalLibrary.java100644 0 0 3440 10513545721 25423 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.services.relation; import javax.management.relation.RelationTypeSupport; import javax.management.relation.RoleInfo; /** * @version $Revision: 1.3 $ */ public class SimplePersonalLibrary extends RelationTypeSupport { public SimplePersonalLibrary(String relationTypeName) { super(relationTypeName); try { RoleInfo ownerRoleInfo = new RoleInfo("owner", // the name of the MBean class of which all members must be an instance. "mx4j.examples.services.relation.SimpleOwner", true, //read true, //write 1, // only one owner 1, "Owner"); addRoleInfo(ownerRoleInfo); RoleInfo booksRoleInfo = new RoleInfo("books", "mx4j.examples.services.relation.SimpleBooks", true, true, 1, // feeling nasty can only own max 4 books and no fewer than 1 4, "Books"); addRoleInfo(booksRoleInfo); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } }mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/HttpAdaptor.java100644 0 0 21643 10513545721 23531 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.adaptor.http; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import mx4j.tools.stats.TimedStatisticsRecorder; /** * Example as how to use the HttpAdaptor and the XSLTProcessor * * @version $Revision: 1.4 $ */ public class HttpAdaptor { private int port = 8080; private String host = "localhost"; private String path = null, pathInJar = null; public static interface TestClassMBean { public URL getURL(); public void setURL(URL url); public String getStr(); public String[] getStrArray(); public Double getDouble(); public boolean isTrue(); public void setStr(String str); public void setStrArray(String[] str); public Boolean aMethod(String string); public void anotherMethod(String string, int test); public Map getaMap(); public List getaList(); public Date getDate(); public void setDate(Date date); public BigInteger getBigInteger(); public void setBigInteger(BigInteger integer); public BigDecimal getBigDecimal(); public void setBigDecimal(BigDecimal decimal); public CompositeData getCompositeData(); public void setCompositeData(CompositeData composite); } public static class TestClass extends NotificationBroadcasterSupport implements TestClassMBean { private String[] strArray = new String[]{"first", "second"}; private String str; private URL url; private List list = new ArrayList(); private Map map = new HashMap(); private Date date = new Date(); private BigInteger bigInteger = new BigInteger("123456789101112131415"); private BigDecimal bigDecimal = new BigDecimal("123456789101112131415.987654321"); private CompositeData compositeData = null; public TestClass(String str, URL url) { this.str = str; this.url = url; list.add("a"); list.add("b"); list.add("c"); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); try { CompositeType type = new CompositeType("My type", "My type", new String[]{"item1", "item2"}, new String[]{"item1", "item2"}, new OpenType[]{SimpleType.STRING, SimpleType.STRING}); compositeData = new CompositeDataSupport(type, new String[]{"item1", "item2"}, new Object[]{"item value 1", "item value 2"}); } catch (OpenDataException e) { e.printStackTrace(); } } public void setCompositeData(CompositeData compositeData) { this.compositeData = compositeData; } public CompositeData getCompositeData() { return compositeData; } public void setBigInteger(BigInteger bigInteger) { this.bigInteger = bigInteger; } public BigInteger getBigInteger() { return bigInteger; } public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } public BigDecimal getBigDecimal() { return bigDecimal; } public void setDate(Date date) { this.date = date; } public Date getDate() { return date; } public void setURL(URL url) { this.url = url; } public URL getURL() { return url; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public String[] getStrArray() { return strArray; } public void setStrArray(String[] strArray) { this.strArray = strArray; } public Double getDouble() { return new Double(100 * Math.random()); } public boolean isTrue() { return true; } public Boolean aMethod(String string) { return new Boolean(string.equals("true")); } public void anotherMethod(String string, int test) { this.str = string; } public MBeanNotificationInfo[] getNotificationInfo() { MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[1]; notifications[0] = new MBeanNotificationInfo(new String[]{"test1" , "test2"}, "name", "test"); return notifications; } public Map getaMap() { return map; } public List getaList() { return list; } } /** * Creates a new HttpAdaptor example. You can optionally pass the host/port as * java -cp CLASSPATH adaptor.http.HttpAdaptor localhost 8080 path */ public HttpAdaptor(String args[]) { if (args.length > 0) { host = args[0]; } if (args.length > 1) { port = Integer.parseInt(args[1]); } if (args.length > 2) { path = args[2]; } if (args.length > 3) { pathInJar = args[3]; } } /** * Starts the http server */ public void start() throws JMException, MalformedURLException { // creates new server MBeanServer server = MBeanServerFactory.createMBeanServer("test"); ObjectName serverName = new ObjectName("Http:name=HttpAdaptor"); server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null); // set attributes if (port > 0) { server.setAttribute(serverName, new Attribute("Port", new Integer(port))); } else { System.out.println("Incorrect port value " + port); } if (host != null) { server.setAttribute(serverName, new Attribute("Host", host)); } else { System.out.println("Incorrect null hostname"); } // set the XSLTProcessor. If you want to use pure XML comment this out ObjectName processorName = new ObjectName("Http:name=XSLTProcessor"); server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null); if (path != null) { server.setAttribute(processorName, new Attribute("File", path)); } server.setAttribute(processorName, new Attribute("UseCache", new Boolean(false))); if (pathInJar != null) { server.setAttribute(processorName, new Attribute("PathInJar", pathInJar)); } server.setAttribute(serverName, new Attribute("ProcessorName", processorName)); // add a couple of MBeans TestClass test1 = new TestClass("t1", new URL("http://mx4j.sourceforge.net")); TestClass test2 = new TestClass("t1", new URL("http://www.sourceforge.net/projects/mx4j")); server.registerMBean(test1, new ObjectName("Test:name=test1")); server.registerMBean(test2, new ObjectName("Test:name=test2")); // add a stats MBean TimedStatisticsRecorder recoder = new TimedStatisticsRecorder(); recoder.setObservedObject(new ObjectName("Test:name=test1")); recoder.setObservedAttribute("Double"); server.registerMBean(recoder, new ObjectName("Test:name=test1recorder")); server.invoke(new ObjectName("Test:name=test1recorder"), "start", null, null); // add a couple of MBeans // add user names server.invoke(serverName, "addAuthorization", new Object[]{"mx4j", "mx4j"}, new String[]{"java.lang.String", "java.lang.String"}); // use basic authentication //server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic")); // starts the server server.invoke(serverName, "start", null, null); } public static void main(String[] str) throws Exception { HttpAdaptor adaptor = new HttpAdaptor(str); adaptor.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/RelationServiceAdaptor.java100644 0 0 31116 10513545721 25704 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.adaptor.http; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.Query; import javax.management.relation.RelationServiceMBean; import javax.management.relation.Role; import javax.management.relation.RoleInfo; import javax.management.relation.RoleList; import javax.management.relation.RoleResult; import mx4j.tools.adaptor.http.DefaultProcessor; import mx4j.tools.adaptor.http.XSLTProcessor; /** * Example as how to use the HttpAdaptor and the XSLTProcessor and the RelationProcessor * To use this example please add as arguments to the command line in this order * * @version $Revision: 1.3 $ */ public class RelationServiceAdaptor { private MBeanServer m_server = null; private RelationServiceMBean m_proxy = null; private mx4j.tools.adaptor.http.HttpAdaptor m_adaptor = null; private DefaultProcessor m_processor = null; private XSLTProcessor m_xsltProcessor = null; private ObjectName httpAdaptorObjectName = null; private ObjectName processorName = null; private ObjectName m_relationServiceObjectName = null; public RelationServiceAdaptor() { m_server = MBeanServerFactory.createMBeanServer("MyAdaptorTests"); m_adaptor = new mx4j.tools.adaptor.http.HttpAdaptor(); m_processor = new DefaultProcessor(); m_xsltProcessor = new XSLTProcessor(); } public void startTests(String[] args) { int defaultPort = 1999; String defaultHost = "localhost"; String defaultPath = "."; if (args.length > 0) { defaultHost = args[0]; } if (args.length > 1) { defaultPort = Integer.parseInt(args[1]); } if (args.length > 2) { defaultPath = args[2]; } try { System.out.println("Building the objectNames and registering the HttpAdaptor, and XSLTProcessor"); // build object names httpAdaptorObjectName = new ObjectName("Server:name=HttpAdaptor"); processorName = new ObjectName("processor:name=XSLTProcessor"); // register adaptor in server m_server.registerMBean(m_adaptor, httpAdaptorObjectName); m_server.registerMBean(m_xsltProcessor, processorName); m_server.setAttribute(processorName, new Attribute("File", defaultPath)); m_adaptor.setPort(defaultPort); m_adaptor.setHost(defaultHost); m_adaptor.setProcessor(m_xsltProcessor); m_adaptor.setAuthenticationMethod("none"); System.out.println("------------------------------------------- done --------------------------------------------"); System.out.println("starting the adpator and then checking all is active"); m_adaptor.start(); if (m_adaptor.isActive()) { System.out.println("Adaptor is active"); System.out.println("The name of the processor: " + m_adaptor.getProcessor().getName()); } System.out.println("------------------------------------------- done --------------------------------------------"); System.out.println("Press enter to register relationService"); waitForEnterPressed(); } catch (Exception ex) { ex.printStackTrace(); } } public void buildMBeans() { try { System.out.println("Building and registering the relationService and 6 MBeans"); String m_relationServiceClassName = "javax.management.relation.RelationService"; m_relationServiceObjectName = new ObjectName("relations:type=" + m_relationServiceClassName + "_1"); Object[] params = {new Boolean(true)}; String[] signature = {"boolean"}; m_server.createMBean(m_relationServiceClassName, m_relationServiceObjectName, null, params, signature); // create a proxy m_proxy = (RelationServiceMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, m_relationServiceObjectName, RelationServiceMBean.class, false); System.out.println("Press ENTER to register 6 MBeans"); waitForEnterPressed(); String mbeanClassName = "mx4j.examples.tools.adaptor.http.SimpleStandard"; ObjectName mbeanObjectName1 = new ObjectName("domain:type=SimpleStandard_1"); ObjectName mbeanObjectName2 = new ObjectName("domain:type=SimpleStandard_2"); ObjectName mbeanObjectName3 = new ObjectName("domain:type=SimpleStandard_3"); ObjectName mbeanObjectName4 = new ObjectName("domain:type=SimpleStandard_4"); ObjectName mbeanObjectName5 = new ObjectName("domain:type=SimpleStandard_5"); ObjectName mbeanObjectName6 = new ObjectName("domain:type=SimpleStandard_6"); m_server.createMBean(mbeanClassName, mbeanObjectName1, null); m_server.createMBean(mbeanClassName, mbeanObjectName2, null); m_server.createMBean(mbeanClassName, mbeanObjectName3, null); m_server.createMBean(mbeanClassName, mbeanObjectName4, null); m_server.createMBean(mbeanClassName, mbeanObjectName5, null); m_server.createMBean(mbeanClassName, mbeanObjectName6, null); System.out.println("------------------------------------------- done --------------------------------------------"); System.out.println("Creating RoleInfos for RelationType"); RoleInfo[] roleInfos = new RoleInfo[2]; String roleName1 = "primary"; roleInfos[0] = new RoleInfo(roleName1, "mx4j.examples.tools.adaptor.http.SimpleStandard", true, true, 1, 1, null); String roleName2 = "secondary"; roleInfos[1] = new RoleInfo(roleName2, "mx4j.examples.tools.adaptor.http.SimpleStandard", true, true, 0, -1, null); // create a relation type with those role infos String relationTypeName = "Building_relation_view1"; m_proxy.createRelationType(relationTypeName, roleInfos); // creating more relationTypes to test String relationTypeName2 = "Testing_2"; m_proxy.createRelationType(relationTypeName2, roleInfos); System.out.println("Creating relationIds for relationTypeName: " + relationTypeName); System.out.println("First create the roles..."); ArrayList roleValue1 = new ArrayList(); roleValue1.add(mbeanObjectName1); Role role1 = new Role(roleName1, roleValue1); ArrayList roleValue2 = new ArrayList(); roleValue2.add(mbeanObjectName2); roleValue2.add(mbeanObjectName3); roleValue2.add(mbeanObjectName4); Role role2 = new Role(roleName2, roleValue2); RoleList roleList1 = new RoleList(); roleList1.add(role1); roleList1.add(role2); /// testing form here ArrayList role5Value = new ArrayList(); role5Value.add(mbeanObjectName2); Role role5 = new Role(roleName1, role5Value); ArrayList roleValue5 = new ArrayList(); roleValue5.add(mbeanObjectName4); Role role6 = new Role(roleName2, roleValue5); RoleList roleList5 = new RoleList(); roleList5.add(role5); roleList5.add(role6); System.out.println("------------------------------------------- done --------------------------------------------"); System.out.println("Now create relations with ids:::"); String relationId1 = "relationId_1"; m_proxy.createRelation(relationId1, relationTypeName, roleList1); String relationId2 = "relationId_2"; m_proxy.createRelation(relationId2, relationTypeName, roleList5); String relationId3 = "relationId_3"; m_proxy.createRelation(relationId3, relationTypeName, roleList1); System.out.println("------------------------------------------- done --------------------------------------------"); System.out.println("creating relationIds for relationtypeName: " + relationTypeName2); String relationId4 = "relationId_number2_1"; m_proxy.createRelation(relationId4, relationTypeName2, roleList1); String relationId5 = "relationId_number2_2"; m_proxy.createRelation(relationId5, relationTypeName2, roleList1); String relationId6 = "relationId_number2_3"; m_proxy.createRelation(relationId6, relationTypeName2, roleList1); System.out.println("------------------------------------------- done --------------------------------------------"); waitForEnterPressed(); System.out.println("create a relation MBean and add it in the Relation Service"); String relMBeanClassName = "mx4j.examples.tools.adaptor.http.SimpleRelationTestSupport"; String relationId7 = "relationId_relationMBean_1"; ObjectName relMBeanObjName1 = new ObjectName("relationType:name=RelationTypeSupportInstance"); m_server.createMBean(relMBeanClassName, relMBeanObjName1, null, new Object[]{relationId7, m_relationServiceObjectName, relationTypeName2, roleList1}, new String[]{"java.lang.String", "javax.management.ObjectName", "java.lang.String", "javax.management.relation.RoleList"}); m_proxy.addRelation(relMBeanObjName1); System.out.println("------------------------------------------- done --------------------------------------------"); waitForEnterPressed(); RoleResult result = m_proxy.getAllRoles(relationId1); Iterator i = result.getRoles().iterator(); while (i.hasNext()) { Role r = (Role)i.next(); List l = r.getRoleValue(); Iterator j = l.iterator(); while (j.hasNext()) { ObjectName objName = (ObjectName)j.next(); System.out.println("ObjectName: " + objName.getCanonicalName() + " for relationId: " + relationId1); } } RoleResult result2 = m_proxy.getAllRoles(relationId2); Iterator i2 = result2.getRoles().iterator(); while (i2.hasNext()) { Role r = (Role)i2.next(); List l = r.getRoleValue(); Iterator j = l.iterator(); while (j.hasNext()) { ObjectName objName = (ObjectName)j.next(); System.out.println("ObjectName: " + objName.getCanonicalName() + " for relationId: " + relationId2); } } System.out.println("getting all relationIds"); List li = m_proxy.getAllRelationIds(); System.out.println("allrelationIds list: " + li.toString()); System.out.println("You can view the adaptor at url http://......"); System.out.println(">>>>>>>>>>>>>>>> PRESS ENTER TO END THE DEMO <<<<<<<<<<<<<<<<<<<<"); waitForEnterPressed(); } catch (Exception ex) { ex.printStackTrace(); } } public void endTests() { try { m_adaptor.stop(); Set mbeanSet = m_server.queryMBeans(null, Query.initialSubString(Query.classattr(), Query.value("test*"))); for (Iterator i = mbeanSet.iterator(); i.hasNext();) { m_server.unregisterMBean(((ObjectInstance)i.next()).getObjectName()); } // release the relationService m_server.unregisterMBean(m_relationServiceObjectName); m_server.unregisterMBean(processorName); m_server.unregisterMBean(httpAdaptorObjectName); // release the MBeanServer MBeanServerFactory.releaseMBeanServer(m_server); System.exit(0); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } public static void main(String[] args) { RelationServiceAdaptor bnb = new RelationServiceAdaptor(); bnb.startTests(args); bnb.buildMBeans(); bnb.endTests(); } private static void waitForEnterPressed() { try { boolean done = false; while (!done) { char ch = (char)System.in.read(); if (ch < 0 || ch == '\n') { done = true; } } } catch (IOException ex) { ex.printStackTrace(); } return; } }mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/SSLHttpAdaptor.java100644 0 0 13244 10513545721 24111 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.adaptor.http; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import mx4j.tools.adaptor.ssl.SSLAdaptorServerSocketFactoryMBean; /** * Example as how to use the HttpAdaptor and the XSLTProcessor with * SSL support. This example assumes that you have created a keystore * as described in the documentation. * * @version $Revision: 1.4 $ */ public class SSLHttpAdaptor { private int port = 8080; private String host = "localhost"; private String path = null, pathInJar = null; private static interface TestClassMBean { public String getStr(); public Double getDouble(); public boolean isTrue(); public void setStr(String str); public Boolean aMethod(String string); public void anotherMethod(String string, int test); } public static class TestClass extends NotificationBroadcasterSupport implements TestClassMBean { private String str; public TestClass(String str) { this.str = str; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public Double getDouble() { return new Double(0); } public boolean isTrue() { return true; } public Boolean aMethod(String string) { return new Boolean(string.equals("true")); } public void anotherMethod(String string, int test) { this.str = string; } public MBeanNotificationInfo[] getNotificationInfo() { MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[1]; notifications[0] = new MBeanNotificationInfo(new String[]{"test1" , "test2"}, "name", "test"); return notifications; } } /** * Creates a new SSLHttpAdaptor example. You can optionally pass the host/port as * java -cp CLASSPATH adaptor.http.HttpAdaptor localhost 8080 path */ public SSLHttpAdaptor(String args[]) { if (args.length > 0) { host = args[0]; } if (args.length > 1) { port = Integer.parseInt(args[1]); } if (args.length > 2) { path = args[2]; } if (args.length > 3) { pathInJar = args[3]; } } /** * Starts the http server */ public void start() throws JMException { // creates new server MBeanServer server = MBeanServerFactory.createMBeanServer("test"); ObjectName serverName = new ObjectName("Http:name=HttpAdaptor"); server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", serverName, null); // set attributes if (port > 0) { server.setAttribute(serverName, new Attribute("Port", new Integer(port))); } else { System.out.println("Incorrect port value " + port); } if (host != null) { server.setAttribute(serverName, new Attribute("Host", host)); } else { System.out.println("Incorrect null hostname"); } // set the XSLTProcessor. If you want to use pure XML comment this out ObjectName processorName = new ObjectName("Http:name=XSLTProcessor"); server.createMBean("mx4j.tools.adaptor.http.XSLTProcessor", processorName, null); if (path != null) { server.setAttribute(processorName, new Attribute("File", path)); } server.setAttribute(processorName, new Attribute("UseCache", new Boolean(false))); if (pathInJar != null) { server.setAttribute(processorName, new Attribute("PathInJar", pathInJar)); } server.setAttribute(serverName, new Attribute("ProcessorName", processorName)); // add a couple of MBeans TestClass test1 = new TestClass("t1"); TestClass test2 = new TestClass("t2"); server.registerMBean(test1, new ObjectName("Test:name=test1")); server.registerMBean(test2, new ObjectName("Test:name=test2")); // add user names //server.invoke(serverName, "addAuthorization", new Object[] {"mx4j", "mx4j"}, new String[] {"java.lang.String", "java.lang.String"}); // use basic authentication //server.setAttribute(serverName, new Attribute("AuthenticationMethod", "basic")); // SSL support ObjectName sslFactory = new ObjectName("Adaptor:service=SSLServerSocketFactory"); server.createMBean("mx4j.tools.adaptor.ssl.SSLAdaptorServerSocketFactory", sslFactory, null); SSLAdaptorServerSocketFactoryMBean factory = (SSLAdaptorServerSocketFactoryMBean)MBeanServerInvocationHandler.newProxyInstance(server, sslFactory, SSLAdaptorServerSocketFactoryMBean.class, false); // Customize the values below factory.setKeyStoreName("certs"); factory.setKeyStorePassword("mx4j"); server.setAttribute(serverName, new Attribute("SocketFactoryName", sslFactory)); // starts the server server.invoke(serverName, "start", null, null); } public static void main(String[] str) throws JMException { SSLHttpAdaptor adaptor = new SSLHttpAdaptor(str); adaptor.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/SimpleRelationTestSupport.java100644 0 0 2046 10513545721 26437 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.adaptor.http; import javax.management.ObjectName; import javax.management.relation.InvalidRoleValueException; import javax.management.relation.RelationSupport; import javax.management.relation.RelationSupportMBean; import javax.management.relation.RoleList; /** * @version $Revision: 1.3 $ */ interface SimpleRelationTestSupportMBean extends RelationSupportMBean { } public class SimpleRelationTestSupport extends RelationSupport implements SimpleRelationTestSupportMBean { public SimpleRelationTestSupport(String relationId, ObjectName relationServiceName, String relationTypeName, RoleList roleList) throws InvalidRoleValueException, IllegalArgumentException { super(relationId, relationServiceName, relationTypeName, roleList); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/SimpleStandard.java100644 0 0 1302 10513545721 24157 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.adaptor.http; /** * @version $Revision: 1.3 $ */ interface SimpleStandardMBean { public void setName(String name); public String getName(); } public class SimpleStandard implements SimpleStandardMBean { private String m_name = "RelationAdaptor Example"; public SimpleStandard() { } public void setName(String name) { m_name = name; } public String getName() { return m_name; } } mx4j-3.0.2/src/examples/mx4j/examples/tools/config/ConfigurationShutdown.java100644 0 0 1523 10513545721 24451 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.config; import java.net.Socket; /** * This class invokes the shutdown section of the XML configuration file bundled * with this example.
* Refer to the ConfigurationLoader documentation for further information. * * @version $Revision: 1.3 $ * @see ConfigurationStartup */ public class ConfigurationShutdown { public static void main(String[] args) throws Exception { String shutdownCommand = "shutdown"; Socket socket = new Socket("127.0.0.1", 9876); socket.getOutputStream().write(shutdownCommand.getBytes()); socket.close(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/config/ConfigurationStartup.java100644 0 0 5313 10513545721 24301 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.config; import java.io.BufferedReader; import java.io.FileReader; import java.io.Reader; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import mx4j.tools.config.ConfigurationLoader; /** * This example shows how to use the XML configuration files to load MBeans into * an MBeanServer.
* The main class is {@link ConfigurationLoader}, that is able to read the XML * configuration format defined by the MX4J project (see the online documentation * for details on the format). * A ConfigurationLoader is an MBean itself, and loads information * from one XML file into one MBeanServer.
* This example runs by specifying the path of an XML configuration file as a * program argument, such as *
 * java -classpath ... mx4j.examples.tools.config.ConfigurationStartup ./config.xml
 * 
* Refer to the documentation about the ConfigurationLoader for further information. * * @version $Revision: 1.3 $ * @see ConfigurationShutdown */ public class ConfigurationStartup { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.newMBeanServer(); // The configuration loader /* Choice 1: as an external object */ // ConfigurationLoader loader = new ConfigurationLoader(server); /* Choice 2: as a created MBean */ // server.createMBean(ConfigurationLoader.class.getName(), ObjectName.getInstance("config:service=loader"), null); /* Choice 3: as a registered MBean */ ConfigurationLoader loader = new ConfigurationLoader(); server.registerMBean(loader, ObjectName.getInstance("config:service=loader")); // The XML file /* Choice 1: read it from classpath using classloaders Note: the directory that contains the XML file must be in the classpath */ // InputStream stream = ConfigurationStartup.class.getClassLoader().getResourceAsStream("config.xml"); // Reader reader = new BufferedReader(new InputStreamReader(stream)); /* Choice 2: read it from a file Note: requires file path to be passed as program argument */ String path = args[0]; Reader reader = new BufferedReader(new FileReader(path)); // Read and execute the 'startup' section of the XML file loader.startup(reader); reader.close(); System.out.println("Application configured successfully"); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/config/config.xml100644 0 0 1404 10513545721 21230 0ustar 0 0 9090 localhost connectors:type=http,processor=xslt mx4j-3.0.2/src/examples/mx4j/examples/tools/jython/ScriptExample.java100644 0 0 4152 10513545721 22735 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.jython; import java.net.MalformedURLException; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; /** * Example as how to use the Jython MBean. An MBean will be created and some scripts executed * * @version $Revision: 1.3 $ */ public class ScriptExample { public ScriptExample() { } /** * Executes the script */ public void start() throws JMException, MalformedURLException { // creates new server MBeanServer server = MBeanServerFactory.createMBeanServer("Script"); ObjectName scriptingName = new ObjectName("Test:name=script"); server.createMBean("mx4j.tools.jython.JythonRunner", scriptingName, null); // Sample. Starts all monitors server.setAttribute(scriptingName, new Attribute("Script", "[proxy(name).start() for name in server.queryNames(None, None) if server.isInstanceOf(name, 'javax.management.monitor.Monitor')]")); server.invoke(scriptingName, "runScript", null, null); // Sample. Stops all timers server.setAttribute(scriptingName, new Attribute("Script", "[proxy(name).start() for name in server.queryNames(None, None) if server.isInstanceOf(name, 'javax.management.timer.Timer')]")); server.invoke(scriptingName, "runScript", null, null); // Sample. prints all MBeans which description is not null server.setAttribute(scriptingName, new Attribute("Script", "desc = [server.getMBeanInfo(name).description for name in server.queryNames(None, None)]\nprint filter(lambda x:x, desc)")); server.invoke(scriptingName, "runScript", null, null); } public static void main(String[] str) throws JMException, MalformedURLException { ScriptExample example = new ScriptExample(); example.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/mail/MailExample.java100644 0 0 6711 10513545721 21765 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.mail; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; /** * Example as how to use the SMTP MBean. There is a monitor which looks for the Str property * on the TestMBean, when the value changes a notification is sent by the Monitor and a mail * is produced. *

* Modify the values of the SMTP server for your needs * * @version $Revision: 1.3 $ */ public class MailExample { private static interface TestClassMBean { public String getStr(); public void setStr(String str); } public static class TestClass implements TestClassMBean { private String str; public TestClass(String str) { this.str = str; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } } public MailExample() { } /** * Starts the http server */ public void start() throws JMException { // creates new server MBeanServer server = MBeanServerFactory.createMBeanServer("Mail"); ObjectName beanName = new ObjectName("Test:name=test"); server.registerMBean(new TestClass("original"), beanName); ObjectName monitorName = new ObjectName("Test:name=monitor"); server.createMBean("javax.management.monitor.StringMonitor", monitorName, null); server.setAttribute(monitorName, new Attribute("ObservedObject", beanName)); server.setAttribute(monitorName, new Attribute("ObservedAttribute", "Str")); server.setAttribute(monitorName, new Attribute("StringToCompare", "original")); server.setAttribute(monitorName, new Attribute("GranularityPeriod", new Integer(100))); server.setAttribute(monitorName, new Attribute("NotifyDiffer", Boolean.TRUE)); server.invoke(monitorName, "start", null, null); ObjectName mailerName = new ObjectName("Test:name=mailer"); server.createMBean("mx4j.tools.mail.SMTP", mailerName, null); // Sets attributes server.setAttribute(mailerName, new Attribute("ObservedObject", monitorName)); server.setAttribute(mailerName, new Attribute("NotificationName", "jmx.monitor.string.differs")); server.setAttribute(mailerName, new Attribute("FromAddress", "monitor@someserver")); server.setAttribute(mailerName, new Attribute("FromName", "MX4J")); server.setAttribute(mailerName, new Attribute("ServerHost", "smpt-server")); server.setAttribute(mailerName, new Attribute("To", "nobody@nobody")); server.setAttribute(mailerName, new Attribute("Subject", "Notification on $date$ at $time$")); server.setAttribute(mailerName, new Attribute("Content", "Notification on $datetime$ sent by $objectname$ on $observed$ monitor and a notification $notification$\nNotice how $$$$ gets expanded to $$")); // this will trigger the monitor and the mailer (Wait for 10 secs app) server.setAttribute(beanName, new Attribute("Str", "something-else")); } public static void main(String[] str) throws JMException { MailExample example = new MailExample(); example.start(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/persister/MBeanOne.java100644 0 0 2321 10513545721 22302 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.persister; /** * An MBean that extends FilePersister to demonstrate the usage of the mx4j.persist.FilePersister * @version $Revision: 1.3 $ */ import java.io.Serializable; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.RuntimeOperationsException; import mx4j.persist.FilePersister; public class MBeanOne extends FilePersister implements Serializable { private String m_location; private String m_name; public MBeanOne(String location, String name) throws MBeanException { super(location, name); m_location = location; m_name = name; } // ask FilePersister to store the Object public void store(Object mbean) throws MBeanException, InstanceNotFoundException { store(mbean); } // return the Object public Object load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException { return load(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/persister/MBeanTwo.java100644 0 0 2634 10513545721 22341 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.persister; import java.io.Serializable; import javax.management.MBeanServer; import javax.management.ObjectName; /** * The MBean that gets to be stored Please note must be Serializable * * @version $Revision: 1.3 $ */ interface MBeanTwoMBean { public void storeIt(MBeanServer server, ObjectName name); public Object loadIt(MBeanServer server, ObjectName name); } public class MBeanTwo implements MBeanTwoMBean, Serializable { private Integer number = null; public MBeanTwo(Integer amount) { number = amount; } public void storeIt(MBeanServer server, ObjectName name) { try { server.invoke(name, "store", new Object[]{this}, new String[]{"java.lang.Object"}); } catch (Exception ex) { System.out.println("exception: MBeanTwo: storeIt"); ex.printStackTrace(); } } public Object loadIt(MBeanServer server, ObjectName name) { Object me = null; try { me = (MBeanTwo)server.invoke(name, "load", new Object[0], new String[0]); } catch (Exception ex) { ex.printStackTrace(); } return me; } } mx4j-3.0.2/src/examples/mx4j/examples/tools/persister/PersisterTest.java100644 0 0 7050 10513545721 23502 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.persister; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.loading.MLet; /** * Our agent which instantiates 2 MLets to load the MBeans contained in their separate jars * * @version $Revision: 1.3 $ */ public class PersisterTest { private MBeanServer m_server = null; public PersisterTest() { } public void endExample() { System.out.println("----- example completed -----"); MBeanServerFactory.releaseMBeanServer(m_server); System.exit(0); } public void doDemo(String[] args) { String jarPath1 = args[0]; String jarPath2 = args[1]; String storePath = args[2]; String filename = args[3]; m_server = MBeanServerFactory.createMBeanServer("test"); try { // register the mlet used to load the MBeans MLet one ObjectName mName1 = new ObjectName("loading:test=mlet1"); MLet mlet1 = new MLet(); m_server.registerMBean(mlet1, mName1); mlet1.addURL(jarPath1); // mlet1.addURL(new File("one.jar").toURL()); ObjectName mName2 = new ObjectName("loading:test=mlet2"); MLet mlet2 = new MLet(); m_server.registerMBean(mlet2, mName2); mlet2.addURL(jarPath2); // mlet2.addURL(new File("two.jar").toURL()); String mbeanClass1 = "mx4j.examples.tools.persister.MBeanOne"; ObjectName mbeanName1 = new ObjectName("test:name=MBeanOne"); m_server.createMBean(mbeanClass1, mbeanName1, mName1, new Object[]{storePath, filename}, new String[]{"java.lang.String", "java.lang.String"}); String mbeanClass2 = "mx4j.examples.tools.persister.MBeanTwo"; ObjectName mbeanName2 = new ObjectName("test:name=MBeanTwo"); m_server.createMBean(mbeanClass2, mbeanName2, mName2, new Object[]{new Integer(15)}, new String[]{"java.lang.Integer"}); m_server.invoke(mbeanName2, "storeIt", new Object[]{m_server, mbeanName1}, new String[]{"javax.management.MBeanServer", "javax.management.ObjectName"}); Object a = m_server.invoke(mbeanName2, "loadIt", new Object[]{m_server, mbeanName1}, new String[]{"javax.management.MBeanServer", "javax.management.ObjectName"}); if (a.getClass().getName() == mbeanClass2) System.out.println("Objects are equal and the same"); } catch (Exception ex) { ex.printStackTrace(); } finally { endExample(); } } public static void usage() { System.out.println("Four arguments are needed to run this example:"); System.out.println("arg[0] = eg: file:C:/dev/one.jar"); System.out.println("arg[1] = eg: file:C:/dev/two.jar"); System.out.println("arg[2] = eg: C:/dev"); System.out.println("arg[3] = eg: myMBean.ser"); System.out.println("Program is exiting......."); System.exit(1); } public static void main(String[] args) { PersisterTest test = new PersisterTest(); if (args.length < 4) { usage(); } test.doDemo(args); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/Client.java100644 0 0 5716 10513545721 23014 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.hessian; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.timer.Timer; /** * This example shows how to connect to a Hessian JMXConnectorServer. * To run this example, you need the following jars: *

    *
  • MX4J 3.x
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Hessian 3.0.8
  • *
      *
    • hessian-3.0.8.jar
    • *
    *
* * @version $Revision: 1.1 $ */ public class Client { public static void main(String[] args) throws Exception { // This JMXServiceURL works only if the connector server is on the same host of // the connector. If this is not the case, set the correct host name. JMXServiceURL address = new JMXServiceURL("hessian", null, 8080, "/hessian"); // Connect a JSR 160 JMXConnector to the server side JMXConnector connector = JMXConnectorFactory.connect(address); // Retrieve an MBeanServerConnection that represent the MBeanServer // the remote connector server is bound to MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side as if it is a local MBeanServer ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; System.out.println(delegate.getImplementationVendor() + " is cool !"); // Register an MBean, and get notifications via the Hessian protocol connection.addNotificationListener(delegateName, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println("Got the following notification: " + notification); } }, null, null); ObjectName timerName = ObjectName.getInstance("services:type=Timer"); connection.createMBean(Timer.class.getName(), timerName, null); // Unregistering the MBean to get another notification connection.unregisterMBean(timerName); // Allow the unregistration notification to arrive before killing this JVM Thread.sleep(1000); connector.close(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/Server.java100644 0 0 3502 10513545721 23033 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.hessian; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to setup a JSR 160 connector server that uses * Caucho's Hessian protocol. *
* MX4J's implementation requires the hessian library version 3.0.8 and * a servlet container to run. The default servlet container used is Jetty. * To run this example, you need the following jars: *
    *
  • MX4J
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Jetty 4.2.x or later
  • *
      *
    • org.mortbay.jetty.jar
    • *
    • servlet.jar
    • *
    • commons-logging.jar
    • *
    *
  • Hessian 3.0.8
  • *
      *
    • hessian-3.0.8.jar
    • *
    *
* * @version : $Revision: 1.1 $ */ public class Server { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Pass null as the host name to tell JMXServiceURL to default to InetAddress.getLocalHost().getHostName() JMXServiceURL url = new JMXServiceURL("hessian", null, 8080, "/hessian"); JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); connectorServer.start(); System.out.println("Server up and running " + connectorServer + " on " + url); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ssl/Client.java100644 0 0 6333 10513545721 23611 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.hessian.ssl; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.timer.Timer; /** * This example shows how to connect to a Hessian JMXConnectorServer over HTTPS. * To run this example, you need the following jars: *
    *
  • MX4J 3.x
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Hessian 3.0.8
  • *
      *
    • hessian-3.0.8.jar
    • *
    *
* * @version $Revision: 1.2 $ */ public class Client { public static void main(String[] args) throws Exception { // Replace the value with the file path of your keystore. // IMPORTANT: this should NOT be done in production environments, it is shown here just as an example. System.setProperty("javax.net.ssl.trustStore", ""); // This JMXServiceURL works only if the connector server is on the same host of // the connector. If this is not the case, set the correct host name. JMXServiceURL address = new JMXServiceURL("hessian+ssl", null, 8443, "/hessianssl"); // Connect a JSR 160 JMXConnector to the server side JMXConnector connector = JMXConnectorFactory.connect(address); // Retrieve an MBeanServerConnection that represent the MBeanServer // the remote connector server is bound to MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side as if it is a local MBeanServer ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; System.out.println(delegate.getImplementationVendor() + " is cool !"); // Register an MBean, and get notifications via the Hessian protocol connection.addNotificationListener(delegateName, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println("Got the following notification: " + notification); } }, null, null); ObjectName timerName = ObjectName.getInstance("services:type=Timer"); connection.createMBean(Timer.class.getName(), timerName, null); // Unregistering the MBean to get another notification connection.unregisterMBean(timerName); // Allow the unregistration notification to arrive before killing this JVM Thread.sleep(1000); connector.close(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ssl/Server.java100644 0 0 4541 10513545721 23640 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.hessian.ssl; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * This example shows how to setup a JSR 160 connector server that uses Caucho's Hessian * protocol over HTTPS as communication protocol with the client. *
* MX4J's implementation requires the hessian library version 3.0.8 and * a servlet container to run. The default servlet container used is Jetty. * To run this example, you need the following jars: *
    *
  • MX4J 3.x
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Jetty 4.2.x or later
  • *
      *
    • org.mortbay.jetty.jar
    • *
    • servlet.jar
    • *
    • commons-logging.jar
    • *
    *
  • Hessian 3.0.8
  • *
      *
    • hessian-3.0.8.jar
    • *
    *
* Furthermore, you need a Jetty configuration file and a keystore * (see the MX4J documentation on how to create these 2 files). * * @version : $Revision: 1.1 $ */ public class Server { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Pass null as the host name to tell JMXServiceURL to default to InetAddress.getLocalHost().getHostName() JMXServiceURL url = new JMXServiceURL("hessian+ssl", null, 8443, "/hessianssl"); // Replace the value of the configuration with the file path of the configuration file Map serverEnv = new HashMap(); serverEnv.put(HTTPConnectorServer.WEB_CONTAINER_CONFIGURATION, ""); JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, server); connectorServer.start(); System.out.println("Server up and running " + connectorServer + " on " + url); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/soap/Client.java100644 0 0 6360 10513545721 22320 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.soap; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.timer.Timer; /** * This example shows how to connect to a JMXConnectorServer over the SOAP protocol. * MX4J's implementation of the SOAP provider requires Axis 1.1, that in turn requires * a servlet container to run. The default servlet container used is Jetty 4.2.x. * To run this example, you need the following jars: *
    *
  • MX4J 2.x
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Axis 1.1
  • *
      *
    • axis.jar
    • *
    • jaxrpc.jar
    • *
    • commons-logging.jar
    • *
    • commons-discovery.jar
    • *
    • saaj.jar
    • *
    • wsdl4j.jar
    • *
    *
* * @version $Revision: 1.4 $ */ public class Client { public static void main(String[] args) throws Exception { // This JMXServiceURL works only if the connector server is in-VM with // the connector. If this is not the case, set the correct host name. JMXServiceURL address = new JMXServiceURL("soap", null, 8080, "/jmxconnector"); // Connect a JSR 160 JMXConnector to the server side JMXConnector connector = JMXConnectorFactory.connect(address); // Retrieve an MBeanServerConnection that represent the MBeanServer // the remote connector server is bound to MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side as if it is a local MBeanServer ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; System.out.println(delegate.getImplementationVendor() + " is cool !"); // Register an MBean, and get notifications via the SOAP protocol connection.addNotificationListener(delegateName, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { System.out.println("Got the following notification: " + notification); } }, null, null); ObjectName timerName = ObjectName.getInstance("services:type=Timer"); connection.createMBean(Timer.class.getName(), timerName, null); // Unregistering the MBean to get another notification connection.unregisterMBean(timerName); // Allow the unregistration notification to arrive before killing this JVM Thread.sleep(1000); connector.close(); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/soap/Server.java100644 0 0 4422 10513545721 22345 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.remote.soap; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; /** * This example shows how to setup a JSR 160 connector server that uses SOAP as * communication protocol with the client. * MX4J's implementation of the SOAP provider requires Axis 1.1, that in turn requires * a servlet container to run. The default servlet container used is Jetty 4.2.x. * Incoming connections from a client will be accepted by Jetty, handed to the * Axis servlet that interpretes the SOAP invocation, and passed to MX4J's * connector server implementation, and finally routed the MBeanServer. * Remote notifications are delivered transparently. * To run this example, you need the following jars: *
    *
  • MX4J 2.x
  • *
      *
    • mx4j.jar
    • *
    • mx4j-remote.jar
    • *
    • mx4j-tools.jar
    • *
    • mx4j-examples.jar
    • *
    *
  • Jetty 4.2.x
  • *
      *
    • org.mortbay.jetty.jar
    • *
    • servlet.jar
    • *
    *
  • Axis 1.1
  • *
      *
    • axis.jar
    • *
    • jaxrpc.jar
    • *
    • commons-logging.jar
    • *
    • commons-discovery.jar
    • *
    • saaj.jar
    • *
    • wsdl4j.jar
    • *
    *
* * @version : $Revision: 1.6 $ */ public class Server { public static void main(String[] args) throws Exception { // The MBeanServer MBeanServer server = MBeanServerFactory.createMBeanServer(); // Pass null as the host name to tell JMXServiceURL to default to InetAddress.getLocalHost().getHostName() JMXServiceURL url = new JMXServiceURL("soap", null, 8080, "/jmxconnector"); // Create and start the connector server // Jetty will listen on port 8080 JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); connectorServer.start(); System.out.println("Server up and running " + connectorServer); } } mx4j-3.0.2/src/examples/mx4j/examples/tools/xdoclet/MyService.java100644 0 0 5077 10513545721 22221 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.examples.tools.xdoclet; /** * Sample MBean implementation. * * @version $Revision: 1.3 $ * @jmx:mbean name="mx4j:name=My MBean" description="My wonderful service." * @jmx:mlet-entry archive="MyApp.jar" codebase="../lib" */ public class MyService implements MyServiceMBean { protected int status = 0; protected String m_dummy = null; /** * Default constructor. * * @jmx:managed-constructor description="Default constructor." */ public MyService() { } /** * Constructor. * * @param type the type, * @param status the status. * @jmx:managed-constructor description="Build the service." * @jmx:managed-constructor-parameter name="type" position="0" description="The type." * @jmx:managed-constructor-parameter name="status" position="1" description="The status." */ public MyService(String type, int status) { } /** * Start my service. * * @jmx:managed-operation description="Starts the service." */ public void start() { } /** * Method that is not an JMX managed operation. */ public void stop() { } /** * Echos a string. * * @jmx:managed-operation description="Echoes the string given as a parameter." * @jmx:managed-operation-parameter name="str" position="0" description="The string to echo." */ public void echo(String str) { } /** * Does some crazy stuff. * * @jmx:managed-operation description="Do some crazy stuff." * @jmx:managed-operation-parameter name="firstObject" position="0" description="My first object." * @jmx:managed-operation-parameter name="secondObject" position="1" description="My second object." */ public int doSomeCrazyStuff(Object firstObject, Object secondObject) { return -1; } /** * Sets the status. * * @jmx:managed-attribute description="My Status." */ public void setStatus(int status) { this.status = status; } /** * Gets the dummy variable. * * @jmx:managed-attribute description="My dummy attribute." */ public String getDummy() { return ""; } /** * Sets the dummy variable. * * @jmx:managed-attribute description="This description should be ignored because of the getter." */ public void setDummy(String dummy) { } } mx4j-3.0.2/src/test/test/MX4JTestCase.java100644 0 0 11015 10513545721 15314 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import junit.framework.TestCase; /** * Base class for MX4J tests * * @version $Revision: 1.11 $ */ public class MX4JTestCase extends TestCase { public MX4JTestCase(String name) { super(name); } protected MBeanServer newMBeanServer() { return MBeanServerFactory.newMBeanServer(); } protected ClassLoader createMX4JClassLoader() throws MalformedURLException { File jmx = new File("dist/test/mx4j-jmx.jar"); File impl = new File("dist/test/mx4j-impl.jar"); return new URLClassLoader(new URL[]{jmx.toURL(), impl.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createJMXRIClassLoader() throws MalformedURLException { File jmxri = new File("dist/test/jmxri.jar"); if (!jmxri.exists()) fail("JMXRI jar is not available"); return new URLClassLoader(new URL[]{jmxri.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createJMXRIWithMX4JImplClassLoader() throws MalformedURLException { File jmxri = new File("dist/test/jmxri.jar"); if (!jmxri.exists()) fail("JMXRI jar is not available"); File mx4j = new File("dist/test/mx4j-impl.jar"); return new URLClassLoader(new URL[]{jmxri.toURL(), mx4j.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createMX4JWithTestsClassLoader() throws MalformedURLException { File jmx = new File("dist/test/mx4j-jmx.jar"); File impl = new File("dist/test/mx4j-impl.jar"); File tests = new File("dist/test/mx4j-tests.jar"); return new URLClassLoader(new URL[]{jmx.toURL(), impl.toURL(), tests.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createRemoteMX4JWithTestsClassLoader() throws MalformedURLException { File jmx = new File("dist/test/mx4j-jmx.jar"); File impl = new File("dist/test/mx4j-impl.jar"); File rjmx = new File("dist/test/mx4j-rjmx.jar"); File rimpl = new File("dist/test/mx4j-rimpl.jar"); File tests = new File("dist/test/mx4j-tests.jar"); File jaas = new File("dist/test/jaas.jar"); return new URLClassLoader(new URL[]{jaas.toURL(), jmx.toURL(), impl.toURL(), rjmx.toURL(), rimpl.toURL(), tests.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createJMXRIWithTestsClassLoader() throws MalformedURLException { File jmxri = new File("dist/test/jmxri.jar"); if (!jmxri.exists()) fail("JMXRI jar is not available"); File tests = new File("dist/test/mx4j-tests.jar"); return new URLClassLoader(new URL[]{jmxri.toURL(), tests.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createRemoteJMXRIWithTestsClassLoader() throws MalformedURLException { File jmx = new File("dist/test/jmxri.jar"); if (!jmx.exists()) fail("JMXRI jar is not available"); File rjmx = new File("dist/test/jmxremote.jar"); if (!rjmx.exists()) fail("JMX Remote jar is not available"); File tests = new File("dist/test/mx4j-tests.jar"); File jaas = new File("dist/test/jaas.jar"); return new URLClassLoader(new URL[]{jaas.toURL(), jmx.toURL(), rjmx.toURL(), tests.toURL()}, getClass().getClassLoader().getParent()); } protected ClassLoader createOptionalRemoteJMXRIWithTestsClassLoader() throws MalformedURLException { File jmx = new File("dist/test/jmxri.jar"); if (!jmx.exists()) fail("JMXRI jar is not available"); File rjmx = new File("dist/test/jmxremote.jar"); if (!rjmx.exists()) fail("JMX Remote jar is not available"); File orjmx = new File("dist/test/jmxremote_optional.jar"); if (!orjmx.exists()) fail("JMX Optional Remote jar is not available"); File tests = new File("dist/test/mx4j-tests.jar"); return new URLClassLoader(new URL[]{jmx.toURL(), rjmx.toURL(), orjmx.toURL(), tests.toURL()}, getClass().getClassLoader().getParent()); } protected void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException x) { Thread.currentThread().interrupt(); } } } mx4j-3.0.2/src/test/test/MultiThreadTestRunner.java100644 0 0 5105 10513545721 17375 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * @version $Revision: 1.3 $ */ public class MultiThreadTestRunner { public abstract static class Test { private List throwables = new ArrayList(); public abstract void test() throws Exception; private synchronized void addThrowable(Throwable x) { throwables.add(x); } private synchronized Throwable[] getThrowables() { return (Throwable[])throwables.toArray(new Throwable[throwables.size()]); } } private class MultiThrowable extends Exception { private final Throwable[] throwables; public MultiThrowable(Throwable[] throwables) { this.throwables = throwables; } public void printStackTrace(PrintStream stream) { synchronized (stream) { stream.println(this); for (int i = 0; i < throwables.length; ++i) throwables[i].printStackTrace(stream); } } public void printStackTrace(PrintWriter writer) { synchronized (writer) { writer.println(this); for (int i = 0; i < throwables.length; ++i) throwables[i].printStackTrace(writer); } } } private final int threads; private final int iterations; public MultiThreadTestRunner(int threads, int iterations) { this.threads = threads; this.iterations = iterations; } public void run(final Test test) throws Exception { Thread[] runners = new Thread[threads]; for (int i = 0; i < threads; ++i) { runners[i] = new Thread(new Runnable() { public void run() { for (int i = 0; i < iterations; ++i) { try { test.test(); } catch (Throwable x) { test.addThrowable(x); } } } }); } for (int i = 0; i < threads; ++i) runners[i].start(); for (int i = 0; i < threads; ++i) runners[i].join(); Throwable[] failures = test.getThrowables(); if (failures != null && failures.length > 0) throw new MultiThrowable(failures); } } mx4j-3.0.2/src/test/test/MutableBoolean.java100644 0 0 1054 10513545721 16011 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; /** * @version $Revision: 1.4 $ * @see */ public class MutableBoolean { private boolean m_value; public MutableBoolean(boolean value) { set(value); } public boolean get() { return m_value; } public void set(boolean value) { m_value = value; } }mx4j-3.0.2/src/test/test/MutableInteger.java100644 0 0 1042 10513545721 16024 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; /** * @version $Revision: 1.4 $ * @see */ public class MutableInteger { private int m_value; public MutableInteger(int value) { m_value = value; } public int get() { return m_value; } public void set(int value) { m_value = value; } } mx4j-3.0.2/src/test/test/MutableLong.java100644 0 0 1040 10513545721 15324 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; /** * @version $Revision: 1.3 $ * @see */ public class MutableLong { private long m_value; public MutableLong(long value) { m_value = value; } public long get() { return m_value; } public void set(long value) { m_value = value; } } mx4j-3.0.2/src/test/test/MutableObject.java100644 0 0 1110 10513545721 15631 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test; /** * @version $Revision: 1.3 $ */ public class MutableObject { private Object object; public MutableObject(Object object) { this.object = object; } public synchronized Object get() { return object; } public synchronized void set(Object object) { this.object = object; } } mx4j-3.0.2/src/test/test/javax/management/BinaryOpValueExpTest.java100644 0 0 3761 10513545721 22411 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import javax.management.Query; import javax.management.QueryExp; import javax.management.ValueExp; import junit.framework.TestCase; /** * @version $Revision: 1.4 $ */ public class BinaryOpValueExpTest extends TestCase { /** * Constructor requested by the JUnit framework */ public BinaryOpValueExpTest(String name) { super(name); } public void testLongOperations() throws Exception { ValueExp value1 = Query.value(new Integer(3)); ValueExp value2 = Query.value(new Integer(4)); ValueExp op = Query.plus(value1, value2); QueryExp result = Query.eq(Query.value(7L), op); assertTrue(result.apply(null)); op = Query.minus(value1, value2); result = Query.eq(Query.value(-1L), op); assertTrue(result.apply(null)); op = Query.times(value1, value2); result = Query.eq(Query.value(12L), op); assertTrue(result.apply(null)); op = Query.div(value1, value2); result = Query.eq(Query.value(0L), op); assertTrue(result.apply(null)); } public void testDoubleOperations() throws Exception { ValueExp value1 = Query.value(new Double(3.0D)); ValueExp value2 = Query.value(new Double(4.0D)); ValueExp op = Query.plus(value1, value2); QueryExp result = Query.eq(Query.value(7.0D), op); assertTrue(result.apply(null)); op = Query.minus(value1, value2); result = Query.eq(Query.value(-1.0D), op); assertTrue(result.apply(null)); op = Query.times(value1, value2); result = Query.eq(Query.value(12.0D), op); assertTrue(result.apply(null)); op = Query.div(value1, value2); result = Query.eq(Query.value(3.0D / 4.0D), op); assertTrue(result.apply(null)); } } mx4j-3.0.2/src/test/test/javax/management/BinaryRelQueryExpTest.java100644 0 0 12235 10513545721 22622 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import javax.management.BadBinaryOpValueExpException; import javax.management.Query; import javax.management.QueryExp; import javax.management.StringValueExp; import javax.management.ValueExp; import junit.framework.TestCase; /** * @version $Revision: 1.4 $ */ public class BinaryRelQueryExpTest extends TestCase { /** * Constructor requested by the JUnit framework */ public BinaryRelQueryExpTest(String name) { super(name); } public void testExceptions() throws Exception { QueryExp operation = Query.eq(null, null); assertTrue(operation.apply(null)); ValueExp value1 = Query.value(new Integer(3)); operation = Query.eq(value1, null); assertTrue(!operation.apply(null)); operation = Query.eq(null, value1); assertTrue(!operation.apply(null)); ValueExp value2 = Query.value(new Long(3)); ValueExp result = Query.plus(value1, value2); operation = Query.eq(Query.value(6), result); assertTrue(operation.apply(null)); // Comparing apple and oranges ValueExp bvalue1 = Query.value(true); operation = Query.eq(bvalue1, value2); assertTrue(!operation.apply(null)); // Adding 2 booleans ValueExp bvalue2 = Query.value(true); result = Query.plus(bvalue1, bvalue2); operation = Query.eq(Query.value(false), result); try { operation.apply(null); } catch (BadBinaryOpValueExpException ignored) { } StringValueExp svalue1 = new StringValueExp("a"); StringValueExp svalue2 = new StringValueExp("b"); operation = Query.eq(svalue1, null); assertTrue(!operation.apply(null)); operation = Query.eq(svalue1, svalue2); assertTrue(!operation.apply(null)); } public void testNumericals() throws Exception { ValueExp value1 = Query.value(new Integer(3)); ValueExp value2 = Query.value(new Long(3)); QueryExp operation = Query.eq(value1, value2); assertTrue(operation.apply(null)); value1 = Query.value(new Integer(5)); value2 = Query.value(new Long(4)); operation = Query.gt(value1, value2); assertTrue(operation.apply(null)); value1 = Query.value(new Integer(3)); value2 = Query.value(new Long(4)); operation = Query.lt(value1, value2); assertTrue(operation.apply(null)); value1 = Query.value(new Double(3)); value2 = Query.value(new Long(3)); operation = Query.eq(value1, value2); assertTrue(operation.apply(null)); value1 = Query.value(new Float(5)); value2 = Query.value(new Double(4)); operation = Query.gt(value1, value2); assertTrue(operation.apply(null)); value1 = Query.value(new Double(3)); value2 = Query.value(new Double(4)); operation = Query.lt(value1, value2); assertTrue(operation.apply(null)); } public void testBooleans() throws Exception { ValueExp value1 = Query.value(true); ValueExp value2 = Query.value(false); QueryExp operation = Query.eq(value1, value2); assertTrue(!operation.apply(null)); operation = Query.or(Query.eq(value1, value1), Query.eq(value1, value2)); assertTrue(operation.apply(null)); operation = Query.or(Query.eq(value1, value2), Query.eq(value2, value2)); assertTrue(operation.apply(null)); operation = Query.and(Query.eq(value1, value2), Query.eq(value2, value2)); assertTrue(!operation.apply(null)); operation = Query.and(Query.eq(value1, value1), Query.eq(value1, value2)); assertTrue(!operation.apply(null)); } public void testStrings() throws Exception { StringValueExp value1 = new StringValueExp("a"); StringValueExp value2 = new StringValueExp("a"); QueryExp operation = Query.eq(value1, value2); assertTrue(operation.apply(null)); operation = Query.geq(value1, value2); assertTrue(operation.apply(null)); operation = Query.gt(value1, value2); assertTrue(!operation.apply(null)); operation = Query.leq(value1, value2); assertTrue(operation.apply(null)); operation = Query.lt(value1, value2); assertTrue(!operation.apply(null)); value1 = new StringValueExp("a"); value2 = new StringValueExp("b"); operation = Query.geq(value1, value2); assertTrue(!operation.apply(null)); operation = Query.geq(value2, value1); assertTrue(operation.apply(null)); operation = Query.gt(value1, value2); assertTrue(!operation.apply(null)); operation = Query.gt(value2, value1); assertTrue(operation.apply(null)); operation = Query.leq(value1, value2); assertTrue(operation.apply(null)); operation = Query.leq(value2, value1); assertTrue(!operation.apply(null)); operation = Query.lt(value1, value2); assertTrue(operation.apply(null)); operation = Query.lt(value2, value1); assertTrue(!operation.apply(null)); } } mx4j-3.0.2/src/test/test/javax/management/DynamicMBeanFunctionalityTest.java100644 0 0 13472 10513545721 24274 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.JMRuntimeException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.RuntimeMBeanException; import test.MX4JTestCase; import test.javax.management.support.MBeanDynamic; /** * @version $Revision: 1.10 $ */ public class DynamicMBeanFunctionalityTest extends MX4JTestCase { private MBeanServer m_server; private ObjectName m_name; public DynamicMBeanFunctionalityTest(String s) { super(s); } protected void setUp() throws Exception { m_server = MBeanServerFactory.createMBeanServer("dynamic"); m_name = new ObjectName(":type=dynamic"); Object dynamic = new MBeanDynamic(); m_server.registerMBean(dynamic, m_name); } protected void tearDown() throws Exception { m_server.unregisterMBean(m_name); MBeanServerFactory.releaseMBeanServer(m_server); } public void testGetAttributes() throws Exception { AttributeList list = null; list = m_server.getAttributes(m_name, new String[0]); assertEquals(list.size(), 0); list = m_server.getAttributes(m_name, new String[]{"doesNotExist"}); if (list.size() != 0) { fail("Attribute does not exist"); } String attributeName = "DynamicAttribute1"; list = m_server.getAttributes(m_name, new String[]{attributeName}); if (list.size() != 1 && ((Attribute)list.get(0)).getName().equals(attributeName)) { fail("Attribute exists"); } } public void testGetSetAttribute() throws Exception { String attributeName = "DynamicAttribute1"; Object valueBefore = m_server.getAttribute(m_name, attributeName); Object newValue = "newValue"; Attribute attribute = new Attribute(attributeName, newValue); m_server.setAttribute(m_name, attribute); Object valueAfter = m_server.getAttribute(m_name, attributeName); if (valueAfter.equals(valueBefore) || !valueAfter.equals(newValue)) { fail("setAttribute does not work"); } } public void testSetAttributes() throws Exception { String attributeName1 = "DynamicAttribute1"; Object value1Before = m_server.getAttribute(m_name, attributeName1); String attributeName2 = "DynamicAttribute2"; Object value2Before = m_server.getAttribute(m_name, attributeName2); AttributeList changeThese = new AttributeList(); AttributeList list = m_server.setAttributes(m_name, changeThese); if (list.size() != 0) { fail("No Attributes were changed"); } if (!value1Before.equals(m_server.getAttribute(m_name, attributeName1)) || !value2Before.equals(m_server.getAttribute(m_name, attributeName2))) { fail("Attribute was not changed"); } Attribute attr = new Attribute(attributeName2, "Value2"); changeThese.add(attr); list = m_server.setAttributes(m_name, changeThese); if (list.size() != 1) { fail("One attribute was changed"); } if (!list.get(0).equals(attr)) { fail("Wrong return value"); } if (!value1Before.equals(m_server.getAttribute(m_name, attributeName1)) || value2Before.equals(m_server.getAttribute(m_name, attributeName2)) || !attr.getValue().equals(m_server.getAttribute(m_name, attributeName2))) { fail("Attribute was not changed"); } } public void testInvoke() throws Exception { String attributeName1 = "DynamicAttribute1"; Object value1 = m_server.getAttribute(m_name, attributeName1); Boolean result = (Boolean)m_server.invoke(m_name, "dynamicOperation", new Object[]{"dummy"}, new String[]{"java.lang.String"}); if (result.booleanValue()) { fail("Operation does not work"); } result = (Boolean)m_server.invoke(m_name, "dynamicOperation", new Object[]{value1}, new String[]{"java.lang.String"}); if (!result.booleanValue()) { fail("Operation does not work"); } } public void testGetMBeanInfoRegistrationException() throws Exception { try { m_server.createMBean("test.javax.management.support.ExceptionGeneratingDMB", new ObjectName(":register=no"), new Object[]{new Boolean(false)}, new String[]{"boolean"}); fail("Expecting NotCompliantMBeanException"); } catch (NotCompliantMBeanException x) { } } public void testGetMBeanInfoInvocationException() throws Exception { try { ObjectName objname = new ObjectName(":register=yes"); m_server.createMBean("test.javax.management.support.ExceptionGeneratingDMB", objname, new Object[]{new Boolean(true)}, new String[]{"boolean"}); m_server.getMBeanInfo(objname); fail("Expecting RuntimeMBeanException"); } catch (RuntimeMBeanException x) { } } public void testNullMBeanInfo() throws Exception { try { ObjectName objname = new ObjectName(":id=testNullMBeanInfo"); m_server.createMBean("test.javax.management.support.NullMBeanInfoDMB", objname); m_server.getMBeanInfo(objname); fail("Expecting JMRuntimeException"); } catch (JMRuntimeException x) { } } } mx4j-3.0.2/src/test/test/javax/management/LocalSecurityManagerTest.java100644 0 0 42331 10513545721 23305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.security.SecurityPermission; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.management.MBeanPermission; import javax.management.MBeanServer; import javax.management.MBeanServerDelegate; import javax.management.MBeanServerFactory; import javax.management.MBeanServerPermission; import javax.management.ObjectName; import javax.management.loading.ClassLoaderRepository; import javax.management.loading.MLet; import junit.framework.TestCase; import mx4j.log.Log; import mx4j.server.MX4JMBeanServer; /** * @version $Revision: 1.5 $ */ public class LocalSecurityManagerTest extends SecurityManagerTestCase { static { // For the way JUnit works, we have one JVM per test class Policy.setPolicy(new LocalModifiablePolicy()); System.setSecurityManager(new SecurityManager()); } public LocalSecurityManagerTest(String s) { super(s); } protected void setUp() throws Exception { // Be sure we have a security manager and the right policy SecurityManager sm = System.getSecurityManager(); if (sm == null) fail(); Policy policy = Policy.getPolicy(); if (!(policy instanceof LocalModifiablePolicy)) fail(); ((LocalModifiablePolicy)policy).initialize(); } protected void addPermission(Permission p) { LocalModifiablePolicy policy = (LocalModifiablePolicy)Policy.getPolicy(); policy.addPermission(p); } protected void resetPermissions() { LocalModifiablePolicy policy = (LocalModifiablePolicy)Policy.getPolicy(); policy.initialize(); } public void testNewMBeanServer() throws Exception { try { MBeanServerFactory.newMBeanServer(); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServerFactory.newMBeanServer(); try { MBeanServerFactory.createMBeanServer(); fail(); } catch (SecurityException ignored) { } } public void testCreateMBeanServer() throws Exception { try { MBeanServerFactory.createMBeanServer(); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanServerPermission("createMBeanServer")); MBeanServer server = MBeanServerFactory.createMBeanServer(); MBeanServerFactory.newMBeanServer(); try { MBeanServerFactory.releaseMBeanServer(server); fail(); } catch (SecurityException ignored) { } // Clean up addPermission(new MBeanServerPermission("releaseMBeanServer")); MBeanServerFactory.releaseMBeanServer(server); } public void testReleaseMBeanServer() throws Exception { addPermission(new MBeanServerPermission("createMBeanServer")); MBeanServer server = MBeanServerFactory.createMBeanServer(); try { MBeanServerFactory.releaseMBeanServer(server); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanServerPermission("releaseMBeanServer")); MBeanServerFactory.releaseMBeanServer(server); } public void testReleaseMBeanServer2() throws Exception { addPermission(new MBeanServerPermission("createMBeanServer, releaseMBeanServer")); MBeanServer server = MBeanServerFactory.createMBeanServer(); MBeanServerFactory.releaseMBeanServer(server); } public void testFindMBeanServer() throws Exception { addPermission(new MBeanServerPermission("createMBeanServer")); MBeanServer server = MBeanServerFactory.createMBeanServer(); try { MBeanServerFactory.findMBeanServer(null); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanServerPermission("findMBeanServer")); ArrayList list = MBeanServerFactory.findMBeanServer(null); if (!list.contains(server)) fail(); // Clean up addPermission(new MBeanServerPermission("releaseMBeanServer")); MBeanServerFactory.releaseMBeanServer(server); } public void testAddRemoveNotificationListener() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testAddRemoveNotificationListener(server); } public void testCreateMBean4Params() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testCreateMBean4Params(server); } public void testCreateMBean5Params() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testCreateMBean5Params(server); } public void testGetAttribute() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetAttribute(server); } public void testGetAttributes() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetAttributes(server); } public void testGetDefaultDomain() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); String domain = "simon"; MBeanServer server = MBeanServerFactory.newMBeanServer(domain); testGetDefaultDomain(server, domain); } public void testGetDomains() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetDomains(server); } public void testGetMBeanCount() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetMBeanCount(server); } public void testGetMBeanInfo() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetMBeanInfo(server); } public void testGetObjectInstance() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testGetObjectInstance(server); } public void testInstantiate() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); String className = "java.lang.String"; try { server.instantiate(className, null); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(className, "instantiate")); server.instantiate(className, null); // Check also the overloaded version, we need an MLet String mletClassName = "javax.management.loading.MLet"; ObjectName name = new ObjectName(server.getDefaultDomain(), "mbean", "mlet"); resetPermissions(); addPermission(new MBeanPermission(mletClassName, "instantiate, registerMBean")); addPermission(new RuntimePermission("createClassLoader")); server.createMBean(mletClassName, name, null); try { server.instantiate(className, null); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(className, "instantiate")); server.instantiate(className, null); } public void testInvoke() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testInvoke(server); } public void testIsInstanceOf() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testIsInstanceOf(server); } public void testIsRegistered() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testIsRegistered(server); } public void testQueryMBeans() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testQueryMBeans(server); } public void testQueryNames() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testQueryNames(server); } public void testRegisterMBean() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); MBeanServerDelegate mbean = new MBeanServerDelegate(); ObjectName name = new ObjectName(server.getDefaultDomain(), "name", "test"); try { server.registerMBean(mbean, name); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(mbean.getClass().getName() + "[" + name.getCanonicalName() + "]", "registerMBean")); server.registerMBean(mbean, name); } public void testSetAttribute() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testSetAttribute(server); } public void testSetAttributes() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testSetAttributes(server); } public void testUnregisterMBean() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); testUnregisterMBean(server); } public void testGetClassLoader() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); // Needed to create an MLet, which is a ClassLoader addPermission(new RuntimePermission("createClassLoader")); ObjectName name = new ObjectName(server.getDefaultDomain(), "mbean", "mlet"); MLet mlet = new MLet(); addPermission(new MBeanPermission(mlet.getClass().getName(), "registerMBean")); server.registerMBean(mlet, name); try { server.getClassLoader(null); fail(); } catch (SecurityException ignored) { } // Dummy class addPermission(new MBeanPermission("foo[" + name.getCanonicalName() + "]", "getClassLoader")); try { server.getClassLoader(name); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(mlet.getClass().getName() + "[" + name.getCanonicalName() + "]", "getClassLoader")); ClassLoader result = server.getClassLoader(name); assertSame(result, mlet); } public void testGetClassLoaderFor() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName delegate = ObjectName.getInstance("JMImplementation", "type", "MBeanServerDelegate"); try { server.getClassLoaderFor(delegate); fail(); } catch (SecurityException x) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "getClassLoaderFor")); ClassLoader loader = server.getClassLoaderFor(delegate); assertNotNull(loader); } public void testGetClassLoaderRepository() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); MBeanServer server = MBeanServerFactory.newMBeanServer(); try { server.getClassLoaderRepository(); fail(); } catch (SecurityException x) { } addPermission(new MBeanPermission("*", "getClassLoaderRepository")); ClassLoaderRepository loader = server.getClassLoaderRepository(); assertNotNull(loader); } /** * A modifiable policy that allow permissions to be added at runtime, used for tests purposes only. */ public static class LocalModifiablePolicy extends Policy { private final ProtectionDomain testDomain; private final Map permissionsMap = new HashMap(); public LocalModifiablePolicy() { // Here we still have no security manager installed testDomain = LocalModifiablePolicy.class.getProtectionDomain(); // Add the permissions needed to run the tests CodeSource junitCodeSource = TestCase.class.getProtectionDomain().getCodeSource(); permissionsMap.put(junitCodeSource, createAllPermissions()); CodeSource mx4jCodeSource = MBeanServerFactory.class.getProtectionDomain().getCodeSource(); permissionsMap.put(mx4jCodeSource, createAllPermissions()); CodeSource implCodeSource = MX4JMBeanServer.class.getProtectionDomain().getCodeSource(); permissionsMap.put(implCodeSource, createAllPermissions()); // In the automated tests, the log classes may be taken from the JSR 160 jars. CodeSource logCodeSource = Log.class.getProtectionDomain().getCodeSource(); permissionsMap.put(logCodeSource, createAllPermissions()); ClassLoader loader = getClass().getClassLoader(); // BCEL try { Class cls = loader.loadClass("org.apache.bcel.generic.Type"); CodeSource bcelCodeSource = cls.getProtectionDomain().getCodeSource(); permissionsMap.put(bcelCodeSource, createAllPermissions()); } catch (ClassNotFoundException ignored) { } // When we run automated, we need also permissions for Ant jars try { Class cls = loader.loadClass("org.apache.tools.ant.Task"); CodeSource antCodeSource = cls.getProtectionDomain().getCodeSource(); permissionsMap.put(antCodeSource, createAllPermissions()); cls = loader.loadClass("org.apache.tools.ant.taskdefs.optional.junit.JUnitTask"); antCodeSource = cls.getProtectionDomain().getCodeSource(); permissionsMap.put(antCodeSource, createAllPermissions()); } catch (ClassNotFoundException ignored) { } initialize(); } private Permissions createAllPermissions() { Permissions allPermissions = new Permissions(); allPermissions.add(new AllPermission()); return allPermissions; } public PermissionCollection getPermissions(CodeSource codesource) { Permissions permissions = (Permissions)permissionsMap.get(codesource); if (permissions == null) { permissions = new Permissions(); permissionsMap.put(codesource, permissions); } return permissions; } public void refresh() { } /** * For JDK 1.4 overriding this method disables caching of Permissions done by the * standard Policy implementation. * This is done because we install this policy *before* installing the security manager. * By doing so, in JDK 1.4 the permissions granted at the moment of policy installation * (no security manager == AllPermission) are cached and will invalidate all tests, since * they will become unmodifiable. *

* The stack trace is when checking a permission is: *

* SecurityManager.checkPermission() * AccessController.checkPermission() * AccessControlContext.checkPermission() * ProtectionDomain.implies() * LocalModifiablePolicy.implies() */ public boolean implies(ProtectionDomain domain, Permission permission) { PermissionCollection perms = getPermissions(domain.getCodeSource()); return perms.implies(permission); } /** * Adds the given permission to the client (the test in this case) codesource */ public void addPermission(Permission p) { Permissions permissions = (Permissions)getPermissions(testDomain.getCodeSource()); permissions.add(p); } /** * Initializes the permissions for the client (the test in this case) codesource */ public synchronized void initialize() { Permissions permissions = new Permissions(); permissions.add(new SecurityPermission("getPolicy")); permissionsMap.put(testDomain.getCodeSource(), permissions); } } } mx4j-3.0.2/src/test/test/javax/management/MBeanComplianceTest.java100644 0 0 23674 10513545721 22216 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mx4j.MX4JSystemKeys; import mx4j.server.MBeanIntrospector; import mx4j.server.MBeanMetaData; import test.MX4JTestCase; import test.javax.management.support.ComplianceSupport; import javax.management.MBeanConstructorInfo; /** * @version $Revision: 1.10 $ */ public class MBeanComplianceTest extends MX4JTestCase { private MBeanIntrospector introspector; public MBeanComplianceTest(String s) { super(s); } protected void setUp() throws Exception { String property = MX4JSystemKeys.MX4J_STRICT_MBEAN_INTERFACE; System.setProperty(property, "no"); introspector = new MBeanIntrospector(); } protected void tearDown() throws Exception { introspector = null; } private MBeanMetaData createMBeanMetaData(Object mbean) throws Exception { MBeanMetaData metadata = MBeanMetaData.Factory.create(); metadata.setMBean(mbean); metadata.setClassLoader(mbean.getClass().getClassLoader()); return metadata; } private boolean isCompliant(Object mbean) throws Exception { Object metadata = createMBeanMetaData(mbean); Method method = introspector.getClass().getDeclaredMethod("testCompliance", new Class[]{MBeanMetaData.class}); method.setAccessible(true); Boolean value = (Boolean)method.invoke(introspector, new Object[]{metadata}); return value.booleanValue(); } private boolean isStandardCompliant(Object mbean) throws Exception { MBeanMetaData metadata = createMBeanMetaData(mbean); Method method = introspector.getClass().getDeclaredMethod("testCompliance", new Class[]{MBeanMetaData.class}); method.setAccessible(true); Boolean value = (Boolean)method.invoke(introspector, new Object[]{metadata}); return value.booleanValue() && metadata.isMBeanStandard() && !metadata.isMBeanDynamic() && metadata.getMBeanInterface() != null; } private boolean isDynamicCompliant(Object mbean) throws Exception { MBeanMetaData metadata = createMBeanMetaData(mbean); Method method = introspector.getClass().getDeclaredMethod("testCompliance", new Class[]{MBeanMetaData.class}); method.setAccessible(true); Boolean value = (Boolean)method.invoke(introspector, new Object[]{metadata}); return value.booleanValue() && !metadata.isMBeanStandard() && metadata.isMBeanDynamic(); } private Class getStandardManagementInterface(Object mbean) throws Exception { MBeanMetaData metadata = createMBeanMetaData(mbean); introspector.introspect(metadata); return metadata.getMBeanInterface(); } private Method[] getStandardManagementMethods(Object mbean) throws Exception { Class intf = getStandardManagementInterface(mbean); return intf.getMethods(); } public void testNotCompliantNoManagement() throws Exception { Object bad = new ComplianceSupport.NoManagement(); if (isCompliant(bad)) fail("MBean is not compliant"); } public void testNotCompliantLexicalPatternNotRespected() throws Exception { Object bad = new ComplianceSupport.DoesntRespectLexicalPattern(); if (isCompliant(bad)) fail("MBean is not compliant"); } public void testNotCompliantOverloadedAttributeSetSet() throws Exception { Object bad = new ComplianceSupport.OverloadedAttributeSetSet(); if (isCompliant(bad)) fail("MBean is not compliant"); } public void testNotCompliantOverloadedAttributeGetGet() throws Exception { // This is guaranteed by the Java compiler: a class with 2 getters that return different types // does not compile } public void testNotCompliantOverloadedAttribute3() throws Exception { Object bad = new ComplianceSupport.OverloadedAttributeGetSet(); if (isCompliant(bad)) fail("MBean is not compliant"); } public void testNotCompliantOverloadedAttribute4() throws Exception { Object bad = new ComplianceSupport.OverloadedAttributeIsGet(); if (isCompliant(bad)) fail("MBean is not compliant"); } public void testCompliantBasicStandard() throws Exception { Object good = new ComplianceSupport.BasicStandard(); if (!isStandardCompliant(good)) fail("MBean is compliant"); Method[] methods = ComplianceSupport.BasicStandardMBean.class.getMethods(); List list = Arrays.asList(methods); Method[] management = getStandardManagementMethods(good); List list2 = Arrays.asList(management); assertTrue("Different management interface", list.containsAll(list2) && list2.containsAll(list)); } public void testCompliantDerived() throws Exception { Object good = new ComplianceSupport.Derived(); if (!isStandardCompliant(good)) fail("MBean is compliant"); Method[] methods = ComplianceSupport.BasicStandardMBean.class.getMethods(); List list = Arrays.asList(methods); Method[] management = getStandardManagementMethods(good); List list2 = Arrays.asList(management); assertTrue("Different management interface", list.containsAll(list2) && list2.containsAll(list)); } public void testCompliantInherited() throws Exception { Object good = new ComplianceSupport.Inherited(); if (!isStandardCompliant(good)) fail("MBean is compliant"); Method[] methods = ComplianceSupport.InheritedMBean.class.getMethods(); List list = Arrays.asList(methods); Method[] management = getStandardManagementMethods(good); List list2 = Arrays.asList(management); assertTrue("Different management interface", list.containsAll(list2) && list2.containsAll(list)); } public void testCompliantNotInherited() throws Exception { Object good = new ComplianceSupport.NotInherited(); if (!isStandardCompliant(good)) fail("MBean is compliant"); Method[] methods = ComplianceSupport.BasicStandardMBean.class.getMethods(); List list = Arrays.asList(methods); Method[] management = getStandardManagementMethods(good); List list2 = Arrays.asList(management); assertTrue("Different management interface", list.containsAll(list2) && list2.containsAll(list)); } public void testCompliantMulti() throws Exception { Object good = new ComplianceSupport.Multi(); if (!isStandardCompliant(good)) fail("MBean is compliant"); Method[] methods = ComplianceSupport.BasicStandardMBean.class.getMethods(); List list = new ArrayList(); list.addAll(Arrays.asList(methods)); methods = ComplianceSupport.InheritedMBean.class.getMethods(); list.addAll(Arrays.asList(methods)); Method[] management = getStandardManagementMethods(good); List list2 = Arrays.asList(management); assertTrue("Different management interface", list.containsAll(list2) && list2.containsAll(list)); } public void testCompliantPackagePrivate() throws Exception { String clsName = "test.javax.management.support.ComplianceSupport$PackagePrivate"; Class cls = getClass().getClassLoader().loadClass(clsName); Constructor ctor = cls.getDeclaredConstructor(new Class[0]); ctor.setAccessible(true); Object good = ctor.newInstance(new Object[0]); if (!isStandardCompliant(good)) fail("MBean is compliant"); } public void testNotCompliantDynamicNoClassName() throws Exception { // In JMX 1.2 it is not possible to create an MBeanInfo with null class name Object mbean = new ComplianceSupport.NoClassNameDynamicMBean(); if (isCompliant(mbean)) fail(); } public void testCompliantBasicDynamic() throws Exception { Object mbean = new ComplianceSupport.BasicDynamic(); if (!isDynamicCompliant(mbean)) fail("MBean is compliant"); } public void testCompliantStandardAndDynamic() throws Exception { // JMX 1.0, this is invalid. For JMX 1.1 this is a dynamic MBean Object mbean = new ComplianceSupport.StandardAndDynamic(); if (!isDynamicCompliant(mbean)) fail("MBean is compliant"); Class intf = getStandardManagementInterface(mbean); if (intf != null) fail("MBean is dynamic"); } public void testCompliantStandardDynamic() throws Exception { // In JMX 1.0 this is an invalid MBean; in JMX 1.1 is a dynamic MBean Object mbean = new ComplianceSupport.StandardDynamic(); if (!isDynamicCompliant(mbean)) fail("MBean is compliant"); Class intf = getStandardManagementInterface(mbean); if (intf != null) fail("MBean is dynamic"); } public void testDynamicFromStandard() throws Exception { // A standard mbean subclassed to be dynamic Object mbean = new ComplianceSupport.DynamicFromStandard(); if (!isDynamicCompliant(mbean)) fail("MBean is compliant"); Class intf = getStandardManagementInterface(mbean); if (intf != null) fail("MBean is dynamic"); } public void testStandardFromDynamic() throws Exception { // A dynamic mbean subclassed to be standard, it remains a dynamic (as of JMX 1.1) Object mbean = new ComplianceSupport.StandardFromDynamic(); if (!isDynamicCompliant(mbean)) fail("MBean is compliant"); Class intf = getStandardManagementInterface(mbean); if (intf != null) fail("MBean is dynamic"); } public void testStandardConstructorInfo() throws Exception { Object mbean = new ComplianceSupport.BasicStandard(); MBeanMetaData md = createMBeanMetaData(mbean); introspector.introspect(md); MBeanConstructorInfo[] constructors = md.getMBeanInfo().getConstructors(); assertEquals(1, constructors.length); MBeanConstructorInfo info = constructors[0]; assertEquals(mbean.getClass().getName(), info.getName()); } } mx4j-3.0.2/src/test/test/javax/management/MBeanIntrospectionTest.java100644 0 0 3207 10513545721 22752 0ustar 0 0 /* ===================================================================== * * Copyright (c) 2004 Jeremy Boynes. All rights reserved. * * ===================================================================== */ package test.javax.management; import test.MX4JTestCase; import mx4j.server.MBeanIntrospector; import mx4j.server.MBeanMetaData; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; /** * @version $Revision: 1.1 $ $Date: 2005/02/08 04:11:49 $ */ public class MBeanIntrospectionTest extends MX4JTestCase { private MBeanIntrospector introspector; public MBeanIntrospectionTest(String name) { super(name); } public void testOperationInfo() throws Exception { MBeanInfo info = introspect(new Basic()); MBeanOperationInfo[] operations = info.getOperations(); assertEquals(1, operations.length); } private MBeanMetaData createMBeanMetaData(Object mbean) throws Exception { MBeanMetaData metadata = MBeanMetaData.Factory.create(); metadata.setMBean(mbean); metadata.setClassLoader(mbean.getClass().getClassLoader()); return metadata; } private MBeanInfo introspect(Object mbean) throws Exception { MBeanMetaData md = createMBeanMetaData(mbean); introspector.introspect(md); return md.getMBeanInfo(); } protected void setUp() throws Exception { introspector = new MBeanIntrospector(); } public static interface BasicMBean { boolean is(); } public static class Basic implements BasicMBean { public boolean is() { throw new UnsupportedOperationException(); } } } mx4j-3.0.2/src/test/test/javax/management/MBeanRegistrationTest.java100644 0 0 36262 10513545721 22613 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import javax.management.*; import javax.management.loading.MLet; import test.MX4JTestCase; import test.MutableBoolean; import test.MutableObject; import test.javax.management.support.RegistrationSupport; /** * @version $Revision: 1.13 $ */ public class MBeanRegistrationTest extends MX4JTestCase { public static interface BarMBean { int getBeer(); void getBEER(); int getBeer(String name); String[] get(); } public static class Bar implements BarMBean { public Bar() { } public String[] get() { return new String[0]; } public int getBeer() { return 0; } public void getBEER() { throw new java.lang.Error("No BEER here"); } public int getBeer(String name) { return 0; } } public MBeanRegistrationTest(String s) { super(s); } public void testNullObjectName() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); Object nullObjectName = new RegistrationSupport.NullObjectName(); try { server.registerMBean(nullObjectName, null); fail("MBean cannot be registered"); } catch (RuntimeOperationsException ignored) { } // Check that was not registered if (server.getMBeanCount().intValue() != count) { fail("MBean with null ObjectName was registered"); } } public void testPreRegisterException() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); Object preRegisterException = new RegistrationSupport.PreRegisterException(); try { server.registerMBean(preRegisterException, null); fail("MBean cannot be registered"); } catch (MBeanRegistrationException ignored) { } // Check that was not registered if (server.getMBeanCount().intValue() != count) { fail("MBean threw exception in preRegister, but was registered"); } } public void testPostRegisterException() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); Object postRegisterException = new RegistrationSupport.PostRegisterException(); ObjectName name = new ObjectName(":test=postRegister"); try { server.registerMBean(postRegisterException, name); fail("MBean must throw an exception"); } catch (RuntimeMBeanException ignored) { } // Check that was registered if (server.getMBeanCount().intValue() != count + 1) { fail("MBean threw exception in postRegister, but was NOT registered"); } } public void testPreDeregisterException() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); Object preDeregisterException = new RegistrationSupport.PreDeregisterException(); ObjectName name = new ObjectName("simon:mbean=test"); server.registerMBean(preDeregisterException, name); if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } try { server.unregisterMBean(name); fail("MBean cannot be unregistered"); } catch (MBeanRegistrationException ignored) { } if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was unregistered"); } } public void testPostDeregisterException() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); Object postDeregisterException = new RegistrationSupport.PostDeregisterException(); ObjectName name = new ObjectName("simon:mbean=test"); server.registerMBean(postDeregisterException, name); if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } try { server.unregisterMBean(name); fail("MBean must throw an exception"); } catch (RuntimeMBeanException ignored) { } if (server.getMBeanCount().intValue() != count) { fail("MBean was NOT unregistered"); } } public void testRegistration() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); final MutableBoolean bool1 = new MutableBoolean(false); final MutableBoolean bool2 = new MutableBoolean(false); Object empty = new RegistrationSupport.Empty(bool1, bool2); final ObjectName name = new ObjectName("simon:mbean=empty"); server.registerMBean(empty, name); // Check registration if (!bool1.get()) { fail("postRegister called with wrong argument value for successful registration"); } if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } } public void testDuplicateRegistration() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); final MutableBoolean bool1 = new MutableBoolean(false); final MutableBoolean bool2 = new MutableBoolean(false); Object empty = new RegistrationSupport.Empty(bool1, bool2); final ObjectName name = new ObjectName("simon:mbean=empty"); server.registerMBean(empty, name); if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } Object duplicate = new RegistrationSupport.EmptyDuplicate(name, bool1); try { server.registerMBean(duplicate, null); fail("MBean with same name cannot be registered"); } catch (InstanceAlreadyExistsException ignored) { } // Check that postRegister was called correctly if (bool1.get()) { fail("postRegister called with wrong argument value for unsuccessful registration"); } if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was registered, and it shouldn't"); } } public void testDeregistration() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); final MutableBoolean bool1 = new MutableBoolean(false); final MutableBoolean bool2 = new MutableBoolean(false); Object empty = new RegistrationSupport.Empty(bool1, bool2); final ObjectName name = new ObjectName("simon:mbean=empty"); server.registerMBean(empty, name); if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } bool1.set(true); bool2.set(true); server.unregisterMBean(name); if (server.getMBeanCount().intValue() != count) { fail("MBean was not unregistered"); } if (bool1.get() || bool2.get()) { fail("preDeregister or postDeregister are not called"); } } public void testDuplicateDeregistration() throws Exception { MBeanServer server = newMBeanServer(); int count = server.getMBeanCount().intValue(); final MutableBoolean bool1 = new MutableBoolean(false); final MutableBoolean bool2 = new MutableBoolean(false); Object empty = new RegistrationSupport.Empty(bool1, bool2); final ObjectName name = new ObjectName("simon:mbean=empty"); server.registerMBean(empty, name); if (server.getMBeanCount().intValue() != count + 1) { fail("MBean was not registered"); } bool1.set(true); bool2.set(true); server.unregisterMBean(name); if (server.getMBeanCount().intValue() != count) { fail("MBean was not unregistered"); } if (bool1.get() || bool2.get()) { fail("preDeregister or postDeregister are not called"); } // Try again try { server.unregisterMBean(name); fail("Already unregistered MBean can be unregistered"); } catch (InstanceNotFoundException ignored) { } } public void testNotificationDuringRegistrationForStdMBean() throws Exception { final MBeanServer server = newMBeanServer(); Object mbean = new RegistrationSupport.Std(); final ObjectName name = new ObjectName(":mbean=std"); server.addNotificationListener(new ObjectName("JMImplementation:type=MBeanServerDelegate"), new NotificationListener() { public void handleNotification(Notification notification, Object handback) { invokeOperationsDuringRegistration(server, name, notification); } }, null, null); server.registerMBean(mbean, name); } public void testNotificationDuringRegistrationForDynMBean() throws Exception { final MBeanServer server = newMBeanServer(); Object mbean = new RegistrationSupport.Dyn(); final ObjectName name = new ObjectName(":mbean=dyn"); server.addNotificationListener(new ObjectName("JMImplementation:type=MBeanServerDelegate"), new NotificationListener() { public void handleNotification(Notification notification, Object handback) { invokeOperationsDuringRegistration(server, name, notification); } }, null, null); server.registerMBean(mbean, name); } private void invokeOperationsDuringRegistration(MBeanServer server, ObjectName name, Notification notification) { if (notification != null) { MBeanServerNotification notif = (MBeanServerNotification)notification; ObjectName registered = notif.getMBeanName(); if (!registered.equals(name)) fail("Notification for the wrong MBean: " + registered + ", should be " + name); if (!MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notif.getType())) fail("Expecting a registration notification"); } try { MBeanInfo info = server.getMBeanInfo(name); if (info.getClassName() == null) fail("MBeanInfo not initialized correctly"); if (info.getOperations().length == 0) fail("MBeanInfo not initialized correctly"); ObjectInstance instance = server.getObjectInstance(name); if (instance == null) fail("ObjectInstance should be already initialized"); boolean isRegistered = server.isRegistered(name); if (!isRegistered) fail("MBean is registered"); // Must be able to invoke it with no exceptions server.invoke(name, RegistrationSupport.StdMBean.class.getMethods()[0].getName(), null, null); } catch (Exception x) { fail("MBean metadata structures are not yet ready, but they should be: " + x); } } public void testInvokeMBeanServerOperationsInCallbacks() throws Exception { MBeanServer server = newMBeanServer(); Object mbean = new InvokeDuringCallbacks(); ObjectName name = ObjectName.getInstance(":name=invoke"); server.registerMBean(mbean, name); server.unregisterMBean(name); } public interface InvokeDuringCallbacksMBean { public void method(); } public class InvokeDuringCallbacks implements InvokeDuringCallbacksMBean, MBeanRegistration { private MBeanServer server; private ObjectName name; public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; this.name = name; return name; } public void postRegister(Boolean registrationDone) { invokeOperationsDuringRegistration(server, name, null); } public void preDeregister() throws Exception { invokeOperationsDuringRegistration(server, name, null); } public void postDeregister() { } public void method() { } } public void testDistinguishAttributesOperations() throws Exception { MBeanServer server = newMBeanServer(); ObjectName objname = new ObjectName("tests:id=distinguishAttributesOperations"); Bar b = new Bar(); server.registerMBean(b, objname); MBeanInfo info = server.getMBeanInfo(objname); assertTrue("Expecting one attribute", info.getAttributes().length == 1); try { assertTrue("No 'Beer' attribute", ((Integer)server.getAttribute(objname, "Beer")).intValue() == 0); String[] getresult = (String[])server.invoke(objname, "get", new Object[0], new String[0]); assertTrue("Expecting zero length result", getresult.length == 0); server.getAttribute(objname, "BEER"); fail("Expecting AttributeNotFoundException"); } catch (AttributeNotFoundException x) { assertTrue(true); } assertTrue("Expecting three operations", info.getOperations().length == 3); } public void testListenerRegistrationUnregistrationDuringCallbacks() throws Exception { MBeanServer server = newMBeanServer(); MutableObject holder = new MutableObject(null); Object mbean = new RegistrationSupport.ListenerRegistrar(holder); ObjectName name = ObjectName.getInstance("test:type=notifications"); server.registerMBean(mbean, name); // Register a new MBean, the holder must be notified ObjectName mlet = ObjectName.getInstance("test:type=mlet"); server.createMBean(MLet.class.getName(), mlet, null); Notification notification = (Notification)holder.get(); assertNotNull(notification); assertEquals(notification.getType(), MBeanServerNotification.REGISTRATION_NOTIFICATION); holder.set(null); server.unregisterMBean(mlet); notification = (Notification)holder.get(); assertNotNull(notification); assertEquals(notification.getType(), MBeanServerNotification.UNREGISTRATION_NOTIFICATION); holder.set(null); // Unregisters also the listeners (in postDeregister) server.unregisterMBean(name); notification = (Notification)holder.get(); assertNotNull(notification); assertEquals(notification.getType(), MBeanServerNotification.UNREGISTRATION_NOTIFICATION); holder.set(null); server.createMBean(MLet.class.getName(), mlet, null); notification = (Notification)holder.get(); assertNull(notification); server.unregisterMBean(mlet); notification = (Notification)holder.get(); assertNull(notification); } public void testAbstractClass() throws Exception { MBeanServer server = newMBeanServer(); try { server.createMBean(Foo.class.getName(), null); fail(); } catch (NotCompliantMBeanException e) { // ok } catch (Exception e) { e.printStackTrace(); fail(); } } public static interface FooMBean { void something(); } public static abstract class Foo implements FooMBean { public void something() { } } } mx4j-3.0.2/src/test/test/javax/management/MBeanServerBuilderTest.java100644 0 0 22077 10513545721 22715 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.lang.reflect.Method; import java.util.HashMap; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MBeanServerBuilder; import javax.management.MBeanServerDelegate; import javax.management.ObjectName; import javax.management.ReflectionException; import mx4j.server.ChainedMBeanServer; import mx4j.server.ChainedMBeanServerBuilder; import mx4j.server.MX4JMBeanServer; import mx4j.server.MX4JMBeanServerBuilder; import mx4j.server.MX4JMBeanServerDelegate; import test.MX4JTestCase; /** * @version $Revision: 1.6 $ */ public class MBeanServerBuilderTest extends MX4JTestCase { private static final String INITIAL_BUILDER = "javax.management.builder.initial"; public MBeanServerBuilderTest(String s) { super(s); } public void testDefaultBuilder() throws Exception { System.getProperties().remove(INITIAL_BUILDER); MBeanServer server = newMBeanServer(); if (!(server instanceof MX4JMBeanServer)) fail("Wrong default server implementation"); } public void testCustomBuilder() throws Exception { try { System.setProperty(INITIAL_BUILDER, CustomBuilder.class.getName()); MBeanServer server = newMBeanServer(); if (!(server instanceof CustomMBeanServer)) fail("Wrong custom server implementation"); if (!server.isInstanceOf(new ObjectName("JMImplementation", "type", "MBeanServerDelegate"), CustomDelegate.class.getName())) fail("wrong delegate implementation"); } finally { System.getProperties().remove(INITIAL_BUILDER); } } public void testMX4JunderJMXRI() throws Exception { ClassLoader jmxriLoader = createJMXRIWithMX4JImplClassLoader(); Class jmxri_c_mBeanServerFactory = jmxriLoader.loadClass("javax.management.MBeanServerFactory"); Method jmxri_m_newMBeanServer = jmxri_c_mBeanServerFactory.getMethod("newMBeanServer", new Class[0]); System.getProperties().remove(INITIAL_BUILDER); Object jmxri_MBeanServer = jmxri_m_newMBeanServer.invoke(null, new Object[0]); boolean isJMXRImBeanServer = jmxri_MBeanServer.getClass().getName().startsWith("com.sun.jmx."); if (!isJMXRImBeanServer) fail("Failed to make use of JMXRI classes"); final ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader(); try { System.setProperty(INITIAL_BUILDER, MX4JMBeanServerBuilder.class.getName()); Thread.currentThread().setContextClassLoader(jmxriLoader); Object mx4j_MBeanServer = jmxri_m_newMBeanServer.invoke(null, new Object[0]); boolean isMX4JMBeanServer = mx4j_MBeanServer.getClass().getName().startsWith("mx4j.server."); if (!isMX4JMBeanServer) fail("Not using MX4J as specified by javax.management.builder.initial"); } finally { System.getProperties().remove(INITIAL_BUILDER); Thread.currentThread().setContextClassLoader(oldContextLoader); } } public void testChainedMBeanServerBuilder() throws Exception { try { System.setProperty(INITIAL_BUILDER, ComplexBuilder.class.getName()); MBeanServer server = newMBeanServer(); if (!(server instanceof LoggingMBeanServer)) fail(); server.registerMBean(new Simple(), new ObjectName(":mbean=simple")); Object vendor = server.getAttribute(new ObjectName("JMImplementation", "type", "MBeanServerDelegate"), "ImplementationVendor"); if (!(vendor instanceof HashMap)) fail(); if (((HashMap)vendor).size() != 4) fail(); } finally { System.getProperties().remove(INITIAL_BUILDER); } } // Support classes /** * This is a simple terminal builder, that is a builder that creates a full MBeanServer implementation. * It cannot be used to chain other builders, it can only be used as the last builder in the chain. */ public static class CustomBuilder extends MBeanServerBuilder { public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate) { return new CustomMBeanServer(defaultDomain, outer, delegate); } public MBeanServerDelegate newMBeanServerDelegate() { return new CustomDelegate(); } } /** * Custom delegate class, for testing. */ public static class CustomDelegate extends MX4JMBeanServerDelegate { } public static class CustomMBeanServer extends MX4JMBeanServer { public CustomMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate) { super(defaultDomain, outer, delegate); } } public static class ComplexBuilder extends ChainedMBeanServerBuilder { public ComplexBuilder() { super(new LoggingBuilder(new PerformanceBuilder(new MX4JMBeanServerBuilder()))); } } public static class LoggingBuilder extends ChainedMBeanServerBuilder { public LoggingBuilder(MBeanServerBuilder chain) { super(chain); } public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate) { LoggingMBeanServer external = new LoggingMBeanServer(); MBeanServer nested = getMBeanServerBuilder().newMBeanServer(defaultDomain, outer == null ? external : outer, delegate); external.setMBeanServer(nested); return external; } } public static class PerformanceBuilder extends ChainedMBeanServerBuilder { public PerformanceBuilder(MBeanServerBuilder chain) { super(chain); } public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate) { TimingMBeanServer external = new TimingMBeanServer(); MBeanServer nested = getMBeanServerBuilder().newMBeanServer(defaultDomain, outer == null ? external : outer, delegate); external.setMBeanServer(new InvocationCounterMBeanServer(nested)); return external; } } public static class LoggingMBeanServer extends ChainedMBeanServer { protected void setMBeanServer(MBeanServer server) { super.setMBeanServer(server); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { HashMap map = (HashMap)super.getAttribute(objectName, attribute); map.put("logged", "logged"); return map; } } public static class TimingMBeanServer extends ChainedMBeanServer { protected void setMBeanServer(MBeanServer server) { super.setMBeanServer(server); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { long start = System.currentTimeMillis(); HashMap ret = (HashMap)super.getAttribute(objectName, attribute); long end = System.currentTimeMillis(); long elapsed = end - start; System.out.println("Elapsed: " + elapsed); ret.put("elapsed", new Long(elapsed)); return ret; } } public static class InvocationCounterMBeanServer extends ChainedMBeanServer { private ThreadLocal getAttributeCount = new ThreadLocal() { protected Object initialValue() { return new Long(0); } }; public InvocationCounterMBeanServer(MBeanServer server) { super(server); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { Long count = (Long)getAttributeCount.get(); count = new Long(count.longValue() + 1); getAttributeCount.set(count); System.out.println("Counted: " + count); HashMap map = new HashMap(); map.put("result", super.getAttribute(objectName, attribute)); map.put("count", count); return map; } } public interface SimpleMBean { } public static class Simple implements SimpleMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if (!(server instanceof LoggingMBeanServer)) fail(); return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } } } mx4j-3.0.2/src/test/test/javax/management/MBeanServerFactoryTest.java100644 0 0 11706 10513545721 22733 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.List; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import junit.framework.TestCase; /** * @version $Revision: 1.7 $ */ public class MBeanServerFactoryTest extends TestCase { public MBeanServerFactoryTest(String s) { super(s); } public void testCreate() throws Exception { MBeanServer server1 = null; try { System.out.print("Creating MBeanServer 1 ... "); server1 = MBeanServerFactory.createMBeanServer(); System.out.println("OK"); System.out.print("Finding MBeanServer... "); List l = MBeanServerFactory.findMBeanServer(null); if (l.size() != 1) { fail("MBeanServer creation is not tracked"); } if (!server1.equals(l.get(0))) { fail("MBeanServer found is different"); } System.out.println("Found, OK"); } finally { MBeanServerFactory.releaseMBeanServer(server1); } } public void testNew() throws Exception { MBeanServer server1 = null; try { System.out.print("Creating MBeanServer 1 ... "); server1 = MBeanServerFactory.createMBeanServer(); System.out.println("OK"); // newMBeanServer must not keep track of the MBeanServer it creates System.out.print("Newing MBeanServer 2 ... "); MBeanServer server2 = MBeanServerFactory.newMBeanServer(); System.out.println("OK"); System.out.print("Finding MBeanServer... "); List l = MBeanServerFactory.findMBeanServer(null); if (l.size() != 1) { fail("newMBeanServer tracks creation"); } if (!server1.equals(l.get(0))) { fail("MBeanServer found is different"); } System.out.println("Found number 1, OK"); } finally { MBeanServerFactory.releaseMBeanServer(server1); } } public void testCreateWithDomain() { MBeanServer server1 = null; MBeanServer server3 = null; try { System.out.print("Creating MBeanServer 1 ... "); server1 = MBeanServerFactory.createMBeanServer(); System.out.println("OK"); String domain = "test"; System.out.print("Creating MBeanServer 3 ... "); server3 = MBeanServerFactory.createMBeanServer(domain); System.out.println("OK"); System.out.print("Finding MBeanServer... "); List l = MBeanServerFactory.findMBeanServer(null); if (l.size() != 2) { fail("MBeanServer creation is not tracked"); } MBeanServer found1 = (MBeanServer)l.get(0); if (!found1.getDefaultDomain().equals(server1.getDefaultDomain())) { fail("MBeanServer found is different"); } if (!server3.equals(l.get(1))) { fail("MBeanServer found is different"); } if (!server3.getDefaultDomain().equals(domain)) { fail("Domain is different"); } System.out.println("Found number 1 & 3, OK"); } finally { MBeanServerFactory.releaseMBeanServer(server1); MBeanServerFactory.releaseMBeanServer(server3); } } public void testRelease() throws Exception { System.out.print("Creating MBeanServer 1 ... "); MBeanServer server1 = MBeanServerFactory.createMBeanServer(); System.out.println("OK"); System.out.print("Creating MBeanServer 2 ... "); String domain = "test"; MBeanServer server2 = MBeanServerFactory.createMBeanServer(domain); System.out.println("OK"); System.out.print("Releasing MBeanServer 1 ... "); List l = MBeanServerFactory.findMBeanServer(null); MBeanServer found1 = (MBeanServer)l.get(0); MBeanServerFactory.releaseMBeanServer(found1); System.out.println("OK"); System.out.print("Finding MBeanServer... "); l = MBeanServerFactory.findMBeanServer(null); if (l.size() != 1) { fail("Removed MBeanServer still present"); } MBeanServer found2 = (MBeanServer)l.get(0); if (!found2.getDefaultDomain().equals(domain)) { fail("Removed wrong MBeanServer"); } System.out.println("Found number 2, OK"); System.out.print("Releasing MBeanServer 2 ... "); MBeanServerFactory.releaseMBeanServer(found2); System.out.println("OK"); System.out.print("Finding MBeanServer... "); l = MBeanServerFactory.findMBeanServer(null); if (l.size() != 0) { fail("Removed MBeanServer still present"); } System.out.println("Found none, OK"); } } mx4j-3.0.2/src/test/test/javax/management/MBeanServerInvocationHandlerTest.java100644 0 0 43732 10513545721 24737 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationBroadcaster; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.naming.NamingException; import test.MX4JTestCase; /** * @version $Revision: 1.8 $ */ public class MBeanServerInvocationHandlerTest extends MX4JTestCase { public MBeanServerInvocationHandlerTest(String s) { super(s); } public void testBadArguments() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); try { MBeanServerInvocationHandler.newProxyInstance(null, name, LocalServiceMBean.class, false); fail("MBeanServerConnection cannot be null"); } catch (IllegalArgumentException x) { } try { MBeanServerInvocationHandler.newProxyInstance(server, null, LocalServiceMBean.class, false); fail("ObjectName cannot be null"); } catch (IllegalArgumentException x) { } try { MBeanServerInvocationHandler.newProxyInstance(server, name, null, false); fail("Class cannot be null"); } catch (IllegalArgumentException x) { } try { MBeanServerInvocationHandler.newProxyInstance(server, name, LocalService.class, false); fail("Class must be an interface"); } catch (IllegalArgumentException x) { } } public void testMBeanNotAnEmitter() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); NotificationEmitter emitter = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, true); try { emitter.addNotificationListener(new TestListener(), null, null); fail("The MBean is not a NotificationEmitter"); } catch (IllegalArgumentException x) { } } public void testDeregisteredMBean() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); // Check what the proxy throws if the ObjectName is removed from the server LocalServiceMBean proxy = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, false); server.unregisterMBean(name); try { proxy.throwCheckedException(); fail(); } catch (NamingException x) { fail("Expecting an InstanceNotFoundException"); } catch (UndeclaredThrowableException x) { Throwable xx = x.getUndeclaredThrowable(); if (!(xx instanceof InstanceNotFoundException)) fail("Expecting an InstanceNotFoundException"); } } public void testCheckedException() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); LocalServiceMBean proxy = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, false); try { proxy.throwCheckedException(); fail(); } catch (NamingException x) { } } public void testMBeanException() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); LocalServiceMBean proxy = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, false); try { proxy.throwMBeanException(); fail(); } catch (MBeanException x) { } } public void testRuntimeException() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); LocalServiceMBean proxy = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, false); try { proxy.throwNullPointerException(); fail(); } catch (NullPointerException x) { } } public void testError() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); LocalServiceMBean proxy = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LocalServiceMBean.class, false); try { proxy.throwError(); fail(); } catch (Error x) { } } public void testNotificationBroadcasterProxy() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalBroadcasterService mbean = new LocalBroadcasterService(); server.registerMBean(mbean, name); // The returned interface should be NotificationEmitter, even though the MBean only implements NotificationBroadcaster NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationBroadcaster.class, true); assertNotNull(proxy); } public void testAddNotificationListener() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalEmitterService mbean = new LocalEmitterService(); server.registerMBean(mbean, name); NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationEmitter.class, true); TestListener listener = new TestListener(); proxy.addNotificationListener(listener, null, null); mbean.test(); if (!listener.received) fail(); } public void testGetNotificationInfo() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalEmitterService mbean = new LocalEmitterService(); server.registerMBean(mbean, name); NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationEmitter.class, true); MBeanNotificationInfo[] infos = proxy.getNotificationInfo(); if (!infos[0].getDescription().equals(LocalEmitterService.DESC)) fail(); } public void testSimpleRemoveNotificationListener() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalEmitterService mbean = new LocalEmitterService(); server.registerMBean(mbean, name); NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationEmitter.class, true); TestListener listener = new TestListener(); proxy.addNotificationListener(listener, null, null); proxy.removeNotificationListener(listener); mbean.test(); if (listener.received) fail(); } public void testRemoveNotificationListener() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalEmitterService mbean = new LocalEmitterService(); server.registerMBean(mbean, name); NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationEmitter.class, true); TestListener listener = new TestListener(); TestFilter filter = new TestFilter(); Object handback = new Object(); proxy.addNotificationListener(listener, filter, handback); proxy.removeNotificationListener(listener, filter, handback); mbean.test(); if (listener.received) fail(); } public void testRemoveMultiNotificationListener() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalEmitterService mbean = new LocalEmitterService(); server.registerMBean(mbean, name); NotificationEmitter proxy = (NotificationEmitter)MBeanServerInvocationHandler.newProxyInstance(server, name, NotificationEmitter.class, true); TestListener listener1 = new TestListener(); TestFilter filter = new TestFilter(); Object handback = new Object(); proxy.addNotificationListener(listener1, filter, handback); TestListener listener2 = new TestListener(); proxy.addNotificationListener(listener2, null, null); mbean.test(); if (!listener1.received) fail(); if (!listener2.received) fail(); try { proxy.removeNotificationListener(listener2, filter, handback); fail("Listener is not registered"); } catch (ListenerNotFoundException x) { } proxy.removeNotificationListener(listener2, null, null); listener1.received = false; listener2.received = false; mbean.test(); if (!listener1.received) fail(); if (listener2.received) fail(); } public void testRemoteExceptionWithRemoteInterface() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); RemoteService remoteMBean = (RemoteService)MBeanServerInvocationHandler.newProxyInstance(mbsc, name, RemoteService.class, false); // Close everything to get IOException cntor.close(); cntorServer.stop(); try { remoteMBean.throwCheckedException(); fail("Must not be able to connect"); } catch (IOException x) { } } public void testRemoteExceptionWithLocalInterface() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); LocalServiceMBean remoteMBean = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalServiceMBean.class, false); // Close everything to get IOException cntor.close(); cntorServer.stop(); // Now try the local interface try { remoteMBean.throwCheckedException(); fail("Must not be able to connect"); } catch (UndeclaredThrowableException x) { Throwable xx = x.getUndeclaredThrowable(); if (!(xx instanceof IOException)) fail(); } } public void testRemoteCheckedException() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("domain:key=value"); LocalService mbean = new LocalService(); server.registerMBean(mbean, name); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); LocalServiceMBean remoteMBean = (LocalServiceMBean)MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalServiceMBean.class, false); try { remoteMBean.throwCheckedException(); fail(); } catch (NamingException x) { } } public interface LocalServiceMBean { public void throwCheckedException() throws NamingException; public void throwMBeanException() throws MBeanException; public void throwNullPointerException(); public void throwError(); } public interface RemoteService { public void throwCheckedException() throws NamingException, IOException; public void throwMBeanException() throws MBeanException, IOException; public void throwNullPointerException() throws IOException; public void throwError() throws IOException; } public class LocalService implements LocalServiceMBean { public void throwCheckedException() throws NamingException { throw new NamingException(); } public void throwMBeanException() throws MBeanException { throw new MBeanException(new Exception()); } public void throwNullPointerException() { throw new NullPointerException(); } public void throwError() { throw new Error(); } } public class LocalBroadcasterService extends LocalService implements NotificationBroadcaster { private NotificationBroadcasterSupport support = new NotificationBroadcasterSupport(); static final String TYPE = "test.notification"; static final String DESC = "Test Notification"; private long sequence; /** * @see javax.management.NotificationBroadcaster#addNotificationListener(NotificationListener, NotificationFilter, Object) */ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { support.addNotificationListener(listener, filter, handback); } /** * @see javax.management.NotificationBroadcaster#getNotificationInfo() */ public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[]{ new MBeanNotificationInfo(new String[]{TYPE}, Notification.class.getName(), DESC), }; } /** * @see javax.management.NotificationBroadcaster#removeNotificationListener(NotificationListener) */ public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { support.removeNotificationListener(listener); } public void test() { Notification notification = new Notification(TYPE, this, ++sequence, System.currentTimeMillis(), DESC); support.sendNotification(notification); } } public class LocalEmitterService extends LocalService implements NotificationEmitter { private NotificationBroadcasterSupport support = new NotificationBroadcasterSupport(); static final String TYPE = "test.notification"; static final String DESC = "Test Notification"; private long sequence; public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { support.addNotificationListener(listener, filter, handback); } public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[]{ new MBeanNotificationInfo(new String[]{TYPE}, Notification.class.getName(), DESC), }; } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { support.removeNotificationListener(listener); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { support.removeNotificationListener(listener, filter, handback); } public void test() { Notification notification = new Notification(TYPE, this, ++sequence, System.currentTimeMillis(), DESC); support.sendNotification(notification); } } public class TestListener implements NotificationListener { boolean received = false; public void handleNotification(Notification notification, Object handback) { received = true; } } public class TestFilter implements NotificationFilter { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(LocalEmitterService.TYPE); } } } mx4j-3.0.2/src/test/test/javax/management/MBeanServerPermissionTest.java100644 0 0 11000 10513545721 23437 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.management.MBeanServerPermission; /** * @version $Revision: 1.9 $ */ public class MBeanServerPermissionTest extends PermissionTestCase { public MBeanServerPermissionTest(String s) { super(s); } public void testInvalid() throws Exception { try { new MBeanServerPermission(null); fail("Invalid MBeanServerPermission"); } catch (NullPointerException ignored) { } try { new MBeanServerPermission(""); fail("Invalid MBeanServerPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanServerPermission(" "); fail("Invalid MBeanServerPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanServerPermission(" , "); fail("Invalid MBeanServerPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanServerPermission("invalid"); fail("Invalid MBeanServerPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanServerPermission("*", "invalid"); fail("Invalid MBeanServerPermission"); } catch (IllegalArgumentException ignored) { } } public void testValid() throws Exception { new MBeanServerPermission("*"); new MBeanServerPermission("*", ""); new MBeanServerPermission("createMBeanServer"); new MBeanServerPermission("releaseMBeanServer, findMBeanServer"); new MBeanServerPermission("newMBeanServer, *"); } public void testShuffledAreEquals() throws Exception { MBeanServerPermission mbsp1 = new MBeanServerPermission("createMBeanServer, releaseMBeanServer"); MBeanServerPermission mbsp2 = new MBeanServerPermission("releaseMBeanServer, createMBeanServer"); shouldBeEqual(mbsp1, mbsp2); MBeanServerPermission mbsp3 = new MBeanServerPermission("*"); MBeanServerPermission mbsp4 = new MBeanServerPermission("releaseMBeanServer, *"); shouldBeEqual(mbsp3, mbsp4); } public void testCreateImpliesNew() throws Exception { shouldImply(new MBeanServerPermission("createMBeanServer"), new MBeanServerPermission("newMBeanServer")); } public void testImplies() throws Exception { shouldImply(new MBeanServerPermission("*"), new MBeanServerPermission("createMBeanServer")); shouldImply(new MBeanServerPermission("*"), new MBeanServerPermission("newMBeanServer")); shouldImply(new MBeanServerPermission("*"), new MBeanServerPermission("findMBeanServer")); shouldImply(new MBeanServerPermission("*"), new MBeanServerPermission("releaseMBeanServer")); shouldImply(new MBeanServerPermission("*"), new MBeanServerPermission("createMBeanServer, releaseMBeanServer")); shouldImply(new MBeanServerPermission("createMBeanServer, releaseMBeanServer"), new MBeanServerPermission("createMBeanServer")); shouldImply(new MBeanServerPermission("createMBeanServer, releaseMBeanServer"), new MBeanServerPermission("releaseMBeanServer")); } public void testNotImplies() { shouldNotImply(new MBeanServerPermission("createMBeanServer"), new MBeanServerPermission("releaseMBeanServer")); shouldNotImply(new MBeanServerPermission("createMBeanServer"), new MBeanServerPermission("newMBeanServer, releaseMBeanServer")); } public void testSerializationDeserialization() throws Exception { MBeanServerPermission permission = new MBeanServerPermission("newMBeanServer, *"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(permission); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); MBeanServerPermission deserialized = (MBeanServerPermission)ois.readObject(); ois.close(); if (!(deserialized.equals(permission))) fail("Serialization/Deserialization failed"); } } mx4j-3.0.2/src/test/test/javax/management/MBeanServerTest.java100644 0 0 32046 10513545721 21403 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.Set; import javax.management.JMRuntimeException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.MBeanServerDelegate; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.RuntimeOperationsException; import test.MX4JTestCase; import test.MutableInteger; import test.javax.management.support.ClassLoaderSupport; import test.javax.management.support.ComplianceSupport; import test.javax.management.support.MBeanThrowingExceptions; import test.javax.management.support.NotificationSupport; import test.javax.management.support.PostRegistrationSupport; /** * @version $Revision: 1.12 $ */ public class MBeanServerTest extends MX4JTestCase { public MBeanServerTest(String s) { super(s); } public void testDefaultDomainConversion() throws Exception { String domain = "test"; MBeanServer server = MBeanServerFactory.newMBeanServer(domain); // Every operation with default domain must match the one with the // explicit domain ObjectName defaultName = new ObjectName(":key=value"); ObjectName explicitName = new ObjectName(server.getDefaultDomain(), "key", "value"); // A broadcaster mbean MBeanServerDelegate broadcaster = new MBeanServerDelegate(); // Register with the explicit object name server.registerMBean(broadcaster, explicitName); // Query Set set = server.queryNames(defaultName, null); if (set.size() != 1) { fail("Default domain not handled in ObjectNames"); } // Register and remove a listener NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; server.addNotificationListener(defaultName, listener, null, null); // Remove throws if the listener is not found server.removeNotificationListener(defaultName, listener); // Invoke operations server.getAttribute(defaultName, "MBeanServerId"); // Metadata server.getMBeanInfo(defaultName); server.getObjectInstance(defaultName); if (!server.isRegistered(defaultName)) { fail("Default domain not handled in ObjectNames"); } server.isInstanceOf(defaultName, "javax.management.MBeanServerDelegateMBean"); } public void testRegistrationOfJMImplementationDomain() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); // Test that MBeans with reserved object names cannot be registered Object mbean = new ComplianceSupport.BasicStandard(); ObjectName reserved = new ObjectName("JMImplementation:simon=true"); try { server.registerMBean(mbean, reserved); fail("MBeans with reserved object names cannot be registered"); } catch (JMRuntimeException ignored) { } } public void testDeregistrationOfJMImplementationDomain() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); // Test that the delegate MBean cannot be unregistered ObjectName delegate = new ObjectName("JMImplementation:type=MBeanServerDelegate"); try { server.unregisterMBean(delegate); fail("Delegate MBean cannot be unregistered"); } catch (RuntimeOperationsException ignored) { } } public void testDelegateID() throws Exception { ObjectName delegate = new ObjectName("JMImplementation:type=MBeanServerDelegate"); MBeanServer server1 = MBeanServerFactory.newMBeanServer(); MBeanServer server2 = MBeanServerFactory.newMBeanServer(); String id1 = (String)server1.getAttribute(delegate, "MBeanServerId"); String id2 = (String)server2.getAttribute(delegate, "MBeanServerId"); // Be sure they're different if (id1.equals(id2)) fail("MBeanServer ID must differ"); } public void testAddRemoveListenerOnMultipleMBeans() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name1 = new ObjectName("domain:key=mbean1"); ObjectName name2 = new ObjectName("domain:key=mbean2"); NotificationBroadcasterSupport mbean1 = new NotificationSupport.Emitter(); NotificationBroadcasterSupport mbean2 = new NotificationSupport.Emitter(); server.registerMBean(mbean1, name1); server.registerMBean(mbean2, name2); final MutableInteger integer = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { integer.set(integer.get() + 1); } }; server.addNotificationListener(name1, listener, null, null); server.addNotificationListener(name2, listener, null, null); Notification notification = new Notification("test", mbean1, 1); mbean1.sendNotification(notification); // Be sure the listener is called assertEquals("Listener is not called", integer.get(), 1); mbean2.sendNotification(notification); // Be sure the listener is called assertEquals("Listener is not called", integer.get(), 2); // Remove one listener server.removeNotificationListener(name1, listener); // Be sure it is not called mbean1.sendNotification(notification); assertEquals("Listener is called", integer.get(), 2); // Be sure it is called mbean2.sendNotification(notification); assertEquals("Listener is not called", integer.get(), 3); try { server.removeNotificationListener(name1, listener); fail("Listener has been removed"); } catch (ListenerNotFoundException ignored) { } // Remove also the second listener server.removeNotificationListener(name2, listener); // Be sure it is not called mbean2.sendNotification(notification); assertEquals("Listener is called", integer.get(), 3); } public void testAddRemoveMixedListenerOnMultipleMBeans() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name1 = new ObjectName("domain:key=mbean1"); ObjectName name2 = new ObjectName("domain:key=mbean2"); NotificationBroadcasterSupport mbean1 = new NotificationSupport.Emitter(); NotificationBroadcasterSupport mbean2 = new NotificationSupport.Emitter(); server.registerMBean(mbean1, name1); server.registerMBean(mbean2, name2); final MutableInteger integer = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { integer.set(integer.get() + 1); } }; server.addNotificationListener(name1, listener, null, null); server.addNotificationListener(name2, listener, null, null); mbean2.addNotificationListener(listener, null, null); Notification notification = new Notification("test", mbean1, 1); mbean1.sendNotification(notification); // Be sure the listener is called assertEquals("Listener is not called", integer.get(), 1); mbean2.sendNotification(notification); // Be sure the listeners are called assertEquals("Listeners are not called", integer.get(), 3); // Remove one listener server.removeNotificationListener(name2, listener); // Be sure the listener is called mbean2.sendNotification(notification); assertEquals("Listener is not called", integer.get(), 4); // Be sure it is called mbean1.sendNotification(notification); assertEquals("Listener is not called", integer.get(), 5); server.removeNotificationListener(name1, listener); // Be sure it is not called mbean1.sendNotification(notification); assertEquals("Listener is called", integer.get(), 5); // Be sure it is called mbean2.sendNotification(notification); assertEquals("Listener is not called", integer.get(), 6); try { server.removeNotificationListener(name2, listener); fail("Listener has been removed"); } catch (ListenerNotFoundException ignored) { } // Remove also the second listener mbean2.removeNotificationListener(listener); // Be sure it is not called mbean2.sendNotification(notification); assertEquals("Listener is called", integer.get(), 6); } public void testObjectInstanceOnPostRegister() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); PostRegistrationSupport mbean = new PostRegistrationSupport(); ObjectName name = new ObjectName(":mbean=postRegistration"); server.registerMBean(mbean, name); } public void testGetDomains() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); String[] domains = server.getDomains(); if (domains.length != 1) fail("Fresh new MBeanServer contains MBeans not in the JMImplementation domain"); if (!"JMImplementation".equals(domains[0])) fail("Fresh new MBeanServer contains MBeans not in the JMImplementation domain"); Object mbean = new ComplianceSupport.BasicStandard(); ObjectName name1 = new ObjectName("domain1", "mbean", "1"); server.registerMBean(mbean, name1); domains = server.getDomains(); Arrays.sort(domains, null); if (domains.length != 2) fail("New MBean domain is not present in getDomains()"); if (!"domain1".equals(domains[1])) fail("New MBean domain is not present in getDomains()"); ObjectName name2 = new ObjectName("domain1", "mbean", "2"); server.registerMBean(mbean, name2); domains = server.getDomains(); Arrays.sort(domains, null); if (domains.length != 2) fail("Existing MBean domain should not be duplicated in getDomains()"); if (!"domain1".equals(domains[1])) fail("Existing MBean domain should not be duplicated in getDomains()"); server.unregisterMBean(name2); domains = server.getDomains(); Arrays.sort(domains, null); if (domains.length != 2) fail("Unregistering still existing MBean domain should not be removed from getDomains()"); if (!"domain1".equals(domains[1])) fail("Unregistering still existing MBean domain should not be removed from getDomains()"); server.unregisterMBean(name1); domains = server.getDomains(); Arrays.sort(domains, null); if (domains.length != 1) fail("Unregistering MBean domain should be removed from getDomains()"); if (!"JMImplementation".equals(domains[0])) fail("Unregistering MBean domain should be removed from getDomains()"); } public void testInstantiate() throws Exception { MBeanServer server = newMBeanServer(); String className = ComplianceSupport.BasicStandard.class.getName(); Object mbean1 = server.instantiate(className, null, new Object[0], new String[0]); // Register one classloader mbean File file = new File("dist/test/mx4j-tests.jar"); ClassLoader parent = getClass().getClassLoader().getParent(); ClassLoaderSupport loader = new ClassLoaderSupport(new URL[]{file.toURL()}, parent); ObjectName loaderName = new ObjectName(":type=ClassLoader"); server.registerMBean(loader, loaderName); Object mbean2 = server.instantiate(className, loaderName, new Object[0], new String[0]); // Now mbean1 should be of a different class from mbean2 if (mbean1.getClass().equals(mbean2.getClass())) fail("MBean classes should be different"); Object mbean3 = server.instantiate(className, new Object[0], new String[0]); // Since JMX 1.2, the CLR has the cl of the MBeanServer in its classpath. if (!mbean1.getClass().equals(mbean3.getClass())) fail("MBean classes should be equal"); server.unregisterMBean(loaderName); Object mbean4 = server.instantiate(className, new Object[0], new String[0]); if (!mbean1.getClass().equals(mbean4.getClass())) fail("MBean classes should be equal"); } public void testWrapExceptionsThrownByMBeanMethods() throws Exception { MBeanServer server = newMBeanServer(); MBeanThrowingExceptions mbean = new MBeanThrowingExceptions(); ObjectName objectName = ObjectName.getInstance(":name=exceptions"); server.registerMBean(mbean, objectName); try { server.invoke(objectName, "throwReflectionException", null, null); fail(); } catch (MBeanException x) { } } } mx4j-3.0.2/src/test/test/javax/management/MBeanStarInfoTest.java100644 0 0 15116 10513545721 21661 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.Map; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import junit.framework.TestCase; /** * @version $Revision: 1.4 $ */ public class MBeanStarInfoTest extends TestCase { public MBeanStarInfoTest(String s) { super(s); } public void testValidMBeanStarInfoNullName() throws Exception { new MBeanAttributeInfo(null, "java.lang.String", "description", true, false, false); new MBeanConstructorInfo(null, "description", null); new MBeanOperationInfo(null, "description", null, "java.lang.String", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo(null, "java.lang.String", "description"); } public void testValidMBeanStarInfoEmptyName() throws Exception { new MBeanAttributeInfo("", "java.lang.String", "description", true, false, false); new MBeanConstructorInfo("", "description", null); new MBeanOperationInfo("", "description", null, "java.lang.String", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("", "java.lang.String", "description"); } public void testValidMBeanStarInfoInvalidName1() throws Exception { new MBeanAttributeInfo("123", "java.lang.String", "description", true, false, false); new MBeanConstructorInfo("123", "description", null); new MBeanOperationInfo("123", "description", null, "java.lang.String", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("123", "java.lang.String", "description"); } public void testValidMBeanStarInfoInvalidName2() throws Exception { new MBeanAttributeInfo(".123", "java.lang.String", "description", true, false, false); new MBeanConstructorInfo(".123", "description", null); new MBeanOperationInfo(".123", "description", null, "java.lang.String", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo(".123", "java.lang.String", "description"); } public void testValidMBeanStarInfoInvalidName3() throws Exception { new MBeanAttributeInfo(" identifier", "java.lang.String", "description", true, false, false); new MBeanConstructorInfo(" identifier", "description", null); new MBeanOperationInfo(" identifier", "description", null, "java.lang.String", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo(" identifier", "java.lang.String", "description"); } public void testValidMBeanStarInfoNullType() throws Exception { new MBeanAttributeInfo("identifier", null, "description", true, false, false); new MBeanNotificationInfo(new String[0], null, "description"); new MBeanOperationInfo("identifier", "description", null, null, MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("identifier", null, "description"); } public void testValidMBeanStarInfoEmptyType() throws Exception { new MBeanAttributeInfo("identifier", "", "description", true, false, false); new MBeanNotificationInfo(new String[0], "", "description"); new MBeanOperationInfo("identifier", "description", null, "", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("identifier", "", "description"); } public void testValidMBeanStarInfoInvalidType1() throws Exception { new MBeanAttributeInfo("identifier", "123", "description", true, false, false); new MBeanNotificationInfo(new String[0], "123", "description"); new MBeanOperationInfo("identifier", "description", null, "123", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("identifier", "123", "description"); } public void testValidMBeanStarInfoInvalidType2() throws Exception { new MBeanAttributeInfo("identifier", ".type", "description", true, false, false); new MBeanNotificationInfo(new String[0], ".type", "description"); new MBeanOperationInfo("identifier", "description", null, ".type", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("identifier", ".type", "description"); } public void testValidMBeanStarInfoInvalidType3() throws Exception { new MBeanAttributeInfo("identifier", " type", "description", true, false, false); new MBeanNotificationInfo(new String[0], " type", "description"); new MBeanOperationInfo("identifier", "description", null, " type", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("identifier", " type", "description"); } public void testValidMBeanStarInfo1() throws Exception { new MBeanAttributeInfo("name", "type", "description", true, false, false); new MBeanConstructorInfo("name", "description", null); new MBeanNotificationInfo(new String[0], "type", "description"); new MBeanOperationInfo("name", "description", null, "type", MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("name", "type", "description"); } public void testValidMBeanStarInfo2() throws Exception { new MBeanAttributeInfo("_", int.class.getName(), "description", true, false, false); new MBeanConstructorInfo("_", "description", null); new MBeanNotificationInfo(new String[0], "java.lang.String", "description"); new MBeanOperationInfo("_", "description", null, int[].class.getName(), MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("_", int[][].class.getName(), "description"); } public void testValidMBeanStarInfo3() throws Exception { new MBeanAttributeInfo("a", String.class.getName(), "description", true, false, false); new MBeanConstructorInfo("a", "description", null); new MBeanNotificationInfo(new String[0], "java.lang.String", "description"); new MBeanOperationInfo("a", "description", null, String[].class.getName(), MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("a", String[][].class.getName(), "description"); } public void testValidMBeanStarInfo4() throws Exception { new MBeanAttributeInfo("a", Map.Entry.class.getName(), "description", true, false, false); new MBeanConstructorInfo("a", "description", null); new MBeanNotificationInfo(new String[0], "java.lang.String", "description"); new MBeanOperationInfo("a", "description", null, Map.Entry[].class.getName(), MBeanOperationInfo.UNKNOWN); new MBeanParameterInfo("a", Map.Entry[][].class.getName(), "description"); } // TODO: implements tests for MBeanInfo } mx4j-3.0.2/src/test/test/javax/management/MultiThreadMBeanServerTest.java100644 0 0 10527 10513545721 23546 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.InstanceNotFoundException; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegate; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.loading.MLet; import javax.management.timer.Timer; import test.MX4JTestCase; import test.MultiThreadTestRunner; /** * @version $Revision: 1.4 $ */ public class MultiThreadMBeanServerTest extends MX4JTestCase { protected MBeanServerConnection server; public MultiThreadMBeanServerTest(String s) { super(s); } protected void setUp() throws Exception { server = newMBeanServer(); } protected void tearDown() throws Exception { server = null; } public void testAddRemoveNotifyListeners() throws Exception { final ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); MultiThreadTestRunner.Test test = new MultiThreadTestRunner.Test() { public void test() throws Exception { final List notifications = new ArrayList(); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { synchronized (notifications) { notifications.add(notification); } } }; // Add the listener server.addNotificationListener(delegateName, listener, null, null); // Emit a notification ObjectName mletName = ObjectName.getInstance(":name=" + new Object().hashCode()); server.createMBean(MLet.class.getName(), mletName, null); // Emit another notification server.unregisterMBean(mletName); // Remove the listener server.removeNotificationListener(delegateName, listener, null, null); } }; MultiThreadTestRunner runner = new MultiThreadTestRunner(50, 10); runner.run(test); } public void testRegisterUnregisterQueryMBeans() throws Exception { MultiThreadTestRunner.Test test = new MultiThreadTestRunner.Test() { public void test() throws Exception { Set names = server.queryNames(null, null); for (Iterator i = names.iterator(); i.hasNext();) { ObjectName name = (ObjectName)i.next(); try { if (server.isInstanceOf(name, MBeanServerDelegate.class.getName())) { server.getAttribute(name, "ImplementationVendor"); } } catch (InstanceNotFoundException ignored) { // The Timer may be unregistered by another thread } } ObjectName timerName = ObjectName.getInstance(":timer=" + new Object().hashCode()); server.createMBean(Timer.class.getName(), timerName, null); Set mbeans = server.queryMBeans(new ObjectName("JMImplementation:*"), null); for (Iterator i = mbeans.iterator(); i.hasNext();) { ObjectInstance instance = (ObjectInstance)i.next(); try { if (server.isInstanceOf(instance.getObjectName(), MBeanServerDelegate.class.getName())) { server.getAttribute(instance.getObjectName(), "ImplementationVendor"); } } catch (InstanceNotFoundException ignored) { // The Timer may be unregistered by another thread } } server.unregisterMBean(timerName); } }; MultiThreadTestRunner runner = new MultiThreadTestRunner(50, 10); runner.run(test); } } mx4j-3.0.2/src/test/test/javax/management/NotificationListenerTest.java100644 0 0 16307 10513545721 23370 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.ArrayList; import java.util.List; import javax.management.ListenerNotFoundException; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import test.MX4JTestCase; import test.MutableInteger; import test.MutableObject; /** * @version $Revision: 1.1 $ */ public class NotificationListenerTest extends MX4JTestCase { public NotificationListenerTest(String name) { super(name); } public void testAddRemoveOneListenerOnOneMBean() throws Exception { MBeanServer server = newMBeanServer(); IdentityEmitter emitter = new IdentityEmitter(); ObjectName objectName = ObjectName.getInstance("test:type=emitter"); server.registerMBean(emitter, objectName); final MutableObject source = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { source.set(notification.getSource()); } }; server.addNotificationListener(objectName, listener, null, null); assertEquals(emitter.getNotificationListeners().size(), 1); Notification notification = new Notification("type", emitter, 0); emitter.sendNotification(notification); assertEquals(objectName, source.get()); server.removeNotificationListener(objectName, listener, null, null); assertEquals(emitter.getNotificationListeners().size(), 0); } public void testAddRemoveOneListenerTwiceOnOneMBean() throws Exception { MBeanServer server = newMBeanServer(); IdentityEmitter emitter = new IdentityEmitter(); ObjectName objectName = ObjectName.getInstance("test:type=emitter"); server.registerMBean(emitter, objectName); final MutableInteger count = new MutableInteger(0); final MutableObject source = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { source.set(notification.getSource()); count.set(count.get() + 1); } }; // Add same listener twice, with different handbacks Object handback = new Object(); server.addNotificationListener(objectName, listener, null, null); server.addNotificationListener(objectName, listener, null, handback); assertEquals(emitter.getNotificationListeners().size(), 2); Notification notification = new Notification("type", emitter, 0); emitter.sendNotification(notification); assertEquals(objectName, source.get()); assertEquals(count.get(), 2); server.removeNotificationListener(objectName, listener, null, null); assertEquals(emitter.getNotificationListeners().size(), 1); server.removeNotificationListener(objectName, listener, null, handback); assertEquals(emitter.getNotificationListeners().size(), 0); } public void testAddRemoveTwoListenersOnOneMBean() throws Exception { MBeanServer server = newMBeanServer(); IdentityEmitter emitter = new IdentityEmitter(); ObjectName objectName = ObjectName.getInstance("test:type=emitter"); server.registerMBean(emitter, objectName); NotificationListener listener1 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; NotificationListener listener2 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; server.addNotificationListener(objectName, listener1, null, null); server.addNotificationListener(objectName, listener2, null, null); assertEquals(emitter.getNotificationListeners().size(), 2); server.removeNotificationListener(objectName, listener1, null, null); assertEquals(emitter.getNotificationListeners().size(), 1); server.removeNotificationListener(objectName, listener2, null, null); assertEquals(emitter.getNotificationListeners().size(), 0); } public void testAddRemoveOneListenerOnTwoMBeans() throws Exception { MBeanServer server = newMBeanServer(); IdentityEmitter emitter1 = new IdentityEmitter(); ObjectName objectName1 = ObjectName.getInstance("test:type=emitter1"); server.registerMBean(emitter1, objectName1); IdentityEmitter emitter2 = new IdentityEmitter(); ObjectName objectName2 = ObjectName.getInstance("test:type=emitter2"); server.registerMBean(emitter2, objectName2); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; server.addNotificationListener(objectName1, listener, null, null); assertEquals(emitter1.getNotificationListeners().size(), 1); assertEquals(emitter2.getNotificationListeners().size(), 0); server.addNotificationListener(objectName2, listener, null, null); assertEquals(emitter1.getNotificationListeners().size(), 1); assertEquals(emitter2.getNotificationListeners().size(), 1); server.removeNotificationListener(objectName1, listener, null, null); assertEquals(emitter1.getNotificationListeners().size(), 0); assertEquals(emitter2.getNotificationListeners().size(), 1); server.removeNotificationListener(objectName2, listener, null, null); assertEquals(emitter1.getNotificationListeners().size(), 0); assertEquals(emitter2.getNotificationListeners().size(), 0); } public interface IdentityEmitterMBean { } public static class IdentityEmitter extends NotificationBroadcasterSupport implements IdentityEmitterMBean { private List listeners = new ArrayList(); public List getNotificationListeners() { return listeners; } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { super.addNotificationListener(listener, filter, handback); listeners.add(listener); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { NotificationListener[] listens = (NotificationListener[])listeners.toArray(new NotificationListener[0]); for (int i = 0; i < listens.length; i++) { NotificationListener listen = listens[i]; if (listen == listener) { super.removeNotificationListener(listener, filter, handback); listeners.remove(listener); return; } } throw new ListenerNotFoundException(); } } } mx4j-3.0.2/src/test/test/javax/management/ObjectNameTest.java100644 0 0 46034 10513545721 21243 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.Hashtable; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import test.MX4JTestCase; /** * @version $Revision: 1.15 $ */ public class ObjectNameTest extends MX4JTestCase { public ObjectNameTest(String s) { super(s); } public void testInvalidDomain() throws Exception { try { new ObjectName("missingColon"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("newLinePresent" + '\n' + ":k=v"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } } public void testValidNonPatternDomain() throws Exception { ObjectName name = new ObjectName(":k=v"); if (name.isDomainPattern()) fail("Not a domain pattern"); name = new ObjectName("domain:k=v"); if (name.isDomainPattern()) fail("Not a domain pattern"); } public void testValidPatternDomain() throws Exception { ObjectName name = new ObjectName("*:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("?:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("*domain:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("?domain:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("dom*ain:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("dom?ain:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("domain*:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); name = new ObjectName("domain?:k=v"); if (!name.isDomainPattern()) fail("Domain is a pattern"); } public void testInvalidProperties() throws Exception { try { new ObjectName("noProps:"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("noPropsWithBlank: "); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("noPropsWithGarbage: abc "); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("noKey:=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("domain:trailingSlash=Invalid,"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:key,invalid=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:key:invalid=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:key*invalid=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:key?invalid=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:?=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:*=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("keyWithInvalidChar:,=value"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("duplicateKey:key=value,key=value1"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } } public void testValidPatternProperties() throws Exception { ObjectName name = new ObjectName("domain:*"); if (!name.isPropertyPattern()) fail("Properties are pattern"); name = new ObjectName("domain:k=v,*"); if (!name.isPropertyPattern()) fail("Properties are pattern"); name = new ObjectName("domain:*,k=v"); if (!name.isPropertyPattern()) fail("Properties are pattern"); name = new ObjectName("domain:k=v,*,k1=v1"); if (!name.isPropertyPattern()) fail("Properties are pattern"); } public void testValidNonPatternProperties() throws Exception { ObjectName name = new ObjectName("domain:k=v"); if (name.isPropertyPattern()) fail("Properties are not pattern"); name = new ObjectName("domain:k=v, k1=v1"); if (name.isPropertyPattern()) fail("Properties are not pattern"); name = new ObjectName("domain:k=\"\\*\""); if (name.isPropertyPattern()) fail("Properties are not pattern"); name = new ObjectName("domain:k=\",\\*\""); if (name.isPropertyPattern()) fail("Properties are not pattern"); } public void testInvalidValue() throws Exception { try { new ObjectName("domain:key=newLinePresent" + '\n'); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("domain:key=\"quotedNewLinePresent" + '\n' + "\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { // Just one quote new ObjectName("domain:key=\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { // Just one quote with a space new ObjectName("domain:key=\" "); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { // Just one quote with a chars new ObjectName("domain:key=\"unterminatedQuote"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { // Just one quote with an escaped quote at the end new ObjectName("domain:key=\"\\\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { // Just one quote with a chars and an escaped quote at the end new ObjectName("domain:key=\"unterminatedQuote\\\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } } public void testEmptyValue() throws Exception { try { new ObjectName("domain:key="); fail("Expecting a MalformedObjectNameException"); } catch (MalformedObjectNameException x) { // success; } } public void testInvalidUnquotedValue() throws Exception { try { new ObjectName("invalidValueChar:k=,"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidValueChar:k=v="); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidValueChar:k=v:"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidValueChar:k=v\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidValueChar:k=v*"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidValueChar:k=v?"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } } public void testInvalidQuotedValue() throws Exception { try { new ObjectName("invalidQuotedValueChar:k=\"v?\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidQuotedValueChar:k=\"v*\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidQuotedValueChar:evenNumberOfBackslashes=\"v" + '\\' + '\\' + "*\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("garbage:afterQuoted=\"value\"garbage"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidEscapedChar:k=\"\\x\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidEscapedChar:k=\"\\\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidEscapedChar:k=\"\\\\\\\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("invalidEscapedChar:k=\"value\\\""); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } try { new ObjectName("domain", "x", "\"unterminated"); fail("Wrong ObjectName"); } catch (MalformedObjectNameException x) { } } public void testValidQuotedObjectName() throws Exception { ObjectName name = new ObjectName("domain:key=\"\""); name = new ObjectName("domain:key=\"\\\\\""); name = new ObjectName("domain:key=\":\""); name = new ObjectName("domain:key=\",\""); name = new ObjectName("domain:key=\"=\""); name = new ObjectName("domain:key=\"\\\"\""); name = new ObjectName("domain:key=\"\\*\""); name = new ObjectName("domain:key=\"\\?\""); name = new ObjectName("domain:key1=\"v1,v2\",key2=value2"); if (name.getKeyPropertyList().size() != 2) fail("Too many properties"); name = new ObjectName("domain:key1=\"k1=v1,k2=v2\", key2= value2"); if (name.getKeyPropertyList().size() != 2) fail("Too many properties"); name = new ObjectName("domain:key1=\"v1,\\*,v2\",*,key2=value2"); if (!name.isPropertyPattern()) fail("ObjectName is property pattern"); if (name.getKeyPropertyList().size() != 2) fail("Too many properties"); } public void testValidObjectNameWithSpaces() throws Exception { String key = " key "; String value = " value "; ObjectName name = new ObjectName("domain:" + key + "=" + value); String val = name.getKeyProperty(key.trim()); if (val != null) fail("Key is not present"); val = name.getKeyProperty(key); if (!value.equals(val)) fail("Wrong value"); } public void testValidObjectNames() throws Exception { ObjectName name = new ObjectName("domain:property1=value1,property2=value2"); if (name.getKeyPropertyList().size() != 2) fail("Wrong properties number"); name = new ObjectName("*:*"); if (!name.isPattern()) fail("ObjectName is a pattern"); if (!name.isDomainPattern()) fail("ObjectName is a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 0) fail("Wrong properties number"); if (name.getKeyPropertyListString().length() != 0) fail("Wrong properties string"); if (name.getCanonicalKeyPropertyListString().length() != 0) fail("Wrong properties string"); name = new ObjectName(""); if (!name.isPattern()) fail("ObjectName is a pattern"); if (!name.isDomainPattern()) fail("ObjectName is a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 0) fail("Wrong properties number"); if (name.getKeyPropertyListString().length() != 0) fail("Wrong properties string"); if (name.getCanonicalKeyPropertyListString().length() != 0) fail("Wrong properties string"); name = new ObjectName(":*"); if (!name.isPattern()) fail("ObjectName is a pattern"); if (name.isDomainPattern()) fail("ObjectName is not a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 0) fail("Wrong properties number"); if (name.getKeyPropertyListString().length() != 0) fail("Wrong properties string"); if (name.getCanonicalKeyPropertyListString().length() != 0) fail("Wrong properties string"); name = new ObjectName(":*,property=value"); if (!name.isPattern()) fail("ObjectName is a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 1) fail("Wrong properties number"); if (!"property=value".equals(name.getKeyPropertyListString())) fail("Wrong properties string"); name = new ObjectName(":property=value,*"); if (!name.isPattern()) fail("ObjectName is a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 1) fail("Wrong properties number"); if (!"property=value".equals(name.getKeyPropertyListString())) fail("Wrong properties string"); name = new ObjectName(":property2=value2,*,property1=value1"); if (!name.isPattern()) fail("ObjectName is a pattern"); if (!name.isPropertyPattern()) fail("ObjectName is a pattern"); if (name.getKeyPropertyList().size() != 2) fail("Wrong properties number"); if (!"property2=value2,property1=value1".equals(name.getKeyPropertyListString())) fail("Wrong properties string"); if (!"property1=value1,property2=value2".equals(name.getCanonicalKeyPropertyListString())) fail("Wrong properties string"); name = new ObjectName("*uu*:*"); if (!name.isDomainPattern()) fail("ObjectName is a domain pattern"); name = new ObjectName("*domain:property=value,*"); if (!name.isDomainPattern()) fail("ObjectName is a domain pattern"); name = new ObjectName("??Domain:*"); if (!name.isDomainPattern()) fail("ObjectName is a domain pattern"); name = new ObjectName("JMImplementation:type=MBeanServerDelegate"); if (name.isPattern()) fail("ObjectName is not a pattern"); name = new ObjectName("domain", "key", "value"); if (name.isPattern()) fail("ObjectName is not a pattern"); if (name.isPropertyPattern()) fail("ObjectName is not a pattern"); if (name.getKeyPropertyList().size() != 1) fail("Wrong properties number"); } public void testProperties() throws Exception { String properties = "b=1,a=2,d=0,c=3,aa=4"; String canonicals = "a=2,aa=4,b=1,c=3,d=0"; ObjectName name = new ObjectName(":" + properties); assertEquals(properties, name.getKeyPropertyListString()); assertEquals(canonicals, name.getCanonicalKeyPropertyListString()); // One of the values is a quoted value with an asterisk properties = "b=1,a=\"\\*2\",d=0,c=3,aa=4"; canonicals = "a=\"\\*2\",aa=4,b=1,c=3,d=0"; name = new ObjectName(":" + properties); assertEquals(properties, name.getKeyPropertyListString()); assertEquals(canonicals, name.getCanonicalKeyPropertyListString()); // Adding the wildcard name = new ObjectName(":b=1,a=\"\\*2\",d=0,*,c=3,aa=4"); assertEquals(properties, name.getKeyPropertyListString()); assertEquals(canonicals, name.getCanonicalKeyPropertyListString()); } public void testCanonicalName() throws Exception { String origin = "domain:a=1,b=1,c=1,*"; ObjectName name = new ObjectName(origin); String canonical = name.getCanonicalName(); assertEquals(canonical, origin); } public void testNullConstructorParameters() throws Exception { try { new ObjectName(null); fail("Expecting a NullPointerException on null 'name'"); } catch (NullPointerException x) { } try { new ObjectName("domain", null); fail("Expecting a NullPointerException on null 'table'"); } catch (NullPointerException x) { } try { new ObjectName(null, new Hashtable()); fail("Expecting a NullPointerException on null 'domain'"); } catch (NullPointerException x) { } try { new ObjectName(null, "key", "value"); fail("Expecting a NullPointerException on null 'domain'"); } catch (NullPointerException x) { } try { new ObjectName("domain", null, "value"); fail("Expecting a NullPointerException on null 'key'"); } catch (NullPointerException x) { } try { new ObjectName("domain", "key", null); fail("Expecting a NullPointerException on null 'value'"); } catch (NullPointerException x) { } } public void testApply() throws Exception { ObjectName notpatone = new ObjectName("names:id=notpatone"); ObjectName notpattwo = new ObjectName("names:id=notpattwo"); ObjectName patone = new ObjectName("names:*"); ObjectName pattwo = new ObjectName("names/patterns:id=pattwo,*"); assertTrue("Expecting true on notpatone.apply(notpatone)", notpatone.apply(notpatone)); assertTrue("Expecting true on patone.apply(notpatone)", patone.apply(notpatone)); assertFalse("Expecting false on notpattwo.apply(notpatone)", notpattwo.apply(notpatone)); assertFalse("Expecting false on notpat.apply(patone)", notpatone.apply(patone)); assertFalse("Expecting false on patone.apply(pattwo)", patone.apply(pattwo)); assertFalse("Expecting false on patone.apply(patone)", patone.apply(patone)); } public void testEmptyHashtable() throws Exception { try { Hashtable ht = new Hashtable(); new ObjectName("afinedomain", ht); fail("Expecting MalformedObjectNameException"); } catch (MalformedObjectNameException x) { } } public void testNonStringProperties() throws Exception { try { Hashtable ht = new Hashtable(); ht.put("key", new Integer(42)); new ObjectName("afinedomain", ht); fail("Expecting MalformedObjectNameException"); } catch (MalformedObjectNameException x) { } } } mx4j-3.0.2/src/test/test/javax/management/PermissionTestCase.java100644 0 0 3761 10513545721 22140 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.security.Permission; import java.security.PermissionCollection; import test.MX4JTestCase; /** * @version $Revision: 1.3 $ */ public class PermissionTestCase extends MX4JTestCase { public PermissionTestCase(String s) { super(s); } protected void shouldBeEqual(Permission p1, Permission p2) { if (!p1.equals(p2)) fail("Permission " + p1 + " should be equal to Permission " + p2); if (p1.hashCode() != p2.hashCode()) fail("Permission " + p1 + " should have hashCode equal to Permission " + p2); } protected void shouldImply(Permission p1, Permission p2) { if (p1.equals(p2)) { // Test identity if (!imply(p1, p2)) fail("Permission " + p1 + " should imply Permission " + p2); if (!imply(p2, p1)) fail("Permission " + p2 + " should imply Permission " + p1); } else { // Test antisymmetry if (!imply(p1, p2)) fail("Permission " + p1 + " should imply Permission " + p2); if (imply(p2, p1)) fail("Permission " + p2 + " should not imply Permission " + p1); } } protected void shouldNotImply(Permission p1, Permission p2) { if (p1.equals(p2)) fail("Permissions cannot be equal"); if (imply(p1, p2)) fail("Permission " + p1 + " should not imply Permission " + p2); if (imply(p2, p1)) fail("Permission " + p2 + " should not imply Permission " + p1); } protected boolean imply(Permission p1, Permission p2) { PermissionCollection pc = p1.newPermissionCollection(); if (pc == null) { // No PermissionCollection provided, go directly to the Permission return p1.implies(p2); } else { return pc.implies(p2); } } } mx4j-3.0.2/src/test/test/javax/management/QueryTest.java100644 0 0 63110 10513545721 20333 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.util.Arrays; import java.util.Set; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.Query; import javax.management.ValueExp; import junit.framework.TestCase; import test.javax.management.support.QuerySupport; /** * Class QueryTest, tests the query service * * @version $Revision: 1.10 $ */ public class QueryTest extends TestCase { public QueryTest(String name) { super(name); } public void testQueryEmpty() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); int count = server.getMBeanCount().intValue(); QuerySupport.Test bean1 = new QuerySupport.Test(null, null, null); server.registerMBean(bean1, new ObjectName("Query:name=bean1")); QuerySupport.Test bean2 = new QuerySupport.Test(null, null, null); server.registerMBean(bean2, new ObjectName("Query:name=bean2")); QuerySupport.Test bean3 = new QuerySupport.Test(null, null, null); server.registerMBean(bean3, new ObjectName("Query:name=bean3")); Set result = server.queryMBeans(null, null); assertNotNull(result); assertEquals(count + 3, result.size()); result = server.queryNames(null, null); assertEquals(count + 3, result.size()); assertNotNull(result); assertTrue(result.contains(new ObjectName("Query:name=bean1"))); assertTrue(result.contains(new ObjectName("Query:name=bean2"))); assertTrue(result.contains(new ObjectName("Query:name=bean3"))); } public void testStringMatch() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("trial", null, null); QuerySupport.Test b = new QuerySupport.Test("arial", null, null); QuerySupport.Test c = new QuerySupport.Test("trial2", null, null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.match(Query.attr("Str"), Query.value("*rial"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.match(Query.attr("Str"), Query.value("[at]rial"))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.match(Query.attr("Str"), Query.value("[a-z]rial"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.match(Query.attr("Str"), Query.value("[b-z]rial?"))); assertEquals(1, result.size()); } public void testArray() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); QuerySupport.Test bean1 = new QuerySupport.Test("a", new Integer(0), null); server.registerMBean(bean1, new ObjectName("Query:name=bean1")); QuerySupport.Test bean2 = new QuerySupport.Test("b", new Integer(1), null); server.registerMBean(bean2, new ObjectName("Query:name=bean2")); QuerySupport.Test bean3 = new QuerySupport.Test("c", new Integer(2), null); server.registerMBean(bean3, new ObjectName("Query:name=bean3")); Set result = server.queryMBeans(null, Query.in(Query.attr("Number"), new ValueExp[]{Query.value(0), Query.value(1)})); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.in(Query.attr("Str"), new ValueExp[]{Query.value("a"), Query.value("d")})); assertEquals(1, result.size()); } public void testFinalSubString() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("trial", null, null); QuerySupport.Test b = new QuerySupport.Test("arial", null, null); QuerySupport.Test c = new QuerySupport.Test("tria2l", null, null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.finalSubString(Query.attr("Str"), Query.value("l"))); assertEquals(3, result.size()); result = server.queryMBeans(null, Query.finalSubString(Query.attr("Str"), Query.value("rial"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.finalSubString(Query.attr("Str"), Query.value("nothing"))); assertEquals(0, result.size()); } public void testInitialString() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("trial", null, null); QuerySupport.Test b = new QuerySupport.Test("arial", null, null); QuerySupport.Test c = new QuerySupport.Test("trial2", null, null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.initialSubString(Query.attr("Str"), Query.value("t"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.initialSubString(Query.attr("Str"), Query.value("tr"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.initialSubString(Query.attr("Str"), Query.value("tri"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.initialSubString(Query.attr("Str"), Query.value("nothing"))); assertEquals(0, result.size()); } public void testMathOperations() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test(null, new Integer(1), null); QuerySupport.Test b = new QuerySupport.Test(null, new Integer(2), null); QuerySupport.Test c = new QuerySupport.Test(null, new Integer(3), null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.eq(Query.value(3), Query.plus(Query.attr("Number"), Query.value(1)))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.eq(Query.value(0), Query.minus(Query.attr("Number"), Query.value(2)))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.eq(Query.value(0), Query.times(Query.attr("Number"), Query.value(0)))); assertEquals(3, result.size()); result = server.queryMBeans(null, Query.eq(Query.value(1), Query.div(Query.attr("Number"), Query.value(3)))); assertEquals(1, result.size()); } public void testAttribute() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test(null, new Integer(1), null); QuerySupport.Test b = new QuerySupport.Test(null, new Integer(2), null); QuerySupport.Test c = new QuerySupport.Test(null, new Integer(2), null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.eq(Query.value(2), Query.attr("Number"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.eq(Query.classattr(), Query.value("test.javax.management.support.QuerySupport$Test"))); assertEquals(3, result.size()); } public void testBetween() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("a", new Integer(1), null); QuerySupport.Test b = new QuerySupport.Test("b", new Integer(2), null); QuerySupport.Test c = new QuerySupport.Test("c", new Integer(5), null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.between(Query.attr("Number"), Query.value(2), Query.value(3))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.between(Query.attr("Number"), Query.value(1), Query.value(3))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.between(Query.attr("Number"), Query.value(1), Query.value(5))); assertEquals(3, result.size()); /* result = server.queryMBeans(null, Query.between(Query.attr("Str"), Query.value("a"), Query.value("b"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.between(Query.attr("Str"), Query.value("a"), Query.value("z"))); assertEquals(3, result.size()); */ } public void testRelation() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); ObjectName name4 = new ObjectName("BigNumber:name=test4"); ObjectName name5 = new ObjectName("BigNumber:name=test5"); ObjectName name6 = new ObjectName("LittleNumber:name=test6"); QuerySupport.Test a = new QuerySupport.Test("a", new Integer(1), null); QuerySupport.Test b = new QuerySupport.Test("b", new Integer(2), null); QuerySupport.Test c = new QuerySupport.Test("c", new Integer(5), null); QuerySupport.Test d = new QuerySupport.Test("d", new Integer(112), null); QuerySupport.DynamicTest e = new QuerySupport.DynamicTest("e", 119L, null); QuerySupport.DynamicTest f = new QuerySupport.DynamicTest("f", 8L, null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); server.registerMBean(d, name4); server.registerMBean(e, name5); server.registerMBean(f, name6); Set result = server.queryMBeans(null, Query.lt(Query.attr("Number"), Query.value(3))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.leq(Query.attr("Number"), Query.value(5))); assertEquals(3, result.size()); result = server.queryMBeans(new ObjectName("StringMatch:*"), Query.eq(Query.attr("Str"), Query.value("a"))); assertEquals(1, result.size()); result = server.queryMBeans(new ObjectName("StringMatch:*"), Query.gt(Query.attr("Number"), Query.value(2))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.gt(Query.attr("Boolean"), Query.value(2))); assertEquals(0, result.size()); result = server.queryMBeans(new ObjectName("StringMatch:*"), Query.geq(Query.attr("Number"), Query.value(2))); assertEquals(2, result.size()); result = server.queryMBeans(new ObjectName("StringMatch:*"), Query.geq(Query.attr("Str"), Query.value("a"))); assertEquals(3, result.size()); result = server.queryMBeans(null, Query.gt(Query.attr("Number"), Query.value(2))); assertEquals(4, result.size()); result = server.queryMBeans(new ObjectName("*Number:*"), Query.gt(Query.attr("Number"), Query.value(100))); assertEquals(2, result.size()); } public void testAnyString() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("trial", null, null); QuerySupport.Test b = new QuerySupport.Test("arial", null, null); QuerySupport.Test c = new QuerySupport.Test("trial2", null, null); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.anySubString(Query.attr("Str"), Query.value("trial"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.anySubString(Query.attr("Str"), Query.value("rial"))); assertEquals(3, result.size()); result = server.queryMBeans(null, Query.anySubString(Query.attr("Str"), Query.value("tri"))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.anySubString(Query.attr("Str"), Query.value("ri"))); assertEquals(3, result.size()); result = server.queryMBeans(null, Query.anySubString(Query.attr("Str"), Query.value("no"))); assertEquals(0, result.size()); } public void testNotOperation() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); QuerySupport.Test a = new QuerySupport.Test(null, null, Boolean.TRUE); server.registerMBean(a, name1); Set result = server.queryMBeans(null, Query.not(Query.eq(Query.value(false), Query.attr("Boolean")))); assertEquals(1, result.size()); } public void testLogical() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("a", new Integer(1), Boolean.TRUE); QuerySupport.Test b = new QuerySupport.Test("b", new Integer(2), Boolean.FALSE); QuerySupport.Test c = new QuerySupport.Test("c", new Integer(5), Boolean.TRUE); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.and(Query.eq(Query.attr("Boolean"), Query.value(true)), Query.lt(Query.attr("Number"), Query.value(3)))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.or(Query.eq(Query.attr("Boolean"), Query.value(true)), Query.eq(Query.attr("Str"), Query.value("a")))); assertEquals(2, result.size()); result = server.queryMBeans(null, Query.or(Query.eq(Query.attr("Boolean"), Query.value(true)), Query.geq(Query.attr("Str"), Query.value("a")))); assertEquals(3, result.size()); } public void testQualifiedAttributeName() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("StringMatch:name=test1"); ObjectName name2 = new ObjectName("StringMatch:name=test2"); ObjectName name3 = new ObjectName("StringMatch:name=test3"); QuerySupport.Test a = new QuerySupport.Test("a", new Integer(1), Boolean.TRUE); QuerySupport.Test b = new QuerySupport.Test("b", new Integer(2), Boolean.FALSE); QuerySupport.Test c = new QuerySupport.Test("c", new Integer(5), Boolean.TRUE); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); Set result = server.queryMBeans(null, Query.eq(Query.attr("test.javax.management.support.QuerySupport$Test", "Number"), Query.value(2))); assertEquals(1, result.size()); result = server.queryMBeans(null, Query.eq(Query.attr("test.javax.management.support.QuerySupport.Test2", "Number"), Query.value(2))); assertEquals(0, result.size()); } public void testQueryScope() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer("query"); ObjectName name1 = new ObjectName("Scope:name0=test0"); ObjectName name2 = new ObjectName("Scope2:name0=test0"); ObjectName name3 = new ObjectName("Scope:name1=test1"); ObjectName name4 = new ObjectName("Scope:name1=test1,name2=test2"); ObjectName name5 = new ObjectName("Scope:name0=test0,name1=test1,name2=test2"); QuerySupport.Test a = new QuerySupport.Test("a", new Integer(1), Boolean.TRUE); QuerySupport.Test b = new QuerySupport.Test("b", new Integer(2), Boolean.TRUE); QuerySupport.Test c = new QuerySupport.Test("c", new Integer(3), Boolean.TRUE); QuerySupport.Test d = new QuerySupport.Test("d", new Integer(4), Boolean.TRUE); QuerySupport.Test e = new QuerySupport.Test("e", new Integer(5), Boolean.TRUE); server.registerMBean(a, name1); server.registerMBean(b, name2); server.registerMBean(c, name3); server.registerMBean(d, name4); server.registerMBean(e, name5); ObjectName scope = new ObjectName("*:*"); int count = server.getMBeanCount().intValue(); Set result = server.queryMBeans(scope, null); assertEquals(count, result.size()); scope = new ObjectName("*:name0=test0"); result = server.queryMBeans(scope, null); assertEquals(2, result.size()); scope = new ObjectName("*:name0=test0,*"); result = server.queryMBeans(scope, null); assertEquals(3, result.size()); scope = new ObjectName("*:name1=test1"); result = server.queryMBeans(scope, null); assertEquals(1, result.size()); scope = new ObjectName("*:*,name1=test1"); result = server.queryMBeans(scope, null); assertEquals(3, result.size()); scope = new ObjectName("*:name1=test1,*"); result = server.queryMBeans(scope, null); assertEquals(3, result.size()); scope = new ObjectName("*:name2=test2"); result = server.queryMBeans(scope, null); assertEquals(0, result.size()); scope = new ObjectName("*:name2=test2,*"); result = server.queryMBeans(scope, null); assertEquals(2, result.size()); scope = new ObjectName("*:name0=test0,name2=test2"); result = server.queryMBeans(scope, null); assertEquals(0, result.size()); scope = new ObjectName("*:name0=test0,name2=test2,*"); result = server.queryMBeans(scope, null); assertEquals(1, result.size()); ObjectName[] xpnames = new ObjectName[]{name1, name2}; scope = new ObjectName("S*:name0=test0"); result = server.queryNames(scope, null); assertTrue(Arrays.asList(xpnames).containsAll(result)); ObjectInstance[] xpinstances = new ObjectInstance[]{ new ObjectInstance(name1, QuerySupport.Test.class.getName()), new ObjectInstance(name2, QuerySupport.Test.class.getName())}; result = server.queryMBeans(scope, null); assertTrue(Arrays.asList(xpinstances).containsAll(result) && result.size() == xpinstances.length); assertEquals(2, result.size()); scope = new ObjectName("S*:*"); xpnames = new ObjectName[]{name1, name2, name3, name4, name5}; result = server.queryNames(scope, null); assertTrue(Arrays.asList(xpnames).containsAll(result) && result.size() == xpnames.length); result = server.queryMBeans(scope, null); xpinstances = new ObjectInstance[]{ new ObjectInstance(name1, QuerySupport.Test.class.getName()), new ObjectInstance(name2, QuerySupport.Test.class.getName()), new ObjectInstance(name3, QuerySupport.Test.class.getName()), new ObjectInstance(name4, QuerySupport.Test.class.getName()), new ObjectInstance(name5, QuerySupport.Test.class.getName())}; assertTrue(Arrays.asList(xpinstances).containsAll(result) && result.size() == xpinstances.length); assertEquals(5, result.size()); scope = new ObjectName("Scope?:*"); xpnames = new ObjectName[]{name2}; result = server.queryNames(scope, null); assertTrue(Arrays.asList(xpnames).containsAll(result) && result.size() == xpnames.length); result = server.queryMBeans(scope, null); xpinstances = new ObjectInstance[]{ new ObjectInstance(name2, QuerySupport.Test.class.getName())}; assertTrue(Arrays.asList(xpinstances).containsAll(result) && result.size() == xpinstances.length); assertEquals(1, result.size()); scope = new ObjectName("S?o?e?:*"); xpnames = new ObjectName[]{name2}; result = server.queryNames(scope, null); assertTrue(Arrays.asList(xpnames).containsAll(result) && result.size() == xpnames.length); result = server.queryMBeans(scope, null); xpinstances = new ObjectInstance[]{ new ObjectInstance(name2, QuerySupport.Test.class.getName())}; assertTrue(Arrays.asList(xpinstances).containsAll(result) && result.size() == xpinstances.length); assertEquals(1, result.size()); scope = new ObjectName("?c*e?:*"); xpnames = new ObjectName[]{name2}; result = server.queryNames(scope, null); assertTrue(Arrays.asList(xpnames).containsAll(result) && result.size() == xpnames.length); result = server.queryMBeans(scope, null); xpinstances = new ObjectInstance[]{ new ObjectInstance(name2, QuerySupport.Test.class.getName())}; assertTrue(Arrays.asList(xpinstances).containsAll(result) && result.size() == xpinstances.length); assertEquals(1, result.size()); } public void testExceptionPropagation() throws Exception { MBeanServer server = MBeanServerFactory.createMBeanServer(); ObjectName objname = new ObjectName("querytest:name=testExceptionPropagation"); QuerySupport.DynamicTest mbean = new QuerySupport.DynamicTest("xyzzy", 42L, Boolean.TRUE); server.registerMBean(mbean, objname); Set result = server.queryNames(null, Query.match(Query.attr("Str"), Query.value("x*y"))); assertEquals(0, result.size()); result = server.queryMBeans(new ObjectName("query*:*"), Query.match(Query.attr("Str"), Query.value("x*y"))); assertEquals(0, result.size()); } } mx4j-3.0.2/src/test/test/javax/management/SecurityManagerTestCase.java100644 0 0 62231 10513545721 23127 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import java.security.Permission; import java.util.Iterator; import java.util.Set; import java.io.IOException; import javax.management.*; import test.MX4JTestCase; /** * Test case class that defines all tests to be performed by a security manager test * both for the local (that is, MBeanServer tests) and the remote (that is, for MBeanServerConnection * tests) case. * It also defines the implementations of the test methods, leaving to subclasses * only the creation of the MBeanServerConnection (or MBeanServer) object. * * @version $Revision: 1.5 $ */ public abstract class SecurityManagerTestCase extends MX4JTestCase { public SecurityManagerTestCase(String s) { super(s); } /** * Adds the given permission to the client codesource, that is the test codesource * * @see #resetPermissions */ protected abstract void addPermission(Permission p); /** * Removes all permissions add via {@link #addPermission} */ protected abstract void resetPermissions(); public abstract void testAddRemoveNotificationListener() throws Exception; public abstract void testCreateMBean4Params() throws Exception; public abstract void testCreateMBean5Params() throws Exception; public abstract void testGetAttribute() throws Exception; public abstract void testGetAttributes() throws Exception; public abstract void testGetDefaultDomain() throws Exception; public abstract void testGetDomains() throws Exception; public abstract void testGetMBeanCount() throws Exception; public abstract void testGetMBeanInfo() throws Exception; public abstract void testGetObjectInstance() throws Exception; public abstract void testInvoke() throws Exception; public abstract void testIsInstanceOf() throws Exception; public abstract void testIsRegistered() throws Exception; public abstract void testQueryMBeans() throws Exception; public abstract void testQueryNames() throws Exception; public abstract void testSetAttribute() throws Exception; public abstract void testSetAttributes() throws Exception; public abstract void testUnregisterMBean() throws Exception; protected void testAddRemoveNotificationListener(MBeanServerConnection server) throws Exception { NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); try { server.addNotificationListener(delegate, listener, null, null); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "addNotificationListener")); server.addNotificationListener(delegate, listener, null, null); // Clean up try { server.removeNotificationListener(delegate, listener); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "removeNotificationListener")); server.removeNotificationListener(delegate, listener); } protected void testCreateMBean4Params(MBeanServerConnection server) throws Exception { // Needed to create an MLet, which is a ClassLoader addPermission(new RuntimePermission("createClassLoader")); ObjectName mletName = new ObjectName(server.getDefaultDomain(), "name", "mlet"); String mletClassName = "javax.management.loading.MLet"; addPermission(new MBeanPermission(mletClassName + "[" + mletName.getCanonicalName() + "]", "instantiate, registerMBean")); server.createMBean(mletClassName, mletName, null, null, null); // Now we have something in the CLR String mbeanClassName = "javax.management.MBeanServerDelegate"; ObjectName mbeanName = new ObjectName(server.getDefaultDomain(), "name", "delegate"); try { server.createMBean(mbeanClassName, mbeanName); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(mbeanClassName + "[" + mbeanName.getCanonicalName() + "]", "instantiate, registerMBean")); ObjectInstance result = server.createMBean(mbeanClassName, mbeanName, null, null); assertNotNull(result); } protected void testCreateMBean5Params(MBeanServerConnection server) throws Exception { // Needed to create an MLet, which is a ClassLoader addPermission(new RuntimePermission("createClassLoader")); ObjectName mletName = new ObjectName(server.getDefaultDomain(), "name", "mlet"); String mletClassName = "javax.management.loading.MLet"; try { server.createMBean(mletClassName, mletName, null); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(mletClassName + "[" + mletName.getCanonicalName() + "]", "instantiate, registerMBean")); ObjectInstance result = server.createMBean(mletClassName, mletName, null, null, null); assertNotNull(result); } protected void testGetAttribute(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); String attribute = "ImplementationName"; try { server.getAttribute(delegate, attribute); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("#" + attribute + "[" + delegate.getCanonicalName() + "]", "getAttribute")); String result = (String)server.getAttribute(delegate, attribute); assertNotNull(result); } protected void testGetAttributes(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); String[] allAttributes = new String[]{"MBeanServerId", "ImplementationName", "ImplementationVendor", "ImplementationVersion", "SpecificationName", "SpecificationVendor", "SpecificationVersion"}; String[] allowed = new String[0]; String[] wanted = new String[0]; try { server.getAttributes(delegate, allAttributes); fail(); } catch (SecurityException ignored) { } // Check that for wrong attribute I get an empty list allowed = new String[]{allAttributes[1]}; wanted = new String[]{allAttributes[0]}; addPermission(new MBeanPermission("#" + allowed[0] + "[" + delegate.getCanonicalName() + "]", "getAttribute")); AttributeList list = server.getAttributes(delegate, wanted); assertEquals(list.size(), 0); // Check that for the right attribute I get it resetPermissions(); allowed = new String[]{allAttributes[0]}; wanted = allAttributes; addPermission(new MBeanPermission("#" + allowed[0] + "[" + delegate.getCanonicalName() + "]", "getAttribute")); list = server.getAttributes(delegate, wanted); assertEquals(list.size(), allowed.length); Attribute attrib = (Attribute)list.get(0); assertEquals(attrib.getName(), allowed[0]); // Check that if I grant some I only get some resetPermissions(); // Only attributes that start with 'Implementation' allowed = new String[]{allAttributes[1], allAttributes[2], allAttributes[3]}; wanted = allAttributes; addPermission(new MBeanPermission("#Implementation*[" + delegate.getCanonicalName() + "]", "getAttribute")); list = server.getAttributes(delegate, wanted); assertEquals(list.size(), allowed.length); for (int i = 0; i < list.size(); ++i) { Attribute attr = (Attribute)list.get(i); assertEquals(attr.getName(), allowed[i]); } // Check that if I grant all I get them all resetPermissions(); allowed = allAttributes; wanted = allAttributes; addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "getAttribute")); list = server.getAttributes(delegate, allAttributes); assertEquals(list.size(), allowed.length); for (int i = 0; i < list.size(); ++i) { Attribute attr = (Attribute)list.get(i); assertEquals(attr.getName(), allowed[i]); } } protected void testGetDefaultDomain(MBeanServerConnection server, String domain) throws Exception { String result = server.getDefaultDomain(); assertEquals(result, domain); } protected void testGetDomains(MBeanServerConnection server) throws Exception { try { server.getDomains(); fail(); } catch (SecurityException e) { // OK } ObjectName name = new ObjectName("test:x=x"); addPermission(new MBeanPermission(Simple.class.getName(), null, name, "instantiate")); addPermission(new MBeanPermission(Simple.class.getName(), null, name, "registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), name); addPermission(new MBeanPermission(null, null, name, "getDomains")); String[] results = server.getDomains(); assertNotNull(results); assertEquals(results.length, 1); assertEquals(results[0], "test"); } protected void testGetMBeanCount(MBeanServerConnection server) throws Exception { Integer count = server.getMBeanCount(); assertNotNull(count); assertTrue(count.intValue() > 1); } protected void testGetMBeanInfo(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); try { server.getMBeanInfo(delegate); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "getMBeanInfo")); MBeanInfo info = server.getMBeanInfo(delegate); assertNotNull(info); } protected void testGetObjectInstance(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); try { server.getObjectInstance(delegate); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "getObjectInstance")); ObjectInstance instance = server.getObjectInstance(delegate); assertNotNull(instance); } protected void testInvoke(MBeanServerConnection server) throws Exception { ObjectName mbeanName = new ObjectName(server.getDefaultDomain(), "mbean", "simple"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), mbeanName, null); addPermission(new MBeanPermission(Simple.class.getName(), "setAttribute")); String initial = "mx4j"; server.setAttribute(mbeanName, new Attribute("FirstAttribute", initial)); String value = "simon"; String operation = "concatenateWithFirstAttribute"; try { server.invoke(mbeanName, operation, new Object[]{value}, new String[]{String.class.getName()}); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("#" + operation + "[" + mbeanName.getCanonicalName() + "]", "invoke")); String result = (String)server.invoke(mbeanName, operation, new Object[]{value}, new String[]{String.class.getName()}); assertEquals(result, initial + value); } protected void testIsInstanceOf(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); String className = "javax.management.MBeanServerDelegateMBean"; try { server.isInstanceOf(delegate, className); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("[" + delegate.getCanonicalName() + "]", "isInstanceOf")); boolean isInstance = server.isInstanceOf(delegate, className); assertTrue(isInstance); } protected void testIsRegistered(MBeanServerConnection server) throws Exception { ObjectName delegate = new ObjectName("JMImplementation", "type", "MBeanServerDelegate"); boolean registered = server.isRegistered(delegate); assertTrue(registered); } protected void testQueryMBeans(MBeanServerConnection server) throws Exception { ObjectName mbeanName = new ObjectName(server.getDefaultDomain(), "mbean", "simple"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), mbeanName, null); try { server.queryMBeans(null, null); fail(); } catch (SecurityException ignored) { } // Check that an ObjectName that does not match returns an empty list ObjectName dummy = new ObjectName(server.getDefaultDomain(), "type", "dummy"); addPermission(new MBeanPermission("[" + dummy.getCanonicalName() + "]", "queryMBeans")); Set mbeans = server.queryMBeans(null, null); assertEquals(mbeans.size(), 0); // Now check the right one resetPermissions(); addPermission(new MBeanPermission("[" + mbeanName.getCanonicalName() + "]", "queryMBeans")); mbeans = server.queryMBeans(null, null); assertEquals(mbeans.size(), 1); ObjectInstance instance = (ObjectInstance)mbeans.iterator().next(); assertEquals(instance.getObjectName(), mbeanName); // Check the right one for a pattern in permission resetPermissions(); addPermission(new MBeanPermission("[" + server.getDefaultDomain() + ":*]", "queryMBeans")); mbeans = server.queryMBeans(null, null); assertEquals(mbeans.size(), 1); instance = (ObjectInstance)mbeans.iterator().next(); assertEquals(instance.getObjectName(), mbeanName); // Check for another pattern resetPermissions(); addPermission(new MBeanPermission("[JMImplementation:*]", "queryMBeans")); mbeans = server.queryMBeans(null, null); assertTrue(mbeans.size() >= 1); for (Iterator iterator = mbeans.iterator(); iterator.hasNext();) { instance = (ObjectInstance)iterator.next(); assertEquals(instance.getObjectName().getDomain(), "JMImplementation"); } // Check for all resetPermissions(); addPermission(new MBeanPermission("*", "queryMBeans")); // Try queryNames to see if the permission is implies mbeans = server.queryNames(null, null); assertEquals(mbeans.size(), server.getMBeanCount().intValue()); // Check for the query expression resetPermissions(); String className = "mx4j.server.MX4JMBeanServerDelegate"; addPermission(new MBeanPermission(className, "queryMBeans")); QueryExp exp = Query.eq(Query.attr(className, "ImplementationName"), Query.value("MX4J")); mbeans = server.queryMBeans(null, exp); assertEquals(mbeans.size(), 0); // Now grant also the permission to retrieve the attribute addPermission(new MBeanPermission(className, "getAttribute, getObjectInstance")); mbeans = server.queryMBeans(null, exp); assertEquals(mbeans.size(), 1); instance = (ObjectInstance)mbeans.iterator().next(); assertEquals(instance.getClassName(), className); } protected void testQueryNames(MBeanServerConnection server) throws Exception { ObjectName mbeanName = new ObjectName(server.getDefaultDomain(), "mbean", "simple"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), mbeanName, null); try { server.queryNames(null, null); fail(); } catch (SecurityException ignored) { } // Check that an ObjectName that does not match returns an empty list ObjectName dummy = new ObjectName(server.getDefaultDomain(), "type", "dummy"); addPermission(new MBeanPermission("[" + dummy.getCanonicalName() + "]", "queryNames")); Set mbeans = server.queryNames(null, null); assertEquals(mbeans.size(), 0); // Now check the right one resetPermissions(); addPermission(new MBeanPermission("[" + mbeanName.getCanonicalName() + "]", "queryNames")); mbeans = server.queryNames(null, null); assertEquals(mbeans.size(), 1); ObjectName name = (ObjectName)mbeans.iterator().next(); assertEquals(name, mbeanName); // Check the right one for a pattern in permission resetPermissions(); addPermission(new MBeanPermission("["+ server.getDefaultDomain() + ":*]", "queryNames")); mbeans = server.queryNames(null, null); assertEquals(mbeans.size(), 1); name = (ObjectName)mbeans.iterator().next(); assertEquals(name, mbeanName); // Check for another pattern resetPermissions(); addPermission(new MBeanPermission("[JMImplementation:*]", "queryNames")); mbeans = server.queryNames(null, null); assertTrue(mbeans.size() >= 1); for (Iterator iterator = mbeans.iterator(); iterator.hasNext();) { name = (ObjectName)iterator.next(); assertEquals(name.getDomain(), "JMImplementation"); } // Check for all resetPermissions(); addPermission(new MBeanPermission("*", "queryNames")); mbeans = server.queryNames(null, null); assertEquals(mbeans.size(), server.getMBeanCount().intValue()); // Check for the query expression resetPermissions(); String className = "mx4j.server.MX4JMBeanServerDelegate"; addPermission(new MBeanPermission(className, "queryNames")); QueryExp exp = Query.eq(Query.attr(className, "ImplementationName"), Query.value("MX4J")); mbeans = server.queryNames(null, exp); assertEquals(mbeans.size(), 0); // Now grant also the permission to retrieve the attribute addPermission(new MBeanPermission(className, "getAttribute, getObjectInstance")); mbeans = server.queryNames(null, exp); assertEquals(mbeans.size(), 1); name = (ObjectName)mbeans.iterator().next(); assertEquals(name, new ObjectName("JMImplementation", "type", "MBeanServerDelegate")); } protected void testSetAttribute(MBeanServerConnection server) throws Exception { ObjectName name = new ObjectName(server.getDefaultDomain(), "name", "test"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), name, null); String attributeName = "FirstAttribute"; String value = "first"; Attribute attribute = new Attribute(attributeName, value); try { server.setAttribute(name, attribute); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission("#" + attributeName + "[" + name.getCanonicalName() + "]", "setAttribute")); server.setAttribute(name, attribute); // Check that it worked addPermission(new MBeanPermission("#" + attributeName, "getAttribute")); String result = (String)server.getAttribute(name, attributeName); assertEquals(result, value); } protected void testSetAttributes(MBeanServerConnection server) throws Exception { ObjectName mbeanName = new ObjectName(server.getDefaultDomain(), "mbean", "simple"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), mbeanName, null); AttributeList allAttributes = new AttributeList(); allAttributes.add(new Attribute("FirstAttribute", "first")); allAttributes.add(new Attribute("SecondAttribute", "second")); allAttributes.add(new Attribute("ThirdAttribute", "third")); allAttributes.add(new Attribute("Running", Boolean.TRUE)); AttributeList allowed = new AttributeList(); AttributeList wanted = new AttributeList(); try { server.setAttributes(mbeanName, allAttributes); fail(); } catch (SecurityException ignored) { } // Check that for wrong attribute I get an empty list allowed.clear(); allowed.add(allAttributes.get(0)); wanted.clear(); wanted.add(allAttributes.get(1)); addPermission(new MBeanPermission("#" + ((Attribute)allowed.get(0)).getName() + "[" + mbeanName.getCanonicalName() + "]", "setAttribute")); AttributeList list = server.setAttributes(mbeanName, wanted); assertEquals(list.size(), 0); // Check that for the right attribute I get it resetPermissions(); allowed.clear(); allowed.add(allAttributes.get(0)); wanted.clear(); wanted.addAll(allAttributes); addPermission(new MBeanPermission("#" + ((Attribute)allowed.get(0)).getName() + "[" + mbeanName.getCanonicalName() + "]", "setAttribute")); list = server.setAttributes(mbeanName, wanted); assertEquals(list.size(), allowed.size()); Attribute attrib = (Attribute)list.get(0); assertEquals(attrib, allowed.get(0)); // Check that if I grant some I only get some resetPermissions(); // Only attributes that ends with 'Attribute' allowed.clear(); allowed.add(allAttributes.get(0)); allowed.add(allAttributes.get(1)); allowed.add(allAttributes.get(2)); wanted.clear(); wanted.addAll(allAttributes); addPermission(new MBeanPermission("#*Attribute[" + mbeanName.getCanonicalName() + "]", "setAttribute")); list = server.setAttributes(mbeanName, wanted); assertEquals(list.size(), allowed.size()); for (int i = 0; i < list.size(); ++i) { Attribute attr = (Attribute)list.get(i); assertEquals(attr, allowed.get(i)); } // Check that if I grant all I get them all resetPermissions(); allowed.clear(); allowed.addAll(allAttributes); wanted.clear(); wanted.addAll(allAttributes); addPermission(new MBeanPermission("[" + mbeanName.getCanonicalName() + "]", "setAttribute")); list = server.setAttributes(mbeanName, wanted); assertEquals(list.size(), allowed.size()); for (int i = 0; i < list.size(); ++i) { Attribute attr = (Attribute)list.get(i); assertEquals(attr, allowed.get(i)); } } protected void testUnregisterMBean(MBeanServerConnection server) throws Exception { ObjectName name = new ObjectName(server.getDefaultDomain(), "name", "test"); addPermission(new MBeanPermission(Simple.class.getName(), "instantiate, registerMBean")); addPermission(new MBeanTrustPermission("register")); server.createMBean(Simple.class.getName(), name, null); try { server.unregisterMBean(name); fail(); } catch (SecurityException ignored) { } addPermission(new MBeanPermission(Simple.class.getName() + "[" + name.getCanonicalName() + "]", "unregisterMBean")); server.unregisterMBean(name); } public interface SimpleMBean { public void setFirstAttribute(String value); public String getFirstAttribute(); public void setSecondAttribute(String value); public String getSecondAttribute(); public void setThirdAttribute(String value); public String getThirdAttribute(); public void setRunning(boolean value); public boolean isRunning(); public String concatenateWithFirstAttribute(String value); } public static class Simple implements SimpleMBean { private String firstAttribute; private String secondAttribute; private String thirdAttribute; private boolean running; public String getFirstAttribute() { return firstAttribute; } public void setFirstAttribute(String value) { this.firstAttribute = value; } public String getSecondAttribute() { return secondAttribute; } public void setSecondAttribute(String secondAttribute) { this.secondAttribute = secondAttribute; } public String getThirdAttribute() { return thirdAttribute; } public void setThirdAttribute(String thirdAttribute) { this.thirdAttribute = thirdAttribute; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } public String concatenateWithFirstAttribute(String value) { return this.firstAttribute + value; } } } mx4j-3.0.2/src/test/test/javax/management/StandardMBeanTest.java100644 0 0 15645 10513545721 21703 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.StandardMBean; import test.MX4JTestCase; import test.javax.management.support.StandardMBeanSupport; /** * @version $Revision: 1.7 $ */ public class StandardMBeanTest extends MX4JTestCase { public StandardMBeanTest(String s) { super(s); } public void testInvalidStandardMBean() throws Exception { try { new StandardMBean(null, null); fail("Implementation cannot be null"); } catch (IllegalArgumentException x) { } try { Object impl = new Object(); new StandardMBean(impl, null); fail(impl.getClass().getName() + " is not a compliant MBean"); } catch (NotCompliantMBeanException x) { } try { Object impl = new Object(); Class mgmt = Cloneable.class; new StandardMBean(impl, mgmt); fail(impl.getClass().getName() + " does not implement " + mgmt.getName()); } catch (NotCompliantMBeanException x) { } try { Object impl = new Object(); Class mgmt = Object.class; new StandardMBean(impl, mgmt); fail("Class " + mgmt.getName() + " is not an interface"); } catch (NotCompliantMBeanException x) { } try { new StandardMBeanSupport.SubclassNotCompliant(); fail("StandardMBean is not compliant"); } catch (NotCompliantMBeanException x) { } } public void testSubclassWithNoManagement() throws Exception { StandardMBean mbean = new StandardMBeanSupport.SubclassWithNoManagement(); testNoManagement(mbean); } public void testSubclassWithManagement() throws Exception { StandardMBean mbean = new StandardMBeanSupport.SubclassWithManagement(); testManagement(mbean); } public void testImplementationWithNoManagement() throws Exception { StandardMBean mbean = new StandardMBean(new StandardMBeanSupport.ImplementationWithNoManagement(), null); testNoManagement(mbean); } public void testImplementationWithManagement() throws Exception { StandardMBean mbean = new StandardMBean(new StandardMBeanSupport.ImplementationWithManagement(), StandardMBeanSupport.Management.class); testManagement(mbean); } private void testNoManagement(Object mbean) throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = ObjectName.getInstance(":type=subclass,management=no"); server.registerMBean(mbean, name); Object result = server.invoke(name, "test", null, null); assertNotNull(result); } private void testManagement(Object mbean) throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = ObjectName.getInstance(":type=subclass,management=yes"); server.registerMBean(mbean, name); Object result = server.invoke(name, "test", null, null); assertNotNull(result); try { server.invoke(name, "cannotCall", null, null); fail("Cannot invoke a method not in the management interface"); } catch (ReflectionException x) { } } public void testMBeanInfoCaching() throws Exception { StandardMBean mbean = new StandardMBeanSupport.SubclassWithNoManagement(); MBeanInfo original = mbean.getMBeanInfo(); // Make a second call and be sure it's cached MBeanInfo info = mbean.getMBeanInfo(); if (info != original) fail("MBeanInfo is not cached"); } public void testCallbacks() throws Exception { StandardMBeanSupport.CallbackCounter mbean = new StandardMBeanSupport.CallbackCounter(0); // Trigger the callbacks mbean.getMBeanInfo(); // There are 10 callbacks: the management interface has 1 attribute and 1 operation, so: // 1 -> class name of MBeanInfo // 2 -> description of MBeanInfo // 3 -> description of attribute // 6 -> description of constructor + parameter name + parameter description // 10 -> description of operation + parameter name + parameter description + operation impact assertEquals(mbean.getCount(), 10); } public void testSetImplementation() throws Exception { StandardMBean mbean = new StandardMBeanSupport.SubclassWithManagement(); mbean.setImplementation(new StandardMBeanSupport.ImplementationWithManagement()); try { mbean.setImplementation(new Object()); fail("New implementation does not implement the management interface " + mbean.getMBeanInterface().getName()); } catch (NotCompliantMBeanException x) { } } public void testPublicManagementInterfaceWithPrivateImplementation() throws Exception { // Tests whether a MBean is acceptable as long as the public interface is public // Checks compliance with p34 of JMX 1.2 specification StandardMBeanSupport.PublicInterfaceMBean mbean = StandardMBeanSupport.createPublicInterfaceMBean(); MBeanServer server = newMBeanServer(); ObjectName name = ObjectName.getInstance(":type=privateimplementation"); server.registerMBean(mbean, name); Object result = server.invoke(name, "test", null, null); assertNotNull(result); try { name = ObjectName.getInstance(":type=privateimplementation2"); server.createMBean("test.javax.management.support.StandardMBeanSupport$PublicInterface", name); fail("Must not be able to create an MBean whose class is private"); } catch (ReflectionException x) { Exception xx = x.getTargetException(); assertTrue(xx instanceof IllegalAccessException); } } public void testIsInstanceOf() throws Exception { MBeanServer mbs = newMBeanServer(); StandardMBean smbone = new StandardMBean(new StandardMBeanSupport.ImplementationWithManagement(), StandardMBeanSupport.Management.class); ObjectName smbonename = new ObjectName(":type=implwmgmt"); mbs.registerMBean(smbone, smbonename); StandardMBean smbtwo = new StandardMBean(new StandardMBeanSupport.CallbackCounter(42), StandardMBeanSupport.FullManagement.class); ObjectName smbtwoname = new ObjectName(":type=cbcounter"); mbs.registerMBean(smbtwo, smbtwoname); assertTrue(mbs.isInstanceOf(smbonename, "test.javax.management.support.StandardMBeanSupport$Management")); assertTrue(mbs.isInstanceOf(smbtwoname, "test.javax.management.support.StandardMBeanSupport$FullManagement")); } } mx4j-3.0.2/src/test/test/javax/management/compliance/ComplianceTestCase.java100644 0 0 5507 10513545721 24174 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import test.MX4JTestCase; /** * @version $Revision: 1.5 $ */ public abstract class ComplianceTestCase extends MX4JTestCase { public ComplianceTestCase(String s) { super(s); } public void testCompliance() throws Exception { ClassLoader loader = createClassLoader(); JarFile jar = loadJar(); Enumeration entries = jar.entries(); ArrayList nonExistingMethods = new ArrayList(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); // Skip directories if (entry.isDirectory()) continue; // Skip Sun's implementation classes String entryName = entry.getName(); if (entryName.startsWith("javax")) { // Take the class String fullClassName = entryName.replace('/', '.'); fullClassName = fullClassName.substring(0, fullClassName.length() - ".class".length()); if (skipClassName(fullClassName)) continue; Class cls = loader.loadClass(fullClassName); if (skipClass(cls)) continue; String name = fullClassName.substring("javax.management".length()); name = name.replace('.', '_'); try { // Verify that a method with this name exists getClass().getMethod("test" + name, new Class[0]); } catch (NoSuchMethodException x) { nonExistingMethods.add(fullClassName); } } } Collections.sort(nonExistingMethods); if (nonExistingMethods.size() > 0) fail("Compliance test incomplete, missing classes are:\n" + nonExistingMethods); } protected abstract boolean skipClassName(String className); protected abstract boolean skipClass(Class cls); protected abstract void checkCompliance(String className) throws Exception; protected abstract ClassLoader createClassLoader() throws MalformedURLException; protected abstract JarFile loadJar() throws IOException; protected void check(String partialClassName) throws Exception { ClassLoader loader = createClassLoader(); String fullName = "javax.management." + partialClassName; if (skipClassName(fullName)) return; if (skipClass(loader.loadClass(fullName))) return; checkCompliance(fullName); } } mx4j-3.0.2/src/test/test/javax/management/compliance/JMXComplianceTestCase.java100644 0 0 45554 10513545721 24601 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.JarFile; /** * @version $Revision: 1.4 $ */ public abstract class JMXComplianceTestCase extends ComplianceTestCase { public JMXComplianceTestCase(String s) { super(s); } protected ClassLoader createClassLoader() throws MalformedURLException { return createJMXRIWithTestsClassLoader(); } protected JarFile loadJar() throws IOException { File jmxri = new File("dist/test/jmxri.jar"); if (!jmxri.exists()) fail("JMXRI jar is not available"); JarFile jmxriJar = new JarFile(jmxri); return jmxriJar; } public void test_AndQueryExp() throws Exception { check("AndQueryExp"); } public void test_Attribute() throws Exception { check("Attribute"); } public void test_AttributeChangeNotification() throws Exception { check("AttributeChangeNotification"); } public void test_AttributeChangeNotificationFilter() throws Exception { check("AttributeChangeNotificationFilter"); } public void test_AttributeList() throws Exception { check("AttributeList"); } public void test_AttributeNotFoundException() throws Exception { check("AttributeNotFoundException"); } public void test_AttributeValueExp() throws Exception { check("AttributeValueExp"); } public void test_BadAttributeValueExpException() throws Exception { check("BadAttributeValueExpException"); } public void test_BadBinaryOpValueExpException() throws Exception { check("BadBinaryOpValueExpException"); } public void test_BadStringOperationException() throws Exception { check("BadStringOperationException"); } public void test_BetweenQueryExp() throws Exception { check("BetweenQueryExp"); } public void test_BinaryOpValueExp() throws Exception { check("BinaryOpValueExp"); } public void test_BinaryRelQueryExp() throws Exception { check("BinaryRelQueryExp"); } public void test_BooleanValueExp() throws Exception { check("BooleanValueExp"); } public void test_ClassAttributeValueExp() throws Exception { check("ClassAttributeValueExp"); } public void test_DefaultLoaderRepository() throws Exception { check("DefaultLoaderRepository"); } public void test_Descriptor() throws Exception { check("Descriptor"); } public void test_DescriptorAccess() throws Exception { check("DescriptorAccess"); } public void test_DynamicMBean() throws Exception { check("DynamicMBean"); } public void test_InQueryExp() throws Exception { check("InQueryExp"); } public void test_InstanceAlreadyExistsException() throws Exception { check("InstanceAlreadyExistsException"); } public void test_InstanceNotFoundException() throws Exception { check("InstanceNotFoundException"); } public void test_IntrospectionException() throws Exception { check("IntrospectionException"); } public void test_InvalidApplicationException() throws Exception { check("InvalidApplicationException"); } public void test_InvalidAttributeValueException() throws Exception { check("InvalidAttributeValueException"); } public void test_JMException() throws Exception { check("JMException"); } public void test_JMRuntimeException() throws Exception { check("JMRuntimeException"); } public void test_ListenerNotFoundException() throws Exception { check("ListenerNotFoundException"); } public void test_MalformedObjectNameException() throws Exception { check("MalformedObjectNameException"); } public void test_MatchQueryExp() throws Exception { check("MatchQueryExp"); } public void test_MBeanAttributeInfo() throws Exception { check("MBeanAttributeInfo"); } public void test_MBeanConstructorInfo() throws Exception { check("MBeanConstructorInfo"); } public void test_MBeanException() throws Exception { check("MBeanException"); } public void test_MBeanFeatureInfo() throws Exception { check("MBeanFeatureInfo"); } public void test_MBeanInfo() throws Exception { check("MBeanInfo"); } public void test_MBeanNotificationInfo() throws Exception { check("MBeanNotificationInfo"); } public void test_MBeanOperationInfo() throws Exception { check("MBeanOperationInfo"); } public void test_MBeanParameterInfo() throws Exception { check("MBeanParameterInfo"); } public void test_MBeanPermission() throws Exception { check("MBeanPermission"); } public void test_MBeanRegistration() throws Exception { check("MBeanRegistration"); } public void test_MBeanRegistrationException() throws Exception { check("MBeanRegistrationException"); } public void test_MBeanServer() throws Exception { check("MBeanServer"); } public void test_MBeanServerBuilder() throws Exception { check("MBeanServerBuilder"); } public void test_MBeanServerConnection() throws Exception { check("MBeanServerConnection"); } public void test_MBeanServerDelegate() throws Exception { check("MBeanServerDelegate"); } public void test_MBeanServerDelegateMBean() throws Exception { check("MBeanServerDelegateMBean"); } public void test_MBeanServerFactory() throws Exception { check("MBeanServerFactory"); } public void test_MBeanServerInvocationHandler() throws Exception { check("MBeanServerInvocationHandler"); } public void test_MBeanServerNotification() throws Exception { check("MBeanServerNotification"); } public void test_MBeanServerPermission() throws Exception { check("MBeanServerPermission"); } public void test_MBeanTrustPermission() throws Exception { check("MBeanTrustPermission"); } public void test_NotCompliantMBeanException() throws Exception { check("NotCompliantMBeanException"); } public void test_Notification() throws Exception { check("Notification"); } public void test_NotificationBroadcaster() throws Exception { check("NotificationBroadcaster"); } public void test_NotificationBroadcasterSupport() throws Exception { check("NotificationBroadcasterSupport"); } public void test_NotificationEmitter() throws Exception { check("NotificationEmitter"); } public void test_NotificationFilter() throws Exception { check("NotificationFilter"); } public void test_NotificationFilterSupport() throws Exception { check("NotificationFilterSupport"); } public void test_NotificationListener() throws Exception { check("NotificationListener"); } public void test_NotQueryExp() throws Exception { check("NotQueryExp"); } public void test_NumericValueExp() throws Exception { check("NumericValueExp"); } public void test_ObjectInstance() throws Exception { check("ObjectInstance"); } public void test_ObjectName() throws Exception { check("ObjectName"); } public void test_OperationsException() throws Exception { check("OperationsException"); } public void test_OrQueryExp() throws Exception { check("OrQueryExp"); } public void test_PersistentMBean() throws Exception { check("PersistentMBean"); } public void test_QualifiedAttributeValueExp() throws Exception { check("QualifiedAttributeValueExp"); } public void test_Query() throws Exception { check("Query"); } public void test_QueryEval() throws Exception { check("QueryEval"); } public void test_QueryExp() throws Exception { check("QueryExp"); } public void test_ReflectionException() throws Exception { check("ReflectionException"); } public void test_RuntimeErrorException() throws Exception { check("RuntimeErrorException"); } public void test_RuntimeMBeanException() throws Exception { check("RuntimeMBeanException"); } public void test_RuntimeOperationsException() throws Exception { check("RuntimeOperationsException"); } public void test_ServiceNotFoundException() throws Exception { check("ServiceNotFoundException"); } public void test_StandardMBean() throws Exception { check("StandardMBean"); } public void test_StringValueExp() throws Exception { check("StringValueExp"); } public void test_ValueExp() throws Exception { check("ValueExp"); } public void test_loading_ClassLoaderRepository() throws Exception { check("loading.ClassLoaderRepository"); } public void test_loading_DefaultLoaderRepository() throws Exception { check("loading.DefaultLoaderRepository"); } public void test_loading_MLet() throws Exception { check("loading.MLet"); } public void test_loading_MLetMBean() throws Exception { check("loading.MLetMBean"); } public void test_loading_PrivateClassLoader() throws Exception { check("loading.PrivateClassLoader"); } public void test_loading_PrivateMLet() throws Exception { check("loading.PrivateMLet"); } public void test_modelmbean_DescriptorSupport() throws Exception { check("modelmbean.DescriptorSupport"); } public void test_modelmbean_InvalidTargetObjectTypeException() throws Exception { check("modelmbean.InvalidTargetObjectTypeException"); } public void test_modelmbean_ModelMBean() throws Exception { check("modelmbean.ModelMBean"); } public void test_modelmbean_ModelMBeanAttributeInfo() throws Exception { check("modelmbean.ModelMBeanAttributeInfo"); } public void test_modelmbean_ModelMBeanConstructorInfo() throws Exception { check("modelmbean.ModelMBeanConstructorInfo"); } public void test_modelmbean_ModelMBeanInfo() throws Exception { check("modelmbean.ModelMBeanInfo"); } public void test_modelmbean_ModelMBeanInfoSupport() throws Exception { check("modelmbean.ModelMBeanInfoSupport"); } public void test_modelmbean_ModelMBeanNotificationBroadcaster() throws Exception { check("modelmbean.ModelMBeanNotificationBroadcaster"); } public void test_modelmbean_ModelMBeanNotificationInfo() throws Exception { check("modelmbean.ModelMBeanNotificationInfo"); } public void test_modelmbean_ModelMBeanOperationInfo() throws Exception { check("modelmbean.ModelMBeanOperationInfo"); } public void test_modelmbean_RequiredModelMBean() throws Exception { check("modelmbean.RequiredModelMBean"); } public void test_modelmbean_XMLParseException() throws Exception { check("modelmbean.XMLParseException"); } public void test_monitor_CounterMonitor() throws Exception { check("monitor.CounterMonitor"); } public void test_monitor_CounterMonitorMBean() throws Exception { check("monitor.CounterMonitorMBean"); } public void test_monitor_GaugeMonitor() throws Exception { check("monitor.GaugeMonitor"); } public void test_monitor_GaugeMonitorMBean() throws Exception { check("monitor.GaugeMonitorMBean"); } public void test_monitor_Monitor() throws Exception { check("monitor.Monitor"); } public void test_monitor_MonitorMBean() throws Exception { check("monitor.MonitorMBean"); } public void test_monitor_StringMonitor() throws Exception { check("monitor.StringMonitor"); } public void test_monitor_StringMonitorMBean() throws Exception { check("monitor.StringMonitorMBean"); } public void test_monitor_MonitorNotification() throws Exception { check("monitor.MonitorNotification"); } public void test_monitor_MonitorSettingException() throws Exception { check("monitor.MonitorSettingException"); } public void test_openmbean_ArrayType() throws Exception { check("openmbean.ArrayType"); } public void test_openmbean_CompositeData() throws Exception { check("openmbean.CompositeData"); } public void test_openmbean_CompositeDataSupport() throws Exception { check("openmbean.CompositeDataSupport"); } public void test_openmbean_CompositeType() throws Exception { check("openmbean.CompositeType"); } public void test_openmbean_InvalidKeyException() throws Exception { check("openmbean.InvalidKeyException"); } public void test_openmbean_InvalidOpenTypeException() throws Exception { check("openmbean.InvalidOpenTypeException"); } public void test_openmbean_KeyAlreadyExistsException() throws Exception { check("openmbean.KeyAlreadyExistsException"); } public void test_openmbean_OpenDataException() throws Exception { check("openmbean.OpenDataException"); } public void test_openmbean_OpenMBeanAttributeInfo() throws Exception { check("openmbean.OpenMBeanAttributeInfo"); } public void test_openmbean_OpenMBeanAttributeInfoSupport() throws Exception { check("openmbean.OpenMBeanAttributeInfoSupport"); } public void test_openmbean_OpenMBeanConstructorInfo() throws Exception { check("openmbean.OpenMBeanConstructorInfo"); } public void test_openmbean_OpenMBeanConstructorInfoSupport() throws Exception { check("openmbean.OpenMBeanConstructorInfoSupport"); } public void test_openmbean_OpenMBeanInfo() throws Exception { check("openmbean.OpenMBeanInfo"); } public void test_openmbean_OpenMBeanInfoSupport() throws Exception { check("openmbean.OpenMBeanInfoSupport"); } public void test_openmbean_OpenMBeanOperationInfo() throws Exception { check("openmbean.OpenMBeanOperationInfo"); } public void test_openmbean_OpenMBeanOperationInfoSupport() throws Exception { check("openmbean.OpenMBeanOperationInfoSupport"); } public void test_openmbean_OpenMBeanParameterInfo() throws Exception { check("openmbean.OpenMBeanParameterInfo"); } public void test_openmbean_OpenMBeanParameterInfoSupport() throws Exception { check("openmbean.OpenMBeanParameterInfoSupport"); } public void test_openmbean_OpenType() throws Exception { check("openmbean.OpenType"); } public void test_openmbean_SimpleType() throws Exception { check("openmbean.SimpleType"); } public void test_openmbean_TabularData() throws Exception { check("openmbean.TabularData"); } public void test_openmbean_TabularDataSupport() throws Exception { check("openmbean.TabularDataSupport"); } public void test_openmbean_TabularType() throws Exception { check("openmbean.TabularType"); } public void test_relation_InvalidRelationIdException() throws Exception { check("relation.InvalidRelationIdException"); } public void test_relation_InvalidRelationServiceException() throws Exception { check("relation.InvalidRelationServiceException"); } public void test_relation_InvalidRelationTypeException() throws Exception { check("relation.InvalidRelationTypeException"); } public void test_relation_InvalidRoleInfoException() throws Exception { check("relation.InvalidRoleInfoException"); } public void test_relation_InvalidRoleValueException() throws Exception { check("relation.InvalidRoleValueException"); } public void test_relation_MBeanServerNotificationFilter() throws Exception { check("relation.MBeanServerNotificationFilter"); } public void test_relation_Relation() throws Exception { check("relation.Relation"); } public void test_relation_RelationException() throws Exception { check("relation.RelationException"); } public void test_relation_RelationNotFoundException() throws Exception { check("relation.RelationNotFoundException"); } public void test_relation_RelationNotification() throws Exception { check("relation.RelationNotification"); } public void test_relation_RelationService() throws Exception { check("relation.RelationService"); } public void test_relation_RelationServiceMBean() throws Exception { check("relation.RelationServiceMBean"); } public void test_relation_RelationServiceNotRegisteredException() throws Exception { check("relation.RelationServiceNotRegisteredException"); } public void test_relation_RelationSupport() throws Exception { check("relation.RelationSupport"); } public void test_relation_RelationSupportMBean() throws Exception { check("relation.RelationSupportMBean"); } public void test_relation_RelationType() throws Exception { check("relation.RelationType"); } public void test_relation_RelationTypeNotFoundException() throws Exception { check("relation.RelationTypeNotFoundException"); } public void test_relation_RelationTypeSupport() throws Exception { check("relation.RelationTypeSupport"); } public void test_relation_Role() throws Exception { check("relation.Role"); } public void test_relation_RoleInfo() throws Exception { check("relation.RoleInfo"); } public void test_relation_RoleInfoNotFoundException() throws Exception { check("relation.RoleInfoNotFoundException"); } public void test_relation_RoleList() throws Exception { check("relation.RoleList"); } public void test_relation_RoleNotFoundException() throws Exception { check("relation.RoleNotFoundException"); } public void test_relation_RoleResult() throws Exception { check("relation.RoleResult"); } public void test_relation_RoleStatus() throws Exception { check("relation.RoleStatus"); } public void test_relation_RoleUnresolved() throws Exception { check("relation.RoleUnresolved"); } public void test_relation_RoleUnresolvedList() throws Exception { check("relation.RoleUnresolvedList"); } public void test_timer_Timer() throws Exception { check("timer.Timer"); } public void test_timer_TimerMBean() throws Exception { check("timer.TimerMBean"); } public void test_timer_TimerAlarmClockNotification() throws Exception { check("timer.TimerAlarmClockNotification"); } public void test_timer_TimerNotification() throws Exception { check("timer.TimerNotification"); } } mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/JMXSerializationTest.java100644 0 0 3445 10513545721 27376 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.serialization; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.JMXComplianceTestCase; import test.javax.management.compliance.serialization.support.SerializationVerifier; /** * @version $Revision: 1.4 $ */ public class JMXSerializationTest extends JMXComplianceTestCase { public JMXSerializationTest(String s) { super(s); } protected boolean skipClassName(String className) { // Skip some classes, not required for compliance if (className.equals("javax.management.MBeanServerPermissionCollection") || className.equals("javax.management.loading.MLet") || className.equals("javax.management.loading.PrivateMLet") || className.equals("javax.management.timer.TimerAlarmClockNotification")) return true; return false; } protected boolean skipClass(Class cls) { if (cls.isInterface() || !Serializable.class.isAssignableFrom(cls) || Modifier.isAbstract(cls.getModifiers())) return true; return false; } protected void checkCompliance(String name) throws Exception { ClassLoader jmxriLoader = createJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createMX4JWithTestsClassLoader(); SerializationVerifier verifier = new SerializationVerifier("test.javax.management.compliance.serialization.support.Instantiator", "test.javax.management.compliance.serialization.support.Comparator"); verifier.verifySerialization(name, jmxriLoader, mx4jLoader); } } mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/Comparator.java100644 0 0 66671 10513545721 27217 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.serialization.support; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; import javax.management.AttributeChangeNotification; import javax.management.AttributeChangeNotificationFilter; import javax.management.AttributeList; import javax.management.AttributeValueExp; import javax.management.BadBinaryOpValueExpException; import javax.management.JMRuntimeException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanFeatureInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServerNotification; import javax.management.MBeanTrustPermission; import javax.management.Notification; import javax.management.NotificationFilterSupport; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.management.RuntimeErrorException; import javax.management.RuntimeMBeanException; import javax.management.RuntimeOperationsException; import javax.management.StringValueExp; import javax.management.ValueExp; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanConstructorInfo; import javax.management.modelmbean.ModelMBeanInfoSupport; import javax.management.modelmbean.ModelMBeanNotificationInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; import javax.management.monitor.MonitorNotification; import javax.management.relation.MBeanServerNotificationFilter; import javax.management.relation.RelationNotification; import javax.management.relation.RelationTypeSupport; import javax.management.relation.Role; import javax.management.relation.RoleInfo; import javax.management.relation.RoleList; import javax.management.relation.RoleResult; import javax.management.relation.RoleUnresolved; import javax.management.relation.RoleUnresolvedList; import javax.management.timer.TimerNotification; /** * @version $Revision: 1.7 $ */ public class Comparator { public void compareAndQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareAttributeChangeNotification(Object o1, Object o2) { compareNotification(o1, o2); AttributeChangeNotification n1 = (AttributeChangeNotification)o1; AttributeChangeNotification n2 = (AttributeChangeNotification)o2; if (!n1.getAttributeName().equals(n2.getAttributeName())) throw new RuntimeException(); if (!n1.getAttributeType().equals(n2.getAttributeType())) throw new RuntimeException(); if (!n1.getNewValue().equals(n2.getNewValue())) throw new RuntimeException(); if (!n1.getOldValue().equals(n2.getOldValue())) throw new RuntimeException(); } public void compareAttributeChangeNotificationFilter(Object o1, Object o2) { AttributeChangeNotificationFilter f1 = (AttributeChangeNotificationFilter)o1; AttributeChangeNotificationFilter f2 = (AttributeChangeNotificationFilter)o2; if (!f1.getEnabledAttributes().equals(f2.getEnabledAttributes())) throw new RuntimeException(); } public void compareAttributeList(Object o1, Object o2) { AttributeList a1 = (AttributeList)o1; AttributeList a2 = (AttributeList)o2; // It's enough AttributeList.equals() if (!a1.equals(a2)) throw new RuntimeException(); } public void compareAttributeNotFoundException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareAttributeValueExp(Object o1, Object o2) { AttributeValueExp val1 = (AttributeValueExp)o1; AttributeValueExp val2 = (AttributeValueExp)o2; if (!val1.getAttributeName().equals(val2.getAttributeName())) throw new RuntimeException(); } public void compareBadAttributeValueExpException(Object o1, Object o2) { // No way to compare them } public void compareBadBinaryOpValueExpException(Object o1, Object o2) { BadBinaryOpValueExpException b1 = (BadBinaryOpValueExpException)o1; BadBinaryOpValueExpException b2 = (BadBinaryOpValueExpException)o2; compareStringValueExp(b1.getExp(), b2.getExp()); } public void compareBadStringOperationException(Object o1, Object o2) { // No way to compare them } public void compareBetweenQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareBinaryOpValueExp(Object o1, Object o2) throws Exception { ValueExp val1 = (ValueExp)o1; ValueExp val2 = (ValueExp)o2; compareNumericValueExp(val1.apply(null), val2.apply(null)); } public void compareBinaryRelQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareBooleanValueExp(Object o1, Object o2) throws Exception { Field field = o1.getClass().getDeclaredField("val"); field.setAccessible(true); boolean res1 = field.getBoolean(o1); boolean res2 = field.getBoolean(o2); if (!res1 || !res2) throw new RuntimeException(); } public void compareClassAttributeValueExp(Object o1, Object o2) { // Nothing to compare } public void compareInQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareInstanceAlreadyExistsException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareInstanceNotFoundException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareIntrospectionException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareInvalidApplicationException(Object o1, Object o2) { // No way to compare them } public void compareInvalidAttributeValueException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareJMException(Object o1, Object o2) { compareException(o1, o2); } public void compareError(Object o1, Object o2) { Error x1 = (Error)o1; Error x2 = (Error)o2; if (!x1.getMessage().equals(x2.getMessage())) throw new RuntimeException(); } public void compareException(Object o1, Object o2) { Exception x1 = (Exception)o1; Exception x2 = (Exception)o2; if (!x1.getMessage().equals(x2.getMessage())) throw new RuntimeException(); } public void compareJMRuntimeException(Object o1, Object o2) { JMRuntimeException x1 = (JMRuntimeException)o1; JMRuntimeException x2 = (JMRuntimeException)o2; if (!x1.getMessage().equals(x2.getMessage())) throw new RuntimeException(); } public void compareListenerNotFoundException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareMalformedObjectNameException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareMatchQueryExp(Object o1, Object o2) throws Exception { // Cannot be compared, require MBeanServer } public void compareMBeanAttributeInfo(Object o1, Object o2) { compareMBeanFeatureInfo(o1, o2); MBeanAttributeInfo a1 = (MBeanAttributeInfo)o1; MBeanAttributeInfo a2 = (MBeanAttributeInfo)o2; if (!a1.getType().equals(a2.getType())) throw new RuntimeException(); if (a1.isReadable() != a2.isReadable()) throw new RuntimeException(); if (a1.isWritable() != a2.isWritable()) throw new RuntimeException(); if (a1.isIs() != a2.isIs()) throw new RuntimeException(); } public void compareMBeanConstructorInfo(Object o1, Object o2) { compareMBeanFeatureInfo(o1, o2); MBeanConstructorInfo c1 = (MBeanConstructorInfo)o1; MBeanConstructorInfo c2 = (MBeanConstructorInfo)o2; MBeanParameterInfo[] p1 = c1.getSignature(); MBeanParameterInfo[] p2 = c2.getSignature(); if (p1.length != p2.length) throw new RuntimeException(); for (int i = 0; i < p1.length; ++i) { compareMBeanParameterInfo(p1[i], p2[i]); } } public void compareMBeanException(Object o1, Object o2) { compareJMException(o1, o2); MBeanException x1 = (MBeanException)o1; MBeanException x2 = (MBeanException)o2; Exception xx1 = x1.getTargetException(); Exception xx2 = x2.getTargetException(); compareException(xx1, xx2); } public void compareMBeanFeatureInfo(Object o1, Object o2) { MBeanFeatureInfo f1 = (MBeanFeatureInfo)o1; MBeanFeatureInfo f2 = (MBeanFeatureInfo)o2; if (!f1.getName().equals(f2.getName())) throw new RuntimeException(); if (!f1.getDescription().equals(f2.getDescription())) throw new RuntimeException(); } public void compareMBeanInfo(Object o1, Object o2) { MBeanInfo i1 = (MBeanInfo)o1; MBeanInfo i2 = (MBeanInfo)o2; if (!i1.getClassName().equals(i2.getClassName())) throw new RuntimeException(); if (!i1.getDescription().equals(i2.getDescription())) throw new RuntimeException(); MBeanAttributeInfo[] a1 = i1.getAttributes(); MBeanAttributeInfo[] a2 = i2.getAttributes(); if (a1.length != a2.length) throw new RuntimeException(); for (int i = 0; i < a1.length; ++i) { compareMBeanAttributeInfo(a1[i], a2[i]); } MBeanConstructorInfo[] c1 = i1.getConstructors(); MBeanConstructorInfo[] c2 = i2.getConstructors(); if (c1.length != c2.length) throw new RuntimeException(); for (int i = 0; i < c1.length; ++i) { compareMBeanConstructorInfo(c1[i], c2[i]); } MBeanNotificationInfo[] n1 = i1.getNotifications(); MBeanNotificationInfo[] n2 = i2.getNotifications(); if (n1.length != n2.length) throw new RuntimeException(); for (int i = 0; i < n1.length; ++i) { compareMBeanNotificationInfo(n1[i], n2[i]); } MBeanOperationInfo[] op1 = i1.getOperations(); MBeanOperationInfo[] op2 = i2.getOperations(); if (op1.length != op2.length) throw new RuntimeException(); for (int i = 0; i < op1.length; ++i) { compareMBeanOperationInfo(op1[i], op2[i]); } } public void compareMBeanNotificationInfo(Object o1, Object o2) { compareMBeanFeatureInfo(o1, o2); MBeanNotificationInfo n1 = (MBeanNotificationInfo)o1; MBeanNotificationInfo n2 = (MBeanNotificationInfo)o2; String[] t1 = n1.getNotifTypes(); String[] t2 = n2.getNotifTypes(); if (t1.length != t2.length) throw new RuntimeException(); for (int i = 0; i < t1.length; ++i) { if (!t1[i].equals(t2[i])) throw new RuntimeException(); } } public void compareMBeanOperationInfo(Object o1, Object o2) { compareMBeanFeatureInfo(o1, o2); MBeanOperationInfo op1 = (MBeanOperationInfo)o1; MBeanOperationInfo op2 = (MBeanOperationInfo)o2; if (op1.getImpact() != op2.getImpact()) throw new RuntimeException(); if (!op1.getReturnType().equals(op2.getReturnType())) throw new RuntimeException(); MBeanParameterInfo[] p1 = op1.getSignature(); MBeanParameterInfo[] p2 = op2.getSignature(); if (p1.length != p2.length) throw new RuntimeException(); for (int i = 0; i < p1.length; ++i) { compareMBeanParameterInfo(p1[i], p2[i]); } } public void compareMBeanParameterInfo(Object o1, Object o2) { compareMBeanFeatureInfo(o1, o2); MBeanParameterInfo p1 = (MBeanParameterInfo)o1; MBeanParameterInfo p2 = (MBeanParameterInfo)o2; if (!p1.getType().equals(p2.getType())) throw new RuntimeException(); } public void compareMBeanRegistrationException(Object o1, Object o2) { compareMBeanException(o1, o2); } public void compareMBeanServerNotification(Object o1, Object o2) { compareNotification(o1, o2); ObjectName obj1 = ((MBeanServerNotification)o1).getMBeanName(); ObjectName obj2 = ((MBeanServerNotification)o2).getMBeanName(); if (!obj1.equals(obj2)) throw new RuntimeException(); } public void compareMBeanTrustPermission(Object o1, Object o2) { MBeanTrustPermission p1 = (MBeanTrustPermission)o1; MBeanTrustPermission p2 = (MBeanTrustPermission)o2; if (!p1.getName().equals(p2.getName())) throw new RuntimeException(); } public void compareNotCompliantMBeanException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareNotification(Object o1, Object o2) { Notification n1 = (Notification)o1; Notification n2 = (Notification)o2; if (!n1.getSource().equals(n2.getSource())) throw new RuntimeException(); if (!n1.getType().equals(n2.getType())) throw new RuntimeException(); if (n1.getSequenceNumber() != n2.getSequenceNumber()) throw new RuntimeException(); if (!n1.getUserData().equals(n2.getUserData())) throw new RuntimeException(); if (!n1.getMessage().equals(n2.getMessage())) throw new RuntimeException(); } public void compareNotificationFilterSupport(Object o1, Object o2) { NotificationFilterSupport f1 = (NotificationFilterSupport)o1; NotificationFilterSupport f2 = (NotificationFilterSupport)o2; Vector types1 = f1.getEnabledTypes(); Vector types2 = f2.getEnabledTypes(); if (!types1.containsAll(types2) || !types2.containsAll(types1)) throw new RuntimeException(); } public void compareNotQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareNumericValueExp(Object o1, Object o2) throws Exception { Method method = o1.getClass().getDeclaredMethod("longValue", new Class[0]); method.setAccessible(true); Object res1 = method.invoke(o1, new Object[0]); Object res2 = method.invoke(o2, new Object[0]); if (!res1.equals(res2)) throw new RuntimeException(); } public void compareOperationsException(Object o1, Object o2) { compareJMException(o1, o2); } public void compareOrQueryExp(Object o1, Object o2) throws Exception { compareQueryExp(o1, o2); } public void compareQualifiedAttributeValueExp(Object o1, Object o2) { compareAttributeValueExp(o1, o2); } public void compareQueryExp(Object o1, Object o2) throws Exception { QueryExp exp1 = (QueryExp)o1; QueryExp exp2 = (QueryExp)o2; if (!exp1.apply(null)) throw new RuntimeException(); if (!exp2.apply(null)) throw new RuntimeException(); } public void compareReflectionException(Object o1, Object o2) { compareJMException(o1, o2); ReflectionException x1 = (ReflectionException)o1; ReflectionException x2 = (ReflectionException)o2; Exception xx1 = x1.getTargetException(); Exception xx2 = x2.getTargetException(); compareException(xx1, xx2); } public void compareRuntimeErrorException(Object o1, Object o2) { compareJMRuntimeException(o1, o2); RuntimeErrorException x1 = (RuntimeErrorException)o1; RuntimeErrorException x2 = (RuntimeErrorException)o2; Error e1 = x1.getTargetError(); Error e2 = x2.getTargetError(); compareError(e1, e2); } public void compareRuntimeMBeanException(Object o1, Object o2) { compareJMRuntimeException(o1, o2); RuntimeMBeanException x1 = (RuntimeMBeanException)o1; RuntimeMBeanException x2 = (RuntimeMBeanException)o2; RuntimeException e1 = x1.getTargetException(); RuntimeException e2 = x2.getTargetException(); compareException(e1, e2); } public void compareRuntimeOperationsException(Object o1, Object o2) { compareJMRuntimeException(o1, o2); RuntimeOperationsException x1 = (RuntimeOperationsException)o1; RuntimeOperationsException x2 = (RuntimeOperationsException)o2; RuntimeException e1 = x1.getTargetException(); RuntimeException e2 = x2.getTargetException(); compareException(e1, e2); } public void compareServiceNotFoundException(Object o1, Object o2) { compareOperationsException(o1, o2); } public void compareStringValueExp(Object o1, Object o2) { StringValueExp s1 = (StringValueExp)o1; StringValueExp s2 = (StringValueExp)o2; if (!s1.getValue().equals(s2.getValue())) throw new RuntimeException(); } // // MODELMBEAN package // public void compareDescriptorSupport(Object o1, Object o2) { DescriptorSupport s1 = (DescriptorSupport)o1; DescriptorSupport s2 = (DescriptorSupport)o2; String[] names1 = s1.getFieldNames(); String[] names2 = s2.getFieldNames(); Object[] values1 = s1.getFieldValues(names1); Object[] values2 = s2.getFieldValues(names2); ArrayList list1 = new ArrayList(Arrays.asList(names1)); ArrayList list2 = new ArrayList(Arrays.asList(names2)); if (!list1.containsAll(list2) || !list2.containsAll(list1)) throw new RuntimeException(); list1 = new ArrayList(Arrays.asList(values1)); list2 = new ArrayList(Arrays.asList(values2)); if (!list1.containsAll(list2) || !list2.containsAll(list1)) throw new RuntimeException(); } public void compareInvalidTargetObjectTypeException(Object o1, Object o2) { // No way to compare them } public void compareModelMBeanAttributeInfo(Object o1, Object o2) { compareMBeanAttributeInfo(o1, o2); ModelMBeanAttributeInfo a1 = (ModelMBeanAttributeInfo)o1; ModelMBeanAttributeInfo a2 = (ModelMBeanAttributeInfo)o2; compareDescriptorSupport(a1.getDescriptor(), a2.getDescriptor()); } public void compareModelMBeanConstructorInfo(Object o1, Object o2) { compareMBeanConstructorInfo(o1, o2); ModelMBeanConstructorInfo a1 = (ModelMBeanConstructorInfo)o1; ModelMBeanConstructorInfo a2 = (ModelMBeanConstructorInfo)o2; compareDescriptorSupport(a1.getDescriptor(), a2.getDescriptor()); } public void compareModelMBeanInfoSupport(Object o1, Object o2) throws MBeanException { compareMBeanInfo(o1, o2); ModelMBeanInfoSupport i1 = (ModelMBeanInfoSupport)o1; ModelMBeanInfoSupport i2 = (ModelMBeanInfoSupport)o2; compareDescriptorSupport(i1.getMBeanDescriptor(), i2.getMBeanDescriptor()); } public void compareModelMBeanNotificationInfo(Object o1, Object o2) { compareMBeanNotificationInfo(o1, o2); ModelMBeanNotificationInfo n1 = (ModelMBeanNotificationInfo)o1; ModelMBeanNotificationInfo n2 = (ModelMBeanNotificationInfo)o2; compareDescriptorSupport(n1.getDescriptor(), n2.getDescriptor()); } public void compareModelMBeanOperationInfo(Object o1, Object o2) { compareMBeanOperationInfo(o1, o2); ModelMBeanOperationInfo op1 = (ModelMBeanOperationInfo)o1; ModelMBeanOperationInfo op2 = (ModelMBeanOperationInfo)o2; compareDescriptorSupport(op1.getDescriptor(), op2.getDescriptor()); } public void compareXMLParseException(Object o1, Object o2) { // Cannot be compared: JMXRI adds a custom message in addition to the one // provided to the XMLParseException constructor. // compareException(o1, o2); } // // MONITOR package // public void compareMonitorNotification(Object o1, Object o2) { compareNotification(o1, o2); MonitorNotification n1 = (MonitorNotification)o1; MonitorNotification n2 = (MonitorNotification)o2; if (!n1.getDerivedGauge().equals(n2.getDerivedGauge())) throw new RuntimeException(); if (!n1.getObservedAttribute().equals(n2.getObservedAttribute())) throw new RuntimeException(); if (!n1.getObservedObject().equals(n2.getObservedObject())) throw new RuntimeException(); if (!n1.getTrigger().equals(n2.getTrigger())) throw new RuntimeException(); } public void compareMonitorSettingException(Object o1, Object o2) { compareJMRuntimeException(o1, o2); } // // OPENMBEANS package // public void compareInvalidKeyException(Object o1, Object o2) { compareException(o1, o2); } public void compareInvalidOpenTypeException(Object o1, Object o2) { compareException(o1, o2); } public void compareKeyAlreadyExistsException(Object o1, Object o2) { compareException(o1, o2); } public void compareOpenDataException(Object o1, Object o2) { compareJMException(o1, o2); } // // RELATION package // public void compareInvalidRelationIdException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareInvalidRelationServiceException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareInvalidRelationTypeException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareInvalidRoleInfoException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareInvalidRoleValueException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareMBeanServerNotificationFilter(Object o1, Object o2) { compareNotificationFilterSupport(o1, o2); MBeanServerNotificationFilter f1 = (MBeanServerNotificationFilter)o1; MBeanServerNotificationFilter f2 = (MBeanServerNotificationFilter)o2; Vector names1 = null; try { names1 = f1.getEnabledObjectNames(); } catch (NullPointerException ignored) { // JMX RI throws this } Vector names2 = null; try { names2 = f2.getEnabledObjectNames(); } catch (NullPointerException ignored) { // JMX RI throws this } if (names1 != null && (!names1.containsAll(names2) || !names2.containsAll(names1))) throw new RuntimeException(); if (names1 == null && names2 != null) throw new RuntimeException(); Vector names3 = null; try { names3 = f1.getDisabledObjectNames(); } catch (NullPointerException ignored) { // JMX RI throws this } Vector names4 = null; try { names4 = f1.getDisabledObjectNames(); } catch (NullPointerException ignored) { // JMX RI throws this } if (names3 != null && (!names3.containsAll(names4) || !names4.containsAll(names3))) throw new RuntimeException(); if (names3 == null && names4 != null) throw new RuntimeException(); } public void compareRelationException(Object o1, Object o2) { compareJMException(o1, o2); } public void compareRelationNotFoundException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareRelationNotification(Object o1, Object o2) { compareNotification(o1, o2); RelationNotification n1 = (RelationNotification)o1; RelationNotification n2 = (RelationNotification)o2; if (!n1.getMBeansToUnregister().equals(n2.getMBeansToUnregister())) throw new RuntimeException(); List news1 = n1.getNewRoleValue(); List news2 = n2.getNewRoleValue(); if (news1.size() != news2.size()) throw new RuntimeException(); if (!n1.getObjectName().equals(n2.getObjectName())) throw new RuntimeException(); List olds1 = n1.getOldRoleValue(); List olds2 = n2.getOldRoleValue(); if (olds1.size() != olds2.size()) throw new RuntimeException(); if (!n1.getRelationId().equals(n2.getRelationId())) throw new RuntimeException(); if (!n1.getRelationTypeName().equals(n2.getRelationTypeName())) throw new RuntimeException(); if (!n1.getRoleName().equals(n2.getRoleName())) throw new RuntimeException(); } public void compareRelationServiceNotRegisteredException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareRelationTypeNotFoundException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareRelationTypeSupport(Object o1, Object o2) { RelationTypeSupport r1 = (RelationTypeSupport)o1; RelationTypeSupport r2 = (RelationTypeSupport)o2; if (!r1.getRelationTypeName().equals(r2.getRelationTypeName())) throw new RuntimeException(); List infos1 = r1.getRoleInfos(); List infos2 = r2.getRoleInfos(); // RoleInfo does not override equals() so List.equals() fails; just use size() here if (infos1.size() != infos2.size()) throw new RuntimeException(); } public void compareRole(Object o1, Object o2) { Role r1 = (Role)o1; Role r2 = (Role)o2; if (!r1.getRoleName().equals(r2.getRoleName())) throw new RuntimeException(); if (!r1.getRoleValue().equals(r2.getRoleValue())) throw new RuntimeException(); } public void compareRoleInfo(Object o1, Object o2) { RoleInfo r1 = (RoleInfo)o1; RoleInfo r2 = (RoleInfo)o2; if (!r1.getDescription().equals(r2.getDescription())) throw new RuntimeException(); if (r1.getMaxDegree() != r2.getMaxDegree()) throw new RuntimeException(); if (r1.getMinDegree() != r2.getMinDegree()) throw new RuntimeException(); if (!r1.getName().equals(r2.getName())) throw new RuntimeException(); if (!r1.getRefMBeanClassName().equals(r2.getRefMBeanClassName())) throw new RuntimeException(); if (!r1.isReadable() || !r2.isReadable()) throw new RuntimeException(); if (!r1.isWritable() || !r2.isWritable()) throw new RuntimeException(); } public void compareRoleInfoNotFoundException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareRoleList(Object o1, Object o2) { RoleList l1 = (RoleList)o1; RoleList l2 = (RoleList)o2; // Role does not override equals() so List.equals() fails; just use size() here if (l1.size() != l2.size()) throw new RuntimeException(); } public void compareRoleNotFoundException(Object o1, Object o2) { compareRelationException(o1, o2); } public void compareRoleResult(Object o1, Object o2) { RoleResult r1 = (RoleResult)o1; RoleResult r2 = (RoleResult)o2; compareRoleList(r1.getRoles(), r2.getRoles()); compareRoleUnresolvedList(r1.getRolesUnresolved(), r2.getRolesUnresolved()); } public void compareRoleUnresolved(Object o1, Object o2) { RoleUnresolved r1 = (RoleUnresolved)o1; RoleUnresolved r2 = (RoleUnresolved)o2; if (r1.getProblemType() != r2.getProblemType()) throw new RuntimeException(); if (!r1.getRoleName().equals(r2.getRoleName())) throw new RuntimeException(); if (!r1.getRoleValue().equals(r2.getRoleValue())) throw new RuntimeException(); } public void compareRoleUnresolvedList(Object o1, Object o2) { RoleUnresolvedList l1 = (RoleUnresolvedList)o1; RoleUnresolvedList l2 = (RoleUnresolvedList)o2; // RoleUnresolved does not override equals() so List.equals() fails; just use size() here if (l1.size() != l2.size()) throw new RuntimeException(); } // // TIMER package // public void compareTimerNotification(Object o1, Object o2) { compareNotification(o1, o2); TimerNotification n1 = (TimerNotification)o1; TimerNotification n2 = (TimerNotification)o2; if (!n1.getNotificationID().equals(n2.getNotificationID())) throw new RuntimeException(); } } mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/Instantiator.java100644 0 0 73022 10513545721 27553 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.serialization.support; import java.lang.reflect.Constructor; import java.util.ArrayList; import javax.management.Attribute; import javax.management.AttributeChangeNotification; import javax.management.AttributeChangeNotificationFilter; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.AttributeValueExp; import javax.management.BadAttributeValueExpException; import javax.management.BadBinaryOpValueExpException; import javax.management.BadStringOperationException; import javax.management.Descriptor; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidApplicationException; import javax.management.InvalidAttributeValueException; import javax.management.JMException; import javax.management.JMRuntimeException; import javax.management.ListenerNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanFeatureInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanPermission; import javax.management.MBeanRegistrationException; import javax.management.MBeanServerDelegate; import javax.management.MBeanServerNotification; import javax.management.MBeanServerPermission; import javax.management.MBeanTrustPermission; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationFilterSupport; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.OperationsException; import javax.management.Query; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.management.RuntimeErrorException; import javax.management.RuntimeMBeanException; import javax.management.RuntimeOperationsException; import javax.management.ServiceNotFoundException; import javax.management.StringValueExp; import javax.management.ValueExp; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.InvalidTargetObjectTypeException; import javax.management.modelmbean.ModelMBean; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanConstructorInfo; import javax.management.modelmbean.ModelMBeanInfo; import javax.management.modelmbean.ModelMBeanInfoSupport; import javax.management.modelmbean.ModelMBeanNotificationBroadcaster; import javax.management.modelmbean.ModelMBeanNotificationInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; import javax.management.modelmbean.XMLParseException; import javax.management.monitor.MonitorNotification; import javax.management.monitor.MonitorSettingException; import javax.management.openmbean.ArrayType; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.InvalidKeyException; import javax.management.openmbean.InvalidOpenTypeException; import javax.management.openmbean.KeyAlreadyExistsException; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenMBeanAttributeInfoSupport; import javax.management.openmbean.OpenMBeanConstructorInfoSupport; import javax.management.openmbean.OpenMBeanInfoSupport; import javax.management.openmbean.OpenMBeanOperationInfo; import javax.management.openmbean.OpenMBeanOperationInfoSupport; import javax.management.openmbean.OpenMBeanParameterInfo; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import javax.management.relation.InvalidRelationIdException; import javax.management.relation.InvalidRelationServiceException; import javax.management.relation.InvalidRelationTypeException; import javax.management.relation.InvalidRoleInfoException; import javax.management.relation.InvalidRoleValueException; import javax.management.relation.MBeanServerNotificationFilter; import javax.management.relation.Relation; import javax.management.relation.RelationException; import javax.management.relation.RelationNotFoundException; import javax.management.relation.RelationNotification; import javax.management.relation.RelationService; import javax.management.relation.RelationServiceNotRegisteredException; import javax.management.relation.RelationType; import javax.management.relation.RelationTypeNotFoundException; import javax.management.relation.RelationTypeSupport; import javax.management.relation.Role; import javax.management.relation.RoleInfo; import javax.management.relation.RoleInfoNotFoundException; import javax.management.relation.RoleList; import javax.management.relation.RoleNotFoundException; import javax.management.relation.RoleResult; import javax.management.relation.RoleStatus; import javax.management.relation.RoleUnresolved; import javax.management.relation.RoleUnresolvedList; import javax.management.timer.TimerNotification; /** * @version $Revision: 1.12 $ */ public class Instantiator { // // JAVAX.MANAGEMENT // public QueryExp createAndQueryExp() { return Query.and(createBetweenQueryExp(), createBinaryRelQueryExp()); } public Attribute createAttribute() { return new Attribute("attr-name", "attr-value"); } public AttributeChangeNotification createAttributeChangeNotification() { AttributeChangeNotification notification = new AttributeChangeNotification("notif-source", 13L, System.currentTimeMillis(), "notif-message", "attr-name", "attr-type", "old", "new"); notification.setUserData("notif-user"); return notification; } public AttributeChangeNotificationFilter createAttributeChangeNotificationFilter() { AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute("attribute-name"); return filter; } public AttributeList createAttributeList() { AttributeList list = new AttributeList(); list.add(createAttribute()); return list; } public AttributeNotFoundException createAttributeNotFoundException() { return new AttributeNotFoundException("AttributeNotFoundException"); } public AttributeValueExp createAttributeValueExp() { return new AttributeValueExp("attribute"); } public BadAttributeValueExpException createBadAttributeValueExpException() { return new BadAttributeValueExpException("BadAttributeValueExpException"); } public BadBinaryOpValueExpException createBadBinaryOpValueExpException() { return new BadBinaryOpValueExpException(createStringValueExp()); } public BadStringOperationException createBadStringOperationException() { return new BadStringOperationException("BadStringOperationException"); } public QueryExp createBetweenQueryExp() { return Query.between(Query.value(5), Query.value(3), Query.value(7)); } public ValueExp createBinaryOpValueExp() { return Query.plus(Query.value(2), Query.value(5)); } public QueryExp createBinaryRelQueryExp() { return Query.eq(Query.value("simon"), Query.value("simon")); } public ValueExp createBooleanValueExp() { return Query.value(true); } public ValueExp createClassAttributeValueExp() { return Query.classattr(); } public Descriptor createDescriptor() { throw new Error(); } public QueryExp createInQueryExp() { return Query.in(Query.value(4), new ValueExp[]{Query.value(3), Query.value(4), Query.value(5)}); } public InstanceAlreadyExistsException createInstanceAlreadyExistsException() { return new InstanceAlreadyExistsException("InstanceAlreadyExistsException"); } public InstanceNotFoundException createInstanceNotFoundException() { return new InstanceNotFoundException("InstanceNotFoundException"); } public IntrospectionException createIntrospectionException() { return new IntrospectionException("IntrospectionException"); } public InvalidApplicationException createInvalidApplicationException() { return new InvalidApplicationException("InvalidApplicationException"); } public InvalidAttributeValueException createInvalidAttributeValueException() { return new InvalidAttributeValueException("InvalidAttributeValueException"); } public JMException createJMException() { return new JMException("JMException"); } public JMRuntimeException createJMRuntimeException() { return new JMRuntimeException("JMRuntimeException"); } public ListenerNotFoundException createListenerNotFoundException() { return new ListenerNotFoundException("ListenerNotFoundException"); } public MalformedObjectNameException createMalformedObjectNameException() { return new MalformedObjectNameException("MalformedObjectNameException"); } public QueryExp createMatchQueryExp() { return Query.match(createAttributeValueExp(), createStringValueExp()); } public MBeanAttributeInfo createMBeanAttributeInfo() { return new MBeanAttributeInfo("name", "boolean", "description", true, true, true); } public MBeanConstructorInfo createMBeanConstructorInfo() { return new MBeanConstructorInfo("name", "description", new MBeanParameterInfo[]{createMBeanParameterInfo()}); } public MBeanException createMBeanException() { return new MBeanException(new NullPointerException("NullPointerException"), "MBeanException"); } public MBeanFeatureInfo createMBeanFeatureInfo() { return new MBeanFeatureInfo("name", "description"); } public MBeanInfo createMBeanInfo() { return new MBeanInfo("my.class.name", "description", new MBeanAttributeInfo[]{createMBeanAttributeInfo()}, new MBeanConstructorInfo[]{createMBeanConstructorInfo()}, new MBeanOperationInfo[]{createMBeanOperationInfo()}, new MBeanNotificationInfo[]{createMBeanNotificationInfo()}); } public MBeanNotificationInfo createMBeanNotificationInfo() { return new MBeanNotificationInfo(new String[]{"type1", "type2"}, "name", "description"); } public MBeanOperationInfo createMBeanOperationInfo() { return new MBeanOperationInfo("name", "description", new MBeanParameterInfo[]{createMBeanParameterInfo()}, "java.lang.Exception", MBeanOperationInfo.UNKNOWN); } public MBeanParameterInfo createMBeanParameterInfo() { return new MBeanParameterInfo("name", "java.lang.Object", "description"); } public MBeanPermission createMBeanPermission() throws MalformedObjectNameException { return new MBeanPermission("className", "methodName", createObjectName(), "instantiate,registerMBean"); } public MBeanRegistrationException createMBeanRegistrationException() { return new MBeanRegistrationException(new NullPointerException("NullPointerException"), "MBeanRegistrationException"); } public MBeanServerDelegate createMBeanServerDelegate() { return new MBeanServerDelegate(); } public MBeanServerNotification createMBeanServerNotification() throws MalformedObjectNameException { MBeanServerNotification n = new MBeanServerNotification(MBeanServerNotification.REGISTRATION_NOTIFICATION, "notif-source", 13L, new ObjectName(":key=value")); n.setUserData("user-data"); return n; } public MBeanServerPermission createMBeanServerPermission() { return new MBeanServerPermission("newMBeanServer"); } public MBeanTrustPermission createMBeanTrustPermission() { return new MBeanTrustPermission("register"); } public NotCompliantMBeanException createNotCompliantMBeanException() { return new NotCompliantMBeanException("NotCompliantMBeanException"); } public Notification createNotification() { Notification notification = new Notification("notif-type", "notif-source", 13L, System.currentTimeMillis(), "notif-message"); notification.setUserData("notif-user"); return notification; } public NotificationBroadcasterSupport createNotificationBroadcasterSupport() { return new NotificationBroadcasterSupport(); } public NotificationFilterSupport createNotificationFilterSupport() { NotificationFilterSupport filter = new NotificationFilterSupport(); filter.enableType("notif-type"); return filter; } public QueryExp createNotQueryExp() { return Query.not(Query.eq(Query.value("simon"), Query.value("bordet"))); } public ValueExp createNumericValueExp() { return Query.value(1); } public ObjectInstance createObjectInstance() throws MalformedObjectNameException { return new ObjectInstance(new ObjectName("domain:p1=v1"), "java.lang.Object"); } public ObjectName createObjectName() throws MalformedObjectNameException { return new ObjectName("domain?:p2=v2,*,p1=v1"); } public OperationsException createOperationsException() { return new OperationsException("OperationsException"); } public QueryExp createOrQueryExp() { return Query.or(createBetweenQueryExp(), createBinaryRelQueryExp()); } public AttributeValueExp createQualifiedAttributeValueExp() { return Query.attr("mx4j.Foo", "attribute"); } public ReflectionException createReflectionException() { return new ReflectionException(new NullPointerException("NullPointerException"), "ReflectionException"); } public RuntimeErrorException createRuntimeErrorException() { return new RuntimeErrorException(new Error("Error"), "RuntimeErrorException"); } public RuntimeMBeanException createRuntimeMBeanException() { return new RuntimeMBeanException(new NullPointerException("NullPointerException"), "RuntimeMBeanException"); } public RuntimeOperationsException createRuntimeOperationsException() { return new RuntimeOperationsException(new NullPointerException("NullPointerException"), "RuntimeOperationsException"); } public ServiceNotFoundException createServiceNotFoundException() { return new ServiceNotFoundException("ServiceNotFoundException"); } public StringValueExp createStringValueExp() { return new StringValueExp("StringValueExp"); } // // JAVAX.MANAGEMENT.MODELMBEAN // public DescriptorSupport createDescriptorSupport() { return new DescriptorSupport(new String[]{"name"}, new Object[]{"value"}); } public InvalidTargetObjectTypeException createInvalidTargetObjectTypeException() { return new InvalidTargetObjectTypeException(new NullPointerException("NullPointerException"), "InvalidTargetObjectTypeException"); } public ModelMBean createModelMBean() { throw new Error(); } public ModelMBeanAttributeInfo createModelMBeanAttributeInfo() { String[] names = new String[]{"name", "descriptortype", "value", "iterable", "displayname"}; Object[] values = new Object[]{"name", "attribute", null, "false", "name"}; DescriptorSupport descriptor = new DescriptorSupport(names, values); return new ModelMBeanAttributeInfo("name", "boolean", "description", true, true, true, descriptor); } public ModelMBeanConstructorInfo createModelMBeanConstructorInfo() { String[] names = new String[]{"name", "descriptortype", "role", "displayname"/*, "lastReturnedTimeStamp"*/}; Object[] values = new Object[]{"name", "operation", "constructor", "name"/*, "0"*/}; DescriptorSupport descriptor = new DescriptorSupport(names, values); return new ModelMBeanConstructorInfo("name", "description", new MBeanParameterInfo[]{createMBeanParameterInfo()}, descriptor); } public ModelMBeanInfo createModelMBeanInfo() { throw new Error(); } public ModelMBeanInfoSupport createModelMBeanInfoSupport() { String[] names = new String[]{"name", "descriptortype", "displayname", "persistpolicy", "log", "export", "visibility"}; Object[] values = new Object[]{"name", "MBean", "name", "Never", "false", "F", "1"}; DescriptorSupport descriptor = new DescriptorSupport(names, values); return new ModelMBeanInfoSupport("my.class.name", "description", new ModelMBeanAttributeInfo[]{createModelMBeanAttributeInfo()}, new ModelMBeanConstructorInfo[]{createModelMBeanConstructorInfo()}, new ModelMBeanOperationInfo[]{createModelMBeanOperationInfo()}, new ModelMBeanNotificationInfo[]{createModelMBeanNotificationInfo()}, descriptor); } public ModelMBeanNotificationBroadcaster createModelMBeanNotificationBroadcaster() { throw new Error(); } public ModelMBeanNotificationInfo createModelMBeanNotificationInfo() { String[] names = new String[]{"name", "descriptortype", "severity", "displayname"/*, "messageId", "log", "logfile"*/}; Object[] values = new Object[]{"name", "notification", "5", "name"/*, "0", "???", "???"*/}; DescriptorSupport descriptor = new DescriptorSupport(names, values); return new ModelMBeanNotificationInfo(new String[]{"type1", "type2"}, "name", "description", descriptor); } public ModelMBeanOperationInfo createModelMBeanOperationInfo() { String[] names = new String[]{"name", "descriptortype", "role", "displayname"/*, "lastReturnedTimeStamp"*/}; Object[] values = new Object[]{"name", "operation", "operation", "name"/*, "0"*/}; DescriptorSupport descriptor = new DescriptorSupport(names, values); return new ModelMBeanOperationInfo("name", "description", new MBeanParameterInfo[]{createMBeanParameterInfo()}, "java.lang.Object", MBeanOperationInfo.UNKNOWN, descriptor); } public XMLParseException createXMLParseException() { return new XMLParseException("XMLParseException"); } // // JAVAX.MANAGEMENT.MONITOR // public MonitorNotification createMonitorNotification() throws Exception { Constructor ctor = MonitorNotification.class.getDeclaredConstructor(new Class[]{String.class, Object.class, long.class, long.class, String.class, ObjectName.class, String.class, Object.class, Object.class}); ctor.setAccessible(true); MonitorNotification notification = (MonitorNotification)ctor.newInstance(new Object[]{"type", "source", new Long(13), new Long(System.currentTimeMillis()), "message", new ObjectName("domain:p1=v1"), "attribute", "gauge", "trigger"}); notification.setUserData("user"); return notification; } public MonitorSettingException createMonitorSettingException() { return new MonitorSettingException("MonitorSettingException"); } // // JAVAX.MANAGEMENT.OPENMBEAN // public ArrayType createArrayType() throws OpenDataException { return new ArrayType(5, SimpleType.BIGDECIMAL); } public CompositeDataSupport createCompositeDataSupport() throws OpenDataException { CompositeType ct = createCompositeType(); return new CompositeDataSupport(ct, new String[]{"key1", "key2"}, new Object[]{"value1", "value2"}); } public CompositeType createCompositeType() throws OpenDataException { return new CompositeType("composite1", "description1", new String[]{"key1", "key2"}, new String[]{"d1", "d2"}, new OpenType[]{SimpleType.STRING, SimpleType.STRING}); } public InvalidKeyException createInvalidKeyException() { return new InvalidKeyException("InvalidKeyException"); } public InvalidOpenTypeException createInvalidOpenTypeException() { return new InvalidOpenTypeException("InvalidOpenTypeException"); } public KeyAlreadyExistsException createKeyAlreadyExistsException() { return new KeyAlreadyExistsException("KeyAlreadyExistsException"); } public OpenDataException createOpenDataException() { return new OpenDataException("OpenDataException"); } public OpenMBeanAttributeInfoSupport createOpenMBeanAttributeInfoSupport() { return new OpenMBeanAttributeInfoSupport("attrib", "An Attribute", SimpleType.STRING, true, true, false); } public OpenMBeanConstructorInfoSupport createOpenMBeanConstructorInfoSupport() { return new OpenMBeanConstructorInfoSupport("const", "a constructor", new OpenMBeanParameterInfoSupport[]{createOpenMBeanParameterInfoSupport()}); } public OpenMBeanInfoSupport createOpenMBeanInfoSupport() throws OpenDataException { OpenMBeanAttributeInfoSupport[] attrInfo = new OpenMBeanAttributeInfoSupport[]{createOpenMBeanAttributeInfoSupport()}; OpenMBeanConstructorInfoSupport[] ctorInfo = new OpenMBeanConstructorInfoSupport[]{createOpenMBeanConstructorInfoSupport()}; OpenMBeanOperationInfo[] operInfo = new OpenMBeanOperationInfoSupport[]{createOpenMBeanOperationInfoSupport()}; MBeanNotificationInfo[] notifInfo = new MBeanNotificationInfo[] { new MBeanNotificationInfo(new String[]{"notif1", "notif2"}, "name", "description") }; return new OpenMBeanInfoSupport("test.class.Name", "description1", attrInfo, ctorInfo, operInfo, notifInfo); } public OpenMBeanOperationInfoSupport createOpenMBeanOperationInfoSupport() { return new OpenMBeanOperationInfoSupport("operation", "A operation", new OpenMBeanParameterInfo[]{createOpenMBeanParameterInfoSupport()}, SimpleType.STRING, MBeanOperationInfo.ACTION); } public OpenMBeanParameterInfoSupport createOpenMBeanParameterInfoSupport() { return new OpenMBeanParameterInfoSupport("param1", "A param", SimpleType.STRING); } public SimpleType createSimpleType() { return SimpleType.STRING; } public TabularDataSupport createTabularDataSupport() throws OpenDataException { return new TabularDataSupport(createTabularType()); } public TabularType createTabularType() throws OpenDataException { return new TabularType("typename", "descr1", createCompositeType(), new String[]{"key1", "key2"}); } // // JAVAX.MANAGEMENT.RELATION // public InvalidRelationIdException createInvalidRelationIdException() { return new InvalidRelationIdException("InvalidRelationIdException"); } public InvalidRelationServiceException createInvalidRelationServiceException() { return new InvalidRelationServiceException("InvalidRelationServiceException"); } public InvalidRelationTypeException createInvalidRelationTypeException() { return new InvalidRelationTypeException("InvalidRelationTypeException"); } public InvalidRoleInfoException createInvalidRoleInfoException() { return new InvalidRoleInfoException("InvalidRoleInfoException"); } public InvalidRoleValueException createInvalidRoleValueException() { return new InvalidRoleValueException("InvalidRoleValueException"); } public MBeanServerNotificationFilter createMBeanServerNotificationFilter() throws MalformedObjectNameException { MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter(); filter.enableType("notif-type"); filter.disableAllObjectNames(); filter.enableObjectName(new ObjectName("domain:key=val")); return filter; } public Relation createRelation() { throw new Error(); } public RelationException createRelationException() { return new RelationException("RelationException"); } public RelationNotFoundException createRelationNotFoundException() { return new RelationNotFoundException("RelationNotFoundException"); } public RelationNotification createRelationNotification() throws MalformedObjectNameException { try { // MX4J version RelationNotification n = new RelationNotification(RelationNotification.RELATION_BASIC_UPDATE, "source", 13L, System.currentTimeMillis(), "message", "relation-id", "relation-type", new ObjectName(":key=value"), "role-name", createRoleList(), createRoleUnresolvedList()); n.setUserData("user-data"); return n; } catch (IllegalArgumentException x) { // JMXRI version RelationNotification n = new RelationNotification(RelationNotification.RELATION_BASIC_UPDATE, new RelationService(true), 13L, System.currentTimeMillis(), "message", "relation-id", "relation-type", new ObjectName(":key=value"), "role-name", createRoleList(), createRoleUnresolvedList()); n.setUserData("user-data"); n.setSource("source"); return n; } } public RelationServiceNotRegisteredException createRelationServiceNotRegisteredException() { return new RelationServiceNotRegisteredException("RelationServiceNotRegisteredException"); } public RelationTypeNotFoundException createRelationTypeNotFoundException() { return new RelationTypeNotFoundException("RelationTypeNotFoundException"); } public RelationType createRelationType() { throw new Error(); } public RelationTypeSupport createRelationTypeSupport() throws InvalidRelationTypeException, InvalidRoleInfoException, ClassNotFoundException, NotCompliantMBeanException { return new RelationTypeSupport("relation-type", new RoleInfo[]{createRoleInfo()}); } public Role createRole() throws MalformedObjectNameException { ArrayList list = new ArrayList(); list.add(new ObjectName("domain:key=value")); return new Role("Role", list); } public RoleInfo createRoleInfo() throws InvalidRoleInfoException, ClassNotFoundException, NotCompliantMBeanException { return new RoleInfo("RoleInfo", "javax.management.MBeanServerDelegate", true, true, 13, 17, "Description"); } public RoleInfoNotFoundException createRoleInfoNotFoundException() { return new RoleInfoNotFoundException("RoleInfoNotFoundException"); } public RoleList createRoleList() throws MalformedObjectNameException { RoleList list = new RoleList(); list.add(createRole()); return list; } public RoleNotFoundException createRoleNotFoundException() { return new RoleNotFoundException("RoleNotFoundException"); } public RoleResult createRoleResult() throws MalformedObjectNameException { return new RoleResult(createRoleList(), createRoleUnresolvedList()); } public RoleUnresolved createRoleUnresolved() throws MalformedObjectNameException { ArrayList list = new ArrayList(); list.add(new ObjectName("domain:key=value")); return new RoleUnresolved("RoleName", list, RoleStatus.NO_ROLE_WITH_NAME); } public RoleUnresolvedList createRoleUnresolvedList() throws MalformedObjectNameException { RoleUnresolvedList list = new RoleUnresolvedList(); list.add(createRoleUnresolved()); return list; } // // JAVAX.MANAGEMENT.TIMER // public TimerNotification createTimerNotification() throws Exception { // First try MX4J version try { Constructor ctor = TimerNotification.class.getDeclaredConstructor(new Class[]{String.class, Object.class, String.class, Integer.class}); ctor.setAccessible(true); TimerNotification notification = (TimerNotification)ctor.newInstance(new Object[]{"type", "source", "message", new Integer(13)}); notification.setUserData("user"); return notification; } catch (NoSuchMethodException x) { // Then try JMX RI version Constructor ctor = TimerNotification.class.getDeclaredConstructor(new Class[]{String.class, Object.class, long.class, long.class, String.class, Integer.class}); ctor.setAccessible(true); TimerNotification notification = (TimerNotification)ctor.newInstance(new Object[]{"type", "source", new Long(0), new Long(0), "message", new Integer(13)}); notification.setUserData("user"); return notification; } } } ././@LongLink100644 0 0 146 10513545722 10260 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/SerializationVerifier.javamx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/SerializationVerifier.jav100644 0 0 13306 10513545721 31243 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.serialization.support; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @version $Revision: 1.4 $ */ public class SerializationVerifier { private String instantiator; private String comparator; public SerializationVerifier(String instantiator, String comparator) { this.instantiator = instantiator; this.comparator = comparator; } public void verifySerialization(String name, ClassLoader jmxriLoader, ClassLoader mx4jLoader) throws Exception { name = name.substring(name.lastIndexOf('.') + 1); // Create the object, one with MX4J, one with JMXRI Thread.currentThread().setContextClassLoader(mx4jLoader); Object mx4j = create(name); Thread.currentThread().setContextClassLoader(jmxriLoader); Object jmxri = create(name); // Be sure they're not the same class if (mx4j.getClass().isInstance(jmxri)) throw new Exception("Classes must be different"); if (jmxri.getClass().isInstance(mx4j)) throw new Exception("Classes must be different"); // Serialize MX4J object Thread.currentThread().setContextClassLoader(mx4jLoader); byte[] mx4jBytes = serialize(mx4j); // Deserialize with JMXRI Thread.currentThread().setContextClassLoader(jmxriLoader); Object jmxriObject = deserialize(mx4jBytes); // Be sure they're not the same class if (mx4j.getClass().isInstance(jmxriObject)) throw new Exception("Classes must be different"); if (jmxriObject.getClass().isInstance(mx4j)) throw new Exception("Classes must be different"); // Be also sure the deserialized is of the same type as JMXRI if (jmxri.getClass() != jmxriObject.getClass()) throw new Exception("Classes must be equal"); // Now compare the original and the deserialized compare(name, jmxri, jmxriObject); // Now, do the opposite // Serialize JMXRI object Thread.currentThread().setContextClassLoader(jmxriLoader); byte[] jmxriBytes = serialize(jmxri); // Deserialize with MX4J Thread.currentThread().setContextClassLoader(mx4jLoader); Object mx4jObject = deserialize(jmxriBytes); // Be sure they're not the same class if (jmxri.getClass().isInstance(mx4jObject)) throw new Exception("Classes must be different"); if (mx4jObject.getClass().isInstance(jmxri)) throw new Exception("Classes must be different"); // Be also sure the deserialized is of the same type as MX4J if (mx4j.getClass() != mx4jObject.getClass()) throw new Exception("Classes must be equal"); // Now compare the original and the deserialized compare(name, mx4j, mx4jObject); } private Object create(String name) throws Exception { // Create an instance of the Instantiator ClassLoader loader = Thread.currentThread().getContextClassLoader(); Object creator = loader.loadClass(instantiator).newInstance(); // Lookup the creation method and call it Method method = creator.getClass().getMethod("create" + name, new Class[0]); Object object = method.invoke(creator, new Object[0]); return object; } private byte[] serialize(Object object) throws Exception { // Must delegate again to another object loaded with the correct classloader, // otherwise the deserialization will use the system classloader instead of // the context classloader ClassLoader loader = Thread.currentThread().getContextClassLoader(); Object serializer = loader.loadClass("test.javax.management.compliance.serialization.support.Serializer").newInstance(); Method method = serializer.getClass().getMethod("serialize", new Class[]{Object.class}); return (byte[])method.invoke(serializer, new Object[]{object}); } private Object deserialize(byte[] bytes) throws Exception { // Must delegate again to another object loaded with the correct classloader, // otherwise the deserialization will use the system classloader instead of // the context classloader ClassLoader loader = Thread.currentThread().getContextClassLoader(); Object serializer = loader.loadClass("test.javax.management.compliance.serialization.support.Serializer").newInstance(); Method method = serializer.getClass().getMethod("deserialize", new Class[]{byte[].class}); return method.invoke(serializer, new Object[]{bytes}); } private void compare(String name, Object obj1, Object obj2) throws Exception { // First check if the class has the equals method try { obj1.getClass().getDeclaredMethod("equals", new Class[]{Object.class}); // It's present if (!obj1.equals(obj2)) throw new RuntimeException(); } catch (NoSuchMethodException x) { // No equals(), create an instance of the Comparator ClassLoader loader = Thread.currentThread().getContextClassLoader(); Object creator = loader.loadClass(comparator).newInstance(); // Lookup the compare method Method method = creator.getClass().getMethod("compare" + name, new Class[]{Object.class, Object.class}); try { method.invoke(creator, new Object[]{obj1, obj2}); } catch (InvocationTargetException xx) { Throwable t = xx.getTargetException(); if (t instanceof Exception) throw (Exception)t; else throw (Error)t; } } } } mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/Serializer.java100644 0 0 2204 10513545721 27157 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.serialization.support; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * @version $Revision: 1.4 $ */ public class Serializer { public byte[] serialize(Object object) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); oos.close(); byte[] bytes = baos.toByteArray(); return bytes; } public Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Object object = ois.readObject(); ois.close(); return object; } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/JMXSignatureTest.java100644 0 0 4576 10513545721 25654 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.JMXComplianceTestCase; import test.javax.management.compliance.signature.support.NotCompliantException; import test.javax.management.compliance.signature.support.NotCompliantWarningException; import test.javax.management.compliance.signature.support.SignatureVerifier; /** * Test that verifies that the signature of the classes in JMXRI are equal to MX4J classes. * It resembles a small TCK, for signatures of the JMX classes only. * * @version $Revision: 1.3 $ */ public class JMXSignatureTest extends JMXComplianceTestCase { public JMXSignatureTest(String s) { super(s); } protected boolean skipClassName(String className) { return "javax.management.MBeanServerPermissionCollection".equals(className); } protected boolean skipClass(Class cls) { // Exclude implementation classes in javax.management package // Do not exclude classes that are package private but serializable // like for example the QueryExp and ValueExp implementations (unless some exception) int modifiers = cls.getModifiers(); boolean isPublic = Modifier.isPublic(modifiers); boolean isProtected = Modifier.isProtected(modifiers); boolean isPackage = !Modifier.isPrivate(modifiers) && !isProtected && !isPublic; boolean isSerializable = Serializable.class.isAssignableFrom(cls); if (isPublic || isProtected || (isPackage && isSerializable)) return false; return true; } protected void checkCompliance(String className) throws Exception { ClassLoader jmxriLoader = createJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createMX4JWithTestsClassLoader(); SignatureVerifier verifier = new SignatureVerifier(); try { verifier.verifySignature(className, jmxriLoader, mx4jLoader); } catch (NotCompliantException x) { fail(x.getMessage()); } catch (NotCompliantWarningException x) { System.out.println("WARNING: " + x.getMessage()); } } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/FieldWrapper.java100644 0 0 1106 10513545721 26556 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; import java.lang.reflect.Field; /** * @version $Revision: 1.3 $ */ public class FieldWrapper extends MemberWrapper { public FieldWrapper(Field field) { modifiers = field.getModifiers(); type = field.getType().getName(); name = field.getName(); } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/MemberWrapper.java100644 0 0 2654 10513545721 26753 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; /** * @version $Revision: 1.3 $ */ public abstract class MemberWrapper { protected int modifiers; protected String type; protected String name; protected String toString; protected MemberWrapper() { } public int hashCode() { return toString().hashCode(); } public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; return toString().equals(obj.toString()); } public String toString() { if (toString == null) { StringBuffer buffer = new StringBuffer(Modifier.toString(modifiers)).append(" "); buffer.append(type).append(" "); buffer.append(name); toString = buffer.toString(); } return toString; } protected ArrayList convert(Class[] classes, boolean sort) { ArrayList list = new ArrayList(); for (int i = 0; i < classes.length; ++i) { list.add(classes[i].getName()); } if (sort) Collections.sort(list); return list; } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/MethodWrapper.java100644 0 0 7436 10513545721 26767 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; import java.lang.reflect.Modifier; import java.util.ArrayList; /** * @version $Revision: 1.4 $ */ public class MethodWrapper extends MemberWrapper { private ArrayList signature; private ArrayList exceptions; private ObjectMethod method; public MethodWrapper(ObjectMethod method) { // Clear synchronized modifier, not relevant int mods = method.getModifiers(); if (Modifier.isSynchronized(mods)) mods -= Modifier.SYNCHRONIZED; modifiers = mods; type = method.getReturnType().getName(); name = method.getName(); signature = convert(method.getParameterTypes(), false); exceptions = convert(method.getExceptionTypes(), true); this.method = method; } public boolean isSameMethod(MethodWrapper other) { int mask = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.STATIC | Modifier.ABSTRACT; if ((modifiers & mask) != (other.modifiers & mask)) return false; return name.equals(other.name) && type.equals(other.type) && signature.equals(other.signature); } public boolean sameSignatureModifiers(MethodWrapper other) { return modifiers == other.modifiers; } public boolean throwsClauseDiffer(MethodWrapper other) { ArrayList thisExceptions = convert(method.getExceptionTypes(), true); ArrayList otherExceptions = convert(other.method.getExceptionTypes(), true); if (thisExceptions.equals(otherExceptions)) return false; return true; } public boolean throwsClauseDifferForRuntimeExceptionsOnly(MethodWrapper other) { Class[] thisTypes = method.getExceptionTypes(); ArrayList thisExceptions = convert(thisTypes, true); Class[] otherTypes = other.method.getExceptionTypes(); ArrayList otherExceptions = convert(otherTypes, true); ArrayList thisCopy = (ArrayList)thisExceptions.clone(); thisExceptions.removeAll(otherExceptions); if (!thisExceptions.isEmpty()) { if (containsCheckedException(thisExceptions, thisTypes)) return false; } otherExceptions.removeAll(thisCopy); if (!otherExceptions.isEmpty()) { if (containsCheckedException(otherExceptions, otherTypes)) return false; } return true; } private boolean containsCheckedException(ArrayList exceptions, Class[] types) { for (int i = 0; i < exceptions.size(); ++i) { String name = (String)exceptions.get(i); boolean found = false; for (int j = 0; j < types.length; ++j) { Class type = types[j]; if (name.equals(type.getName())) { found = true; if (!RuntimeException.class.isAssignableFrom(type)) return true; } } if (!found) throw new IllegalStateException(); } return false; } public String toString() { if (toString == null) { StringBuffer buffer = new StringBuffer(super.toString()); buffer.append("("); for (int i = 0; i < signature.size(); ++i) { if (i > 0) buffer.append(","); buffer.append(signature.get(i)); } buffer.append(")"); if (exceptions.size() > 0) { buffer.append(" throws "); for (int i = 0; i < exceptions.size(); ++i) { if (i > 0) buffer.append(","); buffer.append(exceptions.get(i)); } } toString = buffer.toString(); } return toString; } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/NotCompliantException.java100644 0 0 722 10513545721 30443 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; /** * @version $Revision: 1.3 $ */ public class NotCompliantException extends Exception { public NotCompliantException(String s) { super(s); } } ././@LongLink100644 0 0 151 10513545722 10254 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/NotCompliantWarningException.javamx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/NotCompliantWarningException.100644 0 0 747 10513545721 31136 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; /** * @version $Revision: 1.3 $ */ public class NotCompliantWarningException extends RuntimeException { public NotCompliantWarningException(String s) { super(s); } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/ObjectClass.java100644 0 0 5217 10513545721 26375 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; /** * @version $Revision: 1.3 $ */ public interface ObjectClass { public String getName(); public ObjectMethod[] getDeclaredMethods(); public ObjectMethod[] getMethods(); public ObjectClass getSuperclass(); public static class Constructor implements ObjectClass { private java.lang.Class cls; public Constructor(Class cls) { this.cls = cls; } public String getName() { return cls.getName(); } public ObjectMethod[] getDeclaredMethods() { java.lang.reflect.Constructor[] constructors = cls.getDeclaredConstructors(); ObjectMethod[] ctors = new ObjectMethod[constructors.length]; for (int i = 0; i < ctors.length; ++i) ctors[i] = new ObjectMethod.Constructor(constructors[i]); return ctors; } public ObjectMethod[] getMethods() { java.lang.reflect.Constructor[] constructors = cls.getConstructors(); ObjectMethod[] ctors = new ObjectMethod[constructors.length]; for (int i = 0; i < ctors.length; ++i) ctors[i] = new ObjectMethod.Constructor(constructors[i]); return ctors; } public ObjectClass getSuperclass() { Class superCls = cls.getSuperclass(); return superCls == null ? null : new Constructor(superCls); } } public static class Method implements ObjectClass { private java.lang.Class cls; public Method(Class cls) { this.cls = cls; } public String getName() { return cls.getName(); } public ObjectMethod[] getDeclaredMethods() { java.lang.reflect.Method[] methods = cls.getDeclaredMethods(); ObjectMethod[] mthds = new ObjectMethod[methods.length]; for (int i = 0; i < mthds.length; ++i) mthds[i] = new ObjectMethod.Method(methods[i]); return mthds; } public ObjectMethod[] getMethods() { java.lang.reflect.Method[] methods = cls.getMethods(); ObjectMethod[] mthds = new ObjectMethod[methods.length]; for (int i = 0; i < mthds.length; ++i) mthds[i] = new ObjectMethod.Method(methods[i]); return mthds; } public ObjectClass getSuperclass() { Class superCls = cls.getSuperclass(); return superCls == null ? null : new Method(superCls); } } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/ObjectMethod.java100644 0 0 3647 10513545721 26555 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; /** * @version $Revision: 1.4 $ */ public interface ObjectMethod { public int getModifiers(); public Class getReturnType(); public String getName(); public Class[] getParameterTypes(); public Class[] getExceptionTypes(); public static class Constructor implements ObjectMethod { private java.lang.reflect.Constructor constructor; public Constructor(java.lang.reflect.Constructor ctor) { this.constructor = ctor; } public int getModifiers() { return constructor.getModifiers(); } public Class getReturnType() { return constructor.getDeclaringClass(); } public String getName() { return constructor.getName(); } public Class[] getParameterTypes() { return constructor.getParameterTypes(); } public Class[] getExceptionTypes() { return constructor.getExceptionTypes(); } } public static class Method implements ObjectMethod { private java.lang.reflect.Method method; public Method(java.lang.reflect.Method method) { this.method = method; } public int getModifiers() { return method.getModifiers(); } public Class getReturnType() { return method.getReturnType(); } public String getName() { return method.getName(); } public Class[] getParameterTypes() { return method.getParameterTypes(); } public Class[] getExceptionTypes() { return method.getExceptionTypes(); } } } mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/SignatureVerifier.java100644 0 0 31065 10513545721 27656 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.compliance.signature.support; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @version $Revision: 1.5 $ */ public class SignatureVerifier { public void verifySignature(String className, ClassLoader jmxriLoader, ClassLoader mx4jLoader) throws Exception { Class jmxriClass = jmxriLoader.loadClass(className); Class mx4jClass = mx4jLoader.loadClass(className); int modifiers = jmxriClass.getModifiers(); boolean isPublic = Modifier.isPublic(modifiers); boolean isProtected = Modifier.isProtected(modifiers); boolean isPackage = !Modifier.isPrivate(modifiers) && !isProtected && !isPublic; boolean isSerializable = Serializable.class.isAssignableFrom(jmxriClass); NotCompliantWarningException warning = null; try { checkSameClassModifiers(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } try { checkSameInheritance(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } if (!isPackage) { try { checkSameConstructors(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } try { checkSameMethods(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } try { checkSameFields(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } } if (isSerializable) { try { checkSameSerialVersionUID(jmxriClass, mx4jClass); } catch (NotCompliantWarningException x) { warning = x; } } if (warning != null) throw warning; } private void checkSameClassModifiers(Class jmxri, Class mx4j) throws NotCompliantException { int jmxriModifiers = jmxri.getModifiers(); int mx4jModifers = mx4j.getModifiers(); if (jmxriModifiers != mx4jModifers) { int modifier = jmxriModifiers ^ mx4jModifers; if ((modifier & jmxriModifiers) != 0) { throw new NotCompliantException("JMX class " + jmxri.getName() + " in MX4J implementation is not declared " + Modifier.toString(modifier) + " as it should be"); } if ((modifier & mx4jModifers) != 0) { throw new NotCompliantWarningException("JMX class " + jmxri.getName() + " in MX4J implementation is declared " + Modifier.toString(modifier) + ", it is not in JMXRI"); } } } private void checkSameInheritance(Class jmxri, Class mx4j) throws NotCompliantException { // I have to walk the inheritance hierarchy Set jmxriInterfaces = new HashSet(); Set mx4jInterfaces = new HashSet(); for (Class jmxriParent = jmxri, mx4jParent = mx4j; jmxriParent != null; jmxriParent = jmxriParent.getSuperclass(), mx4jParent = mx4jParent.getSuperclass()) { findInterfaces(jmxriParent, jmxriInterfaces); findInterfaces(mx4jParent, mx4jInterfaces); if (!jmxriParent.getName().equals(mx4jParent.getName())) { throw new NotCompliantException("JMX class " + jmxri.getName() + " in MX4J implementation does not have the same hierarchy as JMXRI: " + mx4jParent.getName() + ", should be " + jmxriParent.getName()); } } if (!jmxriInterfaces.containsAll(mx4jInterfaces)) { mx4jInterfaces.removeAll(jmxriInterfaces); checkInterfacesHaveMethods(jmxri, mx4jInterfaces); } if (!mx4jInterfaces.containsAll(jmxriInterfaces)) { jmxriInterfaces.removeAll(mx4jInterfaces); throw new NotCompliantException("JMX class " + jmxri.getName() + " in MX4J implementation does not implement the required interfaces: " + jmxriInterfaces); } } private void findInterfaces(Class cls, Set interfaces) { Class[] intfs = cls.getInterfaces(); for (int i = 0; i < intfs.length; ++i) { Class intf = intfs[i]; boolean added = interfaces.add(intf.getName()); if (added) findInterfaces(intf, interfaces); } } private void checkInterfacesHaveMethods(Class cls, Set interfaces) throws NotCompliantException { boolean warning = false; for (Iterator i = interfaces.iterator(); i.hasNext();) { String name = (String)i.next(); if (name.equals("java.lang.Cloneable")) warning = true; else warning = false; } if (warning) throw new NotCompliantWarningException("JMX class " + cls.getName() + " in MX4J implementation implements too many tag interfaces: " + interfaces); else throw new NotCompliantException("JMX class " + cls.getName() + " in MX4J implementation implements too many interfaces: " + interfaces); } private void checkSameConstructors(final Class jmxri, Class mx4j) throws NotCompliantException { checkSameObjectMethod(new ObjectClass.Constructor(jmxri), new ObjectClass.Constructor(mx4j)); } private void checkSameMethods(Class jmxri, Class mx4j) throws NotCompliantException { checkSameObjectMethod(new ObjectClass.Method(jmxri), new ObjectClass.Method(mx4j)); } private void checkSameObjectMethod(ObjectClass jmxri, ObjectClass mx4j) throws NotCompliantException { // Public methods first Set jmxriMethods = wrapMethods(jmxri.getMethods()); Set mx4jMethods = wrapMethods(mx4j.getMethods()); checkSameMethods(jmxri.getName(), jmxriMethods, mx4jMethods); // Protected methods now. I should walk the inheritance hierarchy. jmxriMethods.clear(); mx4jMethods.clear(); for (ObjectClass jmxriParent = jmxri, mx4jParent = mx4j; jmxriParent != null; jmxriParent = jmxriParent.getSuperclass(), mx4jParent = mx4jParent.getSuperclass()) { ObjectMethod[] methods = jmxriParent.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (Modifier.isProtected(methods[i].getModifiers())) { jmxriMethods.add(wrapMethod(methods[i])); } } methods = mx4jParent.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (Modifier.isProtected(methods[i].getModifiers())) { mx4jMethods.add(wrapMethod(methods[i])); } } } checkSameMethods(jmxri.getName(), jmxriMethods, mx4jMethods); } private void checkSameFields(Class jmxri, Class mx4j) throws NotCompliantException { // Public fields first Set jmxriFields = wrapFields(jmxri.getFields()); Set mx4jFields = wrapFields(mx4j.getFields()); checkSameFields(jmxri.getName(), jmxriFields, mx4jFields); // Protected fields now. I should walk the inheritance hierarchy. jmxriFields.clear(); mx4jFields.clear(); for (Class jmxriParent = jmxri, mx4jParent = mx4j; jmxriParent != null; jmxriParent = jmxriParent.getSuperclass(), mx4jParent = mx4jParent.getSuperclass()) { Field[] fields = jmxriParent.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if (Modifier.isProtected(fields[i].getModifiers())) { jmxriFields.add(wrapField(fields[i])); } } fields = mx4jParent.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { if (Modifier.isProtected(fields[i].getModifiers())) { mx4jFields.add(wrapField(fields[i])); } } } checkSameFields(jmxri.getName(), jmxriFields, mx4jFields); } private void checkSameSerialVersionUID(Class jmxriClass, Class mx4jClass) throws NotCompliantException { try { Field jmxriField = jmxriClass.getField("serialVersionUID"); jmxriField.setAccessible(true); Field mx4jField = mx4jClass.getField("serialVersionUID"); mx4jField.setAccessible(true); long jmxriValue = jmxriField.getLong(null); long mx4jValue = jmxriField.getLong(null); if (jmxriValue != mx4jValue) throw new NotCompliantException("JMX class " + jmxriClass.getName() + " in MX4J implementation does not have the same serialVersionUID: expecting " + jmxriValue + ", found " + mx4jValue); } catch (NoSuchFieldException ignored) { // If the class did not change between JMX 1.0 and JMX 1.1, then the serialVersionUID is not present } catch (NotCompliantException x) { throw x; } catch (Exception x) { x.printStackTrace(); throw new NotCompliantException("Unknown problems in checking serialVersionUID: " + x); } } private Set wrapMethods(ObjectMethod[] methods) { Set set = new HashSet(); for (int i = 0; i < methods.length; ++i) { set.add(wrapMethod(methods[i])); } return set; } private MethodWrapper wrapMethod(ObjectMethod method) { return new MethodWrapper(method); } private Set wrapFields(Field[] fields) { HashSet set = new HashSet(); for (int i = 0; i < fields.length; ++i) { set.add(wrapField(fields[i])); } return set; } private FieldWrapper wrapField(Field field) { return new FieldWrapper(field); } private void checkSameMethods(String name, Set jmxri, Set mx4j) throws NotCompliantException { if (!jmxri.containsAll(mx4j)) { checkDifferentMethods(name, mx4j, jmxri); } if (!mx4j.containsAll(jmxri)) { checkDifferentMethods(name, jmxri, mx4j); } } private void checkDifferentMethods(String name, Set set1, Set set2) throws NotCompliantException { set1.removeAll(set2); boolean warning = false; boolean error = false; ArrayList warnings = new ArrayList(); ArrayList errors = new ArrayList(); for (Iterator i = set1.iterator(); i.hasNext();) { MethodWrapper method1 = (MethodWrapper)i.next(); boolean found = false; for (Iterator j = set2.iterator(); j.hasNext();) { MethodWrapper method2 = (MethodWrapper)j.next(); if (method1.isSameMethod(method2)) { if (!method1.sameSignatureModifiers(method2)) { warning = true; warnings.add(method1); warnings.add(method2); } else { if (method1.throwsClauseDifferForRuntimeExceptionsOnly(method2)) { warning = true; warnings.add(method1); warnings.add(method2); } else { error = true; errors.add(method1); errors.add(method2); } } found = true; break; } } if (!found) throw new NotCompliantException("JMX class " + name + " in MX4J implementation has different interface: " + set1); } if (error) throw new NotCompliantException("JMX class " + name + " in MX4J implementation has different signature: " + errors); if (warning) throw new NotCompliantWarningException("JMX class " + name + " in MX4J implementation has different signature: " + warnings); throw new IllegalStateException(); } private void checkSameFields(String name, Set jmxri, Set mx4j) throws NotCompliantException { if (!jmxri.containsAll(mx4j)) { mx4j.removeAll(jmxri); throw new NotCompliantException("JMX class " + name + " in MX4J implementation has too many fields: " + mx4j); } if (!mx4j.containsAll(jmxri)) { jmxri.removeAll(mx4j); throw new NotCompliantException("JMX class " + name + " in MX4J implementation does not have the required fields: " + jmxri); } } } mx4j-3.0.2/src/test/test/javax/management/loading/ClassLoaderRepositoryTest.java100644 0 0 7705 10513545721 25127 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.loading; import java.lang.reflect.Method; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.loading.ClassLoaderRepository; import javax.management.loading.MLet; import junit.framework.TestCase; /** * @version $Revision: 1.9 $ */ public class ClassLoaderRepositoryTest extends TestCase { public ClassLoaderRepositoryTest(String s) { super(s); } public void testSingleMBeanServer() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ClassLoaderRepository clr = server.getClassLoaderRepository(); Method method = clr.getClass().getDeclaredMethod("getSize", new Class[0]); method.setAccessible(true); Integer size = (Integer)method.invoke(clr, new Object[0]); int initial = size.intValue(); ObjectName name1 = new ObjectName(":name=mlet1"); ObjectName name2 = new ObjectName(":name=mlet2"); MLet mlet1 = new MLet(); server.registerMBean(mlet1, name1); // Check that the mlet was registered as classloader size = (Integer)method.invoke(clr, new Object[0]); if (size.intValue() != initial + 1) fail("ClassLoader not registered in ClassLoaderRepository"); // Add another classloader MLet mlet2 = new MLet(); server.registerMBean(mlet2, name2); size = (Integer)method.invoke(clr, new Object[0]); if (size.intValue() != initial + 2) fail("ClassLoader not registered in ClassLoaderRepository"); } public void testMultipleMBeanServer() throws Exception { MBeanServer server1 = MBeanServerFactory.newMBeanServer("domain1"); MBeanServer server2 = MBeanServerFactory.newMBeanServer("domain2"); ClassLoaderRepository clr1 = server1.getClassLoaderRepository(); ClassLoaderRepository clr2 = server2.getClassLoaderRepository(); Method method = clr1.getClass().getDeclaredMethod("getSize", new Class[0]); method.setAccessible(true); Integer size1 = (Integer)method.invoke(clr1, new Object[0]); int initial1 = size1.intValue(); Integer size2 = (Integer)method.invoke(clr2, new Object[0]); int initial2 = size2.intValue(); ObjectName name1 = new ObjectName(":name=mlet1"); ObjectName name2 = new ObjectName(":name=mlet2"); MLet mlet1 = new MLet(); server1.registerMBean(mlet1, name1); MLet mlet2 = new MLet(); server2.registerMBean(mlet2, name2); // Check that the mlet was registered as classloader size1 = (Integer)method.invoke(clr1, new Object[0]); if (size1.intValue() != initial1 + 1) fail("ClassLoader not registered in ClassLoaderRepository"); size2 = (Integer)method.invoke(clr2, new Object[0]); if (size2.intValue() != initial2 + 1) fail("ClassLoader not registered in ClassLoaderRepository"); } public void testMultipleRegistrationOfSameClassLoader() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ClassLoaderRepository clr = server.getClassLoaderRepository(); Method method = clr.getClass().getDeclaredMethod("getSize", new Class[0]); method.setAccessible(true); Integer size = (Integer)method.invoke(clr, new Object[0]); int initial = size.intValue(); ObjectName name1 = new ObjectName(":name=mlet1"); ObjectName name2 = new ObjectName(":name=mlet2"); MLet mlet1 = new MLet(); server.registerMBean(mlet1, name1); server.registerMBean(mlet1, name2); // Check that the mlet was registered only once size = (Integer)method.invoke(clr, new Object[0]); if (size.intValue() != initial + 1) fail("Same ClassLoader was registered more than once"); } } mx4j-3.0.2/src/test/test/javax/management/loading/MLetTest.java100644 0 0 55276 10513545721 21522 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.loading; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.List; import java.util.Random; import java.util.Set; import java.util.Iterator; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.loading.MLet; import javax.management.loading.PrivateMLet; import mx4j.MX4JSystemKeys; import mx4j.loading.MLetParseException; import mx4j.loading.MLetParser; import mx4j.loading.MLetTag; import mx4j.server.DefaultClassLoaderRepository; import test.MX4JTestCase; /** * @version $Revision: 1.19 $ */ public class MLetTest extends MX4JTestCase { public MLetTest(String s) { super(s); } public void testInvalidMLetFileParsing() throws Exception { MLetParser parser = new MLetParser(); String content = null; try { parser.parse(content); fail(); } catch (MLetParseException x) { } content = ""; try { parser.parse(content); fail(); } catch (MLetParseException x) { } content = " "; try { parser.parse(content); fail(); } catch (MLetParseException x) { } content = " "; try { parser.parse(content); fail(); } catch (MLetParseException x) { } content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, missing attributes content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, missing archive attribute content = ""; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, missing archive attribute content = "\n\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, missing archive attribute content = "\n\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, missing code or object attribute content = ""; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid, either code or object attribute must be present content = ""; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid arg tag // content = "\n<>"; // try {parser.parse(content); fail();} // catch (MLetParseException x) {} // Invalid arg tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid arg tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid arg tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid name tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid name tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid version tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } // Invalid version tag content = "\n"; try { parser.parse(content); fail(); } catch (MLetParseException x) { } } public void testValidMLetFileParsing() throws Exception { MLetParser parser = new MLetParser(); String content = ""; parser.parse(content); content = "\n\t\n\n"; parser.parse(content); content = "\n\t\n\n"; parser.parse(content); } public void testCompleteMLetFileParsing() throws Exception { MLetParser parser = new MLetParser(); StringBuffer content = new StringBuffer(); content.append(""); content.append("\n"); content.append(" "); content.append(" \n"); content.append(" "); content.append(" \n"); content.append(""); parser.parse(content.toString()); } public void testCodebaseForGetMBeansFromURL() throws Exception { Class cls = Simple.class; String className = cls.getName(); URL url = cls.getProtectionDomain().getCodeSource().getLocation(); String urlString = url.toExternalForm(); int index = urlString.lastIndexOf('/') + 1; String jar = urlString.substring(index); String codebase = "."; String content = ""; MLetParser parser = new MLetParser(); List tags = parser.parse(content); MLetTag tag = (MLetTag)tags.get(0); URL mletFileURL = new URL("http://mx4j.sourceforge.net/mlets/mbeans.mlet"); URL codebaseURL = tag.normalizeCodeBase(mletFileURL); assertEquals(codebaseURL.toExternalForm(), "http://mx4j.sourceforge.net/mlets/"); content = ""; tags = parser.parse(content); tag = (MLetTag)tags.get(0); codebaseURL = tag.normalizeCodeBase(mletFileURL); assertEquals(codebaseURL.toExternalForm(), "http://mx4j.sourceforge.net/mlets/"); codebase = "../lib"; content = ""; tags = parser.parse(content); tag = (MLetTag)tags.get(0); codebaseURL = tag.normalizeCodeBase(mletFileURL); assertEquals(codebaseURL.toExternalForm(), "http://mx4j.sourceforge.net/lib/"); codebase = "ftp://mx4j.sourceforge.net/mbeans"; content = ""; tags = parser.parse(content); tag = (MLetTag)tags.get(0); codebaseURL = tag.normalizeCodeBase(mletFileURL); assertEquals(codebaseURL.toExternalForm(), codebase + "/"); } public void testGetMBeansFromURL() throws Exception { Class cls = Simple.class; String className = cls.getName(); URL url = cls.getProtectionDomain().getCodeSource().getLocation(); String urlString = url.toExternalForm(); int index = urlString.lastIndexOf('/') + 1; String jar = urlString.substring(index); String codebase = urlString.substring(0, index); // Write an MLet file File mletFile = File.createTempFile("mlet", null); mletFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(mletFile); String content = ""; fos.write(content.getBytes()); fos.close(); System.setProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY, CLRWithOnlyMLets.class.getName()); MBeanServer server = newMBeanServer(); ObjectName mletName = new ObjectName(":loader=mlet1"); MLet mlet = new MLet(); server.registerMBean(mlet, mletName); Set mbeans = mlet.getMBeansFromURL(mletFile.toURL()); if (mbeans.size() != 1) fail("Loaded wrong number of MBeans"); ObjectInstance instance = (ObjectInstance)mbeans.iterator().next(); if (!instance.getClassName().equals(className)) fail("Loaded a different MBean"); } public void testGetMBeansFromURLWithNoName() throws Exception { Class cls = SimpleRegistration.class; String className = cls.getName(); URL url = cls.getProtectionDomain().getCodeSource().getLocation(); String urlString = url.toExternalForm(); int index = urlString.lastIndexOf('/') + 1; String jar = urlString.substring(index); String codebase = urlString.substring(0, index); // Write an MLet file File mletFile = File.createTempFile("mletnoname", null); mletFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(mletFile); String content = ""; fos.write(content.getBytes()); fos.close(); System.setProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY, CLRWithOnlyMLets.class.getName()); MBeanServer server = newMBeanServer(); ObjectName mletName = new ObjectName(":loader=mlet1"); MLet mlet = new MLet(); server.registerMBean(mlet, mletName); Set mbeans = mlet.getMBeansFromURL(mletFile.toURL()); if (mbeans.size() != 1) fail("Loaded wrong number of MBeans"); ObjectInstance instance = (ObjectInstance)mbeans.iterator().next(); if (!instance.getClassName().equals(className)) fail("Loaded a different MBean"); } public void testMLetDelegatesToCLR() throws Exception { mletDelegationToCLR(true); } public void testMLetDoesNotDelegateToCLR() throws Exception { try { mletDelegationToCLR(false); fail("MLet does not delegate, cannot load the class"); } catch (ReflectionException ignored) { } } public void mletDelegationToCLR(boolean delegates) throws Exception { System.setProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY, CLRWithOnlyMLets.class.getName()); MBeanServer server = newMBeanServer(); ObjectName loaderName = new ObjectName("Loader", "id", "0"); ObjectName mletName = new ObjectName("Loader", "id", "1"); ObjectName mbeanName = new ObjectName("MBean", "id", "0"); Class cls = Simple.class; URL url = cls.getProtectionDomain().getCodeSource().getLocation(); String className = cls.getName(); MLet loader = new MLet(new URL[]{url}, ClassLoader.getSystemClassLoader().getParent()); server.registerMBean(loader, loaderName); MLet mlet = new MLet(new URL[0], ClassLoader.getSystemClassLoader().getParent(), delegates); // Be sure the MLet cannot load the class try { mlet.loadClass(className); fail("MLet should not be able to load the class"); } catch (ClassNotFoundException ignored) { } server.registerMBean(mlet, mletName); // Try to create the MBean server.createMBean(className, mbeanName, mletName); } public void testSingleMLetLoadClass() throws Exception { System.setProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY, CLRWithOnlyMLets.class.getName()); MBeanServer server = newMBeanServer(); ObjectName loaderName = new ObjectName("Loader", "id", "0"); ObjectName mbeanName = new ObjectName("MBean", "id", "0"); Class cls = Simple.class; URL url = cls.getProtectionDomain().getCodeSource().getLocation(); String className = cls.getName(); MLet mlet = new MLet(new URL[]{url}, ClassLoader.getSystemClassLoader().getParent()); server.registerMBean(mlet, loaderName); server.createMBean(className, mbeanName, loaderName); } public void testManyMLetLoadClass() throws Exception { int loaderCount = 100; int mbeanCount = 200; long elapsed = manyMLetLoadClass(loaderCount, mbeanCount, Simple.class.getName(), false); System.out.println("Loading " + mbeanCount + " MBeans with " + loaderCount + " MLets took " + elapsed + " ms, average is " + (elapsed / mbeanCount)); // Assume registering a valid MBean will take no more than 500 ms if (elapsed > mbeanCount * 500) fail("Test took too much time, probably a problem in MLet loading"); } public void testMultiMLetLoadNonExistingClass() throws Exception { int loaderCount = 100; int mbeanCount = 200; long elapsed = manyMLetLoadClass(loaderCount, mbeanCount, "dummy", true); System.out.println("Loading " + mbeanCount + " non-existing MBeans with " + loaderCount + " MLets took " + elapsed + " ms, average is " + (elapsed / mbeanCount)); // We're looking for a non-existing class, so we have to ask to all classloaders in the CLR before the chosen MLet // The time we spend looking for the class is roughly linear with the number of classloaders in the queried, // that in average is loaderCount / 2 and at most loaderCount: // elapsed = mbeanCount * loaderCount * k // Assume that k > 5 ms is too bad performance if (elapsed > mbeanCount * loaderCount * 5) fail("Test took too much time, probably a problem in MLet loading"); } private long manyMLetLoadClass(int loaderCount, int mbeanCount, String className, boolean ignoreExceptionOnCreation) throws Exception { ObjectName[] loaders = new ObjectName[loaderCount]; ObjectName[] mbeans = new ObjectName[mbeanCount]; MBeanServer server = newMBeanServer(); URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); // Register some MLet for (int i = 0; i < loaderCount; ++i) { loaders[i] = new ObjectName("Loader", "id", String.valueOf(i)); MLet mlet = new MLet(new URL[]{url}, ClassLoader.getSystemClassLoader().getParent()); server.registerMBean(mlet, loaders[i]); } long start = System.currentTimeMillis(); Random random = new Random(start); for (int i = 0; i < mbeanCount; ++i) { mbeans[i] = new ObjectName("MBean", "id", String.valueOf(i)); // Choose an MLet to load the MBean int id = random.nextInt(loaderCount); ObjectName loader = loaders[id]; if (ignoreExceptionOnCreation) { try { server.createMBean(className, mbeans[i], loader); } catch (ReflectionException ignored) { } } else { server.createMBean(className, mbeans[i], loader); } } long end = System.currentTimeMillis(); return end - start; } public void testChildMLetRegisteredBeforeParentMLet() throws Exception { // A test to be sure the MLet implementation does not recurse infinitely when loading classes. URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); MLet parent = new MLet(new URL[]{url}, ClassLoader.getSystemClassLoader().getParent()); MLet child = new MLet(new URL[0], parent); ObjectName parentName = new ObjectName("MLet", "type", "parent"); ObjectName childName = new ObjectName("MLet", "type", "child"); MBeanServer server = newMBeanServer(); // First register the child, then the parent. server.registerMBean(child, childName); server.registerMBean(parent, parentName); // Now in the CLR there are: SystemCL, childMLet, parentMLet. // If I ask someting to parentMLet that it cannot find, it will delegate to the CLR, // and when it comes to the childMLet, the delegation mechanism will ask again to the parentMLet. // If we're not smart in the MLet implementation this ends up in an infinite loop. try { parent.loadClass("dummy"); fail("Class does not exist"); } catch (ClassNotFoundException ignored) { } } public void testPrivateMLetNotAddedToCLR() throws Exception { Class cls = Simple.class; URL url = cls.getProtectionDomain().getCodeSource().getLocation(); PrivateMLet mlet = new PrivateMLet(new URL[]{url}, ClassLoader.getSystemClassLoader().getParent(), true); ObjectName mletName = new ObjectName(":MLet=Private"); ObjectName mbeanName = new ObjectName(":MBean=Simple"); System.setProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY, CLRWithOnlyMLets.class.getName()); MBeanServer server = newMBeanServer(); // The private MLet should not be registered in the CLR server.registerMBean(mlet, mletName); try { // Ask the CLR to load the class server.createMBean(cls.getName(), mbeanName); fail("Class cannot be found by the CLR"); } catch (ReflectionException ignored) { } } public void testFindLibrary() throws Exception { MLet mlet = new MLet(); Method method = mlet.getClass().getDeclaredMethod("findLibrary", new Class[]{String.class}); method.setAccessible(true); String result = (String)method.invoke(mlet, new Object[]{"stat"}); if (result != null) fail("MLet can load non-existing libraries"); } public void testFindLibraryWithLibraryDirectoryInClassPath() throws Exception { // Prepare the library String library = "mlet"; String libraryName = System.mapLibraryName(library); File libraryFile = new File(libraryName); FileOutputStream fos = new FileOutputStream(libraryFile); fos.write("library".getBytes()); fos.close(); assertTrue(libraryFile.exists()); assertTrue(libraryFile.length() > 0); MLet mlet = new MLet(new URL[]{libraryFile.getCanonicalFile().getParentFile().toURL()}); Method method = mlet.getClass().getDeclaredMethod("findLibrary", new Class[]{String.class}); method.setAccessible(true); String result = (String)method.invoke(mlet, new Object[]{library}); assertNotNull(result); assertTrue(libraryFile.exists()); assertTrue(libraryFile.length() > 0); } public void testFindLibraryWithLibraryDirectoryNotInClassPath() throws Exception { // Prepare the library String library = "mlet"; String libraryName = System.mapLibraryName(library); File libraryFile = new File(libraryName); FileOutputStream fos = new FileOutputStream(libraryFile); fos.write("library".getBytes()); fos.close(); assertTrue(libraryFile.exists()); assertTrue(libraryFile.length() > 0); MLet mlet = new MLet(new URL[]{libraryFile.getCanonicalFile().getParentFile().toURL()}); // Set the library directory to some temp directory File temp = File.createTempFile("abc", null); temp.deleteOnExit(); mlet.setLibraryDirectory(temp.getCanonicalFile().getParentFile().getCanonicalPath()); Method method = mlet.getClass().getDeclaredMethod("findLibrary", new Class[]{String.class}); method.setAccessible(true); String result = (String)method.invoke(mlet, new Object[]{library}); assertNotNull(result); assertTrue(libraryFile.exists()); assertTrue(libraryFile.length() > 0); File tempLibrary = new File(mlet.getLibraryDirectory(), libraryName); assertTrue(tempLibrary.exists()); assertTrue(tempLibrary.length() > 0); } public void testDefaultMletName() throws Exception { MBeanServer mbServer = newMBeanServer(); MLet mlet = new MLet(); ObjectName mletName = new ObjectName(mbServer.getDefaultDomain(), "type", "MLet"); assertFalse(mbServer.isRegistered(mletName)); assertEquals(mletName, mbServer.registerMBean(mlet, null).getObjectName()); assertTrue(mbServer.isRegistered(mletName)); } public interface SimpleMBean { } public static class Simple implements SimpleMBean { } public static class SimpleRegistration extends Simple implements MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return ObjectName.getInstance(":name=simple"); } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } } public static class CLRWithOnlyMLets extends DefaultClassLoaderRepository { protected void addClassLoader(ClassLoader cl) { if (cl == null) return; if (cl.getClass() == MLet.class || cl.getClass() == PrivateMLet.class) super.addClassLoader(cl); } } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/DescriptorSupportTest.java100644 0 0 42366 10513545721 25056 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.management.Descriptor; import javax.management.RuntimeOperationsException; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.XMLParseException; import test.MX4JTestCase; /** * @version $Revision: 1.19 $ */ public class DescriptorSupportTest extends MX4JTestCase { public DescriptorSupportTest(String s) { super(s); } public void testValid() throws Exception { // Create a valid Descriptor object String[] attributes = {"name=mytest", "descriptorType=MBean", "role=constructor"}; new DescriptorSupport(attributes); // Try a different constructor String[] names = {"name", "descriptorType", "role", "persistPolicy", "persistPeriod"}; String[] values = {"mytest", "MBean", "constructor", "Never", "1"}; new DescriptorSupport(names, values); // Create a valid Descriptor object. Check that persistPolicy's value is not case sensitive names = new String[]{"name", "descriptorType", "persistPolicy"}; values = new String[]{"mytest", "MBean", "never"}; new DescriptorSupport(names, values); } public void testInvalid() throws Exception { // Create an invalid Descriptor object. Check persist policy String[] names = {"name", "descriptorType", "role", "persistPolicy"}; String[] values = {"mytest", "MBean", "constructor", "Something"}; try { new DescriptorSupport(names, values); fail("Descriptor support object created with invalid attributes"); } catch (RuntimeOperationsException ex) { } // Create an invalid Descriptor object. Check persistPeriod // Persist period should be bigger or equal than -1 names = new String[]{"name", "descriptorType", "persistPolicy", "persistPeriod"}; values = new String[]{"mytest", "MBean", "Never", "-2"}; try { new DescriptorSupport(names, values); fail("Descriptor support object created with invalid persistPeriod"); } catch (RuntimeOperationsException ex) { } // Create an invalid Descriptor object. Check visiblity // visibility should be between 1 and 4 names = new String[]{"name", "descriptorType", "visibility"}; values = new String[]{"mytest", "MBean", "0"}; try { new DescriptorSupport(names, values); fail("Descriptor support object created with invalid visiblity"); } catch (RuntimeOperationsException ex) { } // Create an invalid Descriptor object. Check visiblity // visibility should be between 1 and 4 names = new String[]{"name", "descriptorType", "visibility"}; values = new String[]{"mytest", "MBean", "5"}; try { new DescriptorSupport(names, values); fail("Descriptor support object created with invalid visiblity"); } catch (RuntimeOperationsException ex) { } } public void testIsValid() throws Exception { // Test for bug #686306 String[] names = {"name", "descriptorType", "persistPolicy", "persistPeriod"}; String[] values = {"test", "mbean", "AlwaYs", "-1"}; DescriptorSupport ds = new DescriptorSupport(names, values); assertTrue(ds.isValid()); } public void testSeverityField() throws Exception { // Test for bug #744423 and #775742 String[] names = {"name", "descriptorType", "severity"}; String[] values = {"test", "mbean", "0"}; DescriptorSupport ds = new DescriptorSupport(names, values); assertTrue(ds.isValid()); names = new String[]{"name", "descriptorType", "severity"}; values = new String[]{"test", "mbean", "6"}; ds = new DescriptorSupport(names, values); assertTrue(ds.isValid()); } public void testCaseInsensitiveFieldNames() throws Exception { String[] fields = {"descriptorType", "myField"}; Object[] values = {"MBean", "top secret"}; DescriptorSupport ds = new DescriptorSupport(fields, values); assertEquals("Expecting 'descriptorType' value to be 'mbean'", (String)ds.getFieldValue("DESCRIPTORTYPE"), "MBean"); assertEquals("Expecting 'myField' value to be 'top secret'", (String)ds.getFieldValue("MYfIELD"), "top secret"); fields = new String[]{"name", "descriptorType", "deleteMe"}; values = new String[]{"testCaseInsensitiveFieldNames", "MBean", "nothing of consequence"}; ds = new DescriptorSupport(fields, values); ds.removeField("DELETEmE"); String[] fieldnames = ds.getFields(); List fieldlist = new ArrayList(); for (int i = 0; i < fieldnames.length; i++) fieldlist.add(fieldnames[i]); int fieldcount = fieldnames.length; assertEquals("Expecting 'deleteMe' to be gone", fieldcount, 2); assertFalse(fieldlist.contains("deleteme")); } public void testCaseInsensitiveFieldValues() throws Exception { String[] fields = {"descriptorType", "persistPolicy", "log"}; String[] values = {"mBEAN", "oNuPDATE", "TRUE"}; new DescriptorSupport(fields, values); } public void testCaseSensitivityPreserved() throws Exception { String[] names = {"Name", "DescriptorType"}; String[] values = {"test", "mbean"}; DescriptorSupport descriptor = new DescriptorSupport(names, values); // Check case insensitivity on get String value = (String)descriptor.getFieldValue("name"); assertNotNull(value); assertEquals(value, values[0]); value = (String)descriptor.getFieldValue("descriptorType"); assertNotNull(value); assertEquals(value, values[1]); // Be sure case is preserved String[] fieldNames = descriptor.getFieldNames(); assertNotNull(fieldNames); assertEquals(fieldNames.length, 2); if (!fieldNames[0].equals(names[0]) && !fieldNames[0].equals(names[1])) fail(); if (!fieldNames[1].equals(names[0]) && !fieldNames[1].equals(names[1])) fail(); // Check serialization works ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(descriptor); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); DescriptorSupport newDescriptor = (DescriptorSupport)ois.readObject(); value = (String)newDescriptor.getFieldValue("name"); assertNotNull(value); assertEquals(value, values[0]); // Be sure case is preserved fieldNames = newDescriptor.getFieldNames(); assertNotNull(fieldNames); assertEquals(fieldNames.length, 2); if (!fieldNames[0].equals(names[0]) && !fieldNames[0].equals(names[1])) fail(); if (!fieldNames[1].equals(names[0]) && !fieldNames[1].equals(names[1])) fail(); // Check that removeField() really removes the field, no matter case sensitivity descriptor.removeField("name"); value = (String)descriptor.getFieldValue("name"); assertNull(value); fieldNames = descriptor.getFieldNames(); assertNotNull(fieldNames); assertEquals(fieldNames.length, 1); assertEquals(fieldNames[0], names[1]); } public void testDefaultFieldValuesSize() throws Exception { DescriptorSupport ds = new DescriptorSupport(); Object[] fields = ds.getFieldValues(null); assertTrue("Expecting 0 length array", fields.length == 0); } public void testNullDescriptorConstructorParam() throws Exception { DescriptorSupport ds = new DescriptorSupport((DescriptorSupport)null); assertNotNull(ds.getFields()); assertEquals("Expecting the descriptor to be empty", ds.getFields().length, 0); assertFalse("Expecting the descriptor to be invalid", ds.isValid()); } public void testNullStringConstructorParam() throws Exception { try { new DescriptorSupport((String)null); fail("Expecting RuntimeOperationsException"); } catch (RuntimeOperationsException x) { if (!(x.getTargetException() instanceof IllegalArgumentException)) fail("Target exception should be IllegalArgumentException"); } } public void testNullStringArrayCtorParm() throws Exception { String[] nullfields = null; DescriptorSupport ds = new DescriptorSupport(nullfields); Object[] fields = ds.getFieldValues(null); assertEquals("Expecting 0 length array", fields.length, 0); } public void testToXMLString() throws Exception { String[] fields = {"wine", "vineyard", "year", "price"}; Object[] values = {"Amarone", "Allegrini", "1996", new Integer(90)}; DescriptorSupport ds = new DescriptorSupport(fields, values); String xml = ds.toXMLString(); assertTrue("Descriptor from XML != Descriptor", descriptorsEqual(ds, (new DescriptorSupport(xml)))); fields = new String[]{"wine=Amarone", "vineyard=Allegrini", "year=1996"}; ds = new DescriptorSupport(fields); xml = ds.toXMLString(); assertTrue("Descriptor from XML != Descriptor", descriptorsEqual(ds, (new DescriptorSupport(xml)))); } public void testEmptyDescriptorToXMLString() throws Exception { DescriptorSupport ds = new DescriptorSupport(); String xml = ds.toXMLString(); assertEquals("Unexpected xml: " + xml, xml, ""); } public void testGetFieldsUnknownName() { String[] fields = {"wine", "vineyard", "year"}; String[] values = {"Amarone", "Allegrini", "1996"}; DescriptorSupport ds = new DescriptorSupport(fields, values); Object fv = ds.getFieldValue("price"); assertNull(fv); fields = new String[]{"wine", "vineyard", "year", "price"}; Object[] fvs = ds.getFieldValues(fields); assertEquals("wrong number of values", fvs.length, fields.length); assertNull(fvs[3]); } public void testGetFieldsEmptyArray() { String[] fields = {"wine", "vineyard", "year"}; String[] values = {"Amarone", "Allegrini", "1996"}; DescriptorSupport ds = new DescriptorSupport(fields, values); Object[] fvs = ds.getFieldValues(new String[0]); assertEquals("Expecting empty array", fvs.length, 0); } public void testRemoveField() { String[] fields = {"wine", "vineyard", "year", "price"}; Object[] values = {"Amarone", "Allegrini", "1996", new Integer(90)}; DescriptorSupport ds = new DescriptorSupport(fields, values); assertEquals("Expecting " + fields.length + " names", ds.getFieldNames().length, fields.length); ds.removeField("price"); assertEquals("Expecting " + (fields.length - 1) + " names", ds.getFieldNames().length, fields.length - 1); } public void testRemoveNonexistentFieldDoesntThrow() { String[] fields = {"wine", "vineyard", "year"}; String[] values = {"Amarone", "Allegrini", "1996"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ds.removeField("price"); } public void testRemoveNullField() { String[] fields = {"wine", "vineyard", "year"}; String[] values = {"Amarone", "Allegrini", "1996"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ds.removeField(null); } public void testXMLStringConstructor() throws Exception { StringBuffer xmldescriptor = new StringBuffer(); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); DescriptorSupport ds = new DescriptorSupport(xmldescriptor.toString()); String xml = ds.toXMLString(); assertTrue("Descriptor from XML != Descriptor", descriptorsEqual(ds, (new DescriptorSupport(xml)))); } public void testXMLSpecialStringConstructor() throws Exception { String[] fields = {"name=Lawrence", "nickname=(Larry)"}; DescriptorSupport ds = new DescriptorSupport(fields); String xml = ds.toXMLString(); DescriptorSupport xmlds = new DescriptorSupport(xml); assertTrue("Descriptors not equal", descriptorsEqual(ds, xmlds)); } public void testXMLPrimitiveConstructor() throws Exception { StringBuffer xmldescriptor = new StringBuffer(); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); DescriptorSupport ds = new DescriptorSupport(xmldescriptor.toString()); String xml = ds.toXMLString(); assertTrue("Descriptor from XML != Descriptor", descriptorsEqual(ds, (new DescriptorSupport(xml)))); } public void testXMLClassConstructor() throws Exception { StringBuffer xmldescriptor = new StringBuffer(); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); DescriptorSupport ds = new DescriptorSupport(xmldescriptor.toString()); String xml = ds.toXMLString(); assertTrue("Descriptor from XML != Descriptor", descriptorsEqual(ds, (new DescriptorSupport(xml)))); } public void testBogusXMLConstructor() throws Exception { try { new DescriptorSupport(""); fail("Expecting XMLParseException"); } catch (XMLParseException x) { } } public void testBogusXMLValueCtor() throws Exception { try { StringBuffer xmldescriptor = new StringBuffer(); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); xmldescriptor.append(""); new DescriptorSupport(xmldescriptor.toString()); fail("Expecting XMLParseException"); } catch (XMLParseException x) { } } private boolean descriptorsEqual(Descriptor done, Descriptor dtwo) { Set namesone = new HashSet(Arrays.asList(done.getFieldNames())); Set namestwo = new HashSet(Arrays.asList(dtwo.getFieldNames())); if (!namesone.equals(namestwo)) return false; Iterator i = namesone.iterator(); while (i.hasNext()) { String field = (String)i.next(); Object vone = done.getFieldValue(field); Object vtwo = dtwo.getFieldValue(field); if ((vone == null && vtwo != null) || (vone != null && !vone.equals(vtwo))) { return false; } } return true; } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/ModelMBeanAttributeInfoTest.java100644 0 0 14321 10513545721 25774 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import javax.management.Descriptor; import javax.management.IntrospectionException; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanAttributeInfo; import test.MX4JTestCase; /** * Test case of ModelMBeanAttributeInfo. It will try to verify an appropriate * behaviour in particular with respect to the descriptor values * * @version $Revision: 1.7 $ * @see */ public class ModelMBeanAttributeInfoTest extends MX4JTestCase { public static class BogusNIC { public String getMAC() { return null; } public void setMAC(int mac) { } } public ModelMBeanAttributeInfoTest(String s) { super(s); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testValidDescriptorFields() throws Exception { // testcase for bug #794320 // Test that only name and descriptorType are mandatory Descriptor descriptor = new DescriptorSupport(new String[]{"name", "descriptortype", "default"}, new String[]{"attribute1", "attribute", "default"}); ModelMBeanAttributeInfo attribute = new ModelMBeanAttributeInfo("attribute1", "java.lang.String", "An attribute", true, true, false, descriptor); // in case of bug #794320 the descriptor is overrided assertEquals(attribute.getDescriptor().getFieldValue("default"), "default"); assertNull(attribute.getDescriptor().getFieldValue("value")); } public void testBadCtor() throws Exception { try { Method macgetter = BogusNIC.class.getMethod("getMAC", new Class[0]); Method macsetter = BogusNIC.class.getMethod("setMAC", new Class[]{int.class}); ModelMBeanAttributeInfo attrinfo = new ModelMBeanAttributeInfo("MAC", "MAC Address", macgetter, macsetter); fail("Expecting an IntrospectionException"); } catch (IntrospectionException x) { assertTrue(true); // success; } } public void testValuelessAttribute() throws Exception { ModelMBeanAttributeInfo attrinfo = new ModelMBeanAttributeInfo("SerialNo", "NIC Card's serial number", null, null); attrinfo = new ModelMBeanAttributeInfo("SerialNo", "String", "NIC Card's serial number", false, false, false); } public void testCaseInsenstiveDescriptorType() { DescriptorSupport ds = new DescriptorSupport(new String[]{ "name=PreferredWine", "descriptorType=Attribute", "value=Amarone", "default=Red" }); ModelMBeanAttributeInfo attrinfo = new ModelMBeanAttributeInfo("PreferredWine", "String", "Wine of choice", true, false, false, ds); } public void testGetDescriptor() { DescriptorSupport defds = new DescriptorSupport(new String[]{ "name=PreferredWine", "descriptorType=Attribute", "displayName=PreferredWine"}); DescriptorSupport ds = new DescriptorSupport(new String[]{ "name=PreferredWine", "descriptorType=Attribute", "value=Amarone", "displayName=PreferredWine", "default=Red" }); ModelMBeanAttributeInfo attrinfo = new ModelMBeanAttributeInfo("PreferredWine", "String", "Wine of choice", true, false, false); Descriptor d = attrinfo.getDescriptor(); assertTrue("Expecting default descriptor", descriptorsEqual(d, defds)); attrinfo = new ModelMBeanAttributeInfo("PreferredWine", "String", "Wine of choice", true, false, false, ds); d = attrinfo.getDescriptor(); assertTrue("Expecting copy of ds", descriptorsEqual(d, ds)); } private boolean descriptorsEqual(Descriptor done, Descriptor dtwo) { List cifields = Arrays.asList(new String[]{"descriptortype", "persistpolicy", "log"}); String[] fields = done.getFieldNames(); boolean result = done.getFields().length == dtwo.getFields().length; for (int i = 0; i < fields.length && result == true; i++) { String field = fields[i]; Object vone = done.getFieldValue(field); Object vtwo = done.getFieldValue(field); if (vtwo == null) { result = false; } else if (cifields.contains(field)) { if (!(vone instanceof String) || !(vtwo instanceof String)) { result = false; } else { result = ((String)vone).compareToIgnoreCase((String)vtwo) == 0; } } else { vone.equals(vtwo); } } return result; } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/ModelMBeanConstructorInfoTest.java100644 0 0 7454 10513545721 26347 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.lang.reflect.Constructor; import javax.management.Descriptor; import javax.management.MBeanParameterInfo; import javax.management.RuntimeOperationsException; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanConstructorInfo; import junit.framework.TestCase; import junit.textui.TestRunner; /** * @version $Revision: 1.5 $ */ public class ModelMBeanConstructorInfoTest extends TestCase { public static class Bob { public Bob(String address) { } } public static void main(String[] args) { TestRunner.run(ModelMBeanConstructorInfoTest.class); } public ModelMBeanConstructorInfoTest(String name) { super(name); } public void testValid() throws Exception { Constructor bobctor = ModelMBeanConstructorInfoTest.Bob.class.getConstructor(new Class[]{String.class}); String[] fields = {"name", "descriptorType", "displayName", "role"}; String[] values = {bobctor.getName(), "operation", "bob maker", "constructor"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanConstructorInfo ctorinfo = new ModelMBeanConstructorInfo("BobBuilder", bobctor, ds); } public void testAddDefaultDisplayName() throws Exception { Constructor bobctor = ModelMBeanConstructorInfoTest.Bob.class.getConstructor(new Class[]{String.class}); String[] fields = {"name", "descriptorType", "role"}; String[] values = {bobctor.getName(), "operation", "constructor"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanConstructorInfo ctorinfo = new ModelMBeanConstructorInfo("BobBuilder", bobctor, ds); Descriptor d = ctorinfo.getDescriptor(); String dispname = (String)d.getFieldValue("displayName"); assertTrue("Unexpected displayName", dispname.compareTo(bobctor.getName()) == 0); } public void testBadRole() throws Exception { try { Constructor bobctor = ModelMBeanConstructorInfoTest.Bob.class.getConstructor(new Class[]{String.class}); String[] fields = {"name", "descriptorType", "displayName", "role"}; String[] values = {bobctor.getName(), "operation", "bob maker", "getter"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanConstructorInfo ctorinfo = new ModelMBeanConstructorInfo("BobBuilder", bobctor, ds); fail("Expecting RuntimeOperationsException"); } catch (RuntimeOperationsException x) { if (!(x.getTargetException() instanceof IllegalArgumentException)) { fail("Target exception should be IllegalArgumentException"); } assertTrue(true); // success } } public void testCaseInsensitiveDescriptorType() { DescriptorSupport ds = new DescriptorSupport(new String[]{ "descriptorType=OPERATION", "role=constructor", "name=BobBuilder", "displayname=bob maker"}); ModelMBeanConstructorInfo ctorinfo = new ModelMBeanConstructorInfo("BobBuilder", "Default Bob Constructor", new MBeanParameterInfo[0], ds); } protected void setUp() { } protected void tearDown() { } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/ModelMBeanInfoSupportTest.java100644 0 0 30732 10513545721 25511 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.util.Arrays; import javax.management.Descriptor; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanConstructorInfo; import javax.management.modelmbean.ModelMBeanInfoSupport; import javax.management.modelmbean.ModelMBeanNotificationInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; import junit.framework.TestCase; /** * @version $Revision: 1.7 $ * @see */ public class ModelMBeanInfoSupportTest extends TestCase { public ModelMBeanInfoSupportTest(String s) { super(s); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testGetDescriptor() throws Exception { ModelMBeanAttributeInfo[] attributes = new ModelMBeanAttributeInfo[2]; attributes[0] = new ModelMBeanAttributeInfo("test", "java.lang.String", "A description", true, true, false); attributes[1] = new ModelMBeanAttributeInfo("test2", "java.lang.String", "A description", true, true, false); // testcase for bug #700905 ModelMBeanInfoSupport support = new ModelMBeanInfoSupport("somepackage.someclass", "Test case", attributes, null, null, null); // this worked ok Descriptor descriptor = support.getDescriptor("test", "attribute"); assertNotNull(descriptor); assertEquals("test", descriptor.getFieldValue("name")); // this didn't descriptor = support.getDescriptor("test", null); assertNotNull(descriptor); assertEquals("test", descriptor.getFieldValue("name")); } public void testCaseInsensitiveDescriptorType() { DescriptorSupport ds = new DescriptorSupport(new String[]{ "name=TestMetadata", "descriptorType=mbEAN", "displayname=Test Metadata" }); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport("TestMetadata", "An empty model mbean info instance", new ModelMBeanAttributeInfo[0], new ModelMBeanConstructorInfo[0], new ModelMBeanOperationInfo[0], new ModelMBeanNotificationInfo[0], ds); } public void testGetMBeanDescriptorDefault() throws Exception { ModelMBeanInfoSupport info = new ModelMBeanInfoSupport("TestMetadata", "An empty model mbean info instance", new ModelMBeanAttributeInfo[0], new ModelMBeanConstructorInfo[0], new ModelMBeanOperationInfo[0], new ModelMBeanNotificationInfo[0]); Descriptor dd = info.getMBeanDescriptor(); assertFalse("default descriptor is null", dd == null); assertTrue("Expecting 7 fields", dd.getFieldNames().length == 7); String[] deffields = { "name", "descriptorType", "displayName", "persistPolicy", "log", "export", "visibility"}; String[] fields = dd.getFieldNames(); assertTrue("Expected field names not present", Arrays.asList(fields).containsAll(Arrays.asList(deffields))); assertTrue("Unexpected name", ((String)dd.getFieldValue("name")).compareTo("TestMetadata") == 0); assertTrue("Unexpected descriptorType", ((String)dd.getFieldValue("descriptortype")).compareToIgnoreCase("mbean") == 0); assertTrue("Unexpected displayName: " + dd.getFieldValue("displayname"), ((String)dd.getFieldValue("displayname")).compareTo("TestMetadata") == 0); assertTrue("Unexpected persistpolicy", ((String)dd.getFieldValue("persistpolicy")).compareToIgnoreCase("never") == 0); assertTrue("Unexpected log", ((String)dd.getFieldValue("log")).compareToIgnoreCase("F") == 0); assertTrue("Unexpected export", ((String)dd.getFieldValue("export")).compareTo("F") == 0); assertTrue("Unexpected visibility", ((String)dd.getFieldValue("visibility")).compareTo("1") == 0); info = new ModelMBeanInfoSupport("TestMetadata", "An empty model mbean info instance", new ModelMBeanAttributeInfo[0], new ModelMBeanConstructorInfo[0], new ModelMBeanOperationInfo[0], new ModelMBeanNotificationInfo[0], null); dd = info.getMBeanDescriptor(); assertFalse("default descriptor is null", dd == null); assertTrue("Expecting 7 fields", dd.getFieldNames().length == 7); assertTrue("Expected field names not present", Arrays.asList(fields).containsAll(Arrays.asList(deffields))); assertTrue("Unexpected name", ((String)dd.getFieldValue("name")).compareTo("TestMetadata") == 0); assertTrue("Unexpected descriptorType", ((String)dd.getFieldValue("descriptortype")).compareToIgnoreCase("mbean") == 0); assertTrue("Unexpected displayName: " + dd.getFieldValue("displayname"), ((String)dd.getFieldValue("displayname")).compareTo("TestMetadata") == 0); assertTrue("Unexpected persistpolicy", ((String)dd.getFieldValue("persistpolicy")).compareToIgnoreCase("never") == 0); assertTrue("Unexpected log", ((String)dd.getFieldValue("log")).compareToIgnoreCase("F") == 0); assertTrue("Unexpected export", ((String)dd.getFieldValue("export")).compareTo("F") == 0); assertTrue("Unexpected visibility", ((String)dd.getFieldValue("visibility")).compareTo("1") == 0); } public void testGetMBeanDescriptorAdditionalValues() throws Exception { String[] fields = { "name", "descriptortype", "displayname", "targetObject", "export", "defaultValue"}; Object[] values = { "TestMetadata", "MBEAN", "JMX Metadata for testing purposes", new Double(0), "test metadata", new Double(99.999)}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport("TestMetadata", "An empty model mbean info instance", new ModelMBeanAttributeInfo[0], new ModelMBeanConstructorInfo[0], new ModelMBeanOperationInfo[0], new ModelMBeanNotificationInfo[0], ds); Descriptor d = info.getMBeanDescriptor(); assertFalse("descriptor is null", d == null); assertTrue("Expecting 9 fields", d.getFieldNames().length == 9); String[] deffields = { "name", "descriptortype", "displayname", "persistpolicy", "log", "export", "visibility"}; String[] infofields = d.getFieldNames(); assertTrue("Expected field names not present", Arrays.asList(infofields).containsAll(Arrays.asList(deffields))); assertTrue("Unexpected name", ((String)d.getFieldValue("name")).compareTo((String)ds.getFieldValue("name")) == 0); assertTrue("Unexpected descriptorType", ((String)d.getFieldValue("descriptortype")).compareToIgnoreCase((String)ds.getFieldValue("descriptortype")) == 0); assertTrue("Unexpected displayName: " + d.getFieldValue("displayname"), ((String)d.getFieldValue("displayname")).compareTo((String)ds.getFieldValue("displayname")) == 0); assertTrue("Unexpected targetObject: " + d.getFieldValue("targetObject"), ((Double)d.getFieldValue("targetObject")).equals(new Double(0.0))); assertTrue("Unexpected persistpolicy", ((String)d.getFieldValue("persistpolicy")).compareToIgnoreCase("never") == 0); assertTrue("Unexpected log", ((String)d.getFieldValue("log")).compareToIgnoreCase("F") == 0); assertTrue("Unexpected export", ((String)d.getFieldValue("export")).compareTo((String)ds.getFieldValue("export")) == 0); assertTrue("Unexpected defaultValue", ((Double)d.getFieldValue("defaultValue")).equals(new Double(99.999))); assertTrue("Unexpected visibility", ((String)d.getFieldValue("visibility")).compareTo("1") == 0); } public void testGetMBeanDescriptorCustom() throws Exception { String[] fields = { "name", "descriptortype", "displayname", "persistpolicy", "log", "export", "visibility"}; Object[] values = { "TestMetadata", "MBEAN", "JMX Metadata for testing purposes", "onUPDATE", "T", "test metadata", "4"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport("TestMetadata", "An empty model mbean info instance", new ModelMBeanAttributeInfo[0], new ModelMBeanConstructorInfo[0], new ModelMBeanOperationInfo[0], new ModelMBeanNotificationInfo[0], ds); Descriptor d = info.getMBeanDescriptor(); assertFalse("descriptor is null", d == null); assertTrue("Expecting 7 fields", d.getFieldNames().length == 7); String[] deffields = { "name", "descriptortype", "displayname", "persistpolicy", "log", "export", "visibility"}; String[] infofields = d.getFieldNames(); assertTrue("Expected field names not present", Arrays.asList(infofields).containsAll(Arrays.asList(deffields))); assertTrue("Unexpected name", ((String)d.getFieldValue("name")).compareTo((String)ds.getFieldValue("name")) == 0); assertTrue("Unexpected descriptorType", ((String)d.getFieldValue("descriptortype")).compareToIgnoreCase((String)ds.getFieldValue("descriptortype")) == 0); assertTrue("Unexpected displayName: " + d.getFieldValue("displayname"), ((String)d.getFieldValue("displayname")).compareTo((String)ds.getFieldValue("displayname")) == 0); assertTrue("Unexpected persistpolicy", ( (String)d.getFieldValue("persistpolicy")).compareToIgnoreCase(((String)d.getFieldValue("persistpolicy"))) == 0); assertTrue("Unexpected log", ((String)d.getFieldValue("log")).compareToIgnoreCase(((String)d.getFieldValue("log"))) == 0); assertTrue("Unexpected export", ((String)d.getFieldValue("export")).compareTo((String)ds.getFieldValue("export")) == 0); assertTrue("Unexpected visibility", ((String)d.getFieldValue("visibility")).compareTo(((String)d.getFieldValue("visibility"))) == 0); } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/ModelMBeanNotificationInfoTest.java100644 0 0 4543 10513545721 26444 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import javax.management.Descriptor; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanNotificationInfo; import junit.framework.TestCase; /** * @version $Revision: 1.4 $ * @see */ public class ModelMBeanNotificationInfoTest extends TestCase { public ModelMBeanNotificationInfoTest(String s) { super(s); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testSeverityField() throws Exception { // testcase for bug #775742, #744423 and #775739 // this should work ok Descriptor descriptor = new DescriptorSupport(new String[]{"name", "descriptortype", "severity"}, new String[]{"aNotification", "notification", "6"}); ModelMBeanNotificationInfo notification = new ModelMBeanNotificationInfo(new String[]{"type1"}, "aNotification", "A description", descriptor); assertSame(descriptor.getFieldValue("notification"), notification.getDescriptor().getFieldValue("notification")); descriptor = new DescriptorSupport(new String[]{"name", "descriptortype", "severity"}, new String[]{"aNotification", "notification", "0"}); notification = new ModelMBeanNotificationInfo(new String[]{"type1"}, "aNotification", "A description", descriptor); assertSame(descriptor.getFieldValue("notification"), notification.getDescriptor().getFieldValue("notification")); } public void testCaseInsensitiveDescriptorType() { DescriptorSupport ds = new DescriptorSupport(new String[]{ "name=badthing", "descriptorType=NOTification", "severity=1" }); ModelMBeanNotificationInfo info = new ModelMBeanNotificationInfo(new String[]{"bad.thing"}, "badthing", "The bad thing happened", ds); } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/ModelMBeanOperationInfoTest.java100644 0 0 10674 10513545721 26000 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.lang.reflect.Method; import javax.management.Descriptor; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.RuntimeOperationsException; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanOperationInfo; import test.MX4JTestCase; /** * Test case of ModelMBeanOperationInfo. It will try to verify an appropriate * behaviour in particular with respect to the descriptor values * * @version $Revision: 1.5 $ * @see */ public class ModelMBeanOperationInfoTest extends MX4JTestCase { public static class Surgeon { public boolean appendectomy() { return true; } public boolean tonsillectomy(int tonsils) { return true; } } public ModelMBeanOperationInfoTest(String s) { super(s); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testValidDescriptorFields() throws Exception { // Test that only name and descriptorType are mandatory Descriptor descriptor = new DescriptorSupport(new String[]{"name", "descriptortype", "role", "visibility"}, new String[]{"operation1", "operation", "operation", "1"}); ModelMBeanOperationInfo operation = new ModelMBeanOperationInfo("operation1", "An operation", null, "java.lang.String", ModelMBeanOperationInfo.ACTION, descriptor); // in case the descriptor is not valid this should be overriden assertEquals(operation.getDescriptor().getFieldValue("visibility"), "1"); } public void testAddDefaultDisplayName() throws Exception { Method op = ModelMBeanOperationInfoTest.Surgeon.class.getMethod("appendectomy", new Class[0]); String[] fields = {"name", "descriptorType", "role"}; String[] values = {op.getName(), "operation", "operation"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanOperationInfo info = new ModelMBeanOperationInfo("Good Appendectomy", op, ds); Descriptor d = info.getDescriptor(); String dispname = (String)d.getFieldValue("displayName"); assertTrue("Unexpected displayName", dispname.compareTo(op.getName()) == 0); } public void testRoleValidation() throws Exception { Method op = ModelMBeanOperationInfoTest.Surgeon.class.getMethod("appendectomy", new Class[0]); String[] fields = {"name", "descriptorType", "role", "displayName"}; String[] values = {op.getName(), "operation", "operation", "appendectomy"}; DescriptorSupport ds = new DescriptorSupport(fields, values); ModelMBeanOperationInfo info = new ModelMBeanOperationInfo("Good Appendectomy", op, ds); try { values = new String[]{ op.getName(), "operation", "constructor", "appendectomy"}; ds = new DescriptorSupport(fields, values); info = new ModelMBeanOperationInfo("Bad Appendectomy", op, ds); fail("Expecting RuntimeOperationsException"); } catch (RuntimeOperationsException x) { assertTrue(true); // success } } public void testCaseInsensitiveDescriptorType() { DescriptorSupport ds = new DescriptorSupport(new String[]{ "name=getWineList", "descriptorType=oPERATION", "displayName=Retrieve the list of available wines", "role=getter" }); ModelMBeanOperationInfo attrinfo = new ModelMBeanOperationInfo("getWineList", "Retrieve the list of available wines", new MBeanParameterInfo[0], "String", MBeanOperationInfo.INFO, ds); } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/RequiredModelMBeanTest.java100644 0 0 73336 10513545721 25010 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean; import java.util.List; import javax.management.*; import javax.management.modelmbean.*; import test.MX4JTestCase; import test.MutableBoolean; import test.MutableInteger; import test.javax.management.modelmbean.support.ModelMBeanTarget; /** * @version $Revision: 1.14 $ */ public class RequiredModelMBeanTest extends MX4JTestCase { private MBeanServer m_server; public RequiredModelMBeanTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); m_server = MBeanServerFactory.createMBeanServer("ModelMBean"); } protected void tearDown() throws Exception { super.tearDown(); MBeanServerFactory.releaseMBeanServer(m_server); m_server = null; } public void testCopyConstructor() throws Exception { try { new RequiredModelMBean(null); fail("Expecting RuntimeOperationsException"); } catch (RuntimeOperationsException x) { assertTrue(true); //success } } public void testRegistration() throws Exception { RequiredModelMBean rmmb = new RequiredModelMBean(); ObjectName name = new ObjectName(":type=test"); try { m_server.registerMBean(rmmb, name); m_server.unregisterMBean(name); } catch (NotCompliantMBeanException x) { fail("Default RequireModelMBean cannot be registered"); } try { m_server.createMBean(RequiredModelMBean.class.getName(), name, null); m_server.unregisterMBean(name); } catch (NotCompliantMBeanException x) { fail("Default RequireModelMBean cannot be created"); } rmmb = (RequiredModelMBean)m_server.instantiate(RequiredModelMBean.class.getName(), null); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(Object.class.getName(), "Test", null, null, null, null); rmmb.setModelMBeanInfo(info); m_server.registerMBean(rmmb, name); } public void testGetAttributeDefault() throws Exception { ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String attrName = "FixedContent"; String[] names = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "default", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values = new Object[]{attrName, "attribute", null, "false", "", "DEFAULT", "-1"}; DescriptorSupport attrDescr = new DescriptorSupport(names, values); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo(attrName, String.class.getName(), "", true, false, false, attrDescr); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); // No get method, should always get the default value back int num = 5; for (int i = 0; i < num; ++i) { String value = (String)m_server.getAttribute(name, attrName); assertEquals("Returned value is not the default", value, "DEFAULT"); } assertEquals("Wrong staleness algorithm", 0, counter.get()); } public void testGetAttributeAlwaysStale() throws Exception { ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String attrName = "FixedContent"; String[] names = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "default", "getMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // if currencyTimeLimit is -1 then the value is always stale // fix for bug #794313 Object[] values = new Object[]{attrName, "attribute", null, "false", "", "DEFAULT", "get" + attrName, "-1"}; DescriptorSupport attrDescr = new DescriptorSupport(names, values); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo(attrName, String.class.getName(), "", true, false, false, attrDescr); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); // We set the staleness to 0 (-> always stale) so test if the bean method is always called String fixed = bean.getFixedContent(); counter.set(0); int num = 5; for (int i = 0; i < num; ++i) { String value = (String)m_server.getAttribute(name, attrName); assertEquals("Method returned different value", value, fixed); } assertEquals("Wrong staleness algorithm: " + counter.get(), counter.get(), num); } public void testGetAttributeNeverStale() throws Exception { ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String attrName = "FixedContent"; String[] names = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "default", "getMethod", "currencyTimeLimit", "value"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // if currencyTimeLimit is 0 then the value is never stale // fix for bug #794313 Object[] values = new Object[]{attrName, "attribute", null, "false", "", "DEFAULT", "get" + attrName, "0", "NEVER"}; DescriptorSupport attrDescr = new DescriptorSupport(names, values); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo(attrName, String.class.getName(), "", true, false, false, attrDescr); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); // We set the staleness to 0 (-> never stale) so test that the bean method is never called int num = 5; for (int i = 0; i < num; ++i) { String value = (String)m_server.getAttribute(name, attrName); assertEquals("Method returned different value", value, "NEVER"); } assertEquals("Wrong staleness algorithm", counter.get(), 0); } public void testGetAttributeStale() throws Exception { ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String attrName = "MutableContent"; String[] names = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "default", "getMethod", "currencyTimeLimit"}; Object[] values = new Object[]{attrName, "attribute", null, "false", "", "DEFAULT", "get" + attrName, "2"}; DescriptorSupport attrDescr = new DescriptorSupport(names, values); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo(attrName, "java.lang.String", "", true, false, false, attrDescr); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport("test.javax.management.modelmbean.ModelMBeanTarget", "", new ModelMBeanAttributeInfo[]{attrInfo}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); // We set the staleness to 2 seconds // First time bean.setMutableContent("First"); String attrValue = (String)m_server.getAttribute(name, attrName); assertEquals("getAttribute does not work", attrValue, "First"); // Now value should be cached, check it bean.setMutableContent("Second"); attrValue = (String)m_server.getAttribute(name, attrName); assertEquals("Attribute value caching does not work", attrValue, "First"); // Now wait 2 seconds Thread.sleep(2000); attrValue = (String)m_server.getAttribute(name, attrName); assertEquals("Attribute staleness algorithm does not work", attrValue, "Second"); } public void testGetAttributes() throws Exception { String attrName1 = "FixedContent"; String attrName2 = "MutableContent"; ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String[] names1 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values1 = new Object[]{attrName1, "attribute", null, "false", "", "get" + attrName1, "-1"}; DescriptorSupport attrDescr1 = new DescriptorSupport(names1, values1); String[] names2 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values2 = new Object[]{attrName2, "attribute", null, "false", "", "get" + attrName2, "-1"}; DescriptorSupport attrDescr2 = new DescriptorSupport(names2, values2); ModelMBeanAttributeInfo attrInfo1 = new ModelMBeanAttributeInfo(attrName1, String.class.getName(), "", true, false, false, attrDescr1); ModelMBeanAttributeInfo attrInfo2 = new ModelMBeanAttributeInfo(attrName2, String.class.getName(), "", true, false, false, attrDescr2); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo1, attrInfo2}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); String[] attributes = new String[]{attrName1, attrName2}; AttributeList list = m_server.getAttributes(name, attributes); assertEquals("Wrong number of attributes", list.size(), 2); // Check that they're really the right ones Attribute attr = (Attribute)list.get(0); assertEquals(attr.getName(), attrName1); attr = (Attribute)list.get(1); assertEquals(attr.getName(), attrName2); // Test also a wrong attribute attributes = new String[]{attrName1, null, attrName2}; list = m_server.getAttributes(name, attributes); assertEquals(list.size(), 2); // Check that they're really the right ones attr = (Attribute)list.get(0); assertEquals(attr.getName(), attrName1); attr = (Attribute)list.get(1); assertEquals(attr.getName(), attrName2); // Test also a wrong attribute attributes = new String[]{"NonExisting", attrName1, attrName2}; list = m_server.getAttributes(name, attributes); assertEquals(list.size(), 2); // Check that they're really the right ones attr = (Attribute)list.get(0); assertEquals(attr.getName(), attrName1); attr = (Attribute)list.get(1); assertEquals(attr.getName(), attrName2); // Test also a wrong attribute attributes = new String[]{"NonExisting", attrName2}; list = m_server.getAttributes(name, attributes); assertEquals(list.size(), 1); // Check that it is really the right one attr = (Attribute)list.get(0); assertEquals(attr.getName(), attrName2); } public void testSetAttribute() throws Exception { String attrName1 = "MutableContent"; ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String[] names1 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "setMethod", "getMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values1 = new Object[]{attrName1, "attribute", null, "false", "", "set" + attrName1, "get" + attrName1, "-1"}; DescriptorSupport attrDescr1 = new DescriptorSupport(names1, values1); ModelMBeanAttributeInfo attrInfo1 = new ModelMBeanAttributeInfo(attrName1, String.class.getName(), "", true, true, false, attrDescr1); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo1}, null, null, null); final MutableBoolean storeTester = new MutableBoolean(false); RequiredModelMBean rmmb = new StoreTesterRMMB(storeTester); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); // Adding a attribute change notification listener final MutableInteger listenerCount = new MutableInteger(0); rmmb.addAttributeChangeNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { listenerCount.set(listenerCount.get() + 1); } }, attrName1, null); String value = "SET_FIRST_TIME"; Attribute attribute = new Attribute(attrName1, value); m_server.setAttribute(name, attribute); // check that has really been set assertEquals(bean.getMutableContent(), value); // check through MBeanServer assertEquals(m_server.getAttribute(name, attrName1), value); // check that listener has been called assertEquals(listenerCount.get(), 1); // There is no persistence settings, check that store was not called assertFalse("Store should not have been called", storeTester.get()); // Adding a attribute change notification listener with // null as attribute. test for bug #742389 NotificationListener dummyListener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; rmmb.addAttributeChangeNotificationListener(dummyListener, null, null); rmmb.removeAttributeChangeNotificationListener(dummyListener, null); // Change the persist policy - have to unregeister to call setModelMBeanInfo m_server.unregisterMBean(name); attrDescr1.setField("persistPolicy", "OnUpdate"); info.setDescriptor(attrDescr1, "attribute"); rmmb.setModelMBeanInfo(info); storeTester.set(false); m_server.registerMBean(rmmb, name); value = "SET_SECOND_TIME"; attribute = new Attribute(attrName1, value); m_server.setAttribute(name, attribute); // check that listener has been called assertEquals(listenerCount.get(), 2); // There are persistence settings, check that store was called assertTrue("Store should have been called", storeTester.get()); // Now remove setMethod - again we have to unregister m_server.unregisterMBean(name); names1 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 values1 = new Object[]{attrName1, "attribute", null, "false", "", "get" + attrName1, "-1"}; attrDescr1 = new DescriptorSupport(names1, values1); attrDescr1.setField("persistPolicy", "OnUpdate"); info.setDescriptor(attrDescr1, "attribute"); rmmb.setModelMBeanInfo(info); storeTester.set(false); m_server.registerMBean(rmmb, name); value = "SET_THIRD_TIME"; attribute = new Attribute(attrName1, value); m_server.setAttribute(name, attribute); // check that listener has been called assertEquals(listenerCount.get(), 3); // There are persistence settings, check that store was called assertTrue("Store should have been called", storeTester.get()); // Check the attribute value if (bean.getMutableContent().equals(value)) { fail("No setMethod, bean should not have been modified"); } if (info.getAttribute(attrName1).getDescriptor().getFieldValue("value") != null) { fail("New value should not have been cached since currencyTimeLimit is negative"); } // Test attribute that takes array as parameters m_server.unregisterMBean(name); String attrName = "ArrayAttribute"; String[] names = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "setMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values = new Object[]{attrName, "attribute", null, "true", "", "get" + attrName, "set" + attrName, "-1"}; Descriptor attrDescr = new DescriptorSupport(names, values); ModelMBeanAttributeInfo attrInfo = new ModelMBeanAttributeInfo(attrName, new String[0].getClass().getName(), "", true, true, false, attrDescr); info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo}, null, null, null); rmmb.setModelMBeanInfo(info); m_server.registerMBean(rmmb, name); String[] v = new String[]{"one", "two"}; attribute = new Attribute(attrName, v); m_server.setAttribute(name, attribute); } public void testSetAttributes() throws Exception { String attrName1 = "MutableContent"; String attrName2 = "MutableContent2"; ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String[] names1 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "setMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values1 = new Object[]{attrName1, "attribute", null, "false", "", "get" + attrName1, "set" + attrName1, "-1"}; DescriptorSupport attrDescr1 = new DescriptorSupport(names1, values1); String[] names2 = new String[]{"name", "descriptorType", "value", "iterable", "displayName", "getMethod", "setMethod", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values2 = new Object[]{attrName2, "attribute", null, "false", "", "get" + attrName2, "set" + attrName2, "-1"}; DescriptorSupport attrDescr2 = new DescriptorSupport(names2, values2); ModelMBeanAttributeInfo attrInfo1 = new ModelMBeanAttributeInfo(attrName1, String.class.getName(), "", true, true, false, attrDescr1); ModelMBeanAttributeInfo attrInfo2 = new ModelMBeanAttributeInfo(attrName2, "int", "", true, true, false, attrDescr2); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attrInfo1, attrInfo2}, null, null, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); Attribute attr1 = new Attribute(attrName1, "FIRST"); Attribute attr2 = new Attribute(attrName2, new Integer(5)); AttributeList list = new AttributeList(); list.add(attr1); list.add(attr2); AttributeList result = m_server.setAttributes(name, list); assertEquals("Wrong number of attributes were set", result.size(), 2); // Check that they're really the right ones Attribute attr = (Attribute)result.get(0); assertEquals(attr, attr1); attr = (Attribute)result.get(1); assertEquals(attr, attr2); // Check that they were really set assertEquals(bean.getMutableContent(), attr1.getValue()); assertEquals(bean.getMutableContent2(), ((Integer)attr2.getValue()).intValue()); // Test non-existing attribute attr = new Attribute("NonExisting", null); attr2 = new Attribute(attrName2, new Integer(7)); list.clear(); list.add(attr); list.add(attr2); result = m_server.setAttributes(name, list); assertEquals(result.size(), 1); // Check that they're really the right ones attr = (Attribute)result.get(0); assertEquals(attr, attr2); // Check that they were really set assertEquals(bean.getMutableContent2(), ((Integer)attr2.getValue()).intValue()); attr = new Attribute("NonExisting", null); list.clear(); list.add(attr); result = m_server.setAttributes(name, list); assertEquals(result.size(), 0); } public void testInvoke() throws Exception { String operation = "operation1"; ObjectName name = new ObjectName(":type=test"); MutableInteger counter = new MutableInteger(0); ModelMBeanTarget bean = new ModelMBeanTarget(counter); String[] names1 = new String[]{"name", "descriptorType", "displayName", "role", "targetObject", "targetObjectType", "currencyTimeLimit"}; // changed to match the actual behaviour indicated in the specs about currencyTimeLimit // currencyTimeLimit is now -1 Object[] values1 = new Object[]{operation, "operation", "", "operation", null, null, "-1"}; DescriptorSupport operDescr = new DescriptorSupport(names1, values1); MBeanParameterInfo paramInfo1 = new MBeanParameterInfo("c", "char", ""); MBeanParameterInfo paramInfo2 = new MBeanParameterInfo("s", "short", ""); MBeanParameterInfo paramInfo3 = new MBeanParameterInfo("f", new float[0].getClass().getName(), ""); MBeanParameterInfo paramInfo4 = new MBeanParameterInfo("c", new Object[0][0].getClass().getName(), ""); ModelMBeanOperationInfo operInfo = new ModelMBeanOperationInfo(operation, "", new MBeanParameterInfo[]{paramInfo1, paramInfo2, paramInfo3, paramInfo4}, "java.util.List", ModelMBeanOperationInfo.UNKNOWN, operDescr); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", null, null, new ModelMBeanOperationInfo[]{operInfo}, null); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(bean, "ObjectReference"); m_server.registerMBean(rmmb, name); short s = 10; Object[] args = new Object[]{new Character('z'), new Short(s), new float[]{1.0F}, new Object[][]{{"Hello"}, {"World"}}}; String[] params = new String[]{paramInfo1.getType(), paramInfo2.getType(), paramInfo3.getType(), paramInfo4.getType()}; List list = (List)m_server.invoke(name, operation, args, params); // Test that was really called assertEquals(counter.get(), 1); // Right values ? for (int i = 0; i < list.size(); ++i) { Object obj = list.get(i); assertEquals("Returned value is different: " + obj, args[i], obj); } m_server.unregisterMBean(name); ModelMBeanTarget.TargetBean target = new ModelMBeanTarget.TargetBean(); operDescr.setField("targetObject", target); operDescr.setField("targetObjectType", "ObjectReference"); info.setDescriptor(operDescr, "operation"); rmmb.setModelMBeanInfo(info); m_server.registerMBean(rmmb, name); list = (List)m_server.invoke(name, operation, args, params); // Test that was not called assertEquals("Operation should not have been called", counter.get(), 1); // Right values ? for (int i = 0; i < list.size(); ++i) { Object obj = list.get(list.size() - 1 - i); assertEquals("Returned value is different: " + obj, args[i], obj); } } public void testInvokeModelMBeanMethods() throws Exception { ObjectName name = new ObjectName(":type=test"); ModelMBean mmb = (ModelMBean)m_server.instantiate(RequiredModelMBean.class.getName(), null); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", null, null, null, null); mmb.setModelMBeanInfo(info); m_server.registerMBean(mmb, name); // Now try to invoke methods that are part of the ModelMBean interface try { m_server.setAttribute(name, new Attribute("ModelMBeanInfo", info)); fail("Cannot invoke a ModelMBean method via MBeanServer"); } catch (Exception ignored) { } // Bug #940161 Required ModelMBean methods are not invoked m_server.invoke(name, "setManagedResource", new Object[]{new ModelMBeanTarget(new MutableInteger(0)), "ObjectReference"}, new String[]{Object.class.getName(), String.class.getName()}); m_server.invoke(name, "store", new Object[0], new String[0]); m_server.invoke(name, "sendNotification", new Object[]{"generic"}, new String[]{String.class.getName()}); // Now specify setManagedResource as an operation in the MMBI m_server.unregisterMBean(name); String operation = "setManagedResource"; MBeanParameterInfo paramInfo1 = new MBeanParameterInfo("resource", Object.class.getName(), ""); MBeanParameterInfo paramInfo2 = new MBeanParameterInfo("type", String.class.getName(), ""); ModelMBeanOperationInfo operInfo = new ModelMBeanOperationInfo(operation, "", new MBeanParameterInfo[]{paramInfo1, paramInfo2}, null, ModelMBeanOperationInfo.ACTION, null); info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", null, null, new ModelMBeanOperationInfo[]{operInfo}, null); mmb.setModelMBeanInfo(info); m_server.registerMBean(mmb, name); // Spec says I must be able to invoke it Object target = new ModelMBeanTarget(new MutableInteger(0)); m_server.invoke(name, operation, new Object[]{target, "ObjectReference"}, new String[]{Object.class.getName(), String.class.getName()}); } public void testNotifications() throws Exception { ObjectName name = new ObjectName(":type=test"); ModelMBeanNotificationInfo notification[] = new ModelMBeanNotificationInfo[1]; notification[0] = new ModelMBeanNotificationInfo(new String[]{ModelMBeanTarget.class.getName() + ".notification"}, "name", ""); ModelMBeanAttributeInfo attributeInfo = new ModelMBeanAttributeInfo("MutableContent", String.class.getName(), "", true, true, false); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", new ModelMBeanAttributeInfo[]{attributeInfo}, null, null, notification); RequiredModelMBean rmmb = new RequiredModelMBean(); rmmb.setModelMBeanInfo(info); rmmb.setManagedResource(new ModelMBeanTarget(new MutableInteger(0)), "objectReference"); m_server.registerMBean(rmmb, name); Object listenerHandback = new Object(); TestNotificationListener listener = new TestNotificationListener(); m_server.addNotificationListener(name, listener, null, listenerHandback); rmmb.sendNotification("generic notification"); assertEquals("jmx.modelmbean.generic", listener.type); assertEquals("generic notification", listener.message); assertSame(listenerHandback, listener.handback); rmmb.sendNotification(new Notification("my.type", rmmb, 1, "a message")); assertEquals("my.type", listener.type); assertEquals("a message", listener.message); assertSame(listenerHandback, listener.handback); m_server.setAttribute(name, new Attribute("MutableContent", "Hello World")); assertEquals("jmx.attribute.change", listener.type); } public void testGetNotificationInfo() throws Exception { RequiredModelMBean rmmb = new RequiredModelMBean(); MBeanNotificationInfo[] notificationInfos = rmmb.getNotificationInfo(); assertEquals(2, notificationInfos.length); ModelMBeanNotificationInfo notification[] = new ModelMBeanNotificationInfo[1]; notification[0] = new ModelMBeanNotificationInfo(new String[]{ModelMBeanTarget.class.getName() + ".notification"}, "name", ""); ModelMBeanInfoSupport info = new ModelMBeanInfoSupport(ModelMBeanTarget.class.getName(), "", null, null, null, notification); rmmb.setModelMBeanInfo(info); notificationInfos = rmmb.getNotificationInfo(); assertEquals(3, notificationInfos.length); } public static class StoreTesterRMMB extends RequiredModelMBean { private MutableBoolean m_stored; public StoreTesterRMMB(MutableBoolean storeTester) throws MBeanException { m_stored = storeTester; } public void store() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException { m_stored.set(true); super.store(); } } public static class TestNotificationListener implements NotificationListener { String type = null; String message = null; Object handback = null; public void handleNotification(Notification notification, Object handback) { type = notification.getType(); message = notification.getMessage(); this.handback = handback; } } } mx4j-3.0.2/src/test/test/javax/management/modelmbean/support/ModelMBeanTarget.java100644 0 0 3665 10513545721 25310 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.modelmbean.support; import java.util.ArrayList; import java.util.List; import test.MutableInteger; /** * @version $Revision: 1.3 $ * @see */ public class ModelMBeanTarget { private MutableInteger m_counter; private String m_content; private int m_value; private String[] m_array; public ModelMBeanTarget(MutableInteger integer) { m_counter = integer; } public String getFixedContent() { m_counter.set(m_counter.get() + 1); return "FIXED_CONTENT"; } public String getMutableContent() { return m_content; } public void setMutableContent(String content) { m_content = content; } public int getMutableContent2() { return m_value; } public void setMutableContent2(int value) { m_value = value; } public String[] getArrayAttribute() { return m_array; } public void setArrayAttribute(String[] array) { m_array = array; } public List operation1(char c, short s, float[] f, Object[][] obj) { m_counter.set(m_counter.get() + 1); ArrayList list = new ArrayList(); Character ch = new Character(c); Short sh = new Short(s); list.add(ch); list.add(sh); list.add(f); list.add(obj); return list; } public static class TargetBean { public List operation1(char c, short s, float[] f, Object[][] obj) { // Add in reverse order ArrayList list = new ArrayList(); Character ch = new Character(c); Short sh = new Short(s); list.add(obj); list.add(f); list.add(sh); list.add(ch); return list; } } } mx4j-3.0.2/src/test/test/javax/management/monitor/CounterMonitorTest.java100644 0 0 26172 10513545721 23713 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.monitor; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.monitor.CounterMonitor; import javax.management.monitor.Monitor; import javax.management.monitor.MonitorNotification; import test.MutableInteger; import test.MutableObject; /** * @version : $Revision 1.2 $ */ public class CounterMonitorTest extends MonitorTestCase { public CounterMonitorTest(String name) { super(name); } protected Monitor createMonitor() { return new CounterMonitor(); } public void testCorrectInitialization() throws Exception { CounterMonitor monitor = (CounterMonitor)createMonitor(); assertEquals(new Integer(0), monitor.getInitThreshold()); assertEquals(new Integer(0), monitor.getModulus()); assertEquals(new Integer(0), monitor.getOffset()); assertFalse(monitor.getDifferenceMode()); assertFalse(monitor.getNotify()); } public void testSetThreshold() throws Exception { CounterMonitor monitor = (CounterMonitor)createMonitor(); try { monitor.setThreshold(new Integer(-1)); fail(); } catch (IllegalArgumentException x) { } try { monitor.setInitThreshold(new Integer(-1)); fail(); } catch (IllegalArgumentException x) { } Integer threshold = new Integer(1); monitor.setThreshold(threshold); assertEquals(monitor.getInitThreshold(), threshold); threshold = new Integer(2); monitor.setInitThreshold(threshold); assertEquals(monitor.getInitThreshold(), threshold); } public void testSetModulus() throws Exception { CounterMonitor monitor = (CounterMonitor)createMonitor(); try { monitor.setModulus(new Integer(-1)); fail(); } catch (IllegalArgumentException x) { } Integer modulus = new Integer(1); monitor.setModulus(modulus); assertEquals(monitor.getModulus(), modulus); } public void testSetOffset() throws Exception { CounterMonitor monitor = (CounterMonitor)createMonitor(); try { monitor.setOffset(new Integer(-1)); fail(); } catch (IllegalArgumentException x) { } Integer offset = new Integer(1); monitor.setOffset(offset); assertEquals(monitor.getOffset(), offset); } public void testMonitorNotificationForBadCounter() throws Exception { MBeanServer server = newMBeanServer(); Monitor monitor = createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); Counter counter = new Counter(); ObjectName counterName = ObjectName.getInstance(":mbean=counter"); server.registerMBean(counter, counterName); monitor.addObservedObject(counterName); monitor.setGranularityPeriod(1000); monitor.setObservedAttribute("ObjectCounter"); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }, null, null); monitor.start(); try { // Wait for notification to arrive while (holder.get() == null) sleep(10); // Be sure only one arrived sleep(5000); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.OBSERVED_ATTRIBUTE_TYPE_ERROR); } finally { monitor.stop(); } } public void testIntegerCounter() throws Exception { MBeanServer server = newMBeanServer(); CounterMonitor monitor = (CounterMonitor)createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); Counter counter = new Counter(); ObjectName counterName = ObjectName.getInstance(":mbean=counter"); server.registerMBean(counter, counterName); long period = 1000; monitor.addObservedObject(counterName); monitor.setGranularityPeriod(period); monitor.setObservedAttribute("IntegerCounter"); Integer initThreshold = new Integer(3); monitor.setInitThreshold(initThreshold); monitor.setNotify(true); // No modulus, no offset counter.setIntegerCounter(initThreshold.intValue() - 1); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }, null, null); monitor.start(); try { // Below threshold, no notifications should be sent sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); // Above threshold, just one notification should be sent counter.setIntegerCounter(initThreshold.intValue() + 1); sleep(period * 3); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_VALUE_EXCEEDED); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); } finally { monitor.stop(); } } public void testIntegerCounterWithOffset() throws Exception { MBeanServer server = newMBeanServer(); CounterMonitor monitor = (CounterMonitor)createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); Counter counter = new Counter(); ObjectName counterName = ObjectName.getInstance(":mbean=counter"); server.registerMBean(counter, counterName); long period = 1000; monitor.addObservedObject(counterName); monitor.setGranularityPeriod(period); monitor.setObservedAttribute("IntegerCounter"); Integer initThreshold = new Integer(3); monitor.setInitThreshold(initThreshold); monitor.setNotify(true); Integer offset = new Integer(5); monitor.setOffset(offset); // No modulus counter.setIntegerCounter(initThreshold.intValue() - 1); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }, null, null); monitor.start(); try { // Below threshold, no notifications should be sent sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); // Above threshold, just one notification should be sent counter.setIntegerCounter(initThreshold.intValue() + 1); sleep(period * 3); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_VALUE_EXCEEDED); // The threshold should have offset Number threshold = monitor.getThreshold(counterName); assertEquals(threshold.intValue(), monitor.getInitThreshold().intValue() + offset.intValue()); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); // Above threshold by more than 1 offset counter.setIntegerCounter(initThreshold.intValue() + offset.intValue() * 2 + 1); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_VALUE_EXCEEDED); // The threshold should have offset correctly threshold = monitor.getThreshold(counterName); assertEquals(threshold.intValue(), monitor.getInitThreshold().intValue() + offset.intValue() * 3); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); } finally { monitor.stop(); } } public void testShutDownMonitorThread() throws Exception { MBeanServer server = newMBeanServer(); CounterMonitor monitor = (CounterMonitor)createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); Counter counter = new Counter(); ObjectName counterName = ObjectName.getInstance(":mbean=counter"); server.registerMBean(counter, counterName); long period = 1000; monitor.addObservedObject(counterName); monitor.setGranularityPeriod(period); monitor.setObservedAttribute("IntegerCounter"); Integer initThreshold = new Integer(3); monitor.setInitThreshold(initThreshold); monitor.setNotify(true); // No modulus, no offset counter.setIntegerCounter(initThreshold.intValue() - 1); final MutableObject monitorThread = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { monitorThread.set(Thread.currentThread()); } }, null, null); monitor.start(); // Below threshold, no notifications should be sent sleep(period * 3); // Above threshold, just one notification should be sent counter.setIntegerCounter(initThreshold.intValue() + 1); sleep(period * 3); Thread thread = (Thread)monitorThread.get(); assertNotNull(thread); assertNotSame(thread, Thread.currentThread()); monitor.stop(); sleep(period * 3); assertFalse(thread.isAlive()); } public interface CounterMBean { public Object getObjectCounter(); public Integer getNegativeCounter(); public int getIntegerCounter(); } public static class Counter implements CounterMBean { private int integerCounter; public Object getObjectCounter() { return new Object(); } public Integer getNegativeCounter() { return new Integer(-1); } public int getIntegerCounter() { return integerCounter; } public void setIntegerCounter(int integerCounter) { this.integerCounter = integerCounter; } } } mx4j-3.0.2/src/test/test/javax/management/monitor/CounterNotificationTest.java100644 0 0 25327 10513545721 24713 0ustar 0 0 /* ===================================================================== * * Copyright (c) 2004 Jeremy Boynes. All rights reserved. * * ===================================================================== */ package test.javax.management.monitor; import junit.framework.TestCase; import javax.management.*; import javax.management.monitor.CounterMonitor; import javax.management.monitor.MonitorNotification; import java.util.ArrayList; import java.util.List; import mx4j.log.Log; import mx4j.log.Logger; /** * @version $Revision: 1.1 $ $Date: 2005/02/15 22:31:40 $ */ public class CounterNotificationTest extends TestCase implements NotificationListener { private static final Number ZERO = new Integer(0); private MBeanServer mbServer; private ObjectName observedName; private ObservedObject observed; private ObjectName counterMonitorName; private CounterMonitor counterMonitor; private List notifications; private int granularity; private Logger logger; public void testSimpleIncrementingCounter() throws Exception { initMonitor(ZERO, ZERO, ZERO, false); counterMonitor.start(); setAttribute(new Integer(-2)); sleep(); assertEquals(0, notifications.size()); checkMonitor(new Integer(-2), ZERO); setAttribute(new Integer(-1)); sleep(); assertEquals(0, notifications.size()); checkMonitor(new Integer(-1), ZERO); setAttribute(new Integer(0)); sleep(); assertEquals(1, notifications.size()); checkMonitor(new Integer(0), ZERO); checkNotification((Notification)notifications.get(0)); setAttribute(new Integer(1)); sleep(); assertEquals(1, notifications.size()); checkMonitor(new Integer(1), ZERO); setAttribute(new Integer(2)); sleep(); assertEquals(1, notifications.size()); checkMonitor(new Integer(2), ZERO); } public void testSimpleCounterWithOffset() throws Exception { initMonitor(ZERO, new Integer(2), ZERO, false); counterMonitor.start(); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(2)); assertEquals(1, notifications.size()); checkNotification((Notification)notifications.get(0)); setAttribute(new Integer(1)); sleep(); checkMonitor(new Integer(1), new Integer(2)); assertEquals(1, notifications.size()); setAttribute(new Integer(2)); sleep(); checkMonitor(new Integer(2), new Integer(4)); assertEquals(2, notifications.size()); checkNotification((Notification)notifications.get(1)); setAttribute(new Integer(3)); sleep(); checkMonitor(new Integer(3), new Integer(4)); assertEquals(2, notifications.size()); setAttribute(new Integer(4)); sleep(); checkMonitor(new Integer(4), new Integer(6)); assertEquals(3, notifications.size()); checkNotification((Notification)notifications.get(2)); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(6)); assertEquals(3, notifications.size()); setAttribute(new Integer(6)); sleep(); checkMonitor(new Integer(6), new Integer(8)); assertEquals(4, notifications.size()); checkNotification((Notification)notifications.get(3)); } public void testSimpleCounterWithModulusAndDecreasingOffset() throws Exception { initMonitor(new Integer(1), new Integer(1), new Integer(5), false); counterMonitor.start(); setAttribute(new Integer(1)); sleep(); checkMonitor(new Integer(1), new Integer(2)); assertEquals(1, notifications.size()); counterMonitor.setOffset(new Integer(2)); setAttribute(new Integer(2)); sleep(); checkMonitor(new Integer(2), new Integer(4)); assertEquals(2, notifications.size()); counterMonitor.setOffset(new Integer(1)); setAttribute(new Integer(4)); sleep(); checkMonitor(new Integer(4), new Integer(5)); assertEquals(3, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(6)); assertEquals(4, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(6)); assertEquals(4, notifications.size()); setAttribute(new Integer(2)); sleep(); checkMonitor(new Integer(2), new Integer(3)); assertEquals(5, notifications.size()); setAttribute(new Integer(1)); sleep(); // Thread.sleep(10000000); checkMonitor(new Integer(1), new Integer(3)); assertEquals(5, notifications.size()); setAttribute(new Integer(1)); sleep(); checkMonitor(new Integer(1), new Integer(3)); assertEquals(5, notifications.size()); setAttribute(new Integer(3)); sleep(); checkMonitor(new Integer(3), new Integer(4)); assertEquals(6, notifications.size()); } public void testDeltaWithModulus() throws Exception { initMonitor(new Integer(2), ZERO, new Integer(7), true); counterMonitor.start(); setAttribute(new Integer(-2)); sleep(); checkMonitor(new Integer(-2), new Integer(2)); assertEquals(0, notifications.size()); setAttribute(new Integer(-1)); sleep(); checkMonitor(new Integer(-1), new Integer(2)); assertEquals(0, notifications.size()); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(2)); assertEquals(0, notifications.size()); setAttribute(new Integer(8)); sleep(); checkMonitor(new Integer(8), new Integer(2)); assertEquals(1, notifications.size()); setAttribute(new Integer(3)); sleep(); checkMonitor(new Integer(3), new Integer(2)); assertEquals(2, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(2)); assertEquals(3, notifications.size()); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(2)); assertEquals(4, notifications.size()); setAttribute(new Integer(1)); sleep(); checkMonitor(new Integer(1), new Integer(2)); assertEquals(4, notifications.size()); setAttribute(new Integer(4)); sleep(); checkMonitor(new Integer(4), new Integer(2)); assertEquals(5, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(2)); assertEquals(5, notifications.size()); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(2)); assertEquals(6, notifications.size()); } public void testDeltaWithOffsetAndModulus() throws Exception { initMonitor(new Integer(2), new Integer(1), new Integer(7), true); counterMonitor.start(); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(2)); assertEquals(0, notifications.size()); setAttribute(new Integer(2)); sleep(); checkMonitor(new Integer(2), new Integer(3)); assertEquals(1, notifications.size()); setAttribute(new Integer(3)); sleep(); checkMonitor(new Integer(3), new Integer(3)); assertEquals(1, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(3)); assertEquals(1, notifications.size()); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(3)); assertEquals(2, notifications.size()); setAttribute(new Integer(1)); sleep(); checkMonitor(new Integer(1), new Integer(3)); assertEquals(2, notifications.size()); setAttribute(new Integer(4)); sleep(); checkMonitor(new Integer(4), new Integer(4)); assertEquals(3, notifications.size()); setAttribute(new Integer(5)); sleep(); checkMonitor(new Integer(5), new Integer(4)); assertEquals(3, notifications.size()); setAttribute(new Integer(0)); sleep(); checkMonitor(new Integer(0), new Integer(3)); assertEquals(4, notifications.size()); } private void setAttribute(Number value) throws Exception { logger.debug("Setting attribute to " + value); mbServer.setAttribute(observedName, new Attribute("Counter", value)); } private void sleep() { try { Thread.sleep(granularity * 3); } catch (InterruptedException e) { } } private void initMonitor(Number initThreshold, Number offset, Number modulus, boolean difference) { counterMonitor.setObservedObject(observedName); counterMonitor.setObservedAttribute("Counter"); counterMonitor.setGranularityPeriod(granularity); counterMonitor.setNotify(true); counterMonitor.setThreshold(initThreshold); counterMonitor.setOffset(offset); counterMonitor.setModulus(modulus); counterMonitor.setDifferenceMode(difference); } private void checkMonitor(Number value, Number threshold) throws Exception { assertEquals(value, mbServer.getAttribute(observedName, "Counter")); assertEquals(threshold, counterMonitor.getThreshold()); } private void checkNotification(Notification notification) { assertEquals(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, notification.getType()); } public void handleNotification(Notification notification, Object handback) { notifications.add(notification); } protected void setUp() throws Exception { logger = Log.getLogger(this.getClass().getName()); granularity = 200; notifications = new ArrayList(); mbServer = MBeanServerFactory.newMBeanServer(); observedName = new ObjectName("test:name=ObservedObject"); observed = new ObservedObject(); mbServer.registerMBean(observed, observedName); counterMonitorName = new ObjectName("test:name=CounterMonitor"); counterMonitor = new CounterMonitor(); mbServer.registerMBean(counterMonitor, counterMonitorName); counterMonitor.addNotificationListener(this, null, null); } protected void tearDown() throws Exception { if (counterMonitor.isActive()) counterMonitor.stop(); mbServer.unregisterMBean(counterMonitorName); mbServer.unregisterMBean(observedName); } public static interface ObservedObjectMBean { Number getCounter(); void setCounter(Number counter); } public static class ObservedObject implements ObservedObjectMBean { private Number counter; public Number getCounter() { return counter; } public void setCounter(Number counter) { this.counter = counter; } } } mx4j-3.0.2/src/test/test/javax/management/monitor/GaugeMonitorTest.java100644 0 0 23446 10513545721 23325 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.monitor; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.monitor.GaugeMonitor; import javax.management.monitor.Monitor; import javax.management.monitor.MonitorNotification; import test.MutableInteger; import test.MutableObject; /** * @version $Revision: 1.12 $ */ public class GaugeMonitorTest extends MonitorTestCase { public GaugeMonitorTest(String name) { super(name); } protected Monitor createMonitor() { return new GaugeMonitor(); } public void testCorrectInitialization() throws Exception { GaugeMonitor monitor = (GaugeMonitor)createMonitor(); assertEquals(new Integer(0), monitor.getHighThreshold()); assertEquals(new Integer(0), monitor.getLowThreshold()); assertFalse(monitor.getDifferenceMode()); assertFalse(monitor.getNotifyHigh()); assertFalse(monitor.getNotifyLow()); } public void testSetThresholds() throws Exception { GaugeMonitor monitor = (GaugeMonitor)createMonitor(); try { monitor.setThresholds(null, null); fail(); } catch (IllegalArgumentException ignored) { } try { monitor.setThresholds(new Integer(0), null); fail(); } catch (IllegalArgumentException ignored) { } try { monitor.setThresholds(null, new Integer(0)); fail(); } catch (IllegalArgumentException ignored) { } try { // Different types monitor.setThresholds(new Integer(1), new Long(0)); fail(); } catch (IllegalArgumentException ignored) { } try { // High less than low monitor.setThresholds(new Integer(0), new Integer(1)); fail(); } catch (IllegalArgumentException ignored) { } monitor.setThresholds(new Float(5.7), new Float(5.0)); } /** * This also serves as a test case for bug #710028 */ public void testHighHysteresisStartBelow() throws Exception { ObjectName name = new ObjectName(":mbean=target"); ObjectName monitorName = new ObjectName(":monitor=gauge"); MBeanServer server = newMBeanServer(); GaugeMonitor monitor = (GaugeMonitor)createMonitor(); monitor.setDifferenceMode(true); monitor.addObservedObject(name); monitor.setObservedAttribute("Integer"); int period = 1000; monitor.setGranularityPeriod(period); Integer high = new Integer(10); Integer low = new Integer(5); monitor.setThresholds(high, low); monitor.setNotifyHigh(true); monitor.setNotifyLow(false); server.registerMBean(monitor, monitorName); // Initial value < lowThreshold MonitorTarget target = new MonitorTarget(); int value = low.intValue() - 1; target.setInteger(value); server.registerMBean(target, name); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }; server.addNotificationListener(monitorName, listener, null, null); monitor.start(); try { sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); // Set gauge above high threshold value = value + high.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); // Set gauge inside threshold value = value + low.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); // Set gauge above threshold again value = value + high.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED); } finally { monitor.stop(); } } /** * This also serves as a test case for bug #742554 */ public void testLowHysteresisStartInside() throws Exception { ObjectName name = new ObjectName(":mbean=target"); ObjectName monitorName = new ObjectName(":monitor=gauge"); MBeanServer server = newMBeanServer(); GaugeMonitor monitor = (GaugeMonitor)createMonitor(); monitor.setDifferenceMode(true); monitor.addObservedObject(name); monitor.setObservedAttribute("Integer"); int period = 1000; monitor.setGranularityPeriod(period); Integer high = new Integer(5); Integer low = new Integer(0); monitor.setThresholds(high, low); monitor.setNotifyHigh(true); monitor.setNotifyLow(true); server.registerMBean(monitor, monitorName); // Initial gauge inside thresholds MonitorTarget target = new MonitorTarget(); int value = low.intValue() + 1; target.setInteger(value); server.registerMBean(target, name); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }; server.addNotificationListener(monitorName, listener, null, null); monitor.start(); try { // Inside the thresholds, be sure low notification sleep(period * 3); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_LOW_VALUE_EXCEEDED); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); // Monitoring takes time, so I disable low notification to be sure to get only the high one // The monitor is in difference mode, so the first time will get the high notification, but // the second time will get zero, since the gauge did not change, which will triggers a low notification monitor.setNotifyLow(false); // Set gauge above high threshold value = value + high.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); monitor.setNotifyHigh(false); monitor.setNotifyLow(true); // Set gauge above high threshold, so just after goes below low threshold value = value + high.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.THRESHOLD_LOW_VALUE_EXCEEDED); times.set(0); holder.set(null); sleep(period * 3); assertEquals(times.get(), 0); // Set gauge inside threshold value = value + low.intValue() + 1; target.setInteger(value); sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); } finally { monitor.stop(); } } /** * This also serves as a test case for bug #822849 */ public void testGetDerivedGauge() throws Exception { ObjectName name = new ObjectName(":mbean=target"); ObjectName monitorName = new ObjectName(":monitor=gauge"); MBeanServer server = newMBeanServer(); GaugeMonitor monitor = (GaugeMonitor)createMonitor(); monitor.setDifferenceMode(false); monitor.addObservedObject(name); monitor.setObservedAttribute("Integer"); int period = 1000; monitor.setGranularityPeriod(period); server.registerMBean(monitor, monitorName); // Set initial gauge MonitorTarget target = new MonitorTarget(); int gauge = 4; target.setInteger(gauge); server.registerMBean(target, name); monitor.start(); try { sleep(period * 3); Number observed = monitor.getDerivedGauge(name); assertEquals(observed.intValue(), gauge); } finally { monitor.stop(); } } public interface MonitorTargetMBean { public int getInteger(); } public static class MonitorTarget implements MonitorTargetMBean { private int value; public int getInteger() { return value; } public void setInteger(int value) { this.value = value; } } } mx4j-3.0.2/src/test/test/javax/management/monitor/MonitorTestCase.java100644 0 0 10760 10513545721 23143 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.monitor; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.monitor.Monitor; import javax.management.monitor.MonitorNotification; import test.MX4JTestCase; import test.MutableInteger; import test.MutableObject; /** * @version : 1.2 $ */ public abstract class MonitorTestCase extends MX4JTestCase { public MonitorTestCase(String name) { super(name); } protected abstract Monitor createMonitor(); public void testStartStopIsActive() throws Exception { Monitor monitor = createMonitor(); monitor.setGranularityPeriod(1000); assertFalse(monitor.isActive()); monitor.start(); sleep(5000); assertTrue(monitor.isActive()); monitor.stop(); assertFalse(monitor.isActive()); monitor.start(); assertTrue(monitor.isActive()); monitor.stop(); assertFalse(monitor.isActive()); } public void testSetObservedObject() throws Exception { Monitor monitor = createMonitor(); ObjectName name1 = ObjectName.getInstance(":name=one"); monitor.addObservedObject(name1); ObjectName name2 = ObjectName.getInstance(":name=two"); monitor.addObservedObject(name2); assertEquals(monitor.getObservedObjects().length, 2); assertTrue(monitor.containsObservedObject(name1)); assertTrue(monitor.containsObservedObject(name2)); monitor.setObservedObject(name1); assertEquals(monitor.getObservedObjects().length, 1); assertTrue(monitor.containsObservedObject(name1)); } public void testMonitorNotificationForMBeanNotRegistered() throws Exception { MBeanServer server = newMBeanServer(); Monitor monitor = createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); ObjectName name1 = ObjectName.getInstance(":name=one"); monitor.addObservedObject(name1); monitor.setGranularityPeriod(1000); monitor.setObservedAttribute("dummy"); final MutableInteger counter = new MutableInteger(0); final MutableObject holder = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { counter.set(counter.get() + 1); holder.set(notification); } }, null, null); monitor.start(); try { // Wait for notification to arrive while (holder.get() == null) sleep(10); // Be sure only one arrived sleep(5000); assertEquals(counter.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.OBSERVED_OBJECT_ERROR); } finally { monitor.stop(); } } public void testMonitorNotificationForUnknownAttribute() throws Exception { MBeanServer server = newMBeanServer(); Monitor monitor = createMonitor(); server.registerMBean(monitor, ObjectName.getInstance(":service=monitor")); ObjectName name1 = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); monitor.addObservedObject(name1); monitor.setGranularityPeriod(1000); monitor.setObservedAttribute("dummy"); final MutableInteger counter = new MutableInteger(0); final MutableObject holder = new MutableObject(null); monitor.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { counter.set(counter.get() + 1); holder.set(notification); } }, null, null); monitor.start(); try { // Wait for notification to arrive while (holder.get() == null) sleep(10); // Be sure only one arrived sleep(5000); assertEquals(counter.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.OBSERVED_ATTRIBUTE_ERROR); } finally { monitor.stop(); } } } mx4j-3.0.2/src/test/test/javax/management/monitor/StringMonitorTest.java100644 0 0 10732 10513545721 23535 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.monitor; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.monitor.Monitor; import javax.management.monitor.MonitorNotification; import javax.management.monitor.StringMonitor; import test.MutableInteger; import test.MutableObject; /** * @version $Revision: 1.8 $ */ public class StringMonitorTest extends MonitorTestCase { public StringMonitorTest(String name) { super(name); } protected Monitor createMonitor() { return new StringMonitor(); } public void testCorrectInitialization() throws Exception { StringMonitor monitor = (StringMonitor)createMonitor(); assertEquals("", monitor.getStringToCompare()); assertFalse(monitor.getNotifyDiffer()); assertFalse(monitor.getNotifyMatch()); } public void testSetStringToCompare() throws Exception { StringMonitor monitor = (StringMonitor)createMonitor(); try { monitor.setStringToCompare(null); fail(); } catch (IllegalArgumentException x) { } } /** * The case outlined in the JMX specification */ public void testSpecificationCase() throws Exception { ObjectName name = new ObjectName(":mbean=target"); ObjectName monitorName = new ObjectName(":monitor=gauge"); MBeanServer server = newMBeanServer(); StringMonitor monitor = (StringMonitor)createMonitor(); String reference = "XYZ"; monitor.setStringToCompare(reference); monitor.setNotifyMatch(true); monitor.setNotifyDiffer(true); monitor.addObservedObject(name); monitor.setObservedAttribute("String"); int period = 1000; monitor.setGranularityPeriod(period); server.registerMBean(monitor, monitorName); MonitorTarget target = new MonitorTarget(); target.setString(reference); server.registerMBean(target, name); final MutableInteger times = new MutableInteger(0); final MutableObject holder = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { times.set(times.get() + 1); holder.set(notification); } }; server.addNotificationListener(monitorName, listener, null, null); monitor.start(); try { sleep(period * 3); assertEquals(times.get(), 1); MonitorNotification notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.STRING_TO_COMPARE_VALUE_MATCHED); times.set(0); holder.set(null); target.setString("xx"); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.STRING_TO_COMPARE_VALUE_DIFFERED); times.set(0); holder.set(null); target.setString(reference); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.STRING_TO_COMPARE_VALUE_MATCHED); times.set(0); holder.set(null); target.setString("yyyy"); sleep(period * 3); assertEquals(times.get(), 1); notification = (MonitorNotification)holder.get(); assertEquals(notification.getType(), MonitorNotification.STRING_TO_COMPARE_VALUE_DIFFERED); times.set(0); holder.set(null); target.setString("zzzzz"); sleep(period * 3); assertEquals(times.get(), 0); assertNull(holder.get()); } finally { monitor.stop(); } } public interface MonitorTargetMBean { public String getString(); } public static class MonitorTarget implements MonitorTargetMBean { private String value; public String getString() { return value; } public void setString(String value) { this.value = value; } } } mx4j-3.0.2/src/test/test/javax/management/openmbean/ArrayTypeTest.java100644 0 0 13431 10513545721 23113 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; /** * @version $Revision: 1.7 $ */ import javax.management.openmbean.ArrayType; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; public class ArrayTypeTest extends TestCase { public ArrayTypeTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testIsValue() throws Exception { ArrayType simple = new ArrayType(1, SimpleType.STRING); String[] stringarray = {"do", "re", "mi"}; assertTrue("Expecting equality for array of strings", simple.isValue(stringarray)); assertFalse("Expecting inequality for array of ints", simple.isValue(new int[]{1, 2, 3, 4})); assertFalse("Expecting inequality for null", simple.isValue(null)); assertFalse("Expecting inequality for string", simple.isValue("fa")); String[] items = {"type", "winery", "vintage"}; String[] descriptions = {"Type of wine", "Wine producer", "Year produced"}; OpenType[] types = {SimpleType.STRING, SimpleType.STRING, SimpleType.INTEGER}; CompositeType wine = new CompositeType("wine", "nectar of the gods", items, descriptions, types); items = new String[]{"type", "brewery"}; descriptions = new String[]{"Type of beer", "Beer producer"}; types = new OpenType[]{SimpleType.STRING, SimpleType.STRING}; CompositeType beer = new CompositeType("beer", "a meal in a glass", items, descriptions, types); ArrayType composite = new ArrayType(1, wine); CompositeDataSupport amarone = new CompositeDataSupport(wine, new String[]{"type", "winery", "vintage"}, new Object[]{"red", "Allegrini", new Integer(1996)}); CompositeDataSupport orvieto = new CompositeDataSupport(wine, new String[]{"type", "winery", "vintage"}, new Object[]{"white", "Ruffino", new Integer(2002)}); CompositeData[] winecellar = {amarone, orvieto}; CompositeData[] sparsewines = {amarone, null, orvieto}; CompositeDataSupport stout = new CompositeDataSupport(beer, new String[]{"type", "brewery"}, new Object[]{"stout", "Guiness"}); CompositeData[] beerlist = {stout}; CompositeData[] mixer = {amarone, stout, orvieto}; assertTrue("Expecting equality for array of wines", composite.isValue(winecellar)); assertTrue("Expecting equality for sparse array of wines", composite.isValue(sparsewines)); assertFalse("Expecting inequality for array of beer", composite.isValue(beerlist)); assertFalse("Expecting inequality for mixed array", composite.isValue(mixer)); assertFalse("Expecting inequality for single wine", composite.isValue(orvieto)); ArrayType winematrix = new ArrayType(2, wine); CompositeData[][] matrix = {{amarone, orvieto}, {orvieto, amarone}}; assertTrue("Expecting equality for wine matrix", winematrix.isValue(matrix)); assertFalse("Expecting inequality for wine vector", winematrix.isValue(winecellar)); winematrix = new ArrayType(2, wine); CompositeData[][] matrix2 = new CompositeData[1][1]; assertTrue("Expecting equality for wine matrix", winematrix.isValue(matrix2)); } public void testEquals() throws Exception { ArrayType a1 = new ArrayType(1, SimpleType.LONG); ArrayType a2 = new ArrayType(1, SimpleType.LONG); ArrayType a3 = new ArrayType(2, SimpleType.LONG); ArrayType a4 = new ArrayType(2, SimpleType.STRING); assertTrue(a1.equals(a2)); assertTrue(!a1.equals(a3)); assertTrue(!a1.equals(a4)); } public void testCompositeEquals() throws Exception { String[] items = {"type", "winery", "vintage"}; String[] descriptions = {"Type of wine", "Wine producer", "Year produced"}; OpenType[] types = {SimpleType.STRING, SimpleType.STRING, SimpleType.DATE}; CompositeType californiaWine = new CompositeType("California", "Vino", items, descriptions, types); ArrayType aone = new ArrayType(2, californiaWine); ArrayType atwo = new ArrayType(2, californiaWine); assertTrue("Expecting equality for identical composite types", aone.equals(atwo)); CompositeType italianWine = new CompositeType("Italia", "Vino", items, descriptions, types); atwo = new ArrayType(2, italianWine); assertFalse("Expecting inequality for different composite types", aone.equals(atwo)); } public void testClassName() throws Exception { ArrayType a1 = new ArrayType(2, SimpleType.STRING); assertEquals(a1.getClassName(), "[[Ljava.lang.String;"); assertEquals(a1.getTypeName(), "[[Ljava.lang.String;"); } public void testHashCode() throws Exception { ArrayType a1 = new ArrayType(2, SimpleType.STRING); ArrayType a2 = new ArrayType(2, SimpleType.STRING); assertTrue(a1.hashCode() == a2.hashCode()); } public void testBadSize() throws Exception { try { ArrayType t = new ArrayType(0, SimpleType.STRING); } catch (IllegalArgumentException x) { assertTrue(true); // success } } } mx4j-3.0.2/src/test/test/javax/management/openmbean/CompositeDataSupportTest.java100644 0 0 13202 10513545721 25320 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Collection; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import junit.framework.TestCase; /** * @version $Revision: 1.7 $ */ public class CompositeDataSupportTest extends TestCase { private String[] itemNames = null; private String[] itemDescriptions = null; private OpenType[] itemTypes; private CompositeType tShirtType; private String[] indexNames; private TabularType allTShirtTypes; private TabularDataSupport tabularSupport; private CompositeDataSupport compositeData; public CompositeDataSupportTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); itemNames = new String[]{"model", "color", "size", "price"}; itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; indexNames = new String[]{"model", "color", "size"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); allTShirtTypes = new TabularType("tShirts", "List of available TShirts", tShirtType, // row type indexNames); Object[] itemValues = new Object[]{"MX4J", "red", "L", new Float(15.0f)}; compositeData = new CompositeDataSupport(tShirtType, itemNames, itemValues); // takes tabular type tabularSupport = new TabularDataSupport(allTShirtTypes); } protected void tearDown() throws Exception { super.tearDown(); } public void testConstructor() { try { Object[] itemValues = new Object[]{"MX4J", "red", "L", new Float(15.0f)}; CompositeDataSupport support = new CompositeDataSupport(tShirtType, itemNames, itemValues); assertTrue(support != null); } catch (OpenDataException e) { e.printStackTrace(); } // test for bug #769086 including a null value try { Object[] itemValues = new Object[]{"MX4J", "red", null, new Float(15.0f)}; CompositeDataSupport support = new CompositeDataSupport(tShirtType, itemNames, itemValues); assertTrue(support != null); } catch (OpenDataException e) { e.printStackTrace(); } } public void testGet() { String expected = "MX4J"; String obj = (String)compositeData.get("model"); assertTrue("expected was stored as the value against model", expected.equals(obj)); } public void testGetAll() { int expectedLength = 4; Object[] obj = compositeData.getAll(itemNames); assertEquals(expectedLength, obj.length); } public void testValues() { int expected = 4; Collection result = compositeData.values(); assertEquals(expected, result.size()); } public void testSparseValues() throws Exception { Object[] sparsevalues = new Object[]{"MX4J", null, "L", new Float(15.0f)}; CompositeDataSupport sparsedata = new CompositeDataSupport(tShirtType, itemNames, sparsevalues); assertTrue("Null instance", sparsedata != null); } public void testEquals() throws Exception { Object[] testvalues = {"MX4J", "White", "XL", new Float(15.0f)}; CompositeDataSupport cdone = new CompositeDataSupport(tShirtType, itemNames, testvalues); assertFalse("cdone equals 'null'", cdone.equals(null)); assertFalse("cdone equals Integer value", cdone.equals(new Integer(42))); String[] items = new String[]{"model", "color", "size", "price"}; String[] descriptions = new String[]{ "TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; OpenType[] types = new OpenType[]{ SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; CompositeType shirt = new CompositeType("tShirt", "A 'Tee' Shirt", items, descriptions, types); CompositeDataSupport cdtwo = new CompositeDataSupport(shirt, items, testvalues); assertTrue("cdtwo not equal to cdone", cdtwo.equals(cdone)); cdone = new CompositeDataSupport(tShirtType, items, new Object[]{"GAP", null, "S", new Float(30.0f)}); cdtwo = new CompositeDataSupport(shirt, items, new Object[]{"GAP", null, "S", new Float(30.0f)}); assertTrue("sparse cdtwo not equal to sparse cdone", cdtwo.equals(cdone)); } } mx4j-3.0.2/src/test/test/javax/management/openmbean/CompositeTypeTest.java100644 0 0 23526 10513545721 24005 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.io.IOException; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; import test.javax.management.compliance.serialization.support.Serializer; /** * @version $Revision: 1.12 $ */ public class CompositeTypeTest extends TestCase { private String[] itemNames = null; private String[] itemDescriptions = null; private OpenType[] itemTypes; private String[] indexNames; private CompositeType tShirtType; public CompositeTypeTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); itemNames = new String[]{"model", "color", "size", "price"}; itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; indexNames = new String[]{"model", "color", "size"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); } protected void tearDown() throws Exception { super.tearDown(); } public void testCreation() { assertTrue(tShirtType != null); } public void testInvalidCreation() { try { // duplicate names itemNames = new String[]{"model", "color", "size", "model"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); fail("Expect exception, invalid itemDescriptions (not the same size as itemNames - we should not see this"); } catch (OpenDataException e) { } try { // empty typeName String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; tShirtType = new CompositeType("", "a TShirt", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // null typeName String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; tShirtType = new CompositeType(null, "a TShirt", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // empty description String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; tShirtType = new CompositeType("tShirt", "", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // null description String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; tShirtType = new CompositeType("tShirt", null, itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // null itemName entry String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemNames = new String[]{"model", null, "size", "price"}; tShirtType = new CompositeType("tShirt", "", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // empty itemName entry String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemNames = new String[]{"model", "color", "", "price"}; tShirtType = new CompositeType("tShirt", "", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // null itemDescription entry String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", null, "TShirt's price"}; tShirtType = new CompositeType("tShirt", "", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // empty itemDescription entry String[] itemDescriptions = new String[]{"TShirt's model name", "", "TShirt's size", "TShirt's price"}; tShirtType = new CompositeType("tShirt", "", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // null itemTypes tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, null); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } try { // mismatched lengths String[] itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's price"}; itemNames = new String[]{"model", "color", "size", "price"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); fail("No exception thrown"); } catch (IllegalArgumentException x) { assertTrue(true); // success } catch (Exception x) { fail("Expecting IllegalArgumentException"); } } public void testContainsKey() { boolean valid = tShirtType.containsKey("model"); assertTrue(valid); // test fail for same name different case assertTrue(tShirtType.containsKey("Model") == false); } public void testGetDescription() { String expected = "TShirt's color"; String result = tShirtType.getDescription("color"); assertTrue(expected == result); } public void testGetType() { OpenType expected = SimpleType.FLOAT; OpenType result = tShirtType.getType("price"); assertEquals(expected, result); } public void testSerialization() { // write out try { Serializer serializer = new Serializer(); byte[] data = serializer.serialize(tShirtType); Object obj = serializer.deserialize(data); // assert instanceof assertTrue(obj instanceof CompositeType); // if instanceof passes continue otherwise we will not get to the rest CompositeType type = (CompositeType)obj; // assert hashcodes are equal assertEquals(type.hashCode(), tShirtType.hashCode()); assertTrue(type.getType("price").equals(SimpleType.FLOAT)); assertEquals(type.getType("size"), tShirtType.getType("size")); assertEquals(type.getDescription("model"), tShirtType.getDescription("model")); assertEquals(type.keySet(), tShirtType.keySet()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { } } public void testHashCode() throws Exception { int ehc = 0; ehc += tShirtType.getTypeName().hashCode(); for (int i = 0; i < itemNames.length; i++) { ehc += itemNames[i].hashCode(); ehc += itemTypes[i].hashCode(); } int hc = tShirtType.hashCode(); assertTrue("Unexpected hashcode", hc == ehc); } public void testEquals() throws Exception { CompositeType undershirt = new CompositeType("UnderShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); assertFalse("tShirtType and undershirt should not be equal", undershirt.equals(tShirtType)); String[] italianDescriptions = {"modello", "nome", "colore", "prezzo"}; CompositeType italianshirt = new CompositeType("UnderShirt", "una Camicia", itemNames, italianDescriptions, itemTypes); assertTrue("undershirt and italianshirt should be equal", italianshirt.equals(undershirt)); } } mx4j-3.0.2/src/test/test/javax/management/openmbean/OpenMBeanAttributeInfoSupportTest.java100644 0 0 63350 10513545721 27101 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; /** * @version $Revision: 1.7 $ */ import java.util.Iterator; import java.util.Set; import javax.management.openmbean.ArrayType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenMBeanAttributeInfoSupport; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; public class OpenMBeanAttributeInfoSupportTest extends TestCase { public OpenMBeanAttributeInfoSupportTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testEquals() throws Exception { try { OpenMBeanAttributeInfoSupport o1 = new OpenMBeanAttributeInfoSupport("name", "The name", SimpleType.STRING, false, true, false); OpenMBeanAttributeInfoSupport o2 = new OpenMBeanAttributeInfoSupport("name", "The name", SimpleType.STRING, false, true, false); OpenMBeanAttributeInfoSupport o3 = new OpenMBeanAttributeInfoSupport("name", "The name", SimpleType.STRING, true, false, false); assertTrue(!o1.equals(null)); assertTrue(o1.equals(o2)); assertEquals(o1.hashCode(), o2.hashCode()); assertTrue(!o1.equals(o3)); } catch (Exception e) { e.printStackTrace(); } } public void testSixParamCtor() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false); assertTrue("Null info constructed", info != null); assertTrue("OpenType should be FLOAT", info.getOpenType().equals(SimpleType.FLOAT)); assertTrue("Attribute should be readable", info.isReadable()); assertFalse("Attribute should not be writeable", info.isWritable()); assertFalse("Attribute is not 'is", info.isIs()); try { info = new OpenMBeanAttributeInfoSupport(null, "how much it costs", SimpleType.FLOAT, true, false, false); fail("Expecting exception for null name"); } catch (IllegalArgumentException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("", "how much it costs", SimpleType.FLOAT, true, false, false); fail("Expecting exception for empty name"); } catch (IllegalArgumentException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", null, SimpleType.FLOAT, true, false, false); fail("Expecting exception for null description"); } catch (IllegalArgumentException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "", SimpleType.FLOAT, true, false, false); fail("Expecting exception for empty description"); } catch (IllegalArgumentException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", null, true, false, false); fail("Expecting exception for null type"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testSevenParamCtor() throws Exception { Float defaultvalue = new Float(1.00); OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue); assertTrue("Null info constructed", info != null); assertTrue("Expecting default value of 1.00", defaultvalue.equals((Float)info.getDefaultValue())); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, null); assertTrue("Null info constructed", info != null); assertFalse("There should be no default value", info.hasDefaultValue()); } public void testEightParamCtor() throws Exception { Float[] legalvalues = {new Float(0.75), new Float(1.00), new Float(1.50)}; Float defaultvalue = new Float(1.00); OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, legalvalues); assertTrue("Null info constructed", info != null); Set legalset = info.getLegalValues(); assertTrue("Legal set is the wrong size", legalset.size() == legalvalues.length); assertTrue("0.75 not in legal set", legalset.contains(new Float(0.75))); assertTrue("1.00 not in legal set", legalset.contains(new Float(1.00))); assertTrue("1.50 not in legal set", legalset.contains(new Float(1.50))); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, null); assertTrue("Null info constructed", info != null); assertFalse("There should be no legal value set for null", info.hasLegalValues()); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, new Float[0]); assertTrue("Null info constructed", info != null); assertFalse("There should be no legal value set for Float[0]", info.hasLegalValues()); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, null, legalvalues); assertTrue("Null info constructed", info != null); assertFalse("Has a default value", info.hasDefaultValue()); try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, "Invalid Default Value", new Float[0]); fail("Expecting exception for invalid default value"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, new Object[]{new Float(0.75), "$1.50"}); fail("Expecting exception for invalid legal value"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", new ArrayType(1, SimpleType.FLOAT), true, false, false, defaultvalue, null); fail("Expecting exception for non null default w/ArrayType attribute"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", new ArrayType(1, SimpleType.FLOAT), true, false, false, null, new Float[]{new Float(0.75), new Float(1.50)}); fail("Expecting exception for non null legal set w/ArrayType attribute"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", new ArrayType(1, SimpleType.FLOAT), true, false, false, new Float(0.25), legalvalues); fail("Expecting exception for default not in legal set"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.INTEGER, true, false, false, new Integer(1), new Integer[]{new Integer(0), new Integer(2)}); fail("Expecting exception for default not in legal set"); } catch (OpenDataException x) { assertTrue(true); } } public void testNineParameCtor() throws Exception { Float defaultvalue = new Float(1.00); Float minvalue = new Float(0.75); Float maxvalue = new Float(1.50); OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, minvalue, maxvalue); assertTrue("Null info constructed", info != null); assertTrue("Expecting min value of 0.75", info.hasMinValue() && minvalue.equals((Float)info.getMinValue())); assertTrue("Expecting max value of 1.50", info.hasMaxValue() && maxvalue.equals((Float)info.getMaxValue())); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, null, maxvalue); assertTrue("Null info constructed", info != null); assertFalse("Not expecting a min value", info.hasMinValue()); assertTrue("Expecting max value of 1.50", info.hasMaxValue() && maxvalue.equals((Float)info.getMaxValue())); info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, minvalue, null); assertTrue("Null info constructed", info != null); assertTrue("Expecting min value of 0.75", info.hasMinValue() && minvalue.equals((Float)info.getMinValue())); assertFalse("Not expecting a max value", info.hasMaxValue()); try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, "1.00", minvalue, maxvalue); fail("Expecting exception for bad default value type"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, "0.75", maxvalue); fail("Expecting exception for bad min value type"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, minvalue, "1.50"); fail("Expecting exception for bad min value type"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", new ArrayType(1, SimpleType.FLOAT), true, false, false, defaultvalue, minvalue, maxvalue); fail("Expecting exception for non-null default value w/ArrayType attribute"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, defaultvalue, maxvalue, minvalue); fail("Expecting exception for min > max"); } catch (OpenDataException x) { assertTrue(true); } try { info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, minvalue, defaultvalue, maxvalue); fail("Expecting exception for default < min"); } catch (OpenDataException x) { assertTrue(true); } } public void testSimpleInfoHashCode() { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false); assertTrue("Unexpected hash code for simple info", info.hashCode() == hashCode(info)); } public void testDefaultValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00)); assertTrue("Unexpected hash code for info w/default value", info.hashCode() == hashCode(info)); } public void testNullDefaultValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, null); assertTrue("Unexpected hash code for info w/null default value", info.hashCode() == hashCode(info)); } public void testLegalValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00), new Float[]{ new Float(0.75), new Float(1.00), new Float(1.50)}); assertTrue("Unexpected hash code for info w/legal values", info.hashCode() == hashCode(info)); } public void testEmptyLegalValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00), new Float[0]); assertTrue("Unexpected hash code for info w/empty legal values", info.hashCode() == hashCode(info)); } public void testMinMaxValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00), new Float(0.75), new Float(1.50)); assertTrue("Unexpected hash code for info w/minmax values", info.hashCode() == hashCode(info)); } public void testNullMinValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00), null, new Float(1.50)); assertTrue("Unexpected hash code for info w/null min values", info.hashCode() == hashCode(info)); } public void testNullMaxValueHashCode() throws Exception { OpenMBeanAttributeInfoSupport info = new OpenMBeanAttributeInfoSupport("price", "how much it costs", SimpleType.FLOAT, true, false, false, new Float(1.00), new Float(0.75), null); assertTrue("Unexpected hash code for info w/empty legal values", info.hashCode() == hashCode(info)); } private int hashCode(OpenMBeanAttributeInfoSupport info) { int result = info.getName().hashCode(); result += info.getOpenType().hashCode(); result += (info.hasDefaultValue() == false) ? 0 : info.getDefaultValue().hashCode(); result += (info.hasLegalValues() == false) ? 0 : hashCode(info.getLegalValues()); result += (info.hasMinValue() == false) ? 0 : info.getMinValue().hashCode(); result += (info.hasMaxValue() == false) ? 0 : info.getMaxValue().hashCode(); return result; } private int hashCode(Set legalvalues) { int result = 0; Iterator i = legalvalues.iterator(); while (i.hasNext()) { Object v = i.next(); result += v.hashCode(); } return result; } } mx4j-3.0.2/src/test/test/javax/management/openmbean/OpenMBeanConstructorInfoSupportTest.java100644 0 0 22642 10513545721 27462 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Arrays; import java.util.Set; import javax.management.openmbean.OpenMBeanConstructorInfo; import javax.management.openmbean.OpenMBeanConstructorInfoSupport; import javax.management.openmbean.OpenMBeanParameterInfo; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; import junit.textui.TestRunner; /** */ public class OpenMBeanConstructorInfoSupportTest extends TestCase { private static class MyMBeanParameterInfo implements OpenMBeanParameterInfo { public boolean equals(Object o) { return false; } public Object getDefaultValue() { return null; } public String getDescription() { return null; } public Set getLegalValues() { return null; } public Comparable getMaxValue() { return null; } public Comparable getMinValue() { return null; } public String getName() { return null; } public OpenType getOpenType() { return null; } public boolean hasDefaultValue() { return false; } public boolean hasLegalValues() { return false; } public boolean hasMinValue() { return false; } public boolean hasMaxValue() { return false; } public boolean isValue(Object o) { return false; } public String toString() { return null; } } private OpenMBeanParameterInfo[] signature; public static void main(String[] args) { TestRunner.run(OpenMBeanConstructorInfoSupportTest.class); } public void testCtor() throws Exception { OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport("wine", "Non-default constructor", signature); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("wine") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("Non-default constructor") == 0); assertTrue("Unexpected signature", Arrays.equals(info.getSignature(), signature)); info = new OpenMBeanConstructorInfoSupport("wine", "Non-default constructor", null); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("wine") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("Non-default constructor") == 0); assertTrue("Unexpected signature", info.getSignature() == null || info.getSignature().length == 0); info = new OpenMBeanConstructorInfoSupport("wine", "Non-default constructor", new OpenMBeanParameterInfoSupport[0]); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("wine") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("Non-default constructor") == 0); assertTrue("Unexpected signature", info.getSignature().length == 0); } public void testCtorNullName() throws Exception { try { OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport(null, "Non-default constructor", signature); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorEmptyName() throws Exception { try { OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport("", "Non-default constructor", signature); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorNullDescription() throws Exception { try { OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport("wine", null, signature); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorEmptyDescription() throws Exception { try { OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport("wine", "", signature); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorBogusSignature() throws Exception { try { MyMBeanParameterInfo[] bogusig = { new MyMBeanParameterInfo(), new MyMBeanParameterInfo(), new MyMBeanParameterInfo()}; OpenMBeanConstructorInfoSupport info = new OpenMBeanConstructorInfoSupport("wine", "Non-default constructor", bogusig); fail("Expecting ArrayStoreException"); } catch (ArrayStoreException x) { assertTrue(true); } } public void testEquals() throws Exception { OpenMBeanConstructorInfo infoone = new OpenMBeanConstructorInfoSupport("wine", "Vino", signature); assertTrue("Null infoone constructed", infoone != null); OpenMBeanConstructorInfo infotwo = new OpenMBeanConstructorInfoSupport("wine", "Nectar of the gods", signature); assertTrue("Null infotwo constructed", infotwo != null); assertTrue("Expected equality", infoone.equals(infotwo)); OpenMBeanConstructorInfo infothree = new OpenMBeanConstructorInfoSupport("Vino", "Vino", signature); assertTrue("Null infothree constructed", infothree != null); assertFalse("Expected inequality based on name", infothree.equals(infoone)); OpenMBeanConstructorInfo infofour = new OpenMBeanConstructorInfoSupport("wine", "Vino", new OpenMBeanParameterInfoSupport[0]); assertTrue("Null infofour constructed", infofour != null); assertFalse("Expected inequality based on signature", infofour.equals(infoone)); } public void testHashCode() throws Exception { OpenMBeanConstructorInfo infoone = new OpenMBeanConstructorInfoSupport("wine", "Vino", signature); assertTrue("Null infoone constructed", infoone != null); assertTrue("Unexpected hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanConstructorInfo infotwo = new OpenMBeanConstructorInfoSupport("wine", "Nectar of the gods", signature); assertTrue("Null infotwo constructed", infotwo != null); assertTrue("Expecting equal hash codes", infoone.hashCode() == infotwo.hashCode()); } protected void setUp() { try { signature = new OpenMBeanParameterInfoSupport[]{ new OpenMBeanParameterInfoSupport("type", "type of wine", SimpleType.STRING, "Red", new String[]{"Red", "White", "Rose"}), new OpenMBeanParameterInfoSupport("winery", "who produced the wine", SimpleType.STRING), new OpenMBeanParameterInfoSupport("vintage", "when the wine was produced", SimpleType.INTEGER, null, new Integer(1900), new Integer(2000)) }; } catch (Exception x) { fail(x.toString()); } } protected void tearDown() { } private int hashCode(OpenMBeanConstructorInfo info) { int result = info.getName().hashCode(); result += Arrays.asList(info.getSignature()).hashCode(); return result; } } mx4j-3.0.2/src/test/test/javax/management/openmbean/OpenMBeanInfoSupportTest.java100644 0 0 37765 10513545721 25230 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Arrays; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.openmbean.ArrayType; import javax.management.openmbean.OpenMBeanAttributeInfo; import javax.management.openmbean.OpenMBeanAttributeInfoSupport; import javax.management.openmbean.OpenMBeanConstructorInfo; import javax.management.openmbean.OpenMBeanConstructorInfoSupport; import javax.management.openmbean.OpenMBeanInfoSupport; import javax.management.openmbean.OpenMBeanOperationInfo; import javax.management.openmbean.OpenMBeanOperationInfoSupport; import javax.management.openmbean.OpenMBeanParameterInfo; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; import junit.textui.TestRunner; /** */ public class OpenMBeanInfoSupportTest extends TestCase { private OpenMBeanAttributeInfo[] attrs; private OpenMBeanConstructorInfo[] ctors; private OpenMBeanOperationInfo[] ops; private MBeanNotificationInfo[] notifs; public static void main(String[] args) { TestRunner.run(OpenMBeanInfoSupportTest.class); } public void testCtor() throws Exception { OpenMBeanInfoSupport info = new OpenMBeanInfoSupport("CurrencyMBean", "Does stuff with currencies", attrs, ctors, ops, notifs); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getClassName().compareTo("CurrencyMBean") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("Does stuff with currencies") == 0); assertTrue("Unexpected attributes", Arrays.equals(info.getAttributes(), attrs)); assertTrue("Unexpected constructors", Arrays.equals(info.getConstructors(), ctors)); assertTrue("Unexpected operations", Arrays.equals(info.getOperations(), ops)); assertTrue("Unexpected notifications", Arrays.equals(info.getNotifications(), notifs)); } public void testEquals() throws Exception { OpenMBeanInfoSupport infoone = new OpenMBeanInfoSupport("CurrencyMBean", "Does stuff with currencies", attrs, ctors, ops, notifs); assertTrue("Null info constructed", infoone != null); OpenMBeanInfoSupport infotwo = new OpenMBeanInfoSupport("CurrencyMBean", "manages currencies", attrs, ctors, ops, notifs); assertTrue("Null info constructed", infotwo != null); assertTrue("Expecting equality (only description is different)", infotwo.equals(infoone)); OpenMBeanAttributeInfo[] testattrs = new OpenMBeanAttributeInfoSupport[]{ new OpenMBeanAttributeInfoSupport("Uptime", "how long it's been running", SimpleType.FLOAT, true, false, false), new OpenMBeanAttributeInfoSupport("Exchanges", "number of exchanges completed", SimpleType.FLOAT, true, false, false)}; OpenMBeanConstructorInfo[] testctors = new OpenMBeanConstructorInfoSupport[]{ new OpenMBeanConstructorInfoSupport("CurrencyMBean", "create a currency mbean", new OpenMBeanParameterInfoSupport[]{ new OpenMBeanParameterInfoSupport("currencies", "currencies that may be exchanged", new ArrayType(1, SimpleType.STRING))}) }; OpenMBeanParameterInfo[] ratesig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING), new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING)}; OpenMBeanParameterInfo[] exsig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING), new OpenMBeanParameterInfoSupport("amount", "amount of currency to convert", SimpleType.FLOAT), new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING)}; OpenMBeanOperationInfo[] testops = new OpenMBeanOperationInfoSupport[]{ new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", ratesig, SimpleType.FLOAT, MBeanOperationInfo.INFO), new OpenMBeanOperationInfoSupport("exchange", "compute the exchange rate for two currencies", exsig, SimpleType.FLOAT, MBeanOperationInfo.INFO)}; OpenMBeanInfoSupport infothree = new OpenMBeanInfoSupport("CurrencyMBean", "Does stuff with currencies", testattrs, testctors, testops, notifs); assertTrue("Null info constructed", infoone != null); assertFalse("Expecting inequality (the parameter orders are different)", infothree.equals(infoone)); } public void testHashCode() throws Exception { OpenMBeanInfoSupport infoone = new OpenMBeanInfoSupport("CurrencyMBean", "Does stuff with currencies", attrs, ctors, ops, notifs); assertTrue("Null info constructed", infoone != null); OpenMBeanInfoSupport infotwo = new OpenMBeanInfoSupport("CurrencyMBean", "manages currencies", attrs, ctors, ops, notifs); assertTrue("Null info constructed", infotwo != null); assertTrue("Expecting identical hash codes (only description is different)", infotwo.hashCode() == infoone.hashCode()); OpenMBeanAttributeInfo[] testattrs = new OpenMBeanAttributeInfoSupport[]{ new OpenMBeanAttributeInfoSupport("Uptime", "how long it's been running", SimpleType.FLOAT, true, false, false), new OpenMBeanAttributeInfoSupport("Exchanges", "number of exchanges completed", SimpleType.FLOAT, true, false, false)}; OpenMBeanConstructorInfo[] testctors = new OpenMBeanConstructorInfoSupport[]{ new OpenMBeanConstructorInfoSupport("CurrencyMBean", "create a currency mbean", new OpenMBeanParameterInfoSupport[]{ new OpenMBeanParameterInfoSupport("currencies", "currencies that may be exchanged", new ArrayType(1, SimpleType.STRING))}) }; OpenMBeanParameterInfo[] ratesig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING), new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING)}; OpenMBeanParameterInfo[] exsig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING), new OpenMBeanParameterInfoSupport("amount", "amount of currency to convert", SimpleType.FLOAT), new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING)}; OpenMBeanOperationInfo[] testops = new OpenMBeanOperationInfoSupport[]{ new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", ratesig, SimpleType.FLOAT, MBeanOperationInfo.INFO), new OpenMBeanOperationInfoSupport("exchange", "compute the exchange rate for two currencies", exsig, SimpleType.FLOAT, MBeanOperationInfo.INFO)}; OpenMBeanInfoSupport infothree = new OpenMBeanInfoSupport("CurrencyMBean", "Does stuff with currencies", testattrs, testctors, testops, notifs); assertTrue("Null info constructed", infoone != null); assertFalse("Expecting different hash codes (the parameter orders are different)", infothree.hashCode() == infoone.hashCode()); } protected void setUp() throws Exception { attrs = new OpenMBeanAttributeInfoSupport[]{ new OpenMBeanAttributeInfoSupport("Exchanges", "number of exchanges completed", SimpleType.FLOAT, true, false, false), new OpenMBeanAttributeInfoSupport("Uptime", "how long it's been running", SimpleType.FLOAT, true, false, false)}; ctors = new OpenMBeanConstructorInfoSupport[]{ new OpenMBeanConstructorInfoSupport("CurrencyMBean", "create a currency mbean", new OpenMBeanParameterInfoSupport[]{ new OpenMBeanParameterInfoSupport("currencies", "currencies that may be exchanged", new ArrayType(1, SimpleType.STRING))}) }; OpenMBeanParameterInfo[] ratesig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING), new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING)}; OpenMBeanParameterInfo[] exsig = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING), new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING), new OpenMBeanParameterInfoSupport("amount", "amount of currency to convert", SimpleType.FLOAT)}; ops = new OpenMBeanOperationInfoSupport[]{ new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", ratesig, SimpleType.FLOAT, MBeanOperationInfo.INFO), new OpenMBeanOperationInfoSupport("exchange", "compute the exchange rate for two currencies", exsig, SimpleType.FLOAT, MBeanOperationInfo.INFO)}; notifs = new MBeanNotificationInfo[0]; } protected void tearDown() { } } mx4j-3.0.2/src/test/test/javax/management/openmbean/OpenMBeanOperationInfoSupportTest.java100644 0 0 26062 10513545721 27075 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; /** * @version $Revision: 1.5 $ */ import java.util.Arrays; import javax.management.MBeanOperationInfo; import javax.management.openmbean.OpenMBeanOperationInfo; import javax.management.openmbean.OpenMBeanOperationInfoSupport; import javax.management.openmbean.OpenMBeanParameterInfo; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; public class OpenMBeanOperationInfoSupportTest extends TestCase { OpenMBeanParameterInfo[] signature; OpenMBeanParameterInfo[] params = null; public OpenMBeanOperationInfoSupportTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); params = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("name", "The name", SimpleType.STRING) }; signature = new OpenMBeanParameterInfo[]{ new OpenMBeanParameterInfoSupport("from", "currency to convert from", SimpleType.STRING), new OpenMBeanParameterInfoSupport("to", "currency to convert to", SimpleType.STRING)}; } protected void tearDown() throws Exception { super.tearDown(); } public void testCtor() throws Exception { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", signature, SimpleType.FLOAT, MBeanOperationInfo.INFO); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("exchangeRate") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("compute the exchange rate for two currencies") == 0); assertTrue("Unexpected return open type", info.getReturnOpenType().equals(SimpleType.FLOAT)); assertTrue("Unexpected signature", Arrays.equals(info.getSignature(), signature)); assertTrue("Unexpected impact", info.getImpact() == MBeanOperationInfo.INFO); } public void testCtorNullName() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport(null, "compute the exchange rate for two currencies", signature, SimpleType.FLOAT, MBeanOperationInfo.INFO); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorEmptyName() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("", "compute the exchange rate for two currencies", signature, SimpleType.FLOAT, MBeanOperationInfo.INFO); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorNullDescription() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", null, signature, SimpleType.FLOAT, MBeanOperationInfo.INFO); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorEmptyDescription() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "", signature, SimpleType.FLOAT, MBeanOperationInfo.INFO); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorNullSignature() throws Exception { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", null, SimpleType.FLOAT, MBeanOperationInfo.INFO); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("exchangeRate") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("compute the exchange rate for two currencies") == 0); assertTrue("Unexpected return open type", info.getReturnOpenType().equals(SimpleType.FLOAT)); assertTrue("Unexpected signature", Arrays.equals(info.getSignature(), new OpenMBeanParameterInfo[0])); assertTrue("Unexpected impact", info.getImpact() == MBeanOperationInfo.INFO); } public void testCtorEmptySignature() throws Exception { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", new OpenMBeanParameterInfo[0], SimpleType.FLOAT, MBeanOperationInfo.INFO); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("exchangeRate") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("compute the exchange rate for two currencies") == 0); assertTrue("Unexpected return open type", info.getReturnOpenType().equals(SimpleType.FLOAT)); assertTrue("Unexpected signature", Arrays.equals(info.getSignature(), new OpenMBeanParameterInfo[0])); assertTrue("Unexpected impact", info.getImpact() == MBeanOperationInfo.INFO); } public void testCtorNullReturnOpenType() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", signature, null, MBeanOperationInfo.INFO); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testCtorBogusImpact() throws Exception { try { OpenMBeanOperationInfoSupport info = new OpenMBeanOperationInfoSupport("exchangeRate", "compute the exchange rate for two currencies", signature, SimpleType.FLOAT, 42); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testEquals() throws Exception { OpenMBeanOperationInfoSupport o1 = new OpenMBeanOperationInfoSupport("hello", "Say Hello", params, SimpleType.STRING, 1); OpenMBeanOperationInfoSupport o2 = new OpenMBeanOperationInfoSupport("hello", "Say Hello", params, SimpleType.STRING, 1); OpenMBeanOperationInfoSupport o3 = new OpenMBeanOperationInfoSupport("hello", "Say Hello", params, SimpleType.STRING, 0); OpenMBeanOperationInfoSupport o4 = new OpenMBeanOperationInfoSupport("goAway", "Go Away", params, SimpleType.STRING, 1); OpenMBeanOperationInfoSupport o5 = new OpenMBeanOperationInfoSupport("goAway", "Hey There", params, SimpleType.STRING, 1); OpenMBeanOperationInfoSupport o6 = new OpenMBeanOperationInfoSupport("goAway", "Hey There", params, SimpleType.INTEGER, 1); //test assertTrue(!o1.equals(null)); assertTrue(o1.equals(o2)); assertEquals(o1.hashCode(), o2.hashCode()); assertTrue(!o1.equals(o3)); assertTrue(o4.equals(o5)); assertTrue(!o5.equals(o6)); } public void testHashCode() throws Exception { OpenMBeanOperationInfoSupport infoone = new OpenMBeanOperationInfoSupport("convertPrice", "converts the price from one currency to another", signature, SimpleType.FLOAT, MBeanOperationInfo.ACTION); assertTrue("Unexpected hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanOperationInfoSupport infotwo = new OpenMBeanOperationInfoSupport("convertPrice", "multiply Currency by exchange rate to get TargetCurrency price", signature, SimpleType.FLOAT, MBeanOperationInfo.ACTION); assertTrue("Unexpected hash code", infotwo.hashCode() == hashCode(infoone)); } private int hashCode(OpenMBeanOperationInfo info) { int result = info.getName().hashCode(); result += info.getReturnOpenType().hashCode(); result += info.getImpact(); result += java.util.Arrays.asList(info.getSignature()).hashCode(); return result; } } mx4j-3.0.2/src/test/test/javax/management/openmbean/OpenMBeanParameterInfoSupportTest.java100644 0 0 55646 10513545721 27067 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Iterator; import java.util.Set; import javax.management.openmbean.ArrayType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenMBeanParameterInfo; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; import test.javax.management.compliance.serialization.support.Serializer; /** * @version $Revision: 1.6 $ */ public class OpenMBeanParameterInfoSupportTest extends TestCase { private String[] legalModels; private String[] legalColors; private static String[] legalSizes; private float minPrice; private float maxPrice; private OpenMBeanParameterInfoSupport priceParamInfo; public OpenMBeanParameterInfoSupportTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); legalModels = new String[]{"JDMK", "JMX", "JAVA"}; legalColors = new String[]{"black", "white", "red", "green", "blue"}; legalSizes = new String[]{"S", "M", "L", "XL", "XXL"}; minPrice = 9.00f; maxPrice = 19.99f; priceParamInfo = new OpenMBeanParameterInfoSupport("price", "Valid product price", SimpleType.FLOAT, new Float(10.00), // default price new Float(minPrice), // Min legal value for price new Float(maxPrice)); // Max legal value for price } protected void tearDown() throws Exception { super.tearDown(); } public void testEquals() { try { OpenMBeanParameterInfoSupport infoSupport = new OpenMBeanParameterInfoSupport("test", "hello world", SimpleType.STRING, "black", legalColors); OpenMBeanParameterInfoSupport equalInfoSupport = new OpenMBeanParameterInfoSupport("test", "hello world", SimpleType.STRING, "black", legalColors); OpenMBeanParameterInfoSupport info2Support = new OpenMBeanParameterInfoSupport("test2", "hello world2", SimpleType.STRING); OpenMBeanParameterInfoSupport priceParamInfo2 = new OpenMBeanParameterInfoSupport("price", "Valid product price", SimpleType.FLOAT, new Float(10.00), // default price new Float(minPrice), // Min legal value for price new Float(maxPrice)); // Max legal value for price // test we can equal null values assertTrue(!(infoSupport.equals(info2Support))); assertTrue(infoSupport.equals(equalInfoSupport)); assertTrue(equalInfoSupport.equals(infoSupport)); assertTrue(priceParamInfo.equals(priceParamInfo2)); OpenMBeanParameterInfo rebootcmd = new OpenMBeanParameterInfoSupport("reboot", "Reboot the server", SimpleType.INTEGER); OpenMBeanParameterInfo rebootquery = new OpenMBeanParameterInfoSupport("reboot", "Reboot the server", SimpleType.BOOLEAN); assertFalse("activeclients.equals(reboot)", rebootcmd.equals(rebootquery)); } catch (OpenDataException e) { e.printStackTrace(); } } public void testDefaultSerialization() { int expectedHash = priceParamInfo.hashCode(); Serializer serializer = new Serializer(); try { byte[] data = serializer.serialize(priceParamInfo); Object obj = serializer.deserialize(data); // assert instanceof assertTrue(obj instanceof OpenMBeanParameterInfo); // if instanceof passes continue otherwise we will not get to the rest OpenMBeanParameterInfo type = (OpenMBeanParameterInfo)obj; // assert hashcodes are equal assertEquals(type.hashCode(), expectedHash); assertTrue(type.equals(priceParamInfo)); assertTrue(priceParamInfo.equals(type)); } catch (Exception e) { e.printStackTrace(); } } public void testBasicCtor() { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("currency") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("monetary currency") == 0); assertTrue("Unexpected open type", info.getOpenType().equals(SimpleType.STRING)); assertFalse("Shouldn't have default value", info.hasDefaultValue()); assertFalse("Shouldn't have legal values", info.hasLegalValues()); assertFalse("Shouldn't have a min value", info.hasMinValue()); assertFalse("Shouldn't have a max value", info.hasMaxValue()); } public void testBasicCtorNullName() { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport(null, "monetary currency", SimpleType.STRING); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testBasicCtorEmptyName() { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("", "monetary currency", SimpleType.STRING); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testBasicCtorNullDescription() { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", null, SimpleType.STRING); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testBasicCtorEmptyDescription() { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "", SimpleType.STRING); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testBasicCtorNullOpenType() { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testDefaultValueCtor() throws Exception { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro"); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("currency") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("monetary currency") == 0); assertTrue("Unexpected open type", info.getOpenType().equals(SimpleType.STRING)); assertTrue("Should have default value", info.hasDefaultValue()); assertTrue("Unexpected default value", ((String)info.getDefaultValue()).compareTo("Euro") == 0); assertFalse("Shouldn't have legal values", info.hasLegalValues()); assertFalse("Shouldn't have a min value", info.hasMinValue()); assertFalse("Shouldn't have a max value", info.hasMaxValue()); } public void testDefaultValueCtorInvalidType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, new Float(0.42)); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testDefaultValueCtorArrayType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", new ArrayType(1, SimpleType.STRING), null); assertTrue("Null info constructed", info != null); info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", new ArrayType(1, SimpleType.STRING), "Euro"); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testLegalValueCtor() throws Exception { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro", new String[]{"Dollar", "Euro", "Yen"}); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("currency") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("monetary currency") == 0); assertTrue("Unexpected open type", info.getOpenType().equals(SimpleType.STRING)); assertTrue("Should have default value", info.hasDefaultValue()); assertTrue("Unexpected default value", ((String)info.getDefaultValue()).compareTo("Euro") == 0); assertTrue("Should have legal values", info.getLegalValues() != null && info.getLegalValues().size() == 3); assertFalse("Shouldn't have a min value", info.hasMinValue()); assertFalse("Shouldn't have a max value", info.hasMaxValue()); } public void testLegalValueCtorInvalidType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro", new Object[]{"Dollar", "Euro", new Float(0.88)}); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testLegalValueCtorArrayType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", new ArrayType(1, SimpleType.STRING), null, new String[]{"Dollar", "Euro", "Yen"}); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testLegalValueCtorBogusDefaultValue() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Pound", new String[]{"Dollar", "Euro", "Yen"}); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testMinMaxValueCtor() throws Exception { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.00), new Float(0.75), new Float(1.50)); assertTrue("Null info constructed", info != null); assertTrue("Unexpected name", info.getName().compareTo("price") == 0); assertTrue("Unexpected description", info.getDescription().compareTo("how much it costs") == 0); assertTrue("Unexpected open type", info.getOpenType().equals(SimpleType.FLOAT)); assertTrue("Should have default value", info.hasDefaultValue()); assertTrue("Unexpected default value", ((Float)info.getDefaultValue()).equals(new Float(1.00))); assertFalse("Shouldn't have legal values", info.hasLegalValues()); assertTrue("Should have a min value of 0.75", info.hasMinValue() && ((Float)info.getMinValue()).equals(new Float(0.75))); assertTrue("Should have a max value of 1.50", info.hasMaxValue() && ((Float)info.getMaxValue()).equals(new Float(1.50))); } public void testMinMaxValueCtorInvalidMinType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.00), "0.75", new Float(1.50)); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testMinMaxValueCtorInvalidMaxType() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.00), new Float(0.75), "1.50"); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testMinMaxValueCtorMinGTMax() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.00), new Float(1.50), new Float(0.75)); fail("Expecting OpenDataException"); } catch (OpenDataException x) { assertTrue(true); } } public void testMinMaxValueCtorDefaultOutOfRange() throws Exception { try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(0.75), new Float(1.00), new Float(1.50)); fail("Expecting OpenDataException default < min"); } catch (OpenDataException x) { assertTrue(true); } try { OpenMBeanParameterInfoSupport info = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.50), new Float(0.75), new Float(1.00)); fail("Expecting OpenDataException default > max"); } catch (OpenDataException x) { assertTrue(true); } } public void testBasicHashCode() throws Exception { OpenMBeanParameterInfoSupport infoone = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING); assertTrue("Unexpected basic hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanParameterInfoSupport infotwo = new OpenMBeanParameterInfoSupport("currency", "legal tender", SimpleType.STRING); assertTrue("Expecting hash codes to be equal", infotwo.hashCode() == infoone.hashCode()); } public void testDefaultValueHashCode() throws Exception { OpenMBeanParameterInfoSupport infoone = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro"); assertTrue("Unexpected default value hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanParameterInfoSupport infotwo = new OpenMBeanParameterInfoSupport("currency", "legal tender", SimpleType.STRING, "Euro"); assertTrue("Unexpected default value hash code", infotwo.hashCode() == infoone.hashCode()); } public void testLegalValueHashCode() throws Exception { OpenMBeanParameterInfoSupport infoone = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro", new String[]{"Dollar", "Euro", "Yen"}); assertTrue("Unexpected legal value hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanParameterInfoSupport infotwo = new OpenMBeanParameterInfoSupport("currency", "monetary currency", SimpleType.STRING, "Euro", new String[]{"Dollar", "Euro", "Yen"}); assertTrue("Unexpected legal value hash code", infoone.hashCode() == hashCode(infotwo)); } public void testMinMaxHashCode() throws Exception { OpenMBeanParameterInfoSupport infoone = new OpenMBeanParameterInfoSupport("price", "how much it costs", SimpleType.FLOAT, new Float(1.00), new Float(0.75), new Float(1.50)); assertTrue("Unexpected minmax hash code", infoone.hashCode() == hashCode(infoone)); OpenMBeanParameterInfoSupport infotwo = new OpenMBeanParameterInfoSupport("price", "retail", SimpleType.FLOAT, new Float(1.00), new Float(0.75), new Float(1.50)); assertTrue("Unexpected minmax hash code", infotwo.hashCode() == infoone.hashCode()); } private int hashCode(OpenMBeanParameterInfo info) { int result = info.getName().hashCode(); result += info.getOpenType().hashCode(); result += (info.hasDefaultValue() == false) ? 0 : info.getDefaultValue().hashCode(); result += (info.hasLegalValues() == false) ? 0 : hashCode(info.getLegalValues()); result += (info.hasMinValue() == false) ? 0 : info.getMinValue().hashCode(); result += (info.hasMaxValue() == false) ? 0 : info.getMaxValue().hashCode(); return result; } private int hashCode(Set legalvalues) { int result = 0; Iterator i = legalvalues.iterator(); while (i.hasNext()) { Object v = i.next(); result += v.hashCode(); } return result; } } mx4j-3.0.2/src/test/test/javax/management/openmbean/SimpleTypeTest.java100644 0 0 4764 10513545721 23257 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; /** * @version $Revision: 1.6 $ */ import java.util.HashMap; import java.util.Map; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import junit.framework.TestCase; public class SimpleTypeTest extends TestCase { public SimpleTypeTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testIsValue() { OpenType type = SimpleType.BOOLEAN; OpenType type2 = SimpleType.INTEGER; assertTrue(type.isValue(new Boolean(true))); assertTrue(!(type.isValue(new Integer(0)))); } public void testEquals() { OpenType type = SimpleType.BOOLEAN; OpenType type2 = SimpleType.BOOLEAN; OpenType type3 = SimpleType.OBJECTNAME; OpenType type4 = SimpleType.DATE; assertTrue(type.equals(type2)); // test the reverse assertTrue(type2.equals(type)); assertTrue(!(type.equals(type3))); assertTrue(!(type.equals(type4))); // test reverse assertTrue(!(type3.equals(type))); assertTrue(!(type4.equals(type))); assertTrue(type4.equals(SimpleType.DATE)); } public void testHashCode() { Map m = new HashMap(); // these objects are immutable hence the instances must be the same, equal, with an equal hashCode OpenType type = SimpleType.CHARACTER; OpenType type2 = SimpleType.CHARACTER; OpenType type3 = SimpleType.OBJECTNAME; m.put(type, "java.lang.Character"); String value = (String)m.get(type2); assertEquals(value, "java.lang.Character"); assertEquals(type.hashCode(), type2.hashCode()); assertTrue(type.hashCode() != type3.hashCode()); } public void testTypeNameDescriptionClassNameAllEqual() { OpenType type = SimpleType.BIGINTEGER; String typeName = type.getTypeName(); String description = type.getDescription(); String className = type.getClassName(); assertTrue(typeName.equals(description)); assertTrue(typeName.equals(className)); assertTrue(className.equals(description)); assertEquals(typeName, "java.math.BigInteger"); } } mx4j-3.0.2/src/test/test/javax/management/openmbean/TabularDataSupportTest.java100644 0 0 25541 10513545721 24761 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Collection; import java.util.Set; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import junit.framework.TestCase; /** * @version $Revision: 1.10 $ */ public class TabularDataSupportTest extends TestCase { private String[] itemNames = null; private String[] itemDescriptions = null; private OpenType[] itemTypes; private String[] indexNames; private CompositeType tShirtType; private TabularType allTShirtTypes; private TabularDataSupport tabularSupport; private CompositeData compositeData; public TabularDataSupportTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); itemNames = new String[]{"model", "color", "size", "price"}; itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; indexNames = new String[]{"model", "color", "size"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); allTShirtTypes = new TabularType("tShirts", "List of available TShirts", tShirtType, // row type indexNames); Object[] itemValues = new Object[]{"MX4J", "red", "L", new Float(15.0f)}; compositeData = new CompositeDataSupport(tShirtType, itemNames, itemValues); // takes tabular type tabularSupport = new TabularDataSupport(allTShirtTypes); } protected void tearDown() throws Exception { super.tearDown(); } public void testCreation() { TabularDataSupport tabularData2 = new TabularDataSupport(allTShirtTypes); assertTrue(tabularData2 != null); } public void testPut() { try { tabularSupport.put(compositeData); assertTrue("tabularSupport doesn't contain compositeData", tabularSupport.containsValue(compositeData)); } catch (Exception e) { e.printStackTrace(); } } public void testPutAll() throws Exception { CompositeData snmpshirt = new CompositeDataSupport(tShirtType, itemNames, new Object[]{"SNMP", "green", null, new Float(15.0f)}); CompositeData[] shirts = {compositeData, snmpshirt}; tabularSupport.putAll(shirts); assertTrue("tabularSupport doesn't contain compositeData", tabularSupport.containsValue(compositeData)); assertTrue("tabularSupport doesn't contain snmpshirt", tabularSupport.containsValue(snmpshirt)); } public void testRemove() throws Exception { CompositeData snmpshirt = new CompositeDataSupport(tShirtType, itemNames, new Object[]{"SNMP", "green", null, new Float(15.0f)}); CompositeData[] shirts = {compositeData, snmpshirt}; tabularSupport.putAll(shirts); CompositeData oldshirt = tabularSupport.remove(new Object[]{"SNMP", "green", null}); assertFalse("oldshirt is null", oldshirt == null); assertTrue("Expecting oldshirt equals snmpshirt", snmpshirt.equals(oldshirt)); } public void testGetTabularType() { TabularType toVerify = tabularSupport.getTabularType(); assertEquals(toVerify, allTShirtTypes); } public void testCalculateIndex() { // returns an array of the indexNames as represented by the simpleTypes(itemTypes) ie returns the values for the index names which are the simpleTypes Object[] object = tabularSupport.calculateIndex(compositeData); assertTrue(object.length == indexNames.length); } public void testContainsValue() { OpenType[] keyTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}; tabularSupport.put(compositeData); boolean expected = tabularSupport.containsValue(compositeData); assertTrue(expected); } public void testContainsValueMissingValue() throws Exception { CompositeData snmpshirt = new CompositeDataSupport(tShirtType, itemNames, new Object[]{"SNMP", "green", "M", new Float(15.0f)}); tabularSupport.put(compositeData); tabularSupport.put(snmpshirt); assertTrue("Should contain MX4J and SNMP shirts", tabularSupport.containsValue(compositeData) && tabularSupport.containsValue(snmpshirt)); CompositeData jmxshirt = new CompositeDataSupport(tShirtType, itemNames, new Object[]{"JMX", "blue", "M", new Float(15.0f)}); assertFalse("Contains JMX shirt", tabularSupport.containsValue(jmxshirt)); CompositeData bogusshirt = new CompositeDataSupport(tShirtType, itemNames, new Object[]{"Bogus", null, "M", new Float(15.0f)}); assertFalse("Contains Bogus shirt", tabularSupport.containsValue(bogusshirt)); } public void testContainsValueNullValue() throws Exception { assertFalse("Contains 'null'", tabularSupport.containsValue(null)); } public void testKeySet() { tabularSupport.put(compositeData); Set set = tabularSupport.keySet(); assertTrue(set.size() == 1); } public void testValues() { tabularSupport.put(compositeData); Collection values = tabularSupport.values(); assertTrue(values.contains(compositeData)); } public void testEquals() throws Exception { assertFalse("Equal to 'null'", tabularSupport.equals(null)); assertFalse("Equal to Non-TabularData", tabularSupport.equals(new Integer(42))); String[] items = {"model", "color", "size", "price"}; String[] usdescriptions = { "Manufacturer's model name", "The shirt's color", "How big is it", "How much does it cost (dollars)"}; String[] eurodescriptions = { "Designer's model name", "The hue of the garment", "Garment size", "How much does it cost (euros)"}; OpenType[] types = { SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; String[] indices = {"model", "color", "size"}; CompositeType usst = new CompositeType("tShirt", "US Shirt", items, usdescriptions, types); CompositeType eurost = new CompositeType("tShirt", "European Shirt", items, usdescriptions, types); TabularType usstt = new TabularType("tShirts", "List of available US Shirts", usst, indices); TabularType eurostt = new TabularType("tShirts", "List of available European Shirts", eurost, indices); TabularData ussdata = new TabularDataSupport(usstt); TabularData eurosdata = new TabularDataSupport(eurostt); assertTrue("Expecting equality for tabular shirt data", ussdata.equals(eurosdata)); assertTrue("Expecting equal hash codes for equal data", eurosdata.hashCode() == ussdata.hashCode()); OpenType[] txtypes = { SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.DOUBLE}; CompositeType txst = new CompositeType("tShirt", "Texas Shirt", items, usdescriptions, txtypes); TabularType txstt = new TabularType("tShirts", "List of available Texas Shirts", txst, indices); TabularData txsdata = new TabularDataSupport(txstt); assertFalse("Texas shirt equals US shirt", ussdata.equals(txsdata)); CompositeData ussnmpshirt = new CompositeDataSupport(usst, items, new Object[]{"SNMP", "green", "M", new Float(15.0f)}); CompositeData usjmxshirt = new CompositeDataSupport(usst, items, new Object[]{"JMX", "blue", "M", new Float(15.0f)}); ussdata.put(ussnmpshirt); ussdata.put(usjmxshirt); CompositeData eurosnmpshirt = new CompositeDataSupport(usst, items, new Object[]{"SNMP", "green", "M", new Float(15.0f)}); CompositeData eurojmxshirt = new CompositeDataSupport(usst, items, new Object[]{"JMX", "blue", "M", new Float(15.0f)}); eurosdata.put(eurosnmpshirt); eurosdata.put(eurojmxshirt); assertTrue("Expecting US and Euro shirt data to be equal", ussdata.equals(eurosdata)); assertTrue("Expecting US and Euro shirt data hash codes to be equal", eurosdata.hashCode() == ussdata.hashCode()); int ushashcode = ussdata.getTabularType().hashCode(); ushashcode += ussnmpshirt.hashCode(); ushashcode += usjmxshirt.hashCode(); assertTrue("Unexpected hash code computation", ussdata.hashCode() == ushashcode); } } mx4j-3.0.2/src/test/test/javax/management/openmbean/TabularTypeTest.java100644 0 0 22523 10513545721 23431 0ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.openmbean; import java.util.Arrays; import java.util.HashSet; import java.util.List; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularType; import test.MX4JTestCase; /** * @version $Revision: 1.8 $ */ public class TabularTypeTest extends MX4JTestCase { private String[] itemNames = null; private String[] itemDescriptions = null; private OpenType[] itemTypes; private String[] indexNames; private CompositeType tShirtType; private CompositeType wine; private TabularType allTShirtTypes; public TabularTypeTest(String s) { super(s); } protected void setUp() throws Exception { itemNames = new String[]{"model", "color", "size", "price"}; itemDescriptions = new String[]{"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; itemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; indexNames = new String[]{"model", "color", "size"}; tShirtType = new CompositeType("tShirt", "a TShirt", itemNames, itemDescriptions, itemTypes); allTShirtTypes = new TabularType("tShirts", "List of available TShirts", tShirtType, indexNames); wine = new CompositeType("Wine", "Nectar of the gods", new String[]{"Type", "Winery", "Vintage"}, new String[]{ "Red, White, Rose, etc.", "The wine's producer", "The year the wine was made"}, new OpenType[]{ SimpleType.STRING, SimpleType.STRING, SimpleType.INTEGER}); } public void testEquals() throws Exception { String[] itemNames2 = {"model", "color", "size", "price"}; String[] itemDescriptions2 = {"Manufacturer's model name", "The shirt's color", "How big is it", "How much does it cost"}; OpenType[] itemTypes2 = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; String[] indexNames2 = {"model", "color", "size"}; CompositeType tShirtType2 = new CompositeType("tShirt", "a TShirt", itemNames2, itemDescriptions2, itemTypes2); TabularType allTShirtTypes2 = new TabularType("tShirts", "List of available TShirts", tShirtType2, indexNames2); assertTrue(allTShirtTypes.equals(allTShirtTypes2)); // assert reverse assertTrue(allTShirtTypes2.equals(allTShirtTypes)); } public void testNotEqual() throws Exception { String[] itemNames3 = {"model3", "color3", "size3", "price3"}; String[] itemDescriptions3 = {"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; OpenType[] itemTypes3 = {SimpleType.STRING, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.FLOAT}; String[] indexNames3 = {"model3", "color3", "size3"}; CompositeType tShirtType3 = new CompositeType("tShirt3", "a TShirt", itemNames3, itemDescriptions3, itemTypes3); TabularType allTShirtTypes3 = new TabularType("tShirts3", "List of available TShirts", tShirtType3, indexNames3); assertFalse(allTShirtTypes.equals(allTShirtTypes3)); } public void testGetRowType() { CompositeType test = allTShirtTypes.getRowType(); assertEquals(test, tShirtType); } public void testGetIndexNames() { List temp = allTShirtTypes.getIndexNames(); String[] tempList = (String[])temp.toArray(new String[temp.size()]); assertEquals(tempList.length, indexNames.length); // assert all elements are the same for (int i = 0; i < tempList.length; i++) { assertTrue(tempList[i] == indexNames[i]); } } public void testHashCode() throws Exception { String[] itemNames2 = {"model", "color", "size", "price"}; String[] itemDescriptions2 = {"Manufacturer's model name", "The shirt's color", "How big is it", "How much does it cost"}; OpenType[] itemTypes2 = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.FLOAT}; String[] indexNames2 = {"model", "color", "size"}; CompositeType tShirtType2 = new CompositeType("tShirt", "a TShirt", itemNames2, itemDescriptions2, itemTypes2); TabularType allTShirtTypes2 = new TabularType("tShirts", "List of available TShirts", tShirtType2, indexNames2); String[] itemNames3 = {"model3", "color3", "size3", "price3"}; String[] itemDescriptions3 = {"TShirt's model name", "TShirt's color", "TShirt's size", "TShirt's price"}; OpenType[] itemTypes3 = {SimpleType.STRING, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.FLOAT}; String[] indexNames3 = {"model3", "color3", "size3"}; CompositeType tShirtType3 = new CompositeType("tShirt3", "a TShirt", itemNames3, itemDescriptions3, itemTypes3); TabularType allTShirtTypes3 = new TabularType("tShirts3", "List of available TShirts", tShirtType3, indexNames3); int code1 = allTShirtTypes.hashCode(); int code2 = allTShirtTypes2.hashCode(); assertEquals(code2, "tShirts".hashCode() + tShirtType2.hashCode() + (new HashSet(Arrays.asList(indexNames))).hashCode()); int code3 = allTShirtTypes3.hashCode(); assertEquals(code1, code2); assertTrue(code1 != code3); } public void testCtor() throws Exception { TabularType winecatalog = new TabularType("Wine Catalog", "Catalog of available wines", wine, new String[]{"Winery", "Vintage"}); assertTrue("Unexpected name", winecatalog.getTypeName().compareTo("Wine Catalog") == 0); assertTrue("Unexpected CompositeType", winecatalog.getRowType().equals(wine)); List index = winecatalog.getIndexNames(); assertTrue("Incorrect index size", index.size() == 2); assertTrue("Unexpected index entries", ((String)index.get(0)).compareTo("Winery") == 0 && ((String)index.get(1)).compareTo("Vintage") == 0); } public void testCtorNullName() throws Exception { try { new TabularType(null, "Catalog of available wines", wine, new String[]{"Winery", "Vintage"}); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorEmptyName() throws Exception { try { new TabularType("", "Catalog of available wines", wine, new String[]{"Winery", "Vintage"}); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorNullDescriptor() throws Exception { try { new TabularType("Wine Catalog", null, wine, new String[]{"Winery", "Vintage"}); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorEmptyDescriptor() throws Exception { try { new TabularType("Wine Catalog", "", wine, new String[]{"Winery", "Vintage"}); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorNullRowType() throws Exception { try { new TabularType("Wine Catalog", "Catalog of available wines", null, new String[]{"Winery", "Vintage"}); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorNullIndex() throws Exception { try { new TabularType("Wine Catalog", "Catalog of available wines", wine, null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorEmptyIndex() throws Exception { try { new TabularType("Wine Catalog", "Catalog of available wines", wine, new String[0]); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { } } public void testCtorBogusIndex() throws Exception { try { new TabularType("Wine Catalog", "Catalog of available wines", wine, new String[]{"Region", "Vintage"}); fail("Expecting OpenDataException"); } catch (OpenDataException x) { } } } mx4j-3.0.2/src/test/test/javax/management/relation/RelationServiceTest.java100644 0 0 64422 10513545721 24150 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; // Java imports import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.relation.RelationService; import javax.management.relation.RelationTypeNotFoundException; import javax.management.relation.RelationTypeSupport; import javax.management.relation.Role; import javax.management.relation.RoleInfo; import javax.management.relation.RoleList; import javax.management.relation.RoleResult; import javax.management.relation.RoleStatus; import junit.framework.TestCase; /** * @version $Revision: 1.18 $ */ public class RelationServiceTest extends TestCase { private MBeanServer m_server = null; private ObjectName m_relationServiceObjectName = null; private RelationService m_relationService; // convenience MBean ObjectNames ObjectName mbeanObjectName1; ObjectName mbeanObjectName2; ObjectName mbeanObjectName3; ObjectName mbeanObjectName4; ObjectName mbeanObjectName5; ObjectName mbeanObjectName6; public RelationServiceTest(String s) { super(s); } protected void setUp() { m_server = MBeanServerFactory.createMBeanServer(); // create and register relation service try { m_relationServiceObjectName = new ObjectName("DefaultDomain:type=javax.management.relation.RelationService"); } catch (Exception ex) { ex.printStackTrace(); } } public void tearDown() throws Exception { m_server.unregisterMBean(m_relationServiceObjectName); MBeanServerFactory.releaseMBeanServer(m_server); } public void testIsActive() { try { registerRelationService(true); m_relationService.isActive(); } catch (Exception e) { fail("Relation Service should be active"); } } public void testGetFalsePurgeFlag() throws Exception { registerRelationService(false); assertTrue(m_relationService.getPurgeFlag() == false); } public void testGetTruePurgeFlag() throws Exception { registerRelationService(true); assertTrue(m_relationService.getPurgeFlag()); } public void testCreateRelationType() { try { registerRelationService(true); RoleInfo[] roleInfos = createRoleInfos("contained", "container"); m_relationService.createRelationType("relationTypeName1", roleInfos); // create one relation type expect 1 returned from call getAllRelationTypeNames assertTrue(m_relationService.getAllRelationTypeNames().size() == 1); assertEquals("relationTypeName1", m_relationService.getAllRelationTypeNames().get(0)); } catch (Exception e) { fail("Valid call to createRelationType"); } } public void testAddRelationType() { try { registerRelationService(true); String relationTypeName = "RelationTypeUnitTest"; m_relationService.addRelationType(new SimpleRelationType(relationTypeName)); assertTrue(m_relationService.getAllRelationTypeNames().size() == 1); assertEquals(relationTypeName, m_relationService.getAllRelationTypeNames().get(0)); } catch (Exception e) { fail("Valid call to createRelationType"); } } public void testGetAllRelationTypeNames() throws Exception { registerRelationService(true); String relationTypeName1 = "TestRelation1"; String relationTypeName2 = "TestRelation2"; String relationTypeName3 = "TestRelation3"; String relationTypeName4 = "TestRelation4"; m_relationService.addRelationType(new SimpleRelationType(relationTypeName1)); m_relationService.addRelationType(new SimpleRelationType(relationTypeName2)); m_relationService.addRelationType(new SimpleRelationType(relationTypeName3)); m_relationService.addRelationType(new SimpleRelationType(relationTypeName4)); assertTrue(m_relationService.getAllRelationTypeNames().size() == 4); } public void testDuplicateRelationTypeNameThrowsException() throws Exception { registerRelationService(true); String relationTypeName1 = "TestRelation1"; String relationTypeName2 = "TestRelation1"; try { m_relationService.addRelationType(new SimpleRelationType(relationTypeName1)); } catch (Exception e) { fail("first one should be ok as no duplicates"); } try { m_relationService.addRelationType(new SimpleRelationType(relationTypeName2)); fail("Should have had an exception"); } catch (Exception expected) { // should be an exception 2 relationTypeNames the same!! } } public void testGetRoleInfos() throws Exception { registerRelationService(true); registerMBeans(); m_relationService.createRelationType("aRelationTypeName", createRoleInfos("mother", "child")); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "mother", roleList); createRoleList(mbeanObjectName2, "child", roleList); m_relationService.createRelation("relationId1", "aRelationTypeName", roleList); List l = m_relationService.getRoleInfos("aRelationTypeName"); assertTrue(l.size() == 2); } public void testRemoveRelationType() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); m_relationService.createRelationType("testValidRelationTypeNameRemoval", createRoleInfos("car", "owner")); m_relationService.createRelation("relationID", "testValidRelationTypeNameRemoval", roleList); try { m_relationService.removeRelationType("testValidRelationTypeNameRemoval"); } catch (Exception e) { fail("No exception expected as relationType registered and valid"); } assertTrue(m_relationService.getAllRelationTypeNames().size() == 0); } public void testRemoveRelationType_NonExistent() throws Exception { registerRelationService(true); try { m_relationService.removeRelationType("invalidRelationType_notCreated"); fail("Expected a RelationTypeNotFoundException to be thrown"); } catch (RelationTypeNotFoundException expected) { // ok } catch (Exception e) { fail("Wrong exception this was not expected"); } } public void testAddRelationMBeanNotRegistered() throws Exception { registerRelationService(true); ObjectName mbeanObjectName = new ObjectName("domain:name=testMbeanNotRegistered"); try { m_relationService.addRelation(mbeanObjectName); fail("MBean not registered should throw an exception"); } catch (InstanceNotFoundException expected) { //ok exception expected } catch (Exception e) { fail("not expected"); } } /** * Call RelationService.addService passing an object name * of a Relation with a set of roles. *

* Call RelationService.addService passing an object name * of another relation with a different set of roles. *

* Call RelationService.getAllRoles passing the relation id of * the second relation added. *

* You will see that the roles returned are actually those of * the first relation added. * * @throws Exception */ public void testAddRelation_correctRolesReturned() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); SimpleRelationTestSupport relationSupport = new SimpleRelationTestSupport("relationID", m_relationServiceObjectName, "relationTypeName", roleList); m_server.registerMBean(relationSupport, relationSupportObjectName); /* create the relationType */ m_relationService.createRelationType("relationTypeName", createRoleInfos("car", "owner")); /* now add the relation */ m_relationService.addRelation(relationSupportObjectName); //////////////////////////////////////////////////////////////////////////////////////////////// RoleList roleList1 = new RoleList(); createRoleList(mbeanObjectName3, "parent", roleList1); createRoleList(mbeanObjectName4, "child", roleList1); ObjectName relationSupportObjectName2 = new ObjectName("relationDomain:name=aRelationSupport2"); SimpleRelationTestSupport relationSupport2 = new SimpleRelationTestSupport("relationID2", m_relationServiceObjectName, "relationTypeName2", roleList1); m_server.registerMBean(relationSupport2, relationSupportObjectName2); m_relationService.createRelationType("relationTypeName2", createRoleInfos("parent", "child")); m_relationService.addRelation(relationSupportObjectName2); ///////////////// validate querying roles for relationId2(added second) returns the correct roles //////////////////////////////// RoleResult result1 = m_relationService.getAllRoles("relationID2"); RoleList actual1 = result1.getRoles(); // we have to do this as role does not have an equals or hashcode, must check if it is added it will break compatibility!!!! final Role role = (Role)roleList1.get(0); boolean success = false; for (Iterator iterator = actual1.iterator(); iterator.hasNext();) { Role role1 = (Role)iterator.next(); String roleName = role1.getRoleName(); if (roleName.equals(role.getRoleName())) success = true; } assertTrue(success); ///////////////////// validate querying roles for relaionID (added first) returns the expected roles /////////////////////////////// RoleResult result = m_relationService.getAllRoles("relationID"); RoleList actual = result.getRoles(); final Role role2 = (Role)roleList.get(0); boolean success2 = false; for (Iterator iterator = actual.iterator(); iterator.hasNext();) { Role role1 = (Role)iterator.next(); String roleName = role1.getRoleName(); if (roleName.equals(role2.getRoleName())) success2 = true; } assertTrue(success2); //assertTrue(roleList.contains(actual.get(0))); } public void testAddRelation() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); SimpleRelationTestSupport relationSupport = new SimpleRelationTestSupport("relationID", m_relationServiceObjectName, "relationTypeName", roleList); m_server.registerMBean(relationSupport, relationSupportObjectName); /* create the relationType */ m_relationService.createRelationType("relationTypeName", createRoleInfos("car", "owner")); try { /* now add the relation */ m_relationService.addRelation(relationSupportObjectName); } catch (Exception e) { e.printStackTrace(); } } public void testGetRoleInfo() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); SimpleRelationTestSupport relationSupport = new SimpleRelationTestSupport("relationID", m_relationServiceObjectName, "relationTypeName", roleList); m_server.registerMBean(relationSupport, relationSupportObjectName); RoleInfo[] roleInfos = createRoleInfos("car", "owner"); /* create the relationType */ m_relationService.createRelationType("relationTypeName", roleInfos); RoleInfo info = m_relationService.getRoleInfo("relationTypeName", "owner"); assertEquals(info, roleInfos[1]); } public void testIsRelationMBean() throws Exception { String relationID = "relationID"; try { ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); setUpRelationServiceForQueryTesting(relationID, relationSupportObjectName); assertTrue(m_relationService.isRelationMBean(relationID).equals(relationSupportObjectName)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use Options | File Templates. } } public void testIsRelation() { String relationID = "relationID"; try { ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); setUpRelationServiceForQueryTesting(relationID, relationSupportObjectName); assertTrue(m_relationService.isRelation(relationSupportObjectName).equals(relationID)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use Options | File Templates. } } public void testHasRelation() { String relationID = "relationID"; try { ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); setUpRelationServiceForQueryTesting(relationID, relationSupportObjectName); assertTrue((m_relationService.hasRelation(relationID)).booleanValue()); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use Options | File Templates. } } public void tesetGetAllRelationIds() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); /* create the relationType first then creaste the relation*/ m_relationService.createRelationType("relationTypeName1", createRoleInfos("car", "owner")); m_relationService.createRelationType("relationTypeName2", createRoleInfos("car", "owner")); m_relationService.createRelationType("relationTypeName3", createRoleInfos("car", "owner")); m_relationService.createRelation("relationID1", "relationTypeName1", roleList); m_relationService.createRelation("relationID2", "relationTypeName2", roleList); m_relationService.createRelation("relationID3", "relationTypeName3", roleList); List allIds = m_relationService.getAllRelationIds(); assertTrue(allIds.size() == 3); } public void testRoleReading0() throws Exception { registerRelationService(true); registerMBeans(); String relationTypeName = "relationTypeName"; m_relationService.addRelationType(new SimpleRelationType(relationTypeName)); Integer value = m_relationService.checkRoleReading("primary", relationTypeName); // role is a ok returns 0 assertEquals(value.intValue(), 0); } public void testRoleReading1() throws Exception { registerRelationService(true); registerMBeans(); String relationTypeName = "relationTypeName"; m_relationService.addRelationType(new SimpleRelationType(relationTypeName)); Integer value = m_relationService.checkRoleReading("book", relationTypeName); // RoleStatus.NO_ROLE_WITH_NAME = 1 assertEquals(value.intValue(), RoleStatus.NO_ROLE_WITH_NAME); } public void testRoleReading2() throws Exception { registerRelationService(true); registerMBeans(); String relationTypeName = "relationTypeName"; m_relationService.addRelationType(new TestRelationType(relationTypeName)); Integer value = m_relationService.checkRoleReading("primary", relationTypeName); // RoleStatus.ROLE_NOT_READABLE = 2 assertEquals(value.intValue(), RoleStatus.ROLE_NOT_READABLE); } public void testCreateRelation() throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); /* create the relationType first then creaste the relation*/ String relationTypeName = "relationTypeName"; RoleInfo[] roleInfos = createRoleInfos("car", "owner"); Object[] params1 = {relationTypeName, roleInfos}; String[] signature1 = {"java.lang.String", roleInfos.getClass().getName()}; m_server.invoke(m_relationServiceObjectName, "createRelationType", params1, signature1); String relationId = "relationId1"; Object[] params = {relationId, relationTypeName, roleList}; String[] signature = {"java.lang.String", "java.lang.String", "javax.management.relation.RoleList"}; m_server.invoke(m_relationServiceObjectName, "createRelation", params, signature); } private void setUpRelationServiceForQueryTesting(String relationID, ObjectName mbeanObjectName) throws Exception { registerRelationService(true); registerMBeans(); RoleList roleList = new RoleList(); createRoleList(mbeanObjectName1, "owner", roleList); createRoleList(mbeanObjectName2, "car", roleList); //ObjectName relationSupportObjectName = new ObjectName("relationDomain:name=aRelationSupport"); SimpleRelationTestSupport relationSupport = new SimpleRelationTestSupport(relationID, m_relationServiceObjectName, "relationTypeName", roleList); m_server.registerMBean(relationSupport, mbeanObjectName); /* create the relationType */ try { m_relationService.createRelationType("relationTypeName", createRoleInfos("car", "owner")); /* now add the relation */ m_relationService.addRelation(mbeanObjectName); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use Options | File Templates. } } private void registerMBeans() { try { // create and build 6 MBeans in the server to act as relations in the relationService String mbeanClassName = "test.javax.management.relation.SimpleStandard"; mbeanObjectName1 = new ObjectName("domain:type=SimpleStandard_1"); mbeanObjectName2 = new ObjectName("domain:type=SimpleStandard_2"); mbeanObjectName3 = new ObjectName("domain:type=SimpleStandard_3"); mbeanObjectName4 = new ObjectName("domain:type=SimpleStandard_4"); mbeanObjectName5 = new ObjectName("domain:type=SimpleStandard_5"); mbeanObjectName6 = new ObjectName("domain:type=SimpleStandard_6"); m_server.createMBean(mbeanClassName, mbeanObjectName1, null); m_server.createMBean(mbeanClassName, mbeanObjectName2, null); m_server.createMBean(mbeanClassName, mbeanObjectName3, null); m_server.createMBean(mbeanClassName, mbeanObjectName4, null); m_server.createMBean(mbeanClassName, mbeanObjectName5, null); m_server.createMBean(mbeanClassName, mbeanObjectName6, null); } catch (Exception e) { e.printStackTrace(); } } private void registerRelationService(boolean purge) throws Exception { m_relationService = new RelationService(purge); m_server.registerMBean(m_relationService, m_relationServiceObjectName); } private RoleInfo[] createRoleInfos(String roleName1, String roleName2) throws Exception { RoleInfo[] roleInfos = new RoleInfo[2]; roleInfos[0] = new RoleInfo(roleName1, "test.javax.management.relation.SimpleStandard", true, true, 1, -1, null); roleInfos[1] = new RoleInfo(roleName2, "test.javax.management.relation.SimpleStandard", true, true, 0, -1, null); return roleInfos; } private RoleList createRoleList(ObjectName mbeanObjectName, String roleName, RoleList roleList) { ArrayList roleValue = new ArrayList(); roleValue.add(mbeanObjectName); Role role = new Role(roleName, roleValue); roleList.add(role); return roleList; } class TestRelationType extends RelationTypeSupport { public TestRelationType(String relationTypeName) { super(relationTypeName); try { RoleInfo primaryRoleInfo = new RoleInfo("primary", "test.javax.management.relation.SimpleStandard", false, //read true, //write 2, 2, "Primary :)"); addRoleInfo(primaryRoleInfo); RoleInfo secondaryRoleInfo = new RoleInfo("secondary", "test.javax.management.relation.SimpleStandard", true, false, 2, 2, "Secondary"); addRoleInfo(secondaryRoleInfo); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } public void testSimpleRoleListCtor() throws Exception { registerRelationService(true); registerMBeans(); RoleList rl = new RoleList(); assertTrue("New RoleList isn't empty", rl.isEmpty()); rl = new RoleList(42); assertTrue("New RoleList(42) isn't empty", rl.isEmpty()); } public void testRoleListCopyCtor() throws Exception { registerRelationService(true); registerMBeans(); RoleList rl = new RoleList(); rl.add(new Role("romeo", new ArrayList())); rl.add(new Role("juliet", new ArrayList())); RoleList rlcopy = new RoleList(rl); assertTrue("Bogus copy", rl.equals(rlcopy)); try { new RoleList(null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException x) { assertTrue(true); } } public void testUpdateRoleMap() throws Exception { List roleValue = new ArrayList(); roleValue.add(new ObjectName("domain:type=SimpleStandard_2")); Role role = new Role("myTestRoleName", roleValue); String relationID = "myTestRelation"; setUpRelationServiceForQueryTesting(relationID, new ObjectName("domain:type=testType")); m_relationService.updateRoleMap("domain:type=SimpleStandard_1", role, new ArrayList()); Map result = m_relationService.getReferencedMBeans(relationID); assertTrue("The referenced mbeans are not as expected, 2 were added but only " + result.size() + " found", result.size() == 2); } public void testFindReferencingMBeans() throws Exception { //basic init... registerRelationService(true); registerMBeans(); //this is going to be our referenced bean ObjectName targetObjectName = mbeanObjectName1; //create constraint m_relationService.createRelationType("relationType1", createRoleInfos("roleName1", "roleName2")); RoleList roleList = new RoleList(); ArrayList values = new ArrayList(); values.add(targetObjectName); //our test target values.add(mbeanObjectName2); roleList.add(new Role("roleName1", values)); //create first referencing relation (to meanObjectName1); m_relationService.createRelation("relationID1", "relationType1", roleList); roleList = new RoleList(); values = new ArrayList(); values.add(targetObjectName); //our test target values.add(mbeanObjectName3); roleList.add(new Role("roleName1", values)); roleList.add(new Role("roleName2", values)); //create second referencing relation (to meanObjectName1); m_relationService.createRelation("relationID2", "relationType1", roleList); Map result = m_relationService.findReferencingRelations(targetObjectName, null, null); //our test target should have 2 references by now.... //dsamsonoff - under 575066 this would fail - map size would always return 1 assertTrue("The referencing mbeans are not as expected, 2 were added but only " + result.size() + " found", result.size() == 2); } } mx4j-3.0.2/src/test/test/javax/management/relation/RoleTest.java100644 0 0 2240 10513545721 21721 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; import java.util.ArrayList; import java.util.List; import javax.management.ObjectName; import javax.management.relation.Role; import junit.framework.TestCase; /** * @version $Revision: 1.4 $ */ public class RoleTest extends TestCase { private Role _role; public RoleTest(String name) { super(name); } protected void setUp() throws Exception { _role = new Role("test Role", new ArrayList()); } protected void tearDown() throws Exception { } public void testGetRoleValue() throws Exception { List roleValues = _role.getRoleValue(); assertNotNull(roleValues); } public void testGetRoleValue_ListHasElements() throws Exception { List values = new ArrayList(); values.add(new ObjectName("domain:name=test")); Role role = new Role("Test Role", values); assertEquals(1, role.getRoleValue().size()); } }mx4j-3.0.2/src/test/test/javax/management/relation/SimpleRelationTestSupport.java100644 0 0 1570 10513545721 25351 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; import javax.management.ObjectName; import javax.management.relation.InvalidRoleValueException; import javax.management.relation.RelationSupport; import javax.management.relation.RoleList; /** * @version $Revision: 1.7 $ */ public class SimpleRelationTestSupport extends RelationSupport { public SimpleRelationTestSupport(String relationId, ObjectName relationServiceName, String relationTypeName, RoleList roleList) throws InvalidRoleValueException, IllegalArgumentException { super(relationId, relationServiceName, relationTypeName, roleList); } } mx4j-3.0.2/src/test/test/javax/management/relation/SimpleRelationType.java100644 0 0 3225 10513545721 23755 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; import javax.management.relation.RelationTypeSupport; import javax.management.relation.RoleInfo; /** * @version $Revision: 1.5 $ */ public class SimpleRelationType extends RelationTypeSupport { public SimpleRelationType(String relationTypeName) { super(relationTypeName); try { RoleInfo primaryRoleInfo = new RoleInfo("primary", "test.javax.management.relation.SimpleStandard", true, //read true, //write 2, 2, "Primary :)"); addRoleInfo(primaryRoleInfo); RoleInfo secondaryRoleInfo = new RoleInfo("secondary", "test.javax.management.relation.SimpleStandard", true, false, 2, 2, "Secondary"); addRoleInfo(secondaryRoleInfo); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } mx4j-3.0.2/src/test/test/javax/management/relation/SimpleStandard.java100644 0 0 600 10513545721 23050 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; /** * @version $Revision: 1.6 $ */ public class SimpleStandard implements SimpleStandardMBean { } mx4j-3.0.2/src/test/test/javax/management/relation/SimpleStandardMBean.java100644 0 0 552 10513545721 23761 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.relation; /** * @version $Revision: 1.3 $ */ public interface SimpleStandardMBean { } mx4j-3.0.2/src/test/test/javax/management/remote/JMXConnectorFactoryTest.java100644 0 0 7111 10513545721 24341 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.net.MalformedURLException; import java.util.HashMap; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXProviderException; import javax.management.remote.JMXServiceURL; import test.MX4JTestCase; /** * @version $Revision: 1.9 $ */ public class JMXConnectorFactoryTest extends MX4JTestCase { public JMXConnectorFactoryTest(String s) { super(s); } public void testInvalidURLs() throws Exception { try { JMXConnectorFactory.connect(null); fail(); } catch (NullPointerException x) { } } public void testInvalidPackages() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); // Only Strings env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, new Object()); try { JMXConnectorFactory.newJMXConnector(url, env); fail("Only Strings can be specified as provider packages"); } catch (JMXProviderException x) { } // Empty not allowed env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, ""); try { JMXConnectorFactory.newJMXConnector(url, env); fail("Provider package string cannot be empty"); } catch (JMXProviderException x) { } // Empty not allowed env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "dummy| |dummy"); try { JMXConnectorFactory.newJMXConnector(url, env); fail("Provider package string cannot contain an empty string"); } catch (JMXProviderException x) { } } public void testInvalidProtocol() throws Exception { JMXServiceURL url = new JMXServiceURL("service:jmx:dummy://host"); try { JMXConnectorFactory.newJMXConnector(url, null); fail(); } catch (MalformedURLException x) { } } public void testInvalidClassLoader() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_CLASS_LOADER, new Object()); try { JMXConnectorFactory.newJMXConnector(url, env); fail(); } catch (IllegalArgumentException x) { } } public void testLoadProviderWithProvidedClassLoader() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); ClassLoader old = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader().getParent()); env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_CLASS_LOADER, getClass().getClassLoader()); JMXConnector connector = JMXConnectorFactory.newJMXConnector(url, env); assertNotNull(connector); } finally { Thread.currentThread().setContextClassLoader(old); } } public void testRMIProvider() throws Exception { JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); JMXConnector connector = JMXConnectorFactory.newJMXConnector(url, null); assertNotNull(connector); } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXConnectorInvocationTestCase.java100644 0 0 42351 10513545721 25664 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.io.IOException; import java.net.MalformedURLException; import java.security.AccessController; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.RuntimeMBeanException; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXPrincipal; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import test.MX4JTestCase; /** * @version $Revision: 1.7 $ */ public abstract class JMXConnectorInvocationTestCase extends MX4JTestCase { private JMXConnectorServer connectorServer; public JMXConnectorInvocationTestCase(String name) { super(name); } public abstract JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException; public abstract Map getEnvironment(); private MBeanServerConnection getMBeanServerConnection(MBeanServer server) throws IOException { JMXServiceURL url = createJMXConnectorServerAddress(); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); connectorServer.start(); sleep(5000); JMXConnector connector = JMXConnectorFactory.connect(connectorServer.getAddress(), getEnvironment()); return connector.getMBeanServerConnection(); } protected void tearDown() throws Exception { if (connectorServer != null) connectorServer.stop(); sleep(5000); } public void testCallToMBeanServerWithAttributeNotFoundException() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); try { // The attribute does not exist mbsc.getAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), "dummy"); fail(); } catch (AttributeNotFoundException e) { } } public void testCallToMBeanServerWithInstanceNotFoundException() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); try { // The mbean does not exist mbsc.getAttribute(new ObjectName(":type=dummy"), "ImplementationVersion"); fail(); } catch (InstanceNotFoundException x) { } } public void testCreateMBeanWith3Params() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); } public void testCreateMBeanWith5Params() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); String value = "mx4j"; ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null, new Object[]{value}, new String[]{String.class.getName()}); assertNotNull(instance); // Be sure the argument arrived to the MBean String result = (String)mbsc.getAttribute(name, "Name"); assertEquals(result, value); } public void testGetAttribute() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); String value = "mx4j"; ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null, new Object[]{value}, new String[]{String.class.getName()}); assertNotNull(instance); // Be sure the argument arrived to the MBean String result = (String)mbsc.getAttribute(name, "Name"); assertEquals(result, value); } public void testGetAttributes() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); String value = "mx4j"; ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null, new Object[]{value}, new String[]{String.class.getName()}); assertNotNull(instance); // Be sure the argument arrived to the MBean String attribute = "Name"; String[] attributes = new String[]{attribute}; AttributeList result = mbsc.getAttributes(name, attributes); assertNotNull(result); assertEquals(result.size(), attributes.length); assertEquals(((Attribute)result.get(0)).getName(), attribute); assertEquals(((Attribute)result.get(0)).getValue(), value); } public void testGetDefaultDomain() throws Exception { String domain = "DOMAIN"; MBeanServer server = MBeanServerFactory.newMBeanServer(domain); MBeanServerConnection mbsc = getMBeanServerConnection(server); String defaultDomain = mbsc.getDefaultDomain(); assertEquals(defaultDomain, domain); } public void testGetDomains() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); String[] domains = mbsc.getDomains(); if (domains.length < 1) fail(); } public void testGetMBeanCount() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); Integer count = mbsc.getMBeanCount(); if (count.intValue() < 1) fail(); } public void testGetMBeanInfo() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("JMImplementation", "type", "MBeanServerDelegate"); MBeanInfo info = mbsc.getMBeanInfo(name); assertNotNull(info); if (info.getAttributes().length < 1) fail(); } public void testGetObjectInstance() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); ObjectInstance result = mbsc.getObjectInstance(name); assertNotNull(result); assertEquals(result, instance); } public void testInvoke() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); String value = "value"; String result = (String)mbsc.invoke(name, "echo", new Object[]{value}, new String[]{String.class.getName()}); assertNotNull(result); assertEquals(result, value); } public void testInvokeThrowsCustomException() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); try { mbsc.invoke(name, "throwCustomException", null, null); } catch (MBeanException x) { Exception xx = x.getTargetException(); if (xx != null && xx.getClass() != SupportException.class) fail(); } } public void testInvokeThrowsRuntimeException() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); try { mbsc.invoke(name, "throwRuntimeException", null, null); } catch (RuntimeMBeanException x) { Exception xx = x.getTargetException(); if (xx != null && xx.getClass() != IllegalArgumentException.class) fail(); } } public void testIsInstanceOf() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); boolean isInstanceOf = mbsc.isInstanceOf(name, Support.class.getName()); if (!isInstanceOf) fail("Class"); isInstanceOf = mbsc.isInstanceOf(name, SupportMBean.class.getName()); if (!isInstanceOf) fail("Interface"); } public void testIsRegistered() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); boolean isRegistered = mbsc.isRegistered(name); if (!isRegistered) fail(); } public void testQueryMBeansNullNull() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); Set mbeans = mbsc.queryMBeans(null, null); assertNotNull(mbeans); if (mbeans.size() < 1) fail(); } public void testQueryMBeansObjectNameNull() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); Set mbeans = mbsc.queryMBeans(ObjectName.getInstance("JMImplementation:*"), null); assertNotNull(mbeans); if (mbeans.size() < 1) fail(); } public void testQueryMBeansObjectNameQueryExp() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); Set mbeans = mbsc.queryMBeans(ObjectName.getInstance("JMImplementation:*"), new ObjectName("*:type=MBeanServerDelegate")); assertNotNull(mbeans); if (mbeans.size() != 1) fail(); } public void testSetAttribute() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); String attribute = "Name"; String value = "mx4j"; mbsc.setAttribute(name, new Attribute(attribute, value)); String result = (String)mbsc.getAttribute(name, attribute); assertEquals(result, value); } public void testSetAttributes() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); String attribute = "Name"; String value = "mx4j"; AttributeList attributes = new AttributeList(); attributes.add(new Attribute(attribute, value)); AttributeList result = mbsc.setAttributes(name, attributes); assertNotNull(result); assertEquals(result, attributes); } public void testUnregisterMBean() throws Exception { MBeanServerConnection mbsc = getMBeanServerConnection(newMBeanServer()); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); mbsc.unregisterMBean(name); if (mbsc.isRegistered(name)) fail(); } public void testAuthenticatedInvoke() throws Exception { final String principalName = "authenticatedPrincipal"; JMXServiceURL url = createJMXConnectorServerAddress(); Map serverEnv = getEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { Set principals = new HashSet(); principals.add(new JMXPrincipal(principalName)); return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); } }); JMXConnectorServer cntorServer = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, newMBeanServer()); cntorServer.start(); Map clientEnv = getEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[0]); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); Boolean result = (Boolean)mbsc.invoke(name, "authenticated", new Object[]{principalName}, new String[]{String.class.getName()}); assertTrue(result.booleanValue()); } finally { if (cntorServer != null) cntorServer.stop(); } } public void testDelegatedInvoke() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); Map serverEnv = getEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { Set principals = new HashSet(); principals.add(new JMXPrincipal("authenticatedPrincipal")); return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); } }); JMXConnectorServer cntorServer = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, newMBeanServer()); cntorServer.start(); Map clientEnv = getEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[0]); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); Set principals = new HashSet(); String delegatedName = "delegatedPrincipal"; principals.add(new JMXPrincipal(delegatedName)); Subject delegate = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(delegate); ObjectName name = ObjectName.getInstance("", "test", "invocation"); ObjectInstance instance = mbsc.createMBean(Support.class.getName(), name, null); assertNotNull(instance); Boolean result = (Boolean)mbsc.invoke(name, "delegated", new Object[]{delegatedName}, new String[]{String.class.getName()}); assertTrue(result.booleanValue()); } finally { if (cntorServer != null) cntorServer.stop(); } } public static class SupportException extends Exception { } public interface SupportMBean { public String getName(); public void setName(String name); public void throwCustomException() throws SupportException; public void throwRuntimeException() throws IllegalArgumentException; public String echo(String argument); public boolean authenticated(String name); public boolean delegated(String name); } public static class Support implements SupportMBean { private String name; public Support() { } public Support(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void throwCustomException() throws SupportException { throw new SupportException(); } public void throwRuntimeException() throws IllegalArgumentException { throw new IllegalArgumentException(); } public String echo(String argument) { return argument; } public boolean authenticated(String name) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) return false; Set principals = subject.getPrincipals(); return principals.contains(new JMXPrincipal(name)); } public boolean delegated(String name) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null) return false; Set principals = subject.getPrincipals(); return principals.contains(new JMXPrincipal(name)); } } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXConnectorServerFactoryTest.java100644 0 0 6706 10513545721 25541 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.net.MalformedURLException; import java.util.HashMap; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXProviderException; import javax.management.remote.JMXServiceURL; import test.MX4JTestCase; /** * @version $Revision: 1.3 $ */ public class JMXConnectorServerFactoryTest extends MX4JTestCase { public JMXConnectorServerFactoryTest(String s) { super(s); } public void testInvalidURLs() throws Exception { try { JMXConnectorServerFactory.newJMXConnectorServer(null, null, null); fail(); } catch (NullPointerException x) { } } public void testInvalidPackages() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); // Only Strings env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES, new Object()); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail("Only Strings can be specified as provider packages"); } catch (JMXProviderException x) { } // Empty not allowed env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES, ""); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail("Provider package string cannot be empty"); } catch (JMXProviderException x) { } // Empty not allowed env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES, "dummy| |dummy"); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail("Provider package string cannot contain an empty string"); } catch (JMXProviderException x) { } } public void testInvalidProtocol() throws Exception { JMXServiceURL url = new JMXServiceURL("service:jmx:dummy://host"); try { JMXConnectorServerFactory.newJMXConnectorServer(url, null, null); fail(); } catch (MalformedURLException x) { } } public void testInvalidClassLoader() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER, new Object()); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail(); } catch (IllegalArgumentException x) { } } public void testLoadProviderWithProvidedClassLoader() throws Exception { HashMap env = new HashMap(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); env.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER, getClass().getClassLoader()); JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); } public void testRMIProvider() throws Exception { JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://host"); JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, null); assertNotNull(connector); } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXConnectorServerTestCase.java100644 0 0 17746 10513545721 25033 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.MBeanServerForwarder; import test.MX4JTestCase; /** * @version $Revision: 1.11 $ */ public abstract class JMXConnectorServerTestCase extends MX4JTestCase { public JMXConnectorServerTestCase(String name) { super(name); } public abstract JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException; public abstract Map getEnvironment(); public void testNewJMXConnectorServerWithNullURL() throws Exception { try { JMXConnectorServerFactory.newJMXConnectorServer(null, null, null); fail(); } catch (NullPointerException x) { } } public void testNewJMXConnectorServerWithFactory() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), null); if (server == null) fail(); } public void testStartWithoutMBeanServer() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), null); try { server.start(); fail(); } catch (IllegalStateException x) { } } public void testMBeanServerForwarderNoMBeanServer() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), null); MBeanServerForwarder forwarder = (MBeanServerForwarder)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{MBeanServerForwarder.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); try { server.setMBeanServerForwarder(forwarder); fail("No MBeanServer to forward to"); } catch (IllegalStateException x) { } } public void testMBeanServerForwarder() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); MBeanServerForwarder forwarder = (MBeanServerForwarder)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{MBeanServerForwarder.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); server.setMBeanServerForwarder(forwarder); try { server.start(); if (server.getMBeanServer() != forwarder) fail(); } finally { server.stop(); } } public void testStart() throws Exception { JMXConnectorServer cntorServer = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); } finally { if (cntorServer != null) cntorServer.stop(); } } public void testStartStart() throws Exception { JMXConnectorServer cntorServer = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntorServer.start(); } finally { if (cntorServer != null) cntorServer.stop(); } } public void testStartStop() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntorServer.stop(); } public void testStartStopStart() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntorServer.stop(); try { cntorServer.start(); fail(); } catch (IOException x) { } } public void testStartStopStop() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntorServer.stop(); cntorServer.stop(); } public void testTwoConnectorServers() throws Exception { JMXConnectorServer cntorServer1 = null; JMXConnectorServer cntorServer2 = null; JMXConnector cntor10 = null; JMXConnector cntor11 = null; JMXConnector cntor12 = null; JMXConnector cntor20 = null; try { JMXServiceURL url1 = createJMXConnectorServerAddress(); JMXServiceURL url2 = new JMXServiceURL(url1.getProtocol(), url1.getHost(), (url1.getPort() > 0) ? (url1.getPort() + 1) : 0, url1.getURLPath()); MBeanServer server = newMBeanServer(); cntorServer1 = JMXConnectorServerFactory.newJMXConnectorServer(url1, getEnvironment(), server); cntorServer2 = JMXConnectorServerFactory.newJMXConnectorServer(url2, getEnvironment(), server); cntorServer1.start(); cntorServer2.start(); cntor10 = JMXConnectorFactory.connect(cntorServer1.getAddress(), getEnvironment()); cntor11 = JMXConnectorFactory.connect(cntorServer1.getAddress(), getEnvironment()); cntor12 = JMXConnectorFactory.connect(cntorServer1.getAddress(), getEnvironment()); cntor20 = JMXConnectorFactory.connect(cntorServer2.getAddress(), getEnvironment()); if (cntor10.getConnectionId().equals(cntor11.getConnectionId())) fail(); if (cntor10.getConnectionId().equals(cntor12.getConnectionId())) fail(); if (cntor10.getConnectionId().equals(cntor20.getConnectionId())) fail(); } finally { if (cntor20 != null) cntor20.close(); if (cntor12 != null) cntor12.close(); if (cntor11 != null) cntor11.close(); if (cntor10 != null) cntor10.close(); if (cntorServer2 != null) cntorServer2.stop(); if (cntorServer1 != null) cntorServer1.stop(); } } public void testStartWithProviderClassLoader() throws Exception { JMXConnectorServer cntorServer = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); Map serverEnv = getEnvironment(); serverEnv.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER, getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(getClass().getClassLoader().getParent()); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, server); cntorServer.start(); } finally { if (cntorServer != null) cntorServer.stop(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXConnectorTestCase.java100644 0 0 32110 10513545721 23622 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXPrincipal; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import test.MX4JTestCase; /** * @version $Revision: 1.21 $ */ public abstract class JMXConnectorTestCase extends MX4JTestCase { public JMXConnectorTestCase(String name) { super(name); } protected void tearDown() throws Exception { sleep(5000); } public abstract JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException; public abstract Map getEnvironment(); public void testNewJMXConnectorWithNullURL() throws Exception { try { JMXConnectorFactory.connect(null); fail(); } catch (NullPointerException x) { } } public void testConnectionId() throws Exception { // Format is: // protocol:[[host]:port] [clientId] [arbitrary] // Spaces are mandatory, brackets indicates optional parts JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); String connectionId = cntor.getConnectionId(); String protocol = connectionId.substring(0, connectionId.indexOf(':')); assertEquals(protocol, url.getProtocol()); // Match first mandatory space int space = connectionId.indexOf(' '); String remaining = connectionId.substring(space + 1); // Match second mandatory space space = remaining.indexOf(' '); String arbitrary = remaining.substring(space + 1); if (arbitrary.length() < 1) fail("Missing MX4J arbitrary test"); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testConnectionWithNoPath() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testJMXAuthenticator() throws Exception { final String password = "mx4j"; JMXAuthenticator authenticator = new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { if (password.equals(credentials)) { JMXPrincipal principal = new JMXPrincipal("mx4j"); Subject subject = new Subject(); subject.getPrincipals().add(principal); subject.setReadOnly(); return subject; } throw new SecurityException("Authentication Failed"); } }; JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); Map serverEnv = getEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, authenticator); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, server); cntorServer.start(); sleep(5000); // Try to provide wrong password Map clientEnv = getEnvironment(); try { testJMXAuthenticatorConnect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Try now with a correct password clientEnv.put(JMXConnector.CREDENTIALS, password); testJMXAuthenticatorConnect(cntorServer.getAddress(), clientEnv); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } protected void testJMXAuthenticatorConnect(JMXServiceURL url, Map environment) throws SecurityException, IOException { JMXConnectorFactory.connect(url, environment); } public void testStopServerBeforeClosingClient() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); cntorServer.stop(); try { mbsc.getDefaultDomain(); fail(); } catch (IOException x) { } } public void testStopServerAndCloseClientThenInvoke() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); cntor.close(); cntorServer.stop(); try { mbsc.getDefaultDomain(); fail(); } catch (IOException x) { } } public void testSerializedConnectorCanConnect() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.newJMXConnector(cntorServer.getAddress(), getEnvironment()); // Serialize it: we want to test serialization does no reset data members ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(cntor); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); cntor = (JMXConnector)ois.readObject(); ois.close(); cntor.connect(); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); mbsc.getDefaultDomain(); // Again cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); // Serialize it: we want to test serialization does no reset data members baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(cntor); oos.close(); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); cntor = (JMXConnector)ois.readObject(); ois.close(); cntor.connect(); mbsc = cntor.getMBeanServerConnection(); mbsc.getDefaultDomain(); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testDefaultClassLoader() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); Map environment = new HashMap(getEnvironment()); environment.put(JMXConnectorFactory.DEFAULT_CLASS_LOADER, new Object()); try { JMXConnectorFactory.newJMXConnector(url, environment); fail(); } catch (IllegalArgumentException x) { } JMXConnector cntor = JMXConnectorFactory.newJMXConnector(url, getEnvironment()); try { cntor.connect(environment); fail(); } catch (IllegalArgumentException x) { } } public void testListenersAreRemovedOnConnectorClose() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); Emitter emitter = new Emitter(); ObjectName emitterName = ObjectName.getInstance(":name=emitter"); server.registerMBean(emitter, emitterName); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; // Add the listener and be sure the mechanism of removal works fine mbsc.addNotificationListener(emitterName, listener, null, null); assertEquals(emitter.getSize(), 1); mbsc.removeNotificationListener(emitterName, listener, null, null); assertEquals(emitter.getSize(), 0); // Add the listener and close the connector mbsc.addNotificationListener(emitterName, listener, null, null); assertEquals(emitter.getSize(), 1); cntor.close(); assertEquals(emitter.getSize(), 0); } finally { if (cntorServer != null) cntorServer.stop(); } } public void testConnectWithProviderClassLoader() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); Map serverEnv = getEnvironment(); serverEnv.put(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER, getClass().getClassLoader()); ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader().getParent()); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, server); cntorServer.start(); Thread.currentThread().setContextClassLoader(old); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); assertNotNull(mbsc); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public interface EmitterMBean { } private static class Emitter implements NotificationEmitter, EmitterMBean { private List listeners = new ArrayList(); public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { listeners.add(listener); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { listeners.remove(listener); } public MBeanNotificationInfo[] getNotificationInfo() { return new MBeanNotificationInfo[0]; } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { } public int getSize() { return listeners.size(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXNotificationsTestCase.java100644 0 0 72226 10513545721 24515 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerNotification; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationFilter; import javax.management.NotificationFilterSupport; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.loading.MLet; import javax.management.relation.MBeanServerNotificationFilter; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.remote.MX4JRemoteConstants; import test.MX4JTestCase; import test.MutableBoolean; import test.MutableInteger; import test.MutableObject; /** * @version $Revision: 1.10 $ */ public abstract class JMXNotificationsTestCase extends MX4JTestCase { public JMXNotificationsTestCase(String name) { super(name); } protected void tearDown() throws Exception { sleep(5000); } public abstract JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException; public abstract Map getEnvironment(); public void testConnectionNotificationOpenedOnServer() throws Exception { JMXConnectorServer cntorServer = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); final MutableObject holder = new MutableObject(null); cntorServer.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); Notification notification = (Notification) holder.get(); if (!(notification instanceof JMXConnectionNotification)) fail(); assertEquals(notification.getType(), JMXConnectionNotification.OPENED); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntorServer != null) cntorServer.stop(); } } public void testConnectionNotificationClosedOnServer() throws Exception { JMXConnectorServer cntorServer = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); sleep(5000); final MutableObject holder = new MutableObject(null); cntorServer.addNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); cntor.close(); Notification notification = (Notification) holder.get(); if (!(notification instanceof JMXConnectionNotification)) fail(); assertEquals(notification.getType(), JMXConnectionNotification.CLOSED); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntorServer != null) cntorServer.stop(); } } public void testConnectionNotificationOpenedOnClient() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); final MutableObject holder = new MutableObject(null); cntor = JMXConnectorFactory.newJMXConnector(cntorServer.getAddress(), getEnvironment()); cntor.addConnectionNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); cntor.connect(getEnvironment()); JMXConnectionNotification notification = (JMXConnectionNotification) holder.get(); assertEquals(notification.getType(), JMXConnectionNotification.OPENED); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testConnectionNotificationClosedOnClient() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); final MutableObject holder = new MutableObject(null); cntor = JMXConnectorFactory.newJMXConnector(cntorServer.getAddress(), getEnvironment()); cntor.addConnectionNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); cntor.connect(getEnvironment()); cntor.close(); JMXConnectionNotification notification = (JMXConnectionNotification) holder.get(); assertEquals(notification.getType(), JMXConnectionNotification.CLOSED); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testConnectionNotificationFailedOnClient() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); MBeanServer server = newMBeanServer(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); final MutableObject holder = new MutableObject(null); long period = 1000; int retries = 3; try { JMXConnector cntor = JMXConnectorFactory.newJMXConnector(cntorServer.getAddress(), getEnvironment()); cntor.addConnectionNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); Map clientEnv = getEnvironment(); clientEnv.put(MX4JRemoteConstants.CONNECTION_HEARTBEAT_PERIOD, new Long(period)); clientEnv.put(MX4JRemoteConstants.CONNECTION_HEARTBEAT_RETRIES, new Integer(retries)); cntor.connect(clientEnv); JMXConnectionNotification notification = (JMXConnectionNotification) holder.get(); assertEquals(notification.getType(), JMXConnectionNotification.OPENED); holder.set(null); } catch (Exception x) { x.printStackTrace(); throw x; } finally { cntorServer.stop(); sleep(5000); } // Wait for the heartbeat to send the failed notification sleep((retries * 3) * period); JMXConnectionNotification notification = (JMXConnectionNotification) holder.get(); assertNotNull(notification); assertEquals(notification.getType(), JMXConnectionNotification.FAILED); } public void testRemoteNotificationListener() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); ObjectName delegate = new ObjectName("JMImplementation:type=MBeanServerDelegate"); final MutableObject holder = new MutableObject(null); mbsc.addNotificationListener(delegate, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { holder.set(notification); } }, null, null); // Wait for notifications threads to start sleep(1000); // Register a new MBean, it will generate a notification MLet mlet = new MLet(); ObjectName name = new ObjectName(":mbean=mlet"); server.registerMBean(mlet, name); // Wait for notifications to arrive sleep(1000); Notification notification = (Notification) holder.get(); assertEquals(notification.getType(), MBeanServerNotification.REGISTRATION_NOTIFICATION); holder.set(null); // Unregister the MBean server.unregisterMBean(name); // Wait for notifications to arrive sleep(1000); notification = (Notification) holder.get(); assertEquals(notification.getType(), MBeanServerNotification.UNREGISTRATION_NOTIFICATION); holder.set(null); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testNonSerializableNotifications() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), null); ObjectName cntorName = ObjectName.getInstance("connector:protocol=rmi"); server.registerMBean(cntorServer, cntorName); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); final MutableObject plainNotification = new MutableObject(null); mbsc.addNotificationListener(emitterName, new NotificationListener() { public void handleNotification(Notification notification, Object handback) { plainNotification.set(notification); } }, null, null); final MutableObject connectionNotification = new MutableObject(null); cntor.addConnectionNotificationListener(new NotificationListener() { public void handleNotification(Notification notification, Object handback) { connectionNotification.set(notification); } }, null, null); // Wait for notifications threads to start sleep(1000); String type = "notification.type"; Notification notification = new Notification(type, this, 0); // Make it non-serializable notification.setUserData(this); emitter.emit(notification); // Wait for notifications to arrive sleep(1000); assertNull(plainNotification.get()); assertNotNull(connectionNotification.get()); assertEquals(((Notification) connectionNotification.get()).getType(), JMXConnectionNotification.NOTIFS_LOST); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAddRemoveMBeanListener() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); // Register an MBean Listener MutableObject notificationHolder = new MutableObject(null); MutableObject handbackHolder = new MutableObject(null); ObjectName listenerName = ObjectName.getInstance(":mbean=listener"); MBeanListener listener = new MBeanListener(notificationHolder, handbackHolder); server.registerMBean(listener, listenerName); JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); // Non-serializable filter try { mbsc.addNotificationListener(emitterName, listenerName, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return false; } }, null); fail(); } catch (IOException x) { } // Non-serializable handback try { mbsc.addNotificationListener(emitterName, listenerName, null, new Object()); fail(); } catch (IOException x) { } // Non-serializable filter and non serializable handback try { mbsc.addNotificationListener(emitterName, listenerName, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return false; } }, new Object()); fail(); } catch (IOException x) { } // Everything is serializable ObjectName name = ObjectName.getInstance(":mbean=dummy"); MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter(); filter.disableObjectName(name); Object handback = new Integer(13); mbsc.addNotificationListener(emitterName, listenerName, filter, handback); // Wait for notifications threads to start sleep(1000); Notification notification = new MBeanServerNotification(MBeanServerNotification.REGISTRATION_NOTIFICATION, this, 0, name); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure the notification has been filtered assertNull(notificationHolder.get()); assertNull(handbackHolder.get()); // Disable filtering filter.enableAllObjectNames(); // Remove and readd: on server side there is a serialized copy of the filter mbsc.removeNotificationListener(emitterName, listenerName); mbsc.addNotificationListener(emitterName, listenerName, filter, handback); // Wait for notifications threads to start sleep(1000); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure we got it assertEquals(handbackHolder.get(), handback); Notification emitted = (Notification) notificationHolder.get(); assertNotNull(emitted); if (!(notification instanceof MBeanServerNotification)) fail(); assertEquals(((MBeanServerNotification) emitted).getMBeanName(), name); notificationHolder.set(null); handbackHolder.set(null); mbsc.removeNotificationListener(emitterName, listenerName, filter, handback); // Be sure we don't get notifications anymore emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertNull(notificationHolder.get()); assertNull(handbackHolder.get()); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAddRemoveListenerWithNonSerializableFilter() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); MutableObject notificationHolder = new MutableObject(null); MutableObject handbackHolder = new MutableObject(null); MBeanListener listener = new MBeanListener(notificationHolder, handbackHolder); JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); // Non-serializable filter, should run on client side final MutableBoolean enable = new MutableBoolean(false); NotificationFilter filter = new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return enable.get(); } }; mbsc.addNotificationListener(emitterName, listener, filter, null); // Wait for notification threads to start sleep(1000); String type = "notification.type"; Notification notification = new Notification(type, this, 0); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure the notification has been filtered assertNull(notificationHolder.get()); assertNull(handbackHolder.get()); // Disable the filter enable.set(true); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure we got the notification assertNull(handbackHolder.get()); Notification emitted = (Notification) notificationHolder.get(); assertNotNull(emitted); notificationHolder.set(null); handbackHolder.set(null); mbsc.removeNotificationListener(emitterName, listener, filter, null); // Be sure we don't get notifications anymore emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertNull(notificationHolder.get()); assertNull(handbackHolder.get()); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAddRemoveListenerWithNonSerializableHandback() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); MutableObject notificationHolder = new MutableObject(null); MutableObject handbackHolder = new MutableObject(null); MBeanListener listener = new MBeanListener(notificationHolder, handbackHolder); JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); // Non-serializable handback, should stay on client side Object handback = new Object(); mbsc.addNotificationListener(emitterName, listener, null, handback); // Wait for notification threads to start sleep(1000); String type = "notification.type"; Notification notification = new Notification(type, this, 0); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure we got the notification assertSame(handbackHolder.get(), handback); Notification emitted = (Notification) notificationHolder.get(); assertNotNull(emitted); notificationHolder.set(null); handbackHolder.set(null); mbsc.removeNotificationListener(emitterName, listener, null, handback); // Be sure we don't get notifications anymore emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertNull(notificationHolder.get()); assertNull(handbackHolder.get()); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAddRemoveSameListenerMultipleTimesWithDifferentFiltersAndHandbacks() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); final MutableInteger counter1 = new MutableInteger(0); NotificationListener listener1 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { counter1.set(counter1.get() + 1); } }; final MutableInteger counter2 = new MutableInteger(0); NotificationListener listener2 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { counter2.set(counter2.get() + 1); } }; JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); String type = "notification.type"; // First listener mbsc.addNotificationListener(emitterName, listener1, null, null); // Second listener NotificationFilterSupport filter = new NotificationFilterSupport(); filter.enableType(type); mbsc.addNotificationListener(emitterName, listener1, filter, null); // Third listener Object handback = new Object(); mbsc.addNotificationListener(emitterName, listener1, null, handback); // Fourth listener mbsc.addNotificationListener(emitterName, listener2, null, null); // Wait for notification threads to start sleep(1000); Notification notification = new Notification(type, this, 0); emitter.emit(notification); // Wait for notification to arrive sleep(1000); // Be sure we got all notifications assertEquals(counter1.get(), 3); assertEquals(counter2.get(), 1); counter1.set(0); counter2.set(0); // Remove one listener mbsc.removeNotificationListener(emitterName, listener1, null, handback); emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertEquals(counter1.get(), 2); assertEquals(counter2.get(), 1); counter1.set(0); counter2.set(0); // Remove all listeners mbsc.removeNotificationListener(emitterName, listener1); emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertEquals(counter1.get(), 0); assertEquals(counter2.get(), 1); counter1.set(0); counter2.set(0); mbsc.removeNotificationListener(emitterName, listener2); emitter.emit(notification); // Wait for notification to arrive sleep(1000); assertEquals(counter1.get(), 0); assertEquals(counter2.get(), 0); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testTwoMBeanServerConnectionsHaveSameListener() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { MBeanServer server = newMBeanServer(); // Register an MBean Emitter ObjectName emitterName = ObjectName.getInstance(":mbean=emitter"); MBeanEmitter emitter = new MBeanEmitter(); server.registerMBean(emitter, emitterName); final MutableInteger counter = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { counter.set(counter.get() + 1); } }; JMXServiceURL url = createJMXConnectorServerAddress(); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), server); cntorServer.start(); sleep(5000); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc1 = cntor.getMBeanServerConnection(); mbsc1.addNotificationListener(emitterName, listener, null, null); // Wait for notification threads to start sleep(1000); Notification notification = new Notification("type", emitter, 0); emitter.emit(notification); // Wait for the notification to arrive sleep(1000); // Be sure it's received assertEquals(counter.get(), 1); // Be sure I can remove the same listener from another MBeanServerConnection MBeanServerConnection mbsc2 = cntor.getMBeanServerConnection(); mbsc2.removeNotificationListener(emitterName, listener, null, null); emitter.emit(notification); // Be sure no listeners anymore assertEquals(counter.get(), 1); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public interface MBeanListenerMBean { } public static class MBeanListener implements NotificationListener, MBeanListenerMBean { private MutableObject notificationHolder; private MutableObject handbackHolder; public MBeanListener(MutableObject notificationHolder, MutableObject handbackHolder) { this.notificationHolder = notificationHolder; this.handbackHolder = handbackHolder; } public void handleNotification(Notification notification, Object handback) { notificationHolder.set(notification); handbackHolder.set(handback); } } public interface MBeanEmitterMBean { public void emit(Notification notification); } public static class MBeanEmitter extends NotificationBroadcasterSupport implements MBeanEmitterMBean { public void emit(Notification notification) { sendNotification(notification); } } } mx4j-3.0.2/src/test/test/javax/management/remote/JMXServiceURLTest.java100644 0 0 14022 10513545721 23061 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.net.MalformedURLException; import javax.management.remote.JMXServiceURL; import junit.framework.TestCase; /** * @version $Revision: 1.9 $ */ public class JMXServiceURLTest extends TestCase { public JMXServiceURLTest(String s) { super(s); } public void testInvalidJMXServiceURLNull() throws Exception { try { new JMXServiceURL(null); } catch (NullPointerException x) { } } public void testInvalidJMXServiceURLEmpty() throws Exception { try { new JMXServiceURL(""); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLWhiteSpace() throws Exception { try { new JMXServiceURL(" "); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLNoServiceJMX() throws Exception { try { // No service:jmx new JMXServiceURL("dummy"); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLNoProtocol1() throws Exception { try { // No protocol new JMXServiceURL("service:jmx: "); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLNoProtocol2() throws Exception { try { // No protocol new JMXServiceURL("service:jmx: :// "); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLNoHost() throws Exception { try { // No host new JMXServiceURL("service:jmx:rmi:// "); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLBadPort() throws Exception { try { // No host new JMXServiceURL("service:jmx:rmi://host:port"); } catch (MalformedURLException e) { } } public void testInvalidJMXServiceURLWrongPath() throws Exception { try { // Wrong path new JMXServiceURL("service:jmx:rmi://host//path"); } catch (MalformedURLException e) { } } public void testValidJMXServiceURLProtocolOnly() throws Exception { String proto = "rmi"; JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://"); assertEquals(proto, url.getProtocol()); } public void testValidJMXServiceURLProtocolHost() throws Exception { String proto = "rmi"; String host = "host"; JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://" + host); assertEquals(proto, url.getProtocol()); assertEquals(host, url.getHost()); assertEquals(0, url.getPort()); assertEquals("", url.getURLPath()); } public void testValidJMXServiceURLProtocolHostPort() throws Exception { String proto = "rmi"; String host = "host"; int port = 1099; JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://" + host + ":" + port); assertEquals(proto, url.getProtocol()); assertEquals(host, url.getHost()); assertEquals(port, url.getPort()); assertEquals("", url.getURLPath()); } public void testValidJMXServiceURLProtocolHostPortPath() throws Exception { String proto = "rmi"; String host = "host"; int port = 1099; String path = "/path"; JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://" + host + ":" + port + path); assertEquals(proto, url.getProtocol()); assertEquals(host, url.getHost()); assertEquals(port, url.getPort()); assertEquals(path, url.getURLPath()); } public void testValidJMXServiceURLCaseNotSignificant() throws Exception { JMXServiceURL reference = new JMXServiceURL("service:jmx:rmi://"); JMXServiceURL url = new JMXServiceURL("SERVICE:JMX:RMI://"); assertEquals(url, reference); url = new JMXServiceURL("SERVICE:JMX:rmi://"); assertEquals(url, reference); url = new JMXServiceURL("Service:JMX:rmi://"); assertEquals(url, reference); url = new JMXServiceURL("service:JMX:rmi://"); assertEquals(url, reference); url = new JMXServiceURL("service:Jmx:RMI://"); assertEquals(url, reference); url = new JMXServiceURL("service:Jmx:rmi://"); assertEquals(url, reference); } public void testDifferentConstructorsYieldEqualJMXServiceURL() throws Exception { JMXServiceURL one = new JMXServiceURL("service:jmx:rmi://"); JMXServiceURL two = new JMXServiceURL("rmi", null, 0, null); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); assertEquals(one.getURLPath(), two.getURLPath()); one = new JMXServiceURL("service:jmx:rmi://myhost"); two = new JMXServiceURL("rmi", "myhost", 0, null); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); assertEquals(one.getURLPath(), two.getURLPath()); one = new JMXServiceURL("service:jmx:rmi://myhost/"); two = new JMXServiceURL("rmi", "myhost", 0, null); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); assertEquals(one.getURLPath(), two.getURLPath()); one = new JMXServiceURL("service:jmx:rmi://myhost/mypath"); two = new JMXServiceURL("rmi", "myhost", 0, "mypath"); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); assertEquals(one.getURLPath(), two.getURLPath()); one = new JMXServiceURL("service:jmx:rmi://myhost/mypath"); two = new JMXServiceURL("rmi", "myhost", 0, "/mypath"); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); assertEquals(one.getURLPath(), two.getURLPath()); } } mx4j-3.0.2/src/test/test/javax/management/remote/RemoteSecurityManagerTestCase.java100644 0 0 151013 10513545721 25613 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote; import java.net.MalformedURLException; import java.net.SocketPermission; import java.security.AccessController; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.Principal; import java.security.ProtectionDomain; import java.security.SecurityPermission; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.MBeanPermission; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.MBeanServerPermission; import javax.management.MBeanTrustPermission; import javax.management.ObjectName; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXPrincipal; import javax.management.remote.JMXServiceURL; import javax.management.remote.SubjectDelegationPermission; import javax.security.auth.AuthPermission; import javax.security.auth.Subject; import junit.framework.TestCase; import mx4j.remote.MX4JRemoteUtils; import mx4j.server.MX4JMBeanServer; import test.javax.management.SecurityManagerTestCase; /** * @version $Revision: 1.4 $ */ public abstract class RemoteSecurityManagerTestCase extends SecurityManagerTestCase { public RemoteSecurityManagerTestCase(String s) { super(s); } protected void setUp() throws Exception { // Be sure we have a security manager and the right policy SecurityManager sm = System.getSecurityManager(); if (sm == null) fail(); Policy policy = Policy.getPolicy(); if (!(policy instanceof RemoteModifiablePolicy)) fail(); ((RemoteModifiablePolicy)policy).initialize(); } protected void tearDown() throws Exception { // Allow the sockets to shut down sleep(2000); } protected void addPermission(Permission p) { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); policy.addServerPermission(p); } protected void resetPermissions() { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); policy.initialize(); } /** * Creates and returns a suitable JMXServiceURL for the specific JMXConnectorServer * used in the tests. Subclasses implements it to return specific JMXServiceURL. */ protected abstract JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException; /** * Creates and returns a new environment map to be used for the server side * * @see #createClientEnvironment */ protected Map createServerEnvironment() { return new HashMap(); } /** * Creates and returns a new environment map to be used for the client side * * @see #createServerEnvironment */ protected Map createClientEnvironment() { return new HashMap(); } public void testNewJMXConnectorServer() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); try { cntorServer.start(); fail(); } catch (SecurityException x) { } } public void testStartJMXConnectorServer() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); try { cntorServer.start(); } finally { cntorServer.stop(); } } public void testConnect() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); JMXConnector cntor = null; try { cntorServer.start(); RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); policy.setSeparateClientServerPermissions(true); try { JMXConnectorFactory.connect(cntorServer.getAddress()); fail(); } catch (SecurityException x) { } // Allow any client to connect to the server addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); // Allow this client to open a socket to connect to the server policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAuthenticatedConnect() throws Exception { addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); Map serverEnv = createServerEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { if (!(credentials instanceof String[])) throw new SecurityException("No credentials provided"); String[] creds = (String[])credentials; if (creds.length != 2) throw new SecurityException("Bad credentials"); String user = creds[0]; String password = creds[1]; if (!"test".equals(user)) throw new SecurityException("Unknown user"); if (!"test".equals(password)) throw new SecurityException("Wrong password"); Principal principal = new JMXPrincipal(user); Set principals = new HashSet(); principals.add(principal); Subject subject = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); return subject; } }); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); policy.setSeparateClientServerPermissions(true); Map clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"test", "test"}); // Allow this client to open a socket to connect to the server policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); // Allow the authenticated subject to listen and accept a connection policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("localhost:" + url.getPort(), "listen")); policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("*:1024-" + url.getPort(), "accept")); // No credentials try { JMXConnectorFactory.connect(cntorServer.getAddress()); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, null); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new StringBuffer()); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[0]); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"dummy"}); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"dummy", "dummy"}); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"dummy", "dummy", "dummy"}); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } // Bad credentials clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"test", "wrong"}); try { JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); fail(); } catch (SecurityException x) { } clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"test", "test"}); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAuthenticatedSubjectOnServerSide() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); Map serverEnv = createServerEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { if (!(credentials instanceof String[])) throw new SecurityException("No credentials provided"); String[] creds = (String[])credentials; if (creds.length != 2) throw new SecurityException("Bad credentials"); String user = creds[0]; String password = creds[1]; if (!"test".equals(user)) throw new SecurityException("Unknown user"); if (!"test".equals(password)) throw new SecurityException("Wrong password"); Principal principal = new JMXPrincipal(user); Set principals = new HashSet(); principals.add(principal); Subject subject = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); return subject; } }); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); Map clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"test", "test"}); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); policy.addServerPermission(new JMXPrincipal("test"), new AuthPermission("doAsPrivileged")); policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("localhost:" + url.getPort(), "listen")); policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); addPermission(new MBeanTrustPermission("*")); policy.addServerPermission(new JMXPrincipal("test"), new MBeanPermission("*", "instantiate, registerMBean, getAttribute")); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); ObjectName name = ObjectName.getInstance(":name=subject"); cntion.createMBean(SubjectCheck.class.getName(), name, null); policy.addServerPermission(new JMXPrincipal("test"), new AuthPermission("getSubject")); Subject subject = (Subject)cntion.getAttribute(name, "Subject"); Set principals = subject.getPrincipals(); assertNotNull(principals); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertTrue(principal instanceof JMXPrincipal); assertEquals(principal.getName(), "test"); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testDelegateSubjectOnServerSide() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); Map serverEnv = createServerEnvironment(); serverEnv.put(JMXConnectorServer.AUTHENTICATOR, new JMXAuthenticator() { public Subject authenticate(Object credentials) throws SecurityException { if (!(credentials instanceof String[])) throw new SecurityException("No credentials provided"); String[] creds = (String[])credentials; if (creds.length != 2) throw new SecurityException("Bad credentials"); String user = creds[0]; String password = creds[1]; if (!"test".equals(user)) throw new SecurityException("Unknown user"); if (!"test".equals(password)) throw new SecurityException("Wrong password"); Principal principal = new JMXPrincipal(user); Set principals = new HashSet(); principals.add(principal); Subject subject = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); return subject; } }); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, serverEnv, newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); Map clientEnv = createClientEnvironment(); clientEnv.put(JMXConnector.CREDENTIALS, new String[]{"test", "test"}); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); policy.addServerPermission(new JMXPrincipal("test"), new AuthPermission("doAsPrivileged")); policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("localhost:" + url.getPort(), "listen")); policy.addServerPermission(new JMXPrincipal("test"), new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), clientEnv); addPermission(new MBeanTrustPermission("*")); policy.addServerPermission(new JMXPrincipal("delegate"), new MBeanPermission("*", "instantiate, registerMBean, getAttribute")); policy.addServerPermission(new JMXPrincipal("test"), new SubjectDelegationPermission(JMXPrincipal.class.getName() + ".delegate")); Set delegates = new HashSet(); delegates.add(new JMXPrincipal("delegate")); Subject delegate = new Subject(true, delegates, Collections.EMPTY_SET, Collections.EMPTY_SET); MBeanServerConnection cntion = cntor.getMBeanServerConnection(delegate); ObjectName name = ObjectName.getInstance(":name=subject"); cntion.createMBean(SubjectCheck.class.getName(), name, null); policy.addServerPermission(new JMXPrincipal("delegate"), new AuthPermission("getSubject")); Subject subject = (Subject)cntion.getAttribute(name, "Subject"); Set principals = subject.getPrincipals(); assertNotNull(principals); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertTrue(principal instanceof JMXPrincipal); assertEquals(principal.getName(), "delegate"); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testAddRemoveNotificationListener() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testAddRemoveNotificationListener(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testCreateMBean4Params() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testCreateMBean4Params(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testCreateMBean5Params() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testCreateMBean5Params(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetAttribute() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetAttribute(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetAttributes() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetAttributes(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetDefaultDomain() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { String domain = "xxx"; MBeanServer server = MBeanServerFactory.newMBeanServer(domain); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), server); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetDefaultDomain(cntion, domain); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetDomains() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetDomains(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetMBeanCount() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetMBeanCount(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetMBeanInfo() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetMBeanInfo(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testGetObjectInstance() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testGetObjectInstance(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testInvoke() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testInvoke(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testIsInstanceOf() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testIsInstanceOf(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testIsRegistered() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testIsRegistered(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testQueryMBeans() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testQueryMBeans(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testQueryNames() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testQueryNames(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testSetAttribute() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testSetAttribute(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testSetAttributes() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testSetAttributes(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public void testUnregisterMBean() throws Exception { RemoteModifiablePolicy policy = (RemoteModifiablePolicy)Policy.getPolicy(); addPermission(new MBeanServerPermission("newMBeanServer")); JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, createServerEnvironment(), newMBeanServer()); // Required by the server addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); cntorServer.start(); policy.setSeparateClientServerPermissions(true); policy.addClientPermission(new SocketPermission("localhost:" + url.getPort(), "connect")); addPermission(new SocketPermission("localhost:" + url.getPort(), "listen")); addPermission(new SocketPermission("*:1024-" + url.getPort(), "accept")); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), createClientEnvironment()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); testUnregisterMBean(cntion); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public interface SubjectCheckMBean { public Subject getSubject(); } public static class SubjectCheck implements SubjectCheckMBean { public Subject getSubject() { return Subject.getSubject(AccessController.getContext()); } } /** * A modifiable policy that allow permissions to be added at runtime, used for tests purposes only. */ public abstract static class RemoteModifiablePolicy extends Policy { private final ProtectionDomain testDomain; private final Map serverPermissions = new HashMap(); private final Map clientPermissions = new HashMap(); private final Map principalPermissions = new HashMap(); private volatile boolean separated; public RemoteModifiablePolicy() { // Here we still have no security manager installed testDomain = RemoteModifiablePolicy.class.getProtectionDomain(); // Add the permissions needed to run the tests CodeSource junitCodeSource = TestCase.class.getProtectionDomain().getCodeSource(); serverPermissions.put(junitCodeSource, createAllPermissions()); clientPermissions.put(junitCodeSource, createAllPermissions()); CodeSource mx4jCodeSource = MBeanServerFactory.class.getProtectionDomain().getCodeSource(); serverPermissions.put(mx4jCodeSource, createAllPermissions()); clientPermissions.put(mx4jCodeSource, createAllPermissions()); CodeSource implCodeSource = MX4JMBeanServer.class.getProtectionDomain().getCodeSource(); serverPermissions.put(implCodeSource, createAllPermissions()); clientPermissions.put(implCodeSource, createAllPermissions()); CodeSource rmx4jCodeSource = JMXConnector.class.getProtectionDomain().getCodeSource(); serverPermissions.put(rmx4jCodeSource, createAllPermissions()); clientPermissions.put(rmx4jCodeSource, createAllPermissions()); CodeSource rimplCodeSource = MX4JRemoteUtils.class.getProtectionDomain().getCodeSource(); serverPermissions.put(rimplCodeSource, createAllPermissions()); clientPermissions.put(rimplCodeSource, createAllPermissions()); ClassLoader loader = getClass().getClassLoader(); // BCEL try { Class cls = loader.loadClass("org.apache.bcel.generic.Type"); CodeSource bcelCodeSource = cls.getProtectionDomain().getCodeSource(); serverPermissions.put(bcelCodeSource, createAllPermissions()); clientPermissions.put(bcelCodeSource, createAllPermissions()); } catch (ClassNotFoundException ignored) { } // When we run automated, we need also permissions for Ant jars try { Class cls = loader.loadClass("org.apache.tools.ant.Task"); CodeSource antCodeSource = cls.getProtectionDomain().getCodeSource(); serverPermissions.put(antCodeSource, createAllPermissions()); clientPermissions.put(antCodeSource, createAllPermissions()); cls = loader.loadClass("org.apache.tools.ant.taskdefs.optional.junit.JUnitTask"); antCodeSource = cls.getProtectionDomain().getCodeSource(); serverPermissions.put(antCodeSource, createAllPermissions()); clientPermissions.put(antCodeSource, createAllPermissions()); } catch (ClassNotFoundException ignored) { } mapServerPermissions(serverPermissions); initialize(); } /** * Callback for subclasses to add more mappings between a codesource and * (normally) a Permissions object containing AllPermission. * This is necessary if the implementation of the JMXConnectorServer needs additional * jars such as for example commons-logging.jar, whose codesource is normally mapped * with AllPermission. * * @see #createAllPermissions */ protected void mapServerPermissions(Map permissions) { // Nothing necessary here } /** * Creates and returns a Permissions object containing AllPermission. * * @see #mapServerPermissions */ protected Permissions createAllPermissions() { Permissions allPermissions = new Permissions(); allPermissions.add(new AllPermission()); return allPermissions; } /** * Returns whether the current thread is a server side thread or * a client side thread. * Subclasses implement this method by for example looking at the thread name. * * @see #setSeparateClientServerPermissions * @see #isSeparateClientServerPermissions */ public abstract boolean isServerSide(); public PermissionCollection getPermissions(CodeSource codesource) { return getPermissions(codesource, isServerSide()); } private synchronized PermissionCollection getPermissions(CodeSource codesource, boolean serverside) { if (serverside) { PermissionCollection perms = (PermissionCollection)serverPermissions.get(codesource); if (perms == null) perms = new Permissions(); perms = copyIfReadOnly(perms); serverPermissions.put(codesource, perms); return perms; } else { PermissionCollection perms = (PermissionCollection)clientPermissions.get(codesource); if (perms == null) perms = new Permissions(); perms = copyIfReadOnly(perms); clientPermissions.put(codesource, perms); return perms; } } /** * For JDK 1.4 overriding this method disables caching of Permissions done by the * standard Policy implementation. * This is done because we install this policy *before* installing the security manager. * By doing so, in JDK 1.4 the permissions granted at the moment of policy installation * (no security manager == AllPermission) are cached and will invalidate all tests, since * they will become unmodifiable. *

* The stack trace is when checking a permission is: *

* SecurityManager.checkPermission() * AccessController.checkPermission() * AccessControlContext.checkPermission() * ProtectionDomain.implies() * RemoteModifiablePolicy.implies() */ public boolean implies(ProtectionDomain domain, Permission permission) { Principal[] principals = domain.getPrincipals(); boolean injectedDomain = false; CodeSource cs = domain.getCodeSource(); if (principals != null && principals.length > 0 && cs != null && cs.getLocation() == null && domain.getClassLoader() == null) injectedDomain = true; if (!injectedDomain) { PermissionCollection perms = getPermissions(cs); boolean result = perms.implies(permission); // System.out.println("Policy.implies, side is " + (isServerSide() ? "server" : "client") + " codesource " + cs + " on " + permission + " over " + perms + ": " + result); return result; } else { for (int i = 0; i < principals.length; ++i) { Principal principal = principals[i]; PermissionCollection perms = getPrincipalPermissions(principal); if (perms.implies(permission)) return true; } return false; } } private synchronized PermissionCollection getPrincipalPermissions(Principal principal) { PermissionCollection perms = (PermissionCollection)principalPermissions.get(principal); if (perms == null) perms = new Permissions(); perms = copyIfReadOnly(perms); principalPermissions.put(principal, perms); return perms; } public void refresh() { } /** * Adds the given permission to the client (the test in this case) codesource, * on server side */ public void addServerPermission(Permission p) { Permissions permissions = (Permissions)getPermissions(testDomain.getCodeSource(), true); permissions.add(p); } /** * Adds the given permission to the client (the test in this case) codesource, * on client side */ public void addClientPermission(Permission p) { Permissions permissions = (Permissions)getPermissions(testDomain.getCodeSource(), false); permissions.add(p); } /** * Adds the given permission to the JSR 160 injected codesource, * on server side, for the given principal */ public void addServerPermission(Principal principal, Permission p) { Permissions permissions = (Permissions)getPrincipalPermissions(principal); permissions.add(p); addServerPermission(p); } /** * Initializes the permissions for the client (the test in this case) codesource, * and marks this policy as working on server side. * * @see #setSeparateClientServerPermissions */ public synchronized void initialize() { Permissions permissions = new Permissions(); permissions.add(new SecurityPermission("getPolicy")); serverPermissions.put(testDomain.getCodeSource(), permissions); permissions = new Permissions(); permissions.add(new SecurityPermission("getPolicy")); clientPermissions.put(testDomain.getCodeSource(), permissions); principalPermissions.clear(); setSeparateClientServerPermissions(false); } /** * Tells this policy to distinguish the check of permissions basing on the fact * that the thread is a server side thread or a client side thread. * * @see #isServerSide * @see #isSeparateClientServerPermissions */ public synchronized void setSeparateClientServerPermissions(boolean value) { separated = value; } /** * Returns if this policy distinguishes between server side and client side * permission checking. * * @see #setSeparateClientServerPermissions */ protected synchronized boolean isSeparateClientServerPermissions() { return separated; } /** * The RMI marshalling mechanism (and this is only one place I have discovered so far) * sometimes marks the PermissionCollection as read-only via * {@link PermissionCollection#setReadOnly}. Since this policy * adds permissions at runtime, having the Permissions object marked as read-only * causes an exception that invalidates the test. * Here I copy the read-only Permissions into a new Permissions object (by copying * all permissions it contains into the copied object), and return it. * If the Permissions object is not read-only, it is returned immediately. */ private PermissionCollection copyIfReadOnly(PermissionCollection p) { if (!p.isReadOnly()) return p; Permissions permissions = new Permissions(); for (Enumeration e = p.elements(); e.hasMoreElements();) { Permission permission = (Permission)e.nextElement(); permissions.add(permission); } return permissions; } } } ././@LongLink100644 0 0 145 10513545722 10257 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/OptionalRemoteJMXComplianceTestCase.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/OptionalRemoteJMXComplianceTestCase.java100644 0 0 7474 10513545721 30735 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.JarFile; import test.javax.management.compliance.ComplianceTestCase; /** * @version $Revision: 1.4 $ */ public abstract class OptionalRemoteJMXComplianceTestCase extends ComplianceTestCase { public OptionalRemoteJMXComplianceTestCase(String s) { super(s); } protected ClassLoader createClassLoader() throws MalformedURLException { return createOptionalRemoteJMXRIWithTestsClassLoader(); } protected JarFile loadJar() throws IOException { File rjmx = new File("dist/test/jmxremote_optional.jar"); if (!rjmx.exists()) fail("JMX Optional Remote jar is not available"); JarFile jar = new JarFile(rjmx); return jar; } public void test_remote_generic_ConnectionClosedException() throws Exception { check("remote.generic.ConnectionClosedException"); } public void test_remote_generic_GenericConnector() throws Exception { check("remote.generic.GenericConnector"); } public void test_remote_generic_GenericConnectorServer() throws Exception { check("remote.generic.GenericConnectorServer"); } public void test_remote_generic_MessageConnection() throws Exception { check("remote.generic.MessageConnection"); } public void test_remote_generic_MessageConnectionServer() throws Exception { check("remote.generic.MessageConnectionServer"); } public void test_remote_generic_ObjectWrapping() throws Exception { check("remote.generic.ObjectWrapping"); } public void test_remote_jmxmp_JMXMPConnector() throws Exception { check("remote.jmxmp.JMXMPConnector"); } public void test_remote_jmxmp_JMXMPConnectorServer() throws Exception { check("remote.jmxmp.JMXMPConnectorServer"); } public void test_remote_message_CloseMessage() throws Exception { check("remote.message.CloseMessage"); } public void test_remote_message_HandshakeBeginMessage() throws Exception { check("remote.message.HandshakeBeginMessage"); } public void test_remote_message_HandshakeEndMessage() throws Exception { check("remote.message.HandshakeEndMessage"); } public void test_remote_message_HandshakeErrorMessage() throws Exception { check("remote.message.HandshakeErrorMessage"); } public void test_remote_message_JMXMPMessage() throws Exception { check("remote.message.JMXMPMessage"); } public void test_remote_message_MBeanServerRequestMessage() throws Exception { check("remote.message.MBeanServerRequestMessage"); } public void test_remote_message_MBeanServerResponseMessage() throws Exception { check("remote.message.MBeanServerResponseMessage"); } public void test_remote_message_Message() throws Exception { check("remote.message.Message"); } public void test_remote_message_NotificationRequestMessage() throws Exception { check("remote.message.NotificationRequestMessage"); } public void test_remote_message_NotificationResponseMessage() throws Exception { check("remote.message.NotificationResponseMessage"); } public void test_remote_message_ProfileMessage() throws Exception { check("remote.message.ProfileMessage"); } public void test_remote_message_SASLMessage() throws Exception { check("remote.message.SASLMessage"); } public void test_remote_message_TLSMessage() throws Exception { check("remote.message.TLSMessage"); } } mx4j-3.0.2/src/test/test/javax/management/remote/compliance/RemoteJMXComplianceTestCase.java100644 0 0 7740 10513545721 27223 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.jar.JarFile; import test.javax.management.compliance.ComplianceTestCase; /** * @version $Revision: 1.4 $ */ public abstract class RemoteJMXComplianceTestCase extends ComplianceTestCase { public RemoteJMXComplianceTestCase(String s) { super(s); } protected ClassLoader createClassLoader() throws MalformedURLException { return createRemoteJMXRIWithTestsClassLoader(); } protected JarFile loadJar() throws IOException { File rjmx = new File("dist/test/jmxremote.jar"); if (!rjmx.exists()) fail("JMX Remote jar is not available"); JarFile jar = new JarFile(rjmx); return jar; } public void test_remote_JMXAuthenticator() throws Exception { check("remote.JMXAuthenticator"); } public void test_remote_JMXConnectionNotification() throws Exception { check("remote.JMXConnectionNotification"); } public void test_remote_JMXConnector() throws Exception { check("remote.JMXConnector"); } public void test_remote_JMXConnectorFactory() throws Exception { check("remote.JMXConnectorFactory"); } public void test_remote_JMXConnectorProvider() throws Exception { check("remote.JMXConnectorProvider"); } public void test_remote_JMXConnectorServer() throws Exception { check("remote.JMXConnectorServer"); } public void test_remote_JMXConnectorServerFactory() throws Exception { check("remote.JMXConnectorServerFactory"); } public void test_remote_JMXConnectorServerMBean() throws Exception { check("remote.JMXConnectorServerMBean"); } public void test_remote_JMXConnectorServerProvider() throws Exception { check("remote.JMXConnectorServerProvider"); } public void test_remote_JMXPrincipal() throws Exception { check("remote.JMXPrincipal"); } public void test_remote_JMXProviderException() throws Exception { check("remote.JMXProviderException"); } public void test_remote_JMXServerErrorException() throws Exception { check("remote.JMXServerErrorException"); } public void test_remote_JMXServiceURL() throws Exception { check("remote.JMXServiceURL"); } public void test_remote_MBeanServerForwarder() throws Exception { check("remote.MBeanServerForwarder"); } public void test_remote_NotificationResult() throws Exception { check("remote.NotificationResult"); } public void test_remote_SubjectDelegationPermission() throws Exception { check("remote.SubjectDelegationPermission"); } public void test_remote_TargetedNotification() throws Exception { check("remote.TargetedNotification"); } public void test_remote_rmi_RMIConnection() throws Exception { check("remote.rmi.RMIConnection"); } public void test_remote_rmi_RMIConnectionImpl() throws Exception { check("remote.rmi.RMIConnectionImpl"); } public void test_remote_rmi_RMIConnector() throws Exception { check("remote.rmi.RMIConnector"); } public void test_remote_rmi_RMIConnectorServer() throws Exception { check("remote.rmi.RMIConnectorServer"); } public void test_remote_rmi_RMIIIOPServerImpl() throws Exception { check("remote.rmi.RMIIIOPServerImpl"); } public void test_remote_rmi_RMIJRMPServerImpl() throws Exception { check("remote.rmi.RMIJRMPServerImpl"); } public void test_remote_rmi_RMIServer() throws Exception { check("remote.rmi.RMIServer"); } public void test_remote_rmi_RMIServerImpl() throws Exception { check("remote.rmi.RMIServerImpl"); } } ././@LongLink100644 0 0 162 10513545722 10256 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/OptionalRemoteJMXSerializationTest.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/OptionalRemoteJMXSerializa100644 0 0 3171 10513545721 31075 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.serialization.support.SerializationVerifier; import test.javax.management.remote.compliance.OptionalRemoteJMXComplianceTestCase; /** * @version $Revision: 1.5 $ */ public class OptionalRemoteJMXSerializationTest extends OptionalRemoteJMXComplianceTestCase { public OptionalRemoteJMXSerializationTest(String s) { super(s); } protected boolean skipClassName(String className) { // For now the optional JSR 160 part is not implemented return true; } protected boolean skipClass(Class cls) { if (cls.isInterface() || !Serializable.class.isAssignableFrom(cls) || Modifier.isAbstract(cls.getModifiers())) return true; return false; } protected void checkCompliance(String className) throws Exception { ClassLoader jmxriLoader = createOptionalRemoteJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createRemoteMX4JWithTestsClassLoader(); SerializationVerifier verifier = new SerializationVerifier("test.javax.management.remote.compliance.serialization.support.OptionalRemoteInstantiator", "test.javax.management.remote.compliance.serialization.support.OptionalRemoteComparator"); verifier.verifySerialization(className, jmxriLoader, mx4jLoader); } } ././@LongLink100644 0 0 152 10513545722 10255 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/RemoteJMXSerializationTest.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/RemoteJMXSerializationTest100644 0 0 3071 10513545721 31120 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.serialization.support.SerializationVerifier; import test.javax.management.remote.compliance.RemoteJMXComplianceTestCase; /** * @version $Revision: 1.4 $ */ public class RemoteJMXSerializationTest extends RemoteJMXComplianceTestCase { public RemoteJMXSerializationTest(String s) { super(s); } protected boolean skipClassName(String className) { boolean isStub = className.endsWith("_Stub"); return isStub; } protected boolean skipClass(Class cls) { if (cls.isInterface() || !Serializable.class.isAssignableFrom(cls) || Modifier.isAbstract(cls.getModifiers())) return true; return false; } protected void checkCompliance(String className) throws Exception { ClassLoader jmxriLoader = createRemoteJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createRemoteMX4JWithTestsClassLoader(); SerializationVerifier verifier = new SerializationVerifier("test.javax.management.remote.compliance.serialization.support.RemoteInstantiator", "test.javax.management.remote.compliance.serialization.support.RemoteComparator"); verifier.verifySerialization(className, jmxriLoader, mx4jLoader); } } ././@LongLink100644 0 0 160 10513545722 10254 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteComparator.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteComp100644 0 0 612 10513545721 31162 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization.support; /** * @version $Revision: 1.4 $ */ public class OptionalRemoteComparator { } ././@LongLink100644 0 0 162 10513545722 10256 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteInstantiator.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteInst100644 0 0 3670 10513545721 31230 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization.support; import javax.management.remote.message.CloseMessage; import javax.management.remote.message.HandshakeBeginMessage; import javax.management.remote.message.HandshakeEndMessage; import javax.management.remote.message.HandshakeErrorMessage; import javax.management.remote.message.MBeanServerRequestMessage; import javax.management.remote.message.MBeanServerResponseMessage; import javax.management.remote.message.SASLMessage; import javax.management.remote.message.TLSMessage; /** * @version $Revision: 1.5 $ */ public class OptionalRemoteInstantiator { /* public ConnectionClosedException createConnectionClosedException() { } public JMXMPConnector createJMXMPConnector() { return null; } */ public CloseMessage createCloseMessage() { return null; } public HandshakeBeginMessage createHandshakeBeginMessage() { return null; } public HandshakeEndMessage createHandshakeEndMessage() { return null; } public HandshakeErrorMessage createHandshakeErrorMessage() { return null; } /* public JMXMPMessage createJMXMPMessage() { return null; } */ public MBeanServerRequestMessage createMBeanServerRequestMessage() { return null; } public MBeanServerResponseMessage createMBeanServerResponseMessage() { return null; } /* public NotificationRequestMessage createNotificationRequestMessage() { } public NotificationResponseMessage createNotificationResponseMessage() { } */ public SASLMessage createSASLMessage() { return null; } public TLSMessage createTLSMessage() { return null; } } ././@LongLink100644 0 0 150 10513545722 10253 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteComparator.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteComparator.j100644 0 0 11505 10513545721 31160 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization.support; import javax.management.Notification; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXProviderException; import javax.management.remote.JMXServerErrorException; import javax.management.remote.NotificationResult; import javax.management.remote.SubjectDelegationPermission; import javax.management.remote.TargetedNotification; import javax.management.remote.rmi.RMIConnector; /** * @version $Revision: 1.6 $ */ public class RemoteComparator { public void compareJMXConnectionNotification(Object obj1, Object obj2) { JMXConnectionNotification jcn1 = (JMXConnectionNotification)obj1; JMXConnectionNotification jcn2 = (JMXConnectionNotification)obj2; boolean valid = jcn1.getConnectionId().equals(jcn2.getConnectionId()); compareNotifications(jcn1, jcn2); if (!valid) throw new RuntimeException(); } public void compareJMXProviderException(Object obj1, Object obj2) { JMXProviderException jpe1 = (JMXProviderException)obj1; JMXProviderException jpe2 = (JMXProviderException)obj2; boolean valid = true; /* if (jpe1.getCause() != null) valid = valid && (jpe1.getCause().equals(jpe2.getCause())); */ if (jpe1.getLocalizedMessage() != null) valid = valid && (jpe1.getLocalizedMessage().equals(jpe2.getLocalizedMessage())); if (jpe1.getMessage() != null) valid = valid && (jpe1.getMessage().equals(jpe2.getMessage())); valid = valid && (jpe1.toString().equals(jpe2.toString())); if (!valid) throw new RuntimeException(); } public void compareJMXServerErrorException(Object obj1, Object obj2) { JMXServerErrorException jse1 = (JMXServerErrorException)obj1; JMXServerErrorException jse2 = (JMXServerErrorException)obj2; boolean valid = true; // jse1.getCause().getClass().equals(jse2.getCause().getClass()); valid = valid && (jse1.getLocalizedMessage().equals(jse2.getLocalizedMessage())); valid = valid && (jse1.getMessage().equals(jse2.getMessage())); valid = valid && (jse1.toString().equals(jse2.toString())); if (!valid) throw new RuntimeException(); } public void compareNotificationResult(Object obj1, Object obj2) { NotificationResult nr1 = (NotificationResult)obj1; NotificationResult nr2 = (NotificationResult)obj2; boolean valid = nr1.getEarliestSequenceNumber() == nr2.getEarliestSequenceNumber(); valid = valid && (nr1.getNextSequenceNumber() == nr2.getNextSequenceNumber()); TargetedNotification[] tns1 = nr1.getTargetedNotifications(); TargetedNotification[] tns2 = nr2.getTargetedNotifications(); if (tns1.length != tns2.length) throw new RuntimeException(); for (int i = 0; i < tns1.length; i++) { compareTargetedNotification(tns1[i], tns2[i]); } if (!valid) throw new RuntimeException(); } public void compareSubjectDelegationPermission(Object obj1, Object obj2) { SubjectDelegationPermission sdp1 = (SubjectDelegationPermission)obj1; SubjectDelegationPermission sdp2 = (SubjectDelegationPermission)obj2; boolean valid = sdp1.equals(sdp2); valid = valid && (sdp1.getActions().equals(sdp2.getActions())); valid = valid && (sdp1.getName().equals(sdp2.getName())); valid = valid && (sdp1.implies(sdp2)); if (!valid) throw new RuntimeException(); } public void compareTargetedNotification(Object obj1, Object obj2) { TargetedNotification tn1 = (TargetedNotification)obj1; TargetedNotification tn2 = (TargetedNotification)obj2; boolean valid = tn1.getListenerID().equals(tn2.getListenerID()); compareNotifications(tn1.getNotification(), tn2.getNotification()); if (!valid) throw new RuntimeException(); } private void compareNotifications(Notification not1, Notification not2) { boolean valid = (not1.getMessage().equals(not2.getMessage())); valid = valid && (not1.getSequenceNumber() == not2.getSequenceNumber()); valid = valid && (not1.getSource().equals(not2.getSource())); valid = valid && (not1.getType().equals(not2.getType())); valid = valid && (not1.getUserData().equals(not2.getUserData())); if (!valid) throw new RuntimeException(); } public void compareRMIConnector(Object obj1, Object obj2) { RMIConnector rc1 = (RMIConnector)obj1; RMIConnector rc2 = (RMIConnector)obj2; boolean valid = true; // rc1.getConnectionId().equals(rc2.getConnectionId()); if (!valid) throw new RuntimeException(); } } ././@LongLink100644 0 0 152 10513545722 10255 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteInstantiator.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteInstantiator100644 0 0 5503 10513545721 31261 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.serialization.support; import java.net.MalformedURLException; import java.util.HashMap; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXPrincipal; import javax.management.remote.JMXProviderException; import javax.management.remote.JMXServerErrorException; import javax.management.remote.JMXServiceURL; import javax.management.remote.NotificationResult; import javax.management.remote.SubjectDelegationPermission; import javax.management.remote.TargetedNotification; import javax.management.remote.rmi.RMIConnector; /** * @version $Revision: 1.6 $ */ public class RemoteInstantiator { public JMXConnectionNotification createJMXConnectionNotification() { JMXConnectionNotification jcn = new JMXConnectionNotification(JMXConnectionNotification.OPENED, "Source", "ConnectionID", 0L, "Message", "UserData"); return jcn; } public JMXPrincipal createJMXPrincipal() { JMXPrincipal jp = new JMXPrincipal(JMXPrincipal.class.getName()); return jp; } public JMXProviderException createJMXProviderException() { JMXProviderException ex = new JMXProviderException(); return ex; } public JMXServerErrorException createJMXServerErrorException() { JMXServerErrorException see = new JMXServerErrorException("Message", new Error()); return see; } public JMXServiceURL createJMXServiceURL() { try { JMXServiceURL jsu = new JMXServiceURL("rmi", "localhost", 1099); return jsu; } catch (MalformedURLException e) { throw new RuntimeException(); } } public NotificationResult createNotificationResult() { TargetedNotification[] notifs = {createTargetedNotification()}; NotificationResult result = new NotificationResult(0l, 1l, notifs); return result; } public SubjectDelegationPermission createSubjectDelegationPermission() { SubjectDelegationPermission sdp = new SubjectDelegationPermission(SubjectDelegationPermission.class.getName()); return sdp; } public TargetedNotification createTargetedNotification() { TargetedNotification tn = new TargetedNotification(createJMXConnectionNotification(), Integer.decode("1")); return tn; } public RMIConnector createRMIConnector() { RMIConnector rc = new RMIConnector(createJMXServiceURL(), new HashMap()); return rc; } } ././@LongLink100644 0 0 152 10513545722 10255 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/OptionalRemoteJMXSignatureTest.javamx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/OptionalRemoteJMXSignatureTest100644 0 0 4240 10513545721 31075 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.signature; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.signature.support.NotCompliantException; import test.javax.management.compliance.signature.support.NotCompliantWarningException; import test.javax.management.compliance.signature.support.SignatureVerifier; import test.javax.management.remote.compliance.OptionalRemoteJMXComplianceTestCase; /** * @version $Revision: 1.5 $ */ public class OptionalRemoteJMXSignatureTest extends OptionalRemoteJMXComplianceTestCase { public OptionalRemoteJMXSignatureTest(String s) { super(s); } protected boolean skipClassName(String className) { // For now the optional JSR 160 part is not implemented return true; } protected boolean skipClass(Class cls) { // Exclude implementation classes in javax.management.remote optional subpackages int modifiers = cls.getModifiers(); boolean isPublic = Modifier.isPublic(modifiers); boolean isProtected = Modifier.isProtected(modifiers); boolean isPackage = !Modifier.isPrivate(modifiers) && !isProtected && !isPublic; boolean isSerializable = Serializable.class.isAssignableFrom(cls); if (isPublic || isProtected || (isPackage && isSerializable)) return false; return true; } protected void checkCompliance(String className) throws Exception { ClassLoader jmxriLoader = createOptionalRemoteJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createRemoteMX4JWithTestsClassLoader(); SignatureVerifier verifier = new SignatureVerifier(); try { verifier.verifySignature(className, jmxriLoader, mx4jLoader); } catch (NotCompliantException x) { fail(x.getMessage()); } catch (NotCompliantWarningException x) { System.out.println("WARNING: " + x.getMessage()); } } } mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/RemoteJMXSignatureTest.java100644 0 0 4143 10513545721 30311 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.compliance.signature; import java.io.Serializable; import java.lang.reflect.Modifier; import test.javax.management.compliance.signature.support.NotCompliantException; import test.javax.management.compliance.signature.support.NotCompliantWarningException; import test.javax.management.compliance.signature.support.SignatureVerifier; import test.javax.management.remote.compliance.RemoteJMXComplianceTestCase; /** * @version $Revision: 1.4 $ */ public class RemoteJMXSignatureTest extends RemoteJMXComplianceTestCase { public RemoteJMXSignatureTest(String s) { super(s); } protected boolean skipClassName(String className) { boolean isStub = className.endsWith("_Stub"); return isStub; } protected boolean skipClass(Class cls) { // Exclude implementation classes in javax.management.remote package int modifiers = cls.getModifiers(); boolean isPublic = Modifier.isPublic(modifiers); boolean isProtected = Modifier.isProtected(modifiers); boolean isPackage = !Modifier.isPrivate(modifiers) && !isProtected && !isPublic; boolean isSerializable = Serializable.class.isAssignableFrom(cls); if (isPublic || isProtected || (isPackage && isSerializable)) return false; return true; } protected void checkCompliance(String className) throws Exception { ClassLoader jmxriLoader = createRemoteJMXRIWithTestsClassLoader(); ClassLoader mx4jLoader = createRemoteMX4JWithTestsClassLoader(); SignatureVerifier verifier = new SignatureVerifier(); try { verifier.verifySignature(className, jmxriLoader, mx4jLoader); } catch (NotCompliantException x) { fail(x.getMessage()); } catch (NotCompliantWarningException x) { System.out.println("WARNING: " + x.getMessage()); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIConnectorServerTestCase.java100644 0 0 10712 10513545721 25575 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import test.javax.management.remote.JMXConnectorServerTestCase; /** * @version $Revision: 1.8 $ */ public abstract class RMIConnectorServerTestCase extends JMXConnectorServerTestCase implements RMITestCase { public RMIConnectorServerTestCase(String s) { super(s); } public void testNewRMIConnectorServerNullURL() throws Exception { try { new RMIConnectorServer(null, null); fail(); } catch (IllegalArgumentException x) { } } public void testNewRMIConnectorServerNullEnvironment() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); JMXConnectorServer server = new RMIConnectorServer(url, null, newMBeanServer()); try { server.start(); } finally { server.stop(); } } public void testNewRMIConnectorServerWithFactoryWrongClassLoader() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); Map env = getEnvironment(); env.put(JMXConnectorServerFactory.DEFAULT_CLASS_LOADER, new Object()); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail(); } catch (IllegalArgumentException x) { } } public void testNewRMIConnectorServerWithFactoryWrongClassLoaderName() throws Exception { JMXServiceURL url = createJMXConnectorServerAddress(); Map env = getEnvironment(); env.put(JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME, new Object()); try { JMXConnectorServerFactory.newJMXConnectorServer(url, env, null); fail(); } catch (IllegalArgumentException x) { } } public void testJNDIBindWithWrongPath1() throws Exception { JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "/jndi"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); try { cntorServer.start(); fail(); } catch (MalformedURLException x) { } } public void testJNDIBindWithWrongPath2() throws Exception { JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "/jndi"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); try { cntorServer.start(); fail(); } catch (MalformedURLException x) { } } public void testJNDIBindWithRelativePath() throws Exception { JMXConnectorServer cntorServer = null; try { startNaming(); JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "/jndi/jmx"); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); } finally { if (cntorServer != null) cntorServer.stop(); stopNaming(); } } public void testJNDIBindWithAbsolutePath() throws Exception { JMXConnectorServer cntorServer = null; try { startNaming(); JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "/jndi/" + temp.getProtocol() + "://localhost:" + getNamingPort() + "/jmx"); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); } finally { if (cntorServer != null) cntorServer.stop(); stopNaming(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIConnectorTestCase.java100644 0 0 6142 10513545721 24370 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnector; import javax.management.remote.rmi.RMIServer; import test.javax.management.remote.JMXConnectorTestCase; /** * @version $Revision: 1.13 $ */ public abstract class RMIConnectorTestCase extends JMXConnectorTestCase implements RMITestCase { public RMIConnectorTestCase(String s) { super(s); } public void testNewRMIConnectorNullURL() throws Exception { try { new RMIConnector((JMXServiceURL)null, null); fail(); } catch (IllegalArgumentException x) { } } public void testNewRMIConnectorNullRMIServer() throws Exception { try { new RMIConnector((RMIServer)null, null); fail(); } catch (IllegalArgumentException x) { } } public void testJNDILookupWithRelativePath() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { startNaming(); JMXServiceURL url = createJMXConnectorServerAddress(); url = new JMXServiceURL(url.getProtocol(), url.getHost(), url.getPort(), "/jndi/jmx"); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); mbsc.getDefaultDomain(); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); stopNaming(); } } public void testJNDILookupWithAbsolutePath() throws Exception { JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { startNaming(); JMXServiceURL url = createJMXConnectorServerAddress(); url = new JMXServiceURL(url.getProtocol(), url.getHost(), url.getPort(), "/jndi/" + url.getProtocol() + "://localhost:" + getNamingPort() + "/jmx"); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); cntorServer.start(); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); MBeanServerConnection mbsc = cntor.getMBeanServerConnection(); mbsc.getDefaultDomain(); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); stopNaming(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIIIOPConnectorInvocationTest.java100644 0 0 1622 10513545721 26305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.3 $ */ public class RMIIIOPConnectorInvocationTest extends JMXConnectorInvocationTestCase { public RMIIIOPConnectorInvocationTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("iiop", "localhost", 0); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIIIOPConnectorServerTest.java100644 0 0 5435 10513545721 25450 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import mx4j.tools.naming.CosNamingService; import org.omg.CORBA.ORB; /** * @version $Revision: 1.9 $ */ public class RMIIIOPConnectorServerTest extends RMIConnectorServerTestCase { private CosNamingService naming; public RMIIIOPConnectorServerTest(String s) { super(s); } public void startNaming() throws Exception { naming = new CosNamingService(getNamingPort()); naming.start(); Thread.sleep(5000); } public void stopNaming() throws Exception { naming.stop(); naming = null; Thread.sleep(5000); } public int getNamingPort() { return 1100; } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("iiop", "localhost", 0); } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory"); env.put(Context.PROVIDER_URL, "iiop://localhost:" + getNamingPort()); return env; } public void testInvalidProvidedORB() throws Exception { Map environment = new HashMap(); environment.put("java.naming.corba.orb", new Object()); JMXServiceURL url = new JMXServiceURL("iiop", null, 0, "/jndi/iiop://localhost:" + getNamingPort() + "/jmx"); try { JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, newMBeanServer()); connectorServer.start(); fail(); } catch (IllegalArgumentException ignored) { } } public void testProvidedORB() throws Exception { ORB orb = ORB.init((String[])null, null); Map environment = new HashMap(); environment.put("java.naming.corba.orb", orb); JMXServiceURL url = new JMXServiceURL("iiop", null, 0, "/jndi/iiop://localhost:" + getNamingPort() + "/jmx"); JMXConnectorServer connectorServer = null; try { startNaming(); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, newMBeanServer()); connectorServer.start(); } finally { if (connectorServer != null) connectorServer.stop(); stopNaming(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIIIOPConnectorTest.java100644 0 0 4655 10513545721 24264 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import mx4j.tools.naming.CosNamingService; /** * @version $Revision: 1.8 $ */ public class RMIIIOPConnectorTest extends RMIConnectorTestCase { private CosNamingService naming; public RMIIIOPConnectorTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("iiop", "localhost", 0); } public void startNaming() throws Exception { naming = new CosNamingService(getNamingPort()); naming.start(); Thread.sleep(5000); } public void stopNaming() throws Exception { naming.stop(); naming = null; Thread.sleep(5000); } public int getNamingPort() { return 1100; } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory"); env.put(Context.PROVIDER_URL, "iiop://localhost:" + getNamingPort()); // env.put("org.omg.CORBA.ORBInitialPort", String.valueOf(getNamingPort())); return env; } public void testInvalidProvidedORB() throws Exception { Map environment = new HashMap(); environment.put("java.naming.corba.orb", new Object()); JMXServiceURL url = new JMXServiceURL("iiop", null, 0, "/jndi/iiop://localhost:" + getNamingPort() + "/jmx"); JMXConnectorServer connectorServer = null; try { startNaming(); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, newMBeanServer()); connectorServer.start(); JMXConnectorFactory.connect(url, environment); fail(); } catch (IllegalArgumentException ignored) { } finally { if (connectorServer != null) connectorServer.stop(); stopNaming(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIIIOPNotificationsTest.java100644 0 0 2105 10513545721 25127 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import test.javax.management.remote.JMXNotificationsTestCase; /** * @version $Revision: 1.3 $ */ public class RMIIIOPNotificationsTest extends JMXNotificationsTestCase { public RMIIIOPNotificationsTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("iiop", "localhost", 0); } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory"); env.put(Context.PROVIDER_URL, "iiop://localhost:1100"); return env; } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIInteroperabilityTest.java100644 0 0 24160 10513545721 25207 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Map; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.loading.MLet; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import test.MX4JTestCase; import test.MutableObject; /** * @version $Revision: 1.4 $ */ public class RMIInteroperabilityTest extends MX4JTestCase { public RMIInteroperabilityTest(String s) { super(s); } private Object startJMXRIRMIConnectorServer() throws Exception { ClassLoader ri = createRemoteJMXRIWithTestsClassLoader(); Class mbeanServerFactoryClass = ri.loadClass(MBeanServerFactory.class.getName()); Method method = mbeanServerFactoryClass.getMethod("newMBeanServer", new Class[0]); Object mbeanServer = method.invoke(null, new Object[0]); if (!mbeanServer.getClass().getName().startsWith("com.sun")) fail(); Class mbeanServerClass = ri.loadClass(MBeanServer.class.getName()); Class serviceURLClass = ri.loadClass(JMXServiceURL.class.getName()); Constructor constructor = serviceURLClass.getConstructor(new Class[]{String.class}); Object serviceURL = constructor.newInstance(new Object[]{"service:jmx:rmi://localhost"}); Class cntorServerFactoryClass = ri.loadClass(JMXConnectorServerFactory.class.getName()); method = cntorServerFactoryClass.getMethod("newJMXConnectorServer", new Class[]{serviceURLClass, Map.class, mbeanServerClass}); Object cntorServer = method.invoke(null, new Object[]{serviceURL, null, mbeanServer}); method = cntorServer.getClass().getMethod("start", new Class[0]); method.invoke(cntorServer, new Object[0]); return cntorServer; } public void testJMXRIOnServerMX4JOnClientGetMBeanInfo() throws Exception { Object cntorServer = startJMXRIRMIConnectorServer(); Method method = cntorServer.getClass().getMethod("getAddress", new Class[0]); Object address = method.invoke(cntorServer, new Object[0]); String url = address.toString(); JMXConnector cntor = JMXConnectorFactory.connect(new JMXServiceURL(url)); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); MBeanInfo info = cntion.getMBeanInfo(ObjectName.getInstance("JMImplementation", "type", "MBeanServerDelegate")); assertNotNull(info); cntor.close(); method = cntorServer.getClass().getMethod("stop", new Class[0]); method.invoke(cntorServer, new Object[0]); sleep(2000); } public void testJMXRIOnServerMX4JOnClientNotificationReceiving() throws Exception { Object cntorServer = startJMXRIRMIConnectorServer(); Method method = cntorServer.getClass().getMethod("getAddress", new Class[0]); Object address = method.invoke(cntorServer, new Object[0]); String url = address.toString(); JMXConnector cntor = JMXConnectorFactory.connect(new JMXServiceURL(url)); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); InteroperabilityListener listener = new InteroperabilityListener(); ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); cntion.addNotificationListener(delegateName, listener, null, null); sleep(1000); ObjectName name = ObjectName.getInstance(":mbean=mlet"); cntion.createMBean(MLet.class.getName(), name, null); sleep(1000); Notification notification = (Notification)listener.get(); assertNotNull(notification); listener.reset(); cntion.removeNotificationListener(delegateName, listener); cntion.unregisterMBean(name); sleep(1000); notification = (Notification)listener.get(); assertNull(notification); cntor.close(); method = cntorServer.getClass().getMethod("stop", new Class[0]); method.invoke(cntorServer, new Object[0]); sleep(2000); } private Object connectJMXRIConnector(ClassLoader ri, String url) throws Exception { Class serviceURLClass = ri.loadClass(JMXServiceURL.class.getName()); Constructor constructor = serviceURLClass.getConstructor(new Class[]{String.class}); Object serviceURL = constructor.newInstance(new Object[]{url}); Class cntorFactoryClass = ri.loadClass(JMXConnectorFactory.class.getName()); Method method = cntorFactoryClass.getMethod("connect", new Class[]{serviceURLClass}); return method.invoke(null, new Object[]{serviceURL}); } public void testMX4JOnServerJMXRIOnClientGetMBeanInfo() throws Exception { MBeanServer server = newMBeanServer(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); url = cntorServer.getAddress(); ClassLoader ri = createRemoteJMXRIWithTestsClassLoader(); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ri); Object cntor = connectJMXRIConnector(ri, url.toString()); Method method = cntor.getClass().getMethod("getMBeanServerConnection", new Class[0]); Object cntion = method.invoke(cntor, new Object[0]); Class cntionClass = ri.loadClass(MBeanServerConnection.class.getName()); Class objectNameClass = ri.loadClass(ObjectName.class.getName()); method = objectNameClass.getMethod("getInstance", new Class[]{String.class}); Object objectName = method.invoke(null, new Object[]{"JMImplementation:type=MBeanServerDelegate"}); method = cntionClass.getMethod("getMBeanInfo", new Class[]{objectNameClass}); Object info = method.invoke(cntion, new Object[]{objectName}); assertNotNull(info); method = cntor.getClass().getMethod("close", new Class[0]); method.invoke(cntor, new Object[0]); Thread.currentThread().setContextClassLoader(tccl); cntorServer.stop(); sleep(2000); } public void testMX4JOnServerJMXRIOnClientNotificationReceiving() throws Exception { MBeanServer server = newMBeanServer(); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost"); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); url = cntorServer.getAddress(); ClassLoader ri = createRemoteJMXRIWithTestsClassLoader(); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ri); Object cntor = connectJMXRIConnector(ri, url.toString()); Method method = cntor.getClass().getMethod("getMBeanServerConnection", new Class[0]); Object cntion = method.invoke(cntor, new Object[0]); Class cntionClass = ri.loadClass(MBeanServerConnection.class.getName()); Class objectNameClass = ri.loadClass(ObjectName.class.getName()); method = objectNameClass.getMethod("getInstance", new Class[]{String.class}); Object delegateName = method.invoke(null, new Object[]{"JMImplementation:type=MBeanServerDelegate"}); Class notificationListenerClass = ri.loadClass(NotificationListener.class.getName()); Class notificationFilterClass = ri.loadClass(NotificationFilter.class.getName()); Object listener = ri.loadClass(InteroperabilityListener.class.getName()).newInstance(); method = cntionClass.getMethod("addNotificationListener", new Class[]{objectNameClass, notificationListenerClass, notificationFilterClass, Object.class}); method.invoke(cntion, new Object[]{delegateName, listener, null, null}); sleep(1000); method = objectNameClass.getMethod("getInstance", new Class[]{String.class}); Object mletName = method.invoke(null, new Object[]{":mbean=mlet"}); method = cntionClass.getMethod("createMBean", new Class[]{String.class, objectNameClass, objectNameClass}); method.invoke(cntion, new Object[]{MLet.class.getName(), mletName, null}); sleep(1000); method = listener.getClass().getMethod("get", new Class[0]); Object notification = method.invoke(listener, new Object[0]); assertNotNull(notification); method = listener.getClass().getMethod("reset", new Class[0]); method.invoke(listener, new Object[0]); method = cntionClass.getMethod("removeNotificationListener", new Class[]{objectNameClass, notificationListenerClass}); method.invoke(cntion, new Object[]{delegateName, listener}); method = cntionClass.getMethod("unregisterMBean", new Class[]{objectNameClass}); method.invoke(cntion, new Object[]{mletName}); sleep(1000); method = listener.getClass().getMethod("get", new Class[0]); notification = method.invoke(listener, new Object[0]); assertNull(notification); method = cntor.getClass().getMethod("close", new Class[0]); method.invoke(cntor, new Object[0]); Thread.currentThread().setContextClassLoader(tccl); cntorServer.stop(); sleep(2000); } public static class InteroperabilityListener implements NotificationListener { private final MutableObject holder; public InteroperabilityListener() { this.holder = new MutableObject(null); } public void handleNotification(Notification notification, Object handback) { holder.set(notification); } public void reset() { holder.set(null); } public Object get() { return holder.get(); } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPConnectorInvocationTest.java100644 0 0 1621 10513545721 26314 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.3 $ */ public class RMIJRMPConnectorInvocationTest extends JMXConnectorInvocationTestCase { public RMIJRMPConnectorInvocationTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("rmi", "localhost", 0); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPConnectorServerTest.java100644 0 0 2652 10513545721 25456 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import mx4j.tools.naming.NamingService; /** * @version $Revision: 1.7 $ */ public class RMIJRMPConnectorServerTest extends RMIConnectorServerTestCase { private NamingService naming; public RMIJRMPConnectorServerTest(String s) { super(s); } public void startNaming() throws Exception { naming = new NamingService(getNamingPort()); naming.start(); } public void stopNaming() throws Exception { naming.stop(); naming = null; Thread.sleep(5000); } public int getNamingPort() { return 1099; } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("rmi", "localhost", 0); } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:" + getNamingPort()); return env; } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPConnectorTest.java100644 0 0 6701 10513545721 24266 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.Socket; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import javax.naming.Context; import mx4j.tools.naming.NamingService; import test.MutableBoolean; /** * @version $Revision: 1.9 $ */ public class RMIJRMPConnectorTest extends RMIConnectorTestCase { private NamingService naming; public RMIJRMPConnectorTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("rmi", "localhost", 0); } public void startNaming() throws Exception { naming = new NamingService(getNamingPort()); naming.start(); } public void stopNaming() throws Exception { naming.stop(); naming = null; Thread.sleep(5000); } public int getNamingPort() { return 1099; } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:" + getNamingPort()); return env; } public void testRMIConnectorWithCustomSocketFactories() throws Exception { RMIClientSocketFactory client = new RMICSF(); final MutableBoolean serverCheck = new MutableBoolean(false); RMIServerSocketFactory server = new RMISSF(serverCheck); JMXServiceURL url = createJMXConnectorServerAddress(); Map env = getEnvironment(); env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, client); env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, server); JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, newMBeanServer()); cntorServer.start(); cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); assertTrue(serverCheck.get()); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } public static class RMICSF implements RMIClientSocketFactory, Serializable { public Socket createSocket(String host, int port) throws IOException { return new Socket(host, port); } } public static class RMISSF implements RMIServerSocketFactory { private MutableBoolean check; public RMISSF(MutableBoolean check) { this.check = check; } public ServerSocket createServerSocket(int port) throws IOException { check.set(true); return new ServerSocket(port); } } } ././@LongLink100644 0 0 146 10513545722 10260 Lustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPMultiThreadMBeanServerConnectionTest.javamx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPMultiThreadMBeanServerConnectionTest.jav100644 0 0 2725 10513545721 30531 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import javax.management.MBeanServer; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import test.javax.management.MultiThreadMBeanServerTest; /** * @version $Revision: 1.3 $ */ public class RMIJRMPMultiThreadMBeanServerConnectionTest extends MultiThreadMBeanServerTest { private JMXConnectorServer connectorServer; public RMIJRMPMultiThreadMBeanServerConnectionTest(String s) { super(s); } protected void setUp() throws Exception { MBeanServer server = newMBeanServer(); JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); connectorServer.start(); sleep(1000); JMXConnector connector = JMXConnectorFactory.connect(connectorServer.getAddress()); this.server = connector.getMBeanServerConnection(); } protected void tearDown() throws Exception { super.tearDown(); connectorServer.stop(); sleep(1000); } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPNotificationsTest.java100644 0 0 2120 10513545721 25134 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import javax.naming.Context; import test.javax.management.remote.JMXNotificationsTestCase; /** * @version $Revision: 1.3 $ */ public class RMIJRMPNotificationsTest extends JMXNotificationsTestCase { public RMIJRMPNotificationsTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("rmi", "localhost", 0); } public Map getEnvironment() { HashMap env = new HashMap(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:1099"); return env; } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPRemoteSecurityManagerTest.java100644 0 0 2542 10513545721 26611 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.net.MalformedURLException; import java.security.Policy; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.RemoteSecurityManagerTestCase; /** * @version $Revision: 1.3 $ */ public class RMIJRMPRemoteSecurityManagerTest extends RemoteSecurityManagerTestCase { static { // For the way JUnit works, we have one JVM per test class Policy.setPolicy(new RMIJRMPRemoteModifiablePolicy()); System.setSecurityManager(new SecurityManager()); } public RMIJRMPRemoteSecurityManagerTest(String s) { super(s); } protected JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("rmi", "localhost", 7777); } public static class RMIJRMPRemoteModifiablePolicy extends RemoteModifiablePolicy { public boolean isServerSide() { if (!isSeparateClientServerPermissions()) return true; String name = Thread.currentThread().getName(); if (name.indexOf("RMI") >= 0) return true; return false; } } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIMarshallingTest.java100644 0 0 20372 10513545721 24124 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; import java.io.File; import java.io.Serializable; import java.net.URL; import java.util.Set; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.Notification; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.loading.PrivateMLet; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import test.MX4JTestCase; import test.javax.management.remote.support.Marshalling; import test.javax.management.remote.support.Unknown; /** * @version $Revision: 1.5 $ */ public class RMIMarshallingTest extends MX4JTestCase { private MBeanServer server = null; private MBeanServerConnection conn = null; private JMXConnectorServer cntorServer = null; private JMXConnector cntor = null; private ObjectName mbeanName; private ObjectName mbeanLoaderName; public RMIMarshallingTest(String s) { super(s); } public void setUp() throws Exception { super.setUp(); // Create a classloader that sees only the MBean and its parameter classes (Unknown) File mbeanJar = new File("dist/test/mx4j-tests.jar"); PrivateMLet mbeanLoader = new PrivateMLet(new URL[]{mbeanJar.toURL()}, getClass().getClassLoader().getParent(), false); mbeanLoaderName = ObjectName.getInstance("marshal:type=mlet"); server = newMBeanServer(); server.registerMBean(mbeanLoader, mbeanLoaderName); JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server); cntorServer.start(); cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); conn = cntor.getMBeanServerConnection(); mbeanName = ObjectName.getInstance("marshal:type=mbean"); } public void tearDown() throws Exception { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } protected static class MockNotificationListener implements NotificationListener, Serializable { long numberOfNotifications = 0; public void handleNotification(Notification notification, Object handback) { // System.out.println("[MockNotificationListener] Notification: "+notification+" Handback: "+handback); assertEquals(notification.getSequenceNumber(), numberOfNotifications); assertEquals(notification.getType(), Unknown.class.getName()); numberOfNotifications++; synchronized (this) { this.notify(); } } public synchronized void waitOnNotification(long timeout, long sequence) throws InterruptedException { long to; if (timeout > 0) to = System.currentTimeMillis() + timeout; else to = -1; while (numberOfNotifications < sequence) // Check for missed notification { this.wait(timeout); if (to > -1 && System.currentTimeMillis() >= to) // Check if waited for full timeout { Thread.currentThread().interrupt(); break; } } } } protected static class MockNotificationFilter implements NotificationFilter, Serializable { public boolean isNotificationEnabled(Notification notification) { // System.out.println("[MockNotificationFilter] Notification: "+notification); return true; } } private void createMBean() throws Exception { ObjectInstance inst = conn.createMBean(Marshalling.class.getName(), mbeanName, new Object[]{new Unknown()}, new String[]{Unknown.class.getName()}); } public void testCreateMBean() throws Exception { conn.createMBean(Marshalling.class.getName(), mbeanName); checkRegistration(); conn.createMBean(Marshalling.class.getName(), mbeanName, new Object[]{new Unknown()}, new String[]{Unknown.class.getName()}); checkRegistration(); } private void checkRegistration() throws Exception { // Check registrations if (!conn.isRegistered(mbeanName)) fail(); if (!server.isRegistered(mbeanName)) fail(); conn.unregisterMBean(mbeanName); } public void testInstanceOf() throws Exception { createMBean(); // Check instanceof if (!conn.isInstanceOf(mbeanName, Marshalling.class.getName())) fail(); if (!server.isInstanceOf(mbeanName, Marshalling.class.getName())) fail(); } public void testInvocationUnknownReturn() throws Exception { createMBean(); // Check invocation Object returned = conn.invoke(mbeanName, "unknownReturnValue", new Object[0], new String[0]); if (!returned.getClass().getName().equals(Unknown.class.getName())) fail(); returned = server.invoke(mbeanName, "unknownReturnValue", new Object[0], new String[0]); if (!returned.getClass().getName().equals(Unknown.class.getName())) fail(); Object remoteUnk = conn.invoke(mbeanName, "unknownArgument", new Object[]{new Unknown()}, new String[]{Unknown.class.getName()}); Object localUnk = server.invoke(mbeanName, "unknownArgument", new Object[]{new Unknown()}, new String[]{Unknown.class.getName()}); assertEquals(remoteUnk, localUnk); } public void testUnregisterMBean() throws Exception { createMBean(); // Check unregistration conn.unregisterMBean(mbeanName); if (conn.isRegistered(mbeanName)) fail(); if (server.isRegistered(mbeanName)) fail(); } public void testNotifications() throws Exception { createMBean(); MockNotificationListener listener = new MockNotificationListener(); conn.addNotificationListener(mbeanName, listener, new MockNotificationFilter(), new Object()); Thread.sleep(1000L); Attribute att = new Attribute("UnknownAttribute", new Unknown()); conn.setAttribute(mbeanName, att); Thread.sleep(1000L); // This triggers a notification try { listener.waitOnNotification(1000L, 1); } catch (InterruptedException ignore) { } assertEquals(1, listener.numberOfNotifications); conn.removeNotificationListener(mbeanName, listener); Thread.sleep(1000L); conn.setAttribute(mbeanName, att); Thread.sleep(1000L); // This triggers a notification try { listener.waitOnNotification(1000L, 2); } catch (InterruptedException ignore) { } assertEquals(1, listener.numberOfNotifications); } public void testQuery() throws Exception { createMBean(); ObjectName pattern = mbeanName; ObjectName query = mbeanName; Set beans = conn.queryMBeans(pattern, query); Object[] set = beans.toArray(); assertEquals(1, set.length); // System.out.println("set[0]: "+set[0]+" class: "+set[0].getClass()); ObjectInstance inst = (ObjectInstance)set[0]; assertTrue(inst.getClassName().equals(Marshalling.class.getName())); beans = conn.queryNames(pattern, query); set = beans.toArray(); assertEquals(1, set.length); // System.out.println("set[0]: "+set[0]+" class: "+set[0].getClass()); ObjectName nm = (ObjectName)set[0]; assertTrue(nm.equals(mbeanName)); } public void testAttributes() throws Exception { createMBean(); Unknown value = new Unknown(); Attribute att = new Attribute("UnknownAttribute", value); conn.setAttribute(mbeanName, att); Object returned = conn.getAttribute(mbeanName, "UnknownAttribute"); assertTrue(returned.getClass().getName().equals(Unknown.class.getName())); } } mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMITestCase.java100644 0 0 776 10513545721 22504 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.rmi; /** * @version $Revision: 1.6 $ */ public interface RMITestCase { public abstract void startNaming() throws Exception; public abstract void stopNaming() throws Exception; public abstract int getNamingPort(); } mx4j-3.0.2/src/test/test/javax/management/remote/support/Marshalling.java100644 0 0 4114 10513545721 23615 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.support; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; /** * @version $Revision: 1.3 $ */ public class Marshalling implements MarshallingMBean, NotificationEmitter { private NotificationBroadcasterSupport nbs = new NotificationBroadcasterSupport(); private long sequenceNo = 0; public Marshalling() { } public Marshalling(Unknown u) { } public Unknown unknownReturnValue() { return new Unknown(); } public void unknownArgument(Unknown u) { } public Unknown getUnknownAttribute() { return new Unknown(); } public void setUnknownAttribute(Unknown u) { Notification notification = new Notification(u.getClass().getName(), this, sequenceNo); sequenceNo++; nbs.sendNotification(notification); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { nbs.removeNotificationListener(listener, filter, handback); } public MBeanNotificationInfo[] getNotificationInfo() { return nbs.getNotificationInfo(); } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { nbs.addNotificationListener(listener, filter, handback); } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { nbs.removeNotificationListener(listener); } } mx4j-3.0.2/src/test/test/javax/management/remote/support/MarshallingMBean.java100644 0 0 1033 10513545721 24515 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.support; /** * @version $Revision: 1.3 $ */ public interface MarshallingMBean { public Unknown unknownReturnValue(); public void unknownArgument(Unknown u); public Unknown getUnknownAttribute(); public void setUnknownAttribute(Unknown u); } mx4j-3.0.2/src/test/test/javax/management/remote/support/Unknown.java100644 0 0 1316 10513545721 23014 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.remote.support; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * @version $Revision: 1.3 $ */ public class Unknown implements Serializable { private transient ClassLoader loader = getClass().getClassLoader(); private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); loader = getClass().getClassLoader(); } } mx4j-3.0.2/src/test/test/javax/management/support/ClassLoaderSupport.java100644 0 0 1066 10513545721 23655 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import java.net.URL; import java.net.URLClassLoader; /** * @version $Revision: 1.3 $ */ public class ClassLoaderSupport extends URLClassLoader implements ClassLoaderSupportMBean { public ClassLoaderSupport(URL[] urls, ClassLoader parent) { super(urls, parent); } } mx4j-3.0.2/src/test/test/javax/management/support/ClassLoaderSupportMBean.java100644 0 0 555 10513545721 24542 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; /** * @version $Revision: 1.3 $ */ public interface ClassLoaderSupportMBean { } mx4j-3.0.2/src/test/test/javax/management/support/ComplianceSupport.java100644 0 0 22657 10513545721 23564 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.ReflectionException; /** * @version $Revision: 1.6 $ */ public class ComplianceSupport { // Not a manageable class: missing management interface public static class NoManagement { } // Not a manageable class: implements an interface with different name public interface LexicalPatternNotRespectedMBean { public void fake(); } public static class DoesntRespectLexicalPattern implements LexicalPatternNotRespectedMBean { public void fake() { } } // MBeans with overloaded attributes are not compliant public interface OverloadedAttributeSetSetMBean { public void setAttribute(String s); public void setAttribute(Integer i); } public static class OverloadedAttributeSetSet implements OverloadedAttributeSetSetMBean { public void setAttribute(String s) { } public void setAttribute(Integer i) { } } public interface OverloadedAttributeGetSetMBean { public String getAttribute(); public void setAttribute(Integer i); } public static class OverloadedAttributeGetSet implements OverloadedAttributeGetSetMBean { public String getAttribute() { return null; } public void setAttribute(Integer i) { } } public interface OverloadedAttributeIsGetMBean { public boolean isBoolean(); public boolean getBoolean(); } public static class OverloadedAttributeIsGet implements OverloadedAttributeIsGetMBean { public boolean isBoolean() { return false; } public boolean getBoolean() { return false; } } // In JMX 1.0 this is not a manageable class: it's abstract // In JMX 1.1 the requirement for the MBean class to be concrete has been removed // public interface AbstractMBean {} // public static abstract class Abstract implements AbstractMBean {} // Valid MBean public static interface BasicStandardMBean { public void test(); } public static class BasicStandard implements BasicStandardMBean { private int m_count; // This method should not be part of the management interface public void noManage() { } public void test() { ++m_count; } } // Valid MBean that inherits from parent its manageability public static class Derived extends BasicStandard { public void derivedNoManage() { } } // Valid MBean with inherited management interface public interface BaseMBean { public void base(); } public interface InheritedMBean extends BaseMBean { public void derived(); public void test2(); public void retest(); } public static class Inherited implements InheritedMBean { public void base() { } public void derived() { } public void test2() { } public void retest() { } } // Valid MBean with a trap: the management interface should be only the one inherited from Basic public static class NotInherited extends BasicStandard implements InheritedMBean { public void base() { } public void derived() { } public void retest() { } public void test2() { } public void unManage() { } } // Valid MBean with multiple inheritance public interface MultiMBean extends BasicStandardMBean, InheritedMBean { } public static class Multi extends Inherited implements MultiMBean { public void test() { } } // Valid MBean even if the class is package private public interface PackagePrivateMBean { } static class PackagePrivate implements PackagePrivateMBean { } // In JMX 1.0 this is not a valid MBean: it is standard and dynamic // In JMX 1.1 it is dynamic, since the spec says that every class that implements DynamicMBean is a dynamic mbean // However, I assume that if someone writes such a class, or it did not understand JMX or is trying to fool the MBeanServer public interface StandardDynamicMBean { } public static class StandardDynamic implements DynamicMBean, StandardDynamicMBean { public MBeanInfo getMBeanInfo() { return new MBeanInfo(getClass().getName(), null, null, null, null, null); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return new AttributeList(); } public AttributeList setAttributes(AttributeList attributes) { return new AttributeList(); } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } } // JMX 1.0: Invalid MBean: the standard MBean interface is a dynamic MBean // JMX 1.1: This is a dynamic MBean public interface StandardAndDynamicMBean extends DynamicMBean { public void mix(); } public static class StandardAndDynamic implements StandardAndDynamicMBean { public void mix() { } public MBeanInfo getMBeanInfo() { return new MBeanInfo(getClass().getName(), null, null, null, null, null); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return null; } public AttributeList setAttributes(AttributeList attributes) { return null; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } } // A valid dynamic MBean public static class BasicDynamic implements DynamicMBean { public MBeanInfo getMBeanInfo() { return new MBeanInfo(getClass().getName(), null, null, null, null, null); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return null; } public AttributeList setAttributes(AttributeList attributes) { return null; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } } // Invalid dynamic MBean because getClassName() returns null public static class NoClassNameDynamicMBean extends BasicDynamic { public MBeanInfo getMBeanInfo() { MBeanInfo info = super.getMBeanInfo(); return new MBeanInfo(null, info.getDescription(), info.getAttributes(), info.getConstructors(), info.getOperations(), info.getNotifications()); } } // Valid dynamic MBean, even if its parent is standard public static class DynamicFromStandard extends BasicStandard implements DynamicMBean { public MBeanInfo getMBeanInfo() { return new MBeanInfo(getClass().getName(), null, null, null, null, null); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return new AttributeList(); } public AttributeList setAttributes(AttributeList attributes) { return new AttributeList(); } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } } // In JMX 1.0, this is a valid standard MBean even if its parent is dynamic // In JMX 1.1, this is a dynamic MBean public interface StandardFromDynamicMBean { } public static class StandardFromDynamic extends DynamicFromStandard implements StandardFromDynamicMBean { } } mx4j-3.0.2/src/test/test/javax/management/support/ExceptionGeneratingDMB.java100644 0 0 5600 10513545721 24347 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; /** * @version $Revision: 1.3 $ */ public class ExceptionGeneratingDMB implements DynamicMBean, MBeanRegistration { private boolean invoked = false; private boolean register; public ExceptionGeneratingDMB(boolean register) { this.register = register; } public MBeanInfo getMBeanInfo() { if ((this.register == false) || (this.invoked == true)) { throw new RuntimeException(); } else { invoked = true; return new MBeanInfo("test.javax.management.support.test.ExceptionGeneratingDMB", "Exception generating DynamicMBean", new MBeanAttributeInfo[0], new MBeanConstructorInfo[0], new MBeanOperationInfo[0], new MBeanNotificationInfo[0]); } } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return null; } public AttributeList setAttributes(AttributeList attributes) { return null; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if (name.getKeyProperty("register").compareTo("no") == 0) { this.register = false; } return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } } mx4j-3.0.2/src/test/test/javax/management/support/MBeanDynamic.java100644 0 0 13371 10513545721 22375 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ReflectionException; /** * @version $Revision: 1.4 $ */ public class MBeanDynamic implements DynamicMBean { private String m_value1 = ""; private String m_value2 = ""; public MBeanInfo getMBeanInfo() { MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[2]; attrs[0] = new MBeanAttributeInfo("DynamicAttribute1", "java.lang.String", "A first dynamic attribute", true, true, false); attrs[1] = new MBeanAttributeInfo("DynamicAttribute2", "java.lang.String", "A second dynamic attribute", true, true, false); MBeanConstructorInfo[] ctors = new MBeanConstructorInfo[1]; ctors[0] = new MBeanConstructorInfo("ParameterlessConstructor", "A dynamic constructor", new MBeanParameterInfo[0]); MBeanOperationInfo[] opers = new MBeanOperationInfo[1]; MBeanParameterInfo[] params = new MBeanParameterInfo[1]; params[0] = new MBeanParameterInfo("supposedAttributeValue", "java.lang.String", "Checks if the value of the argument is equal to the value of the attribute"); opers[0] = new MBeanOperationInfo("dynamicOperation", "A dynamic operation", params, "boolean", MBeanOperationInfo.INFO); MBeanNotificationInfo[] notifs = new MBeanNotificationInfo[0]; return new MBeanInfo(getClass().getName(), "A MBeanDynamic MBean", attrs, ctors, opers, notifs); } private String getDynamicAttribute1() { return m_value1; } private void setDynamicAttribute1(String value) { m_value1 = value; } private String getDynamicAttribute2() { return m_value2; } private void setDynamicAttribute2(String value) { m_value2 = value; } private boolean dynamicOperation(String value) { return m_value1.equals(value); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attribute.equals("DynamicAttribute1")) { return getDynamicAttribute1(); } else if (attribute.equals("DynamicAttribute2")) { return getDynamicAttribute2(); } else throw new AttributeNotFoundException(attribute); } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (attribute.getName().equals("DynamicAttribute1")) { Object val = attribute.getValue(); if (val instanceof String) { setDynamicAttribute1((String)val); } else { throw new InvalidAttributeValueException(val == null ? "null" : val.toString()); } } else if (attribute.getName().equals("DynamicAttribute2")) { Object val = attribute.getValue(); if (val instanceof String) { setDynamicAttribute2((String)val); } else { throw new InvalidAttributeValueException(val == null ? "null" : val.toString()); } } else { throw new AttributeNotFoundException(attribute.getName()); } } public AttributeList getAttributes(String[] attributes) { AttributeList list = new AttributeList(); for (int i = 0; i < attributes.length; ++i) { if (attributes[i].equals("DynamicAttribute1")) { list.add(new Attribute(attributes[i], getDynamicAttribute1())); } else if (attributes[i].equals("DynamicAttribute2")) { list.add(new Attribute(attributes[i], getDynamicAttribute2())); } } return list; } public AttributeList setAttributes(AttributeList attributes) { AttributeList list = new AttributeList(); for (int i = 0; i < attributes.size(); ++i) { Attribute attr = (Attribute)attributes.get(i); if (attr.getName().equals("DynamicAttribute1") || attr.getName().equals("DynamicAttribute2")) { try { setAttribute(attr); list.add(attr); } catch (AttributeNotFoundException ignored) { } catch (InvalidAttributeValueException ignored) { } catch (MBeanException ignored) { } catch (ReflectionException ignored) { } } } return list; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { if (method.equals("dynamicOperation") && params.length == 1 && params[0].equals("java.lang.String") && arguments.length == 1 && arguments[0] instanceof String) { boolean match = dynamicOperation((String)arguments[0]); return new Boolean(match); } else { throw new MBeanException(new IllegalArgumentException("Invalid method or arguments for invoke")); } } } mx4j-3.0.2/src/test/test/javax/management/support/MBeanThrowingExceptions.java100644 0 0 1071 10513545721 24626 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.ReflectionException; /** * @version $Revision: 1.1 $ */ public class MBeanThrowingExceptions implements MBeanThrowingExceptionsMBean { public void throwReflectionException() throws ReflectionException { throw new ReflectionException(null); } } mx4j-3.0.2/src/test/test/javax/management/support/MBeanThrowingExceptionsMBean.java100644 0 0 746 10513545721 25521 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.ReflectionException; /** * @version $Revision: 1.1 $ */ public interface MBeanThrowingExceptionsMBean { public void throwReflectionException() throws ReflectionException; } mx4j-3.0.2/src/test/test/javax/management/support/NotificationSupport.java100644 0 0 1062 10513545721 24103 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.NotificationBroadcasterSupport; /** * @version $Revision: 1.3 $ */ public class NotificationSupport { public interface EmitterMBean { } public static class Emitter extends NotificationBroadcasterSupport implements EmitterMBean { } } mx4j-3.0.2/src/test/test/javax/management/support/NullMBeanInfoDMB.java100644 0 0 5123 10513545721 23036 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; /** * @version $Revision: 1.4 $ */ public class NullMBeanInfoDMB implements DynamicMBean, MBeanRegistration { private boolean registered; public MBeanInfo getMBeanInfo() { return (registered) ? null : new MBeanInfo("test.javax.management.support.NullMBeanInfoDMB", "A DynamicMBean that returns null in response to getMBeanInfo() invocations", new MBeanAttributeInfo[0], new MBeanConstructorInfo[0], new MBeanOperationInfo[0], new MBeanNotificationInfo[0]); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { } public AttributeList getAttributes(String[] attributes) { return null; } public AttributeList setAttributes(AttributeList attributes) { return null; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } public void postDeregister() { } public void postRegister(Boolean registrationDone) { registered = registrationDone.booleanValue(); } public void preDeregister() throws Exception { } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } } mx4j-3.0.2/src/test/test/javax/management/support/PostRegistrationSupport.java100644 0 0 2406 10513545721 25000 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import java.util.Set; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; /** * @version $Revision: 1.3 $ */ public class PostRegistrationSupport implements PostRegistrationSupportMBean, MBeanRegistration { private MBeanServer server; private ObjectName name; public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; this.name = name; return name; } public void postRegister(Boolean registrationDone) { if (registrationDone.booleanValue()) { Set mbeans = server.queryMBeans(name, null); if (mbeans.size() != 1) throw new Error(); ObjectInstance instance = (ObjectInstance)mbeans.iterator().next(); if (instance == null) throw new Error(); } } public void preDeregister() throws Exception { } public void postDeregister() { } } mx4j-3.0.2/src/test/test/javax/management/support/PostRegistrationSupportMBean.java100644 0 0 562 10513545721 25664 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; /** * @version $Revision: 1.3 $ */ public interface PostRegistrationSupportMBean { } mx4j-3.0.2/src/test/test/javax/management/support/PrivateMBeanDynamic.java100644 0 0 13543 10513545721 23731 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ReflectionException; /** * @version $Revision: 1.3 $ */ class PrivateMBeanDynamic implements DynamicMBean { private String m_value1 = ""; private String m_value2 = ""; public MBeanInfo getMBeanInfo() { MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[2]; attrs[0] = new MBeanAttributeInfo("DynamicAttribute1", "java.lang.String", "A first dynamic attribute", true, true, false); attrs[1] = new MBeanAttributeInfo("DynamicAttribute2", "java.lang.String", "A second dynamic attribute", true, true, false); MBeanConstructorInfo[] ctors = new MBeanConstructorInfo[1]; ctors[0] = new MBeanConstructorInfo("Parameterless Constructor", "A dynamic constructor", new MBeanParameterInfo[0]); MBeanOperationInfo[] opers = new MBeanOperationInfo[1]; MBeanParameterInfo[] params = new MBeanParameterInfo[1]; params[0] = new MBeanParameterInfo("supposedAttributeValue", "java.lang.String", "Checks if the value of the argument is equal to the value of the attribute"); opers[0] = new MBeanOperationInfo("dynamicOperation", "A dynamic operation", params, "boolean", MBeanOperationInfo.INFO); MBeanNotificationInfo[] notifs = new MBeanNotificationInfo[0]; return new MBeanInfo(getClass().getName(), "A MBeanDynamic MBean", attrs, ctors, opers, notifs); } private String getDynamicAttribute1() { return m_value1; } private void setDynamicAttribute1(String value) { m_value1 = value; } private String getDynamicAttribute2() { return m_value2; } private void setDynamicAttribute2(String value) { m_value2 = value; } private boolean dynamicOperation(String value) { return m_value1.equals(value); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attribute.equals("DynamicAttribute1")) { return getDynamicAttribute1(); } else if (attribute.equals("DynamicAttribute2")) { return getDynamicAttribute2(); } else throw new AttributeNotFoundException(attribute); } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (attribute.getName().equals("DynamicAttribute1")) { Object val = attribute.getValue(); if (val instanceof String) { setDynamicAttribute1((String)val); } else { throw new InvalidAttributeValueException(val == null ? "null" : val.toString()); } } else if (attribute.getName().equals("DynamicAttribute2")) { Object val = attribute.getValue(); if (val instanceof String) { setDynamicAttribute2((String)val); } else { throw new InvalidAttributeValueException(val == null ? "null" : val.toString()); } } else { throw new AttributeNotFoundException(attribute.getName()); } } public AttributeList getAttributes(String[] attributes) { AttributeList list = new AttributeList(); for (int i = 0; i < attributes.length; ++i) { if (attributes[i].equals("DynamicAttribute1")) { list.add(new Attribute(attributes[i], getDynamicAttribute1())); } else if (attributes[i].equals("DynamicAttribute2")) { list.add(new Attribute(attributes[i], getDynamicAttribute2())); } } return list; } public AttributeList setAttributes(AttributeList attributes) { AttributeList list = new AttributeList(); for (int i = 0; i < attributes.size(); ++i) { Attribute attr = (Attribute)attributes.get(i); if (attr.getName().equals("DynamicAttribute1") || attr.getName().equals("DynamicAttribute2")) { try { setAttribute(attr); list.add(attr); } catch (AttributeNotFoundException ignored) { } catch (InvalidAttributeValueException ignored) { } catch (MBeanException ignored) { } catch (ReflectionException ignored) { } } } return list; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { if (method.equals("dynamicOperation") && params.length == 1 && params[0].equals("java.lang.String") && arguments.length == 1 && arguments[0] instanceof String) { boolean match = dynamicOperation((String)arguments[0]); return new Boolean(match); } else { throw new MBeanException(new IllegalArgumentException("Invalid method or arguments for invoke")); } } } mx4j-3.0.2/src/test/test/javax/management/support/QuerySupport.java100644 0 0 15515 10513545721 22612 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.ReflectionException; /** * @version $Revision: 1.5 $ */ public class QuerySupport { public interface TestMBean { public Integer getNumber(); public String getStr(); public Boolean getBoolean(); } public static class Test implements TestMBean { private Integer n; private String str; private Boolean b; public Test(String str, Integer n, Boolean b) { this.str = str; this.n = n; this.b = b; } public Integer getNumber() { return n; } public String getStr() { return str; } public Boolean getBoolean() { return b; } } public static class DynamicTest implements DynamicMBean { private Boolean boolval; private long numval; private String strval; public DynamicTest(String s, long n, Boolean b) { this.boolval = b; this.numval = n; this.strval = s; } public Boolean getBoolean() { return this.boolval; } public long getNumber() { return this.numval; } public void setNumber(long value) { this.numval = value; } public String getStr() { throw new RuntimeException("Don't call me!"); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { Object result; if (attribute.compareTo("Boolean") == 0) { result = getBoolean(); } else if (attribute.compareTo("Number") == 0) { result = new Long(getNumber()); } else if (attribute.compareTo("Str") == 0) { result = getStr(); } else { throw new AttributeNotFoundException("Can't find " + attribute); } return result; } public AttributeList getAttributes(String[] attributes) { List attrnames = new ArrayList(); MBeanAttributeInfo[] attrs = getMBeanInfo().getAttributes(); for (int i = 0; i < attrs.length; i++) { attrnames.add(attrs[i].getName()); } AttributeList result = new AttributeList(); for (int i = 0; i < attributes.length; i++) { if (attrnames.contains(attributes[i])) { try { Attribute attr = new Attribute(attributes[i], getAttribute(attributes[i])); result.add(attr); } catch (AttributeNotFoundException e) { // Don't add this attribute } catch (MBeanException e) { // Don't add this attribute } catch (ReflectionException e) { // Don't add this attribute } } } return result; } public MBeanInfo getMBeanInfo() { MBeanInfo result; MBeanAttributeInfo[] attrs; try { attrs = new MBeanAttributeInfo[]{ new MBeanAttributeInfo("Number", "A number", DynamicTest.class.getMethod("getNumber", new Class[0]), DynamicTest.class.getMethod("setNumber", new Class[]{long.class})), new MBeanAttributeInfo("Str", "A string", DynamicTest.class.getMethod("getStr", new Class[0]), null), new MBeanAttributeInfo("Boolean", "A Boolean", DynamicTest.class.getMethod("getBoolean", new Class[0]), null) }; } catch (Exception x) { attrs = new MBeanAttributeInfo[0]; } MBeanConstructorInfo[] ctors = new MBeanConstructorInfo[0]; MBeanOperationInfo[] ops = new MBeanOperationInfo[0]; MBeanNotificationInfo[] notifs = new MBeanNotificationInfo[0]; result = new MBeanInfo(DynamicTest.class.getName(), "DynamicTest MBean", attrs, ctors, ops, notifs); return result; } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return null; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (attribute.getName().compareTo("Number") == 0) { setNumber(((Long)attribute.getValue()).longValue()); } else { throw new AttributeNotFoundException("Can't find " + attribute.getName()); } } public AttributeList setAttributes(AttributeList attributes) { AttributeList result = new AttributeList(); Iterator i = attributes.iterator(); while (i.hasNext()) { try { Attribute attr = (Attribute)i.next(); setAttribute(attr); result.add(attr); } catch (Exception x) { // Don't add this to the result } } return result; } } } mx4j-3.0.2/src/test/test/javax/management/support/RegistrationSupport.java100644 0 0 16453 10513545721 24161 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.InstanceNotFoundException; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import mx4j.AbstractDynamicMBean; import test.MutableBoolean; import test.MutableObject; /** * @version $Revision: 1.7 $ */ public class RegistrationSupport { public interface NullObjectNameMBean { } public static class NullObjectName implements NullObjectNameMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return null; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } } public interface PreRegisterExceptionMBean { } public static class PreRegisterException implements PreRegisterExceptionMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { throw new Exception(); } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } } public interface PostRegisterExceptionMBean { } public static class PostRegisterException implements PostRegisterExceptionMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { throw new RuntimeException(); } public void preDeregister() throws Exception { } public void postDeregister() { } } public interface PreDeregisterExceptionMBean { } public static class PreDeregisterException implements PreDeregisterExceptionMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { throw new Exception(); } public void postDeregister() { } } public interface PostDeregisterExceptionMBean { } public static class PostDeregisterException implements PostDeregisterExceptionMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { throw new RuntimeException(); } } public interface EmptyMBean { } public static class Empty implements EmptyMBean, MBeanRegistration { private MutableBoolean m_bool1; private MutableBoolean m_bool2; public Empty(MutableBoolean bool1, MutableBoolean bool2) { m_bool1 = bool1; m_bool2 = bool2; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { m_bool1.set(registrationDone.booleanValue()); } public void preDeregister() throws Exception { m_bool1.set(false); } public void postDeregister() { m_bool2.set(false); } } public interface EmptyDuplicateMBean { } public static class EmptyDuplicate implements EmptyDuplicateMBean, MBeanRegistration { private ObjectName m_name; private MutableBoolean m_bool1; public EmptyDuplicate(ObjectName name, MutableBoolean bool1) { m_name = name; m_bool1 = bool1; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return m_name; } public void postRegister(Boolean registrationDone) { m_bool1.set(registrationDone.booleanValue()); } public void preDeregister() throws Exception { } public void postDeregister() { } } public interface StdMBean { public void method(); } public static class Std implements StdMBean, MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } public void method() { } } public static class Dyn extends AbstractDynamicMBean implements MBeanRegistration { public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } public void method() { } protected MBeanOperationInfo[] createMBeanOperationInfo() { return new MBeanOperationInfo[]{new MBeanOperationInfo(StdMBean.class.getMethods()[0].getName(), null, new MBeanParameterInfo[0], "void", MBeanOperationInfo.UNKNOWN)}; } } public interface ListenerRegistrarMBean { } public static class ListenerRegistrar implements ListenerRegistrarMBean, MBeanRegistration, NotificationListener { private final MutableObject holder; private MBeanServer server; private ObjectName delegate; public ListenerRegistrar(MutableObject holder) { this.holder = holder; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; delegate = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); return name; } public void postRegister(Boolean registrationDone) { try { server.addNotificationListener(delegate, this, null, null); } catch (InstanceNotFoundException x) { throw new Error(x.toString()); } } public void preDeregister() throws Exception { } public void postDeregister() { try { server.removeNotificationListener(delegate, this); } catch (Exception x) { throw new Error(x.toString()); } } public void handleNotification(Notification notification, Object handback) { holder.set(notification); } } } mx4j-3.0.2/src/test/test/javax/management/support/StandardMBeanSupport.java100644 0 0 12110 10513545721 24134 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.support; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.NotCompliantMBeanException; import javax.management.StandardMBean; import test.MutableInteger; /** * @version $Revision: 1.5 $ */ public class StandardMBeanSupport { /** * No management interface and it is not a standard MBean */ public static class SubclassNotCompliant extends StandardMBean { public SubclassNotCompliant() throws NotCompliantMBeanException { super(null); } } /** * Valid StandardMBean with a standard MBean as implementation */ public static class SubclassWithNoManagement extends StandardMBean implements SubclassWithNoManagementMBean { public SubclassWithNoManagement() throws NotCompliantMBeanException { super(null); } public Object test() { return new Object(); } } public interface SubclassWithNoManagementMBean { public Object test(); } public static class SubclassWithManagement extends StandardMBean implements Management { public SubclassWithManagement() throws NotCompliantMBeanException { super(Management.class); } public void cannotCall() { } public Object test() { return new Object(); } } public interface Management { public Object test(); } public static class ImplementationWithNoManagement implements ImplementationWithNoManagementMBean { public Object test() { return new Object(); } } public interface ImplementationWithNoManagementMBean { public Object test(); } public static class ImplementationWithManagement implements Management { public Object test() { return new Object(); } } public interface FullManagement { public void setAttrib(int i); public void operation(int i); } public interface PublicInterfaceMBean { public Object test(); } private static class PublicInterface implements PublicInterfaceMBean { public PublicInterface() { } public Object test() { return new Object(); } } public static PublicInterfaceMBean createPublicInterfaceMBean() { return new PublicInterface(); } public static class CallbackCounter extends StandardMBean implements FullManagement { private MutableInteger count; public CallbackCounter(int dummy) throws NotCompliantMBeanException { // Variable dummy only serves to enable the callback on the constructor parameter super(FullManagement.class); } public void setAttrib(int i) { } public void operation(int i) { } public int getCount() { return count.get(); } protected String getClassName(MBeanInfo info) { increment(); return super.getClassName(info); } protected String getDescription(MBeanInfo info) { increment(); return super.getDescription(info); } protected String getDescription(MBeanAttributeInfo info) { increment(); return super.getDescription(info); } protected String getDescription(MBeanConstructorInfo info) { increment(); return super.getDescription(info); } protected String getDescription(MBeanOperationInfo info) { increment(); return super.getDescription(info); } protected String getDescription(MBeanConstructorInfo constructor, MBeanParameterInfo param, int sequence) { increment(); return super.getDescription(constructor, param, sequence); } protected String getDescription(MBeanOperationInfo operation, MBeanParameterInfo param, int sequence) { increment(); return super.getDescription(operation, param, sequence); } protected String getParameterName(MBeanConstructorInfo constructor, MBeanParameterInfo param, int sequence) { increment(); return super.getParameterName(constructor, param, sequence); } protected String getParameterName(MBeanOperationInfo operation, MBeanParameterInfo param, int sequence) { increment(); return super.getParameterName(operation, param, sequence); } protected int getImpact(MBeanOperationInfo info) { increment(); return super.getImpact(info); } private void increment() { if (count == null) count = new MutableInteger(0); count.set(count.get() + 1); } } } mx4j-3.0.2/src/test/test/javax/management/timer/TimerTest.java100644 0 0 54255 10513545721 21440 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.javax.management.timer; import java.util.Date; import java.util.Vector; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.timer.Timer; import javax.management.timer.TimerMBean; import javax.management.timer.TimerNotification; import test.MX4JTestCase; import test.MutableBoolean; import test.MutableInteger; import test.MutableLong; /** * @version $Revision: 1.13 $ */ public class TimerTest extends MX4JTestCase { private MBeanServer m_server; private ObjectName m_timerName; private TimerMBean m_timer; public TimerTest(String s) { super(s); } protected void setUp() throws Exception { m_server = newMBeanServer(); m_timerName = new ObjectName("Service:type=Timer"); m_server.createMBean("javax.management.timer.Timer", m_timerName, null); m_timer = (TimerMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, m_timerName, TimerMBean.class, false); } protected void tearDown() throws Exception { m_server.unregisterMBean(m_timerName); } public void testStartStop() throws Exception { m_timer.start(); assertTrue(m_timer.isActive()); m_timer.stop(); assertFalse(m_timer.isActive()); } public void testStartStopStart() throws Exception { m_timer.start(); assertTrue(m_timer.isActive()); m_timer.stop(); assertFalse(m_timer.isActive()); m_timer.start(); assertTrue(m_timer.isActive()); // Will be stopped during unregistration } public void testOneShotNotification() throws Exception { m_timer.start(); final long now = System.currentTimeMillis(); final MutableInteger mid = new MutableInteger(-1); final MutableInteger occurrencesCount = new MutableInteger(0); final String notifType = "timer-test"; final long delay = 3 * Timer.ONE_SECOND; NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { // Test that the listener has been called at the specified time long elapsed = System.currentTimeMillis() - now; assertTrue(elapsed >= delay); assertFalse(elapsed - delay > 50); assertTrue(notification instanceof TimerNotification); Integer id = ((TimerNotification)notification).getNotificationID(); assertEquals(mid.get(), id.intValue()); occurrencesCount.set(occurrencesCount.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(notifType); } }, null); // Notify after a while Date date = new Date(now + delay); // One shot notification at the specified time Integer id = m_timer.addNotification(notifType, "timer-message", "user-data", date); mid.set(id.intValue()); // Sleep to wait for the notification to happen sleep(delay * 2); // Check notification arrived assertTrue(occurrencesCount.get() == 1); // Check that it won't be notified again assertTrue(m_timer.getNbNotifications() == 0); } public void testPeriodicNotification() throws Exception { m_timer.start(); final String notifType = "timer-test"; final String periodicNotifType = "timer-test-periodic"; final MutableInteger occurrencesCount = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { occurrencesCount.set(occurrencesCount.get() + 1); } }; final MutableInteger periodicOccurrences = new MutableInteger(0); NotificationListener periodicListener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { periodicOccurrences.set(periodicOccurrences.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(notifType); } }, null); m_server.addNotificationListener(m_timerName, periodicListener, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(periodicNotifType); } }, null); // Register to happen 3 times on the first listener long now = System.currentTimeMillis(); // Notify in one second Date date = new Date(now + Timer.ONE_SECOND); String message = "timer-message"; Integer id = m_timer.addNotification(notifType, message, "user-data", date, Timer.ONE_SECOND, 3L); // Register to happen periodically // Notify in one second date = new Date(now + Timer.ONE_SECOND); String userDataPeriodic = "user-data-periodic"; Integer periodicID = m_timer.addNotification(periodicNotifType, "timer-message-periodic", userDataPeriodic, date, Timer.ONE_SECOND); // Sleep some time sleep(Timer.ONE_SECOND); Vector v = m_timer.getAllNotificationIDs(); assertEquals(v.size(), 2); assertTrue(v.contains(id)); assertTrue(v.contains(periodicID)); v = m_timer.getNotificationIDs(periodicNotifType); assertEquals(v.size(), 1); assertTrue(v.contains(periodicID)); assertEquals(m_timer.getNotificationMessage(id), message); assertEquals(m_timer.getNotificationUserData(periodicID), userDataPeriodic); // Sleep till the end of the three-time notification sleep(Timer.ONE_SECOND * 6); // Check that was called the right number of times assertEquals(occurrencesCount.get(), 3); // The three-time notification is expired now v = m_timer.getAllNotificationIDs(); assertEquals(v.size(), 1); assertTrue(v.contains(periodicID)); Long p = m_timer.getPeriod(periodicID); assertEquals(p.longValue(), Timer.ONE_SECOND); assertEquals(m_timer.getNotificationType(periodicID), periodicNotifType); // Removing non existing notification try { m_timer.removeNotifications("dummy"); fail("Removed non-existing notification"); } catch (InstanceNotFoundException ignored) { } // Should have already been removed, was the three-shot notification try { m_timer.removeNotification(id); fail("Removed non-existing notification"); } catch (InstanceNotFoundException ignored) { } // Some more wait sleep(Timer.ONE_SECOND * 3); // Removing existing notification m_timer.removeNotification(periodicID); // Check that none are still present assertTrue(m_timer.isEmpty()); // Wait some more to be sure the periodic listener is not notified anymore int periodTimes = periodicOccurrences.get(); assertTrue(periodTimes > 0); sleep(Timer.ONE_SECOND * 5); assertEquals(periodicOccurrences.get(), periodTimes); } public void testTimerNotStarted() throws Exception { // Don't start the Timer. Notification should not be emitted // m_timer.start(); final MutableBoolean bool = new MutableBoolean(false); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { bool.set(true); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); m_timer.addNotification("timer-notif", "Must not be emitted", null, new Date(now + Timer.ONE_SECOND)); // Sleep to wait for the notification to happen sleep(Timer.ONE_SECOND * 2); assertFalse(bool.get()); } public void testAddStopRemoveNotification() throws Exception { // Check that add + stop + remove behaves correctly final MutableInteger count = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { count.set(count.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); Date date = new Date(now + Timer.ONE_SECOND); // Periodic notification Integer id = m_timer.addNotification("notif-type", "notif-message", "notif-data", date, Timer.ONE_SECOND); m_timer.start(); // Wait for the notifications to arrive... sleep(Timer.ONE_SECOND * 2); m_timer.stop(); int counted = count.get(); assertEquals(m_timer.getNbNotifications(), 1); m_timer.removeNotification(id); assertTrue(m_timer.isEmpty()); // Wait some more to be sure that there are no more notifications Thread.sleep(Timer.ONE_SECOND * 5); assertEquals(counted, count.get()); } public void testSendPastNotifications1() throws Exception { final MutableBoolean bool = new MutableBoolean(false); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { bool.set(true); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This one-shot notification is already passed, sendPastNotifications is false // so the notification must not be emitted Date date = new Date(now - Timer.ONE_SECOND); m_timer.setSendPastNotifications(false); m_timer.addNotification("notif-type", "notif-message", "notif-data", date); m_timer.start(); // Wait that the notification arrives sleep(Timer.ONE_SECOND); assertFalse(bool.get()); assertTrue(m_timer.isEmpty()); } public void testNotificationsWithOldDate() throws Exception { final MutableBoolean bool = new MutableBoolean(false); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { bool.set(true); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); m_timer.start(); Date date = new Date(now - Timer.ONE_SECOND); m_timer.addNotification("notif-type", "notif-message", "notif-data", date); // Wait that the notification arrives sleep(Timer.ONE_SECOND); assertTrue(bool.get()); assertTrue(m_timer.isEmpty()); } public void testSendPastNotifications2() throws Exception { final MutableBoolean bool = new MutableBoolean(false); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { bool.set(true); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This one-shot notification is already passed, sendPastNotifications is true // so the notification must be emitted Date date = new Date(now - Timer.ONE_SECOND); m_timer.setSendPastNotifications(true); m_timer.addNotification("notif-type", "notif-message", "notif-data", date); m_timer.start(); // Wait that the notification arrives sleep(Timer.ONE_SECOND); assertTrue(bool.get()); assertTrue(m_timer.isEmpty()); } public void testSendPastNotifications3() throws Exception { final MutableInteger count = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { count.set(count.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This periodic notification started in the past, sendPastNotifications is false // so only some notification must be emitted long occurrences = 10; long skip = 4; Date date = new Date(now - Timer.ONE_SECOND * skip); m_timer.setSendPastNotifications(false); m_timer.addNotification("notif-type", "notif-message", "notif-data", date, Timer.ONE_SECOND, occurrences); m_timer.start(); // Wait for the notifications to happen sleep(Timer.ONE_SECOND * (occurrences + 1)); // Sometimes we loose one notification because we're not that fast, it's ok. long expected = occurrences - skip; if (count.get() != expected && count.get() != expected - 1) fail("Expected notifications not emitted: expecting " + expected + " got " + count.get()); assertTrue(m_timer.isEmpty()); } public void testSendPastNotifications4() throws Exception { final MutableInteger count = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { count.set(count.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This periodic notification started in the past, sendPastNotifications is true // so all notifications must be emitted long occurrences = 10; long skip = 4; Date date = new Date(now - Timer.ONE_SECOND * skip); m_timer.setSendPastNotifications(true); m_timer.addNotification("notif-type", "notif-message", "notif-data", date, Timer.ONE_SECOND, occurrences); m_timer.start(); // Wait for the notifications to happen sleep(Timer.ONE_SECOND * (occurrences + 1)); assertEquals(count.get(), occurrences); assertTrue(m_timer.isEmpty()); } public void testSendPastNotifications5() throws Exception { final MutableInteger count = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { count.set(count.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This periodic notification is started, sendPastNotifications is false // the Timer is started, then stopped, then restarted long occurrences = 10; long pre = 2; long skip = 4; Date date = new Date(now + Timer.ONE_SECOND); m_timer.setSendPastNotifications(false); m_timer.addNotification("notif-type", "notif-message", "notif-data", date, Timer.ONE_SECOND, occurrences); m_timer.start(); // Wait for the notifications to happen sleep(Timer.ONE_SECOND * pre); m_timer.stop(); // Sometimes we loose one notification because we're not that fast, it's ok. if (count.get() != pre && count.get() != pre - 1) fail("Expected notifications not emitted: expecting " + pre + " got " + count.get()); assertEquals(m_timer.getNbNotifications(), 1); // Wait to skip some notification sleep(Timer.ONE_SECOND * skip); // Restart the Timer m_timer.start(); // Wait for the remaining notifications to happen sleep(Timer.ONE_SECOND * (occurrences - pre - skip + 1)); m_timer.stop(); // Sometimes we loose one notification because we're not that fast, it's ok. long expected = occurrences - skip; if (count.get() != expected && count.get() != expected - 1) fail("Expected notifications not emitted. Expected " + expected + " or " + (expected - 1) + ". got " + count.get()); assertTrue(m_timer.isEmpty()); } public void testSendPastNotifications6() throws Exception { final MutableInteger count = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { count.set(count.get() + 1); } }; m_server.addNotificationListener(m_timerName, listener, null, null); long now = System.currentTimeMillis(); // This periodic notification is started, sendPastNotifications is true // the Timer is started, then stopped, then restarted long occurrences = 10; long pre = 2; long skip = 4; Date date = new Date(now + Timer.ONE_SECOND); m_timer.setSendPastNotifications(true); m_timer.addNotification("notif-type", "notif-message", "notif-data", date, Timer.ONE_SECOND, occurrences, true); m_timer.start(); // Wait for the notifications to happen sleep(Timer.ONE_SECOND * pre); m_timer.stop(); // Sometimes we loose one notification because we're not that fast, it's ok. if (count.get() != pre && count.get() != pre - 1) fail("Expected notifications not emitted: expecting " + pre + " got " + count.get()); assertFalse(m_timer.isEmpty()); // Wait to skip some notification sleep(Timer.ONE_SECOND * skip); // Restart the Timer m_timer.start(); // Wait for the remaining notifications to happen sleep(Timer.ONE_SECOND * (occurrences - pre - skip + 1)); m_timer.stop(); assertEquals(count.get(), occurrences); assertTrue(m_timer.isEmpty()); } public void testFixedDelay() throws Exception { m_timer.start(); final int occurrences = 100; final String fdNotifType = "timer-test-fixed-delay"; final String frNotifType = "timer-test-fixed-rate"; final MutableInteger frOccurrences = new MutableInteger(0); final MutableLong frElapsedTime = new MutableLong(0); final MutableLong frLastTime = new MutableLong(System.currentTimeMillis()); NotificationListener frListener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { if (frOccurrences.get() < occurrences) { long now = System.currentTimeMillis(); frElapsedTime.set(frElapsedTime.get() + (now - frLastTime.get())); frLastTime.set(now); frOccurrences.set(frOccurrences.get() + 1); } } }; final MutableInteger fdOccurrences = new MutableInteger(0); final MutableLong fdElapsedTime = new MutableLong(0); final MutableLong fdLastTime = new MutableLong(System.currentTimeMillis()); NotificationListener fdListener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { if (fdOccurrences.get() < occurrences) { long now = System.currentTimeMillis(); fdElapsedTime.set(fdElapsedTime.get() + (now - fdLastTime.get())); fdLastTime.set(now); fdOccurrences.set(fdOccurrences.get() + 1); } } }; m_server.addNotificationListener(m_timerName, fdListener, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(fdNotifType); } }, null); m_server.addNotificationListener(m_timerName, frListener, new NotificationFilter() { public boolean isNotificationEnabled(Notification notification) { return notification.getType().equals(frNotifType); } }, null); // Testing fixed delay/fixed rate long now = System.currentTimeMillis(); // Notify in one second Date date = new Date(now + Timer.ONE_SECOND); // Register to happen 10 times m_timer.addNotification(fdNotifType, "timer-message", "user-data", date, 10, occurrences, false); m_timer.addNotification(frNotifType, "timer-message", "user-data", date, 10, occurrences, true); // Sleep some time while (frOccurrences.get() < occurrences || fdOccurrences.get() < occurrences) { sleep(10); System.gc(); } assertEquals(frOccurrences.get(), occurrences); assertEquals(fdOccurrences.get(), occurrences); if (((1.0f * frElapsedTime.get()) / fdElapsedTime.get()) > 0.95) fail("Fixed rate and fixed delay exhibit no execution rate differences"); } public void testRemoveNotifications() throws Exception { m_timer.addNotification("mx4j.timer.test", "test notification", null, new Date(System.currentTimeMillis()), 8); m_timer.addNotification("mx4j.timer.ignore", "ignore me", null, new Date(System.currentTimeMillis()), 4); m_timer.addNotification("mx4j.timer.test", "another test", null, new Date(System.currentTimeMillis()), 8); assertEquals(m_timer.getNbNotifications(), 3); m_timer.start(); m_timer.removeNotifications("mx4j.timer.ignore"); assertEquals(m_timer.getNbNotifications(), 2); } public void testRemoveNonexistentNotifications() throws Exception { m_timer.addNotification("mx4j.timer.test", "test notification", null, new Date(System.currentTimeMillis()), 4); m_timer.start(); try { m_timer.removeNotifications("mx4j.timer.bogus"); fail("Expecting InstanceNotFoundException"); } catch (InstanceNotFoundException x) { } } } mx4j-3.0.2/src/test/test/mx4j/AbstractDynamicMBeanTest.java100644 0 0 26323 10513545721 20643 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j; import java.util.ArrayList; import java.util.List; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.ReflectionException; import mx4j.AbstractDynamicMBean; import test.MX4JTestCase; /** * @version $Revision: 1.5 $ */ public class AbstractDynamicMBeanTest extends MX4JTestCase { public AbstractDynamicMBeanTest(String s) { super(s); } public void testRegistration() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); } public void testGetAttibuteForIsAttribute() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); Object result = server.getAttribute(name, "Running"); if (!((Boolean)result).booleanValue()) fail("getAttribute does not work"); } public void testGetAttibuteForGetAttribute() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); Object result = server.getAttribute(name, "Name"); assertEquals(result, mbean.getName()); } public void testGetAttibuteForPrimitiveType() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); DynamicDerived mbean = new DynamicDerived(); server.registerMBean(mbean, name); Integer result = (Integer)server.getAttribute(name, "Status"); assertEquals(result.intValue(), mbean.getStatus()); } public void testSetAttibute() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); String value = "simon"; server.setAttribute(name, new Attribute("Name", value)); assertEquals(value, mbean.getName()); Object result = server.getAttribute(name, "Name"); assertEquals(result, value); } public void testSetAttributeWithPrimitiveType() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); DynamicDerived mbean = new DynamicDerived(); server.registerMBean(mbean, name); Integer value = new Integer(13); server.setAttribute(name, new Attribute("Status", value)); Integer result = (Integer)server.getAttribute(name, "Status"); assertEquals(result.intValue(), value.intValue()); } public void testSetAttributeWithNullValue() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); String value = null; server.setAttribute(name, new Attribute("Name", value)); assertEquals(value, mbean.getName()); Object result = server.getAttribute(name, "Name"); assertEquals(result, value); } public void testOperation() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); String key = "key"; Object value = new Object(); List list = (List)server.invoke(name, "operation", new Object[]{key, value}, new String[]{String.class.getName(), Object.class.getName()}); assertEquals(list.size(), 2); assertEquals(list.get(0), key); assertEquals(list.get(1), value); } public void testInvocationOfMethodsNotPresentInMBeanInfo() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); try { server.getAttribute(name, "MBeanInfo"); fail("getMBeanInfo should not be invocable"); } catch (AttributeNotFoundException x) { } } public void testInvocationOfNonExistingSetter() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); Dynamic mbean = new Dynamic(); server.registerMBean(mbean, name); try { server.setAttribute(name, new Attribute("Running", Boolean.FALSE)); fail("getMBeanInfo should not be invocable"); } catch (ReflectionException x) { } } public void testComposedDynamicMBean() throws Exception { MBeanServer server = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("domain", "mbean", "dynamic"); ComposedDynamicMBean mbean = new ComposedDynamicMBean(); server.registerMBean(mbean, name); // Try to invoke an attribute int value = 17; mbean.setStatus(value); Integer result = (Integer)server.getAttribute(name, "Status"); if (result.intValue() != value) fail("getAttribute does not work"); // Set the attribute value = 3; server.setAttribute(name, new Attribute("Status", new Integer(value))); if (mbean.getStatus() != value) fail("setAttribute does not work"); // Invoke operations mbean.disable(); server.invoke(name, "enable", null, null); if (!mbean.isEnabled()) fail("invoke does not work"); server.invoke(name, "disable", null, null); if (mbean.isEnabled()) fail("invoke does not work"); } public static class Dynamic extends AbstractDynamicMBean { private String m_name = "dummy"; protected MBeanAttributeInfo[] createMBeanAttributeInfo() { return new MBeanAttributeInfo[] { new MBeanAttributeInfo("Name", String.class.getName(), "The name", true, true, false), new MBeanAttributeInfo("Running", boolean.class.getName(), "The running status", true, false, true) }; } protected MBeanOperationInfo[] createMBeanOperationInfo() { return new MBeanOperationInfo[] { new MBeanOperationInfo("operation", "An operation", new MBeanParameterInfo[] { new MBeanParameterInfo("key", String.class.getName(), "The key"), new MBeanParameterInfo("value", Object.class.getName(), "The value") }, List.class.getName(), MBeanOperationInfo.INFO) }; } public String getName() { return m_name; } public void setName(String name) { m_name = name; } public boolean isRunning() { return true; } public List operation(String key, Object value) { ArrayList list = new ArrayList(); list.add(key); list.add(value); return list; } } public static class DynamicDerived extends Dynamic { private int m_status; protected MBeanAttributeInfo[] createMBeanAttributeInfo() { MBeanAttributeInfo[] info = super.createMBeanAttributeInfo(); MBeanAttributeInfo[] newInfo = new MBeanAttributeInfo[info.length + 1]; System.arraycopy(info, 0, newInfo, 0, info.length); newInfo[info.length] = new MBeanAttributeInfo("Status", int.class.getName(), "The status", true, true, false); return newInfo; } public MBeanInfo getMBeanInfo() { // Disable caching return createMBeanInfo(); } public int getStatus() { return m_status; } public void setStatus(int status) { m_status = status; } } public static class ComposedDynamicMBean implements DynamicMBean { private AbstractDynamicMBean delegate = new AbstractDynamicMBean() { protected MBeanAttributeInfo[] createMBeanAttributeInfo() { return new MBeanAttributeInfo[] { new MBeanAttributeInfo("Status", int.class.getName(), "The status", true, true, false), new MBeanAttributeInfo("Enabled", boolean.class.getName(), "The enable status", true, false, true) }; } protected MBeanOperationInfo[] createMBeanOperationInfo() { return new MBeanOperationInfo[] { new MBeanOperationInfo("enable", "Enables this MBean", new MBeanParameterInfo[0], Void.class.getName(), MBeanOperationInfo.ACTION), new MBeanOperationInfo("disable", "Disables this MBean", new MBeanParameterInfo[0], Void.class.getName(), MBeanOperationInfo.ACTION) }; } }; private int status; private boolean enabled; public ComposedDynamicMBean() { delegate.setResource(this); } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { return delegate.getAttribute(attribute); } public AttributeList getAttributes(String[] attributes) { return delegate.getAttributes(attributes); } public MBeanInfo getMBeanInfo() { return delegate.getMBeanInfo(); } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { return delegate.invoke(method, arguments, params); } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { delegate.setAttribute(attribute); } public AttributeList setAttributes(AttributeList attributes) { return delegate.setAttributes(attributes); } public void setStatus(int status) { this.status = status; } public int getStatus() { return status; } public boolean isEnabled() { return this.enabled; } public void enable() { this.enabled = true; } public void disable() { this.enabled = false; } } } mx4j-3.0.2/src/test/test/mx4j/MiscellaneousTest.java100644 0 0 17051 10513545721 17471 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j; import mx4j.util.Utils; import test.MX4JTestCase; /** * @version $Revision: 1.8 $ */ public class MiscellaneousTest extends MX4JTestCase { public MiscellaneousTest(String s) { super(s); } private boolean wildcardMatch(String pattern, String value) throws Exception { return Utils.wildcardMatch(pattern, value); } public void testRegexpMatch() throws Exception { String p1 = "*"; if (!wildcardMatch(p1, "")) { fail(); } if (!wildcardMatch(p1, "a")) { fail(); } if (!wildcardMatch(p1, "abc")) { fail(); } System.out.print("."); p1 = "?"; if (!wildcardMatch(p1, "a")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "aa")) { fail(); } System.out.print("."); p1 = "ab"; if (!wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "abcd")) { fail(); } System.out.print("."); p1 = "*?"; if (!wildcardMatch(p1, "a")) { fail(); } if (!wildcardMatch(p1, "aa")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } System.out.print("."); p1 = "?*"; if (!wildcardMatch(p1, "a")) { fail(); } if (!wildcardMatch(p1, "aa")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } System.out.print("."); p1 = "*a"; if (!wildcardMatch(p1, "a")) { fail(); } if (!wildcardMatch(p1, "aa")) { fail(); } if (!wildcardMatch(p1, "ba")) { fail(); } if (!wildcardMatch(p1, "bca")) { fail(); } if (!wildcardMatch(p1, "caba")) { fail(); } if (wildcardMatch(p1, "b")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "cab")) { fail(); } System.out.print("."); p1 = "a*"; if (!wildcardMatch(p1, "a")) { fail(); } if (!wildcardMatch(p1, "aa")) { fail(); } if (!wildcardMatch(p1, "ab")) { fail(); } if (!wildcardMatch(p1, "abc")) { fail(); } if (wildcardMatch(p1, "ba")) { fail(); } if (wildcardMatch(p1, "bca")) { fail(); } if (wildcardMatch(p1, "bcab")) { fail(); } System.out.print("."); p1 = "?ab"; if (!wildcardMatch(p1, "aab")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "abc")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } System.out.print("."); p1 = "ab?"; if (!wildcardMatch(p1, "aba")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "cab")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } System.out.print("."); p1 = "a*b"; if (!wildcardMatch(p1, "aab")) { fail(); } if (!wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "aaba")) { fail(); } System.out.print("."); p1 = "a?b"; if (!wildcardMatch(p1, "aab")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "aaba")) { fail(); } System.out.print("."); p1 = "*ab*"; if (!wildcardMatch(p1, "ab")) { fail(); } if (!wildcardMatch(p1, "abc")) { fail(); } if (!wildcardMatch(p1, "cabd")) { fail(); } if (!wildcardMatch(p1, "aabbc")) { fail(); } if (wildcardMatch(p1, "ba")) { fail(); } if (wildcardMatch(p1, "bca")) { fail(); } System.out.print("."); p1 = "?ab?"; if (!wildcardMatch(p1, "cabd")) { fail(); } if (wildcardMatch(p1, "aab")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "abb")) { fail(); } if (wildcardMatch(p1, "aabbc")) { fail(); } System.out.print("."); p1 = "*a*b*"; if (!wildcardMatch(p1, "ab")) { fail(); } if (!wildcardMatch(p1, "abc")) { fail(); } if (!wildcardMatch(p1, "cabd")) { fail(); } if (!wildcardMatch(p1, "caebd")) { fail(); } if (wildcardMatch(p1, "ba")) { fail(); } if (wildcardMatch(p1, "bca")) { fail(); } if (wildcardMatch(p1, "a")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } System.out.print("."); p1 = "?a?b?"; if (!wildcardMatch(p1, "aabbc")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } if (wildcardMatch(p1, "aazb")) { fail(); } System.out.print("."); p1 = "*?ab"; if (!wildcardMatch(p1, "aab")) { fail(); } if (!wildcardMatch(p1, "aaab")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } System.out.print("."); p1 = "?*ab"; if (!wildcardMatch(p1, "aab")) { fail(); } if (!wildcardMatch(p1, "aaab")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } System.out.print("."); p1 = "ab*?"; if (!wildcardMatch(p1, "abb")) { fail(); } if (!wildcardMatch(p1, "abbb")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } System.out.print("."); p1 = "ab?*"; if (!wildcardMatch(p1, "abb")) { fail(); } if (!wildcardMatch(p1, "abbb")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } System.out.print("."); p1 = "a*?b"; if (!wildcardMatch(p1, "abb")) { fail(); } if (!wildcardMatch(p1, "abbb")) { fail(); } if (wildcardMatch(p1, "")) { fail(); } if (wildcardMatch(p1, "ab")) { fail(); } System.out.print("."); System.out.println(); } } mx4j-3.0.2/src/test/test/mx4j/log/LogRedirectionTest.java100644 0 0 17246 10513545721 20366 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.log; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.StringReader; import java.net.URL; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Log4JLogger; import mx4j.log.Logger; import mx4j.log.LoggerBroadcasterMBean; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import test.MX4JTestCase; import test.MutableInteger; /** * @version $Revision: 1.9 $ * @see */ public class LogRedirectionTest extends MX4JTestCase { private int m_defaultPriority; public LogRedirectionTest(String s) { super(s); } protected void setUp() throws Exception { m_defaultPriority = Log.getDefaultPriority(); Log.setDefaultPriority(Logger.TRACE); } protected void tearDown() throws Exception { Log.setDefaultPriority(m_defaultPriority); } public void testDirectRedirection() throws Exception { PrintStream out = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // Replace System.out be be able to check results System.setOut(new PrintStream(baos)); // Redirect logging Log.redirectTo(new LoggerTestRedirector()); // Create some log MBeanServer server = newMBeanServer(); server.createMBean("javax.management.loading.MLet", new ObjectName(":type=test"), null); } finally { // Stop redirection Log.redirectTo(null); // Re-set normal System.out System.setOut(out); } // Collect and test results byte[] bytes = baos.toByteArray(); String log = new String(bytes); BufferedReader br = new BufferedReader(new StringReader(log)); String line = null; while ((line = br.readLine()) != null) { if (!line.startsWith("{")) fail("Redirection failed"); } } public void testMBeanRedirection() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName(":type=test"); // Register a logger mbean server.createMBean("mx4j.log.LoggerBroadcaster", name, null); LoggerBroadcasterMBean redirector = (LoggerBroadcasterMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, LoggerBroadcasterMBean.class, false); try { // Register a notification listener final MutableInteger notified = new MutableInteger(0); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { notified.set(notified.get() + 1); } }; server.addNotificationListener(name, listener, null, null); // Redirect logging redirector.start(); // Create some log ObjectName mlet = new ObjectName(":type=mlet"); server.createMBean("javax.management.loading.MLet", mlet, null); // This should create some log server.invoke(mlet, "addURL", new Object[]{new URL("http://mx4j.sourceforge.net")}, new String[]{"java.net.URL"}); // Test if redirection worked if (notified.get() < 1) fail("Notification listener not called"); } finally { redirector.stop(); } } public void testLog4JRedirection() throws Exception { PrintStream out = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // Replace System.out be be able to check results System.setOut(new PrintStream(baos)); org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger(); root.removeAllAppenders(); ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%c] %p: %m%n")); root.addAppender(console); Log.redirectTo(new Log4JLogger()); // Create some log newMBeanServer(); } finally { // Stop redirection Log.redirectTo(null); // Re-set normal System.out System.setOut(out); org.apache.log4j.Logger.getRoot().removeAllAppenders(); } // Collect and test results byte[] bytes = baos.toByteArray(); String log = new String(bytes); BufferedReader br = new BufferedReader(new StringReader(log)); String line = null; while ((line = br.readLine()) != null) { if (!line.startsWith("[")) { fail("Redirection failed"); } } } public void testPartialDirectRedirection() throws Exception { PrintStream out = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); String category = MBeanServerFactory.class.getName(); try { // Replace System.out be be able to check results System.setOut(new PrintStream(baos)); org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger(); root.removeAllAppenders(); ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%c] %p: %m%n")); root.addAppender(console); Log.redirectTo(new Log4JLogger(), category); Log.redirectTo(new LoggerTestRedirector()); // Create some log for log4j redirector MBeanServer server = newMBeanServer(); // Create some log for the test redirector ObjectName mlet = new ObjectName(":type=mlet"); server.createMBean("javax.management.loading.MLet", mlet, null); // This should create one info log server.invoke(mlet, "addURL", new Object[]{new URL("http://mx4j.sourceforge.net")}, new String[]{"java.net.URL"}); } finally { // Stop redirection Log.redirectTo(null); Log.redirectTo(null, category); // Re-set normal System.out System.setOut(out); org.apache.log4j.Logger.getRootLogger().removeAllAppenders(); } // Collect and test results byte[] bytes = baos.toByteArray(); String log = new String(bytes); BufferedReader br = new BufferedReader(new StringReader(log)); String line = null; boolean bracketFound = false, braceFound = false; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("[")) { bracketFound = true; } else if (line.startsWith("{")) { braceFound = true; } else { fail("Redirection failed"); } } if (!bracketFound || !braceFound) { fail("Redirection failed"); } } public static class LoggerTestRedirector extends Logger { public LoggerTestRedirector() { super.setPriority(Logger.TRACE); } public void setPriority(int priority) { // Ignore the default priority set by the internal logging system // Here we want to trace } protected void log(int priority, Object message, Throwable t) { String msg = message == null ? "" : message.toString(); StringBuffer b = new StringBuffer("{").append(getCategory()).append("} ").append(msg); super.log(priority, b, t); } } } mx4j-3.0.2/src/test/test/mx4j/remote/RemoteNotificationClientHandlerTest.java100644 0 0 35615 10513545721 24426 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.remote; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.NotificationResult; import javax.management.remote.TargetedNotification; import mx4j.remote.AbstractRemoteNotificationClientHandler; import mx4j.remote.MX4JRemoteConstants; import mx4j.remote.NotificationTuple; import mx4j.remote.RemoteNotificationClientHandler; import test.MX4JTestCase; import test.MutableBoolean; import test.MutableLong; import test.MutableObject; /** * @version $Revision: 1.10 $ */ public class RemoteNotificationClientHandlerTest extends MX4JTestCase { public RemoteNotificationClientHandlerTest(String s) { super(s); } protected void tearDown() throws Exception { sleep(2000); } public void testListenerEquality() throws Exception { AbstractRemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, null) { protected NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) { sleep(timeout); return null; } protected void sendConnectionNotificationLost(long number) { } protected long getRetryPeriod() { return 1000; } protected int getMaxRetries() { return 2; } }; try { handler.start(); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; ObjectName name = ObjectName.getInstance(":name=emitter"); handler.addNotificationListener(new Integer(1), new NotificationTuple(name, listener, null, null)); handler.addNotificationListener(new Integer(2), new NotificationTuple(name, listener, null, new Object())); assertTrue(handler.isActive()); Integer[] ids = handler.getNotificationListeners(new NotificationTuple(name, listener)); assertEquals(ids.length, 2); handler.removeNotificationListeners(new Integer[]{new Integer(1), new Integer(2)}); assertTrue(handler.isActive()); handler.stop(); assertTrue(!handler.isActive()); } finally { handler.stop(); } } public void testAddRemove() throws Exception { RemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, null) { public NotificationResult fetchNotifications(long sequenceNumber, int maxNumber, long timeout) { sleep(timeout); return null; } protected void sendConnectionNotificationLost(long number) { } protected long getRetryPeriod() { return 1000; } protected int getMaxRetries() { return 2; } }; NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; try { handler.start(); ObjectName name = ObjectName.getInstance(":name=emitter"); handler.addNotificationListener(new Integer(1), new NotificationTuple(name, listener, null, null)); Object handback = new Object(); handler.addNotificationListener(new Integer(2), new NotificationTuple(name, listener, null, handback)); handler.removeNotificationListeners(new Integer[]{new Integer(2)}); assertFalse(handler.contains(new NotificationTuple(name, listener, null, handback))); assertTrue(handler.contains(new NotificationTuple(name, listener, null, null))); Integer id = handler.getNotificationListener(new NotificationTuple(name, listener, null, null)); assertEquals(id.intValue(), 1); handler.removeNotificationListeners(new Integer[]{new Integer(1)}); assertFalse(handler.contains(new NotificationTuple(name, listener, null, null))); } finally { handler.stop(); } } public void testNotificationDelivery() throws Exception { final MutableObject holder = new MutableObject(null); final ObjectName name = ObjectName.getInstance(":name=emitter"); final int nextSequence = 1; RemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, null) { public NotificationResult fetchNotifications(long sequenceNumber, int maxNumber, long timeout) { synchronized (holder) { Notification notification = new Notification("type", name, 0); TargetedNotification targeted = new TargetedNotification(notification, new Integer(1)); if (sequenceNumber < 0) { // Return nextSequence as next sequence number: next call must have this sequence number NotificationResult result1 = new NotificationResult(0, nextSequence, new TargetedNotification[]{targeted}); holder.set(result1); return result1; } if (sequenceNumber == nextSequence) { NotificationResult result2 = new NotificationResult(1, nextSequence + 1, new TargetedNotification[]{targeted}); holder.set(result2); return result2; } try { holder.wait(timeout); } catch (InterruptedException x) { Thread.currentThread().interrupt(); } holder.set(null); return null; } } protected void sendConnectionNotificationLost(long number) { } protected int getMaxRetries() { return 2; } protected long getRetryPeriod() { return 1000; } }; final MutableObject notifHolder = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { notifHolder.set(notification); } }; try { handler.start(); handler.addNotificationListener(new Integer(1), new NotificationTuple(name, listener, null, null)); synchronized (holder) { // This wait time is much less than the sleep time for the fetcher thread while (holder.get() == null) holder.wait(10); NotificationResult result = (NotificationResult)holder.get(); assertEquals(result.getNextSequenceNumber(), nextSequence); holder.set(null); // Wait for the notification to arrive while (notifHolder.get() == null) holder.wait(10); Notification notif = (Notification)notifHolder.get(); assertEquals(notif.getSource(), name); // Wait for the second fetchNotification call while (holder.get() == null) holder.wait(10); result = (NotificationResult)holder.get(); assertEquals(result.getNextSequenceNumber(), nextSequence + 1); } handler.removeNotificationListeners(new Integer[]{new Integer(1)}); sleep(2000); } finally { handler.stop(); } } public void testNotificationsLost() throws Exception { final MutableObject holder = new MutableObject(null); final MutableLong lost = new MutableLong(0); final ObjectName name = ObjectName.getInstance(":name=emitter"); final long losts = 1; RemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, null) { public NotificationResult fetchNotifications(long sequenceNumber, int maxNumber, long timeout) { synchronized (holder) { if (sequenceNumber < 0) return new NotificationResult(0, 0, new TargetedNotification[0]); // Avoid to spin loop the fetcher thread sleep(1000); // Return a earliest sequence greater than the requested, to test notification lost behavior return new NotificationResult(losts, losts, new TargetedNotification[0]); } } protected void sendConnectionNotificationLost(long number) { synchronized (holder) { lost.set(number); } } protected int getMaxRetries() { return 2; } protected long getRetryPeriod() { return 1000; } }; Integer id = new Integer(1); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; try { handler.start(); handler.addNotificationListener(id, new NotificationTuple(name, listener, null, null)); synchronized (holder) { while (lost.get() == 0) holder.wait(10); assertEquals(lost.get(), losts); } handler.removeNotificationListeners(new Integer[]{id}); } finally { handler.stop(); } } public void testConnectionFailure() throws Exception { final int retries = 2; final long period = 1000; AbstractRemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, null) { protected NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) throws IOException { throw new IOException(); } protected void sendConnectionNotificationLost(long number) { } protected int getMaxRetries() { return retries; } protected long getRetryPeriod() { return period; } }; NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; try { handler.start(); ObjectName name = ObjectName.getInstance(":name=emitter"); Integer id = new Integer(1); handler.addNotificationListener(id, new NotificationTuple(name, listener, null, null)); sleep(5000 + period * retries); assertTrue(!handler.isActive()); } finally { handler.stop(); } } public void testQueueOverflow() throws Exception { final Object lock = new Object(); int queueCapacity = 10; final int count = 4; final long sleep = 500; final Integer id = new Integer(1); final ObjectName name = ObjectName.getInstance(":name=emitter"); final MutableBoolean notify = new MutableBoolean(true); final MutableLong queued = new MutableLong(0); final MutableLong delivered = new MutableLong(0); Map environment = new HashMap(); environment.put(MX4JRemoteConstants.NOTIFICATION_QUEUE_CAPACITY, new Integer(queueCapacity)); RemoteNotificationClientHandler handler = new AbstractRemoteNotificationClientHandler(null, null, environment) { protected NotificationResult fetchNotifications(long sequenceNumber, int maxNumber, long timeout) { if (sequenceNumber < 0) return new NotificationResult(0, 0, new TargetedNotification[0]); boolean doNotify = false; synchronized (lock) { doNotify = notify.get(); } if (doNotify) { // Avoid spin looping the fetcher thread, but don't sleep too much, we have to fill the client's queue sleep(sleep); TargetedNotification[] notifications = new TargetedNotification[count]; for (int i = 0; i < count; ++i) notifications[i] = new TargetedNotification(new Notification("type", name, sequenceNumber + i), id); long nextSequence = sequenceNumber + count; NotificationResult result = new NotificationResult(0, nextSequence, notifications); synchronized (lock) { queued.set(getNotificationsCount()); } return result; } else { sleep(timeout); return new NotificationResult(0, sequenceNumber, new TargetedNotification[0]); } } protected long getRetryPeriod() { return 1000; } protected int getMaxRetries() { return 5; } protected void sendConnectionNotificationLost(long number) { System.out.println("Lost notifications: " + number); // Stop sending notifications synchronized (lock) { notify.set(false); // Deliver notifications until the last we queued on the client queued.set(getNotificationsCount()); } } }; NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { long sequence = notification.getSequenceNumber(); synchronized (lock) { delivered.set(sequence); } System.out.println("Received notification, sequence is " + sequence); // Sleep longer than notification emission, to fill the client's queue sleep(sleep * 2); System.out.println("Handled notification, sequence is " + sequence); } }; try { handler.start(); handler.addNotificationListener(id, new NotificationTuple(name, listener, null, null)); // Wait until we empty the client's queue synchronized (lock) { while (notify.get()) { lock.wait(50); if (queued.get() > queueCapacity) fail("Queued notifications " + queued.get() + " must not pass max capacity " + queueCapacity); } // Test timeouts if we don't deliver everything while (delivered.get() < queued.get()) lock.wait(10); } } finally { handler.stop(); } } } mx4j-3.0.2/src/test/test/mx4j/remote/RemoteNotificationServerHandlerTest.java100644 0 0 23464 10513545721 24455 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.remote; import java.util.HashMap; import java.util.Map; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.remote.NotificationResult; import mx4j.remote.DefaultRemoteNotificationServerHandler; import mx4j.remote.MX4JRemoteConstants; import mx4j.remote.RemoteNotificationServerHandler; import test.MX4JTestCase; /** * @version $Revision: 1.6 $ */ public class RemoteNotificationServerHandlerTest extends MX4JTestCase { public RemoteNotificationServerHandlerTest(String s) { super(s); } public void testFirstFetch() throws Exception { RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(null); // First call is with sequence number negative; no notification waiting NotificationResult result = handler.fetchNotifications(-1, 10, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), 0); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, 0); } public void testNotificationMissBetweenAddAndFetch() throws Exception { RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(null); // Add a notification NotificationListener listener = handler.getServerNotificationListener(); Notification notification = new Notification("dummy", this, 0); Integer listenerID = new Integer(1); listener.handleNotification(notification, listenerID); // Fetch notifications NotificationResult result = handler.fetchNotifications(-1, 10, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), 1); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, 0); // Add another notification listener.handleNotification(notification, listenerID); // Fetch again result = handler.fetchNotifications(result.getNextSequenceNumber(), 10, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), 2); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, 1); } public void testBufferWithSmallCapacity() throws Exception { int bufferCapacity = 1; Map environment = new HashMap(); environment.put(MX4JRemoteConstants.NOTIFICATION_BUFFER_CAPACITY, new Integer(bufferCapacity)); RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(environment); // Fill the buffer NotificationListener listener = handler.getServerNotificationListener(); Notification notification = new Notification("dummy", this, 0); Integer listenerID = new Integer(1); for (int i = 0; i < bufferCapacity; ++i) listener.handleNotification(notification, listenerID); // Fetch first time NotificationResult result = handler.fetchNotifications(-1, bufferCapacity + 1, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), bufferCapacity); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, 0); // Add another notification: the buffer is full, the earliest sequence number must change listener.handleNotification(notification, listenerID); // Fetch again result = handler.fetchNotifications(result.getNextSequenceNumber(), bufferCapacity + 1, 100); assertEquals(result.getEarliestSequenceNumber(), bufferCapacity); assertEquals(result.getNextSequenceNumber(), bufferCapacity + 1); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, 1); } public void testPurgeNotifications() throws Exception { int distance = 2; Map environment = new HashMap(); environment.put(MX4JRemoteConstants.NOTIFICATION_PURGE_DISTANCE, new Integer(distance)); RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(environment); // Fetch NotificationResult result = handler.fetchNotifications(-1, 10, 100); // Add notifications NotificationListener listener = handler.getServerNotificationListener(); Notification notification = new Notification("dummy", this, 0); Integer listenerID = new Integer(1); int count = distance + 1; for (int i = 0; i < count; ++i) listener.handleNotification(notification, listenerID); // Fetch again result = handler.fetchNotifications(result.getNextSequenceNumber(), count + 1, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), count); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, count); // Fetch again: this call triggers purge of old notifications, which changes the earliest sequence number result = handler.fetchNotifications(result.getNextSequenceNumber(), count + 1, 100); // Check that the earliest sequence number has changed long oldEarliest = result.getEarliestSequenceNumber(); result = handler.fetchNotifications(result.getNextSequenceNumber(), count + 1, 100); if (oldEarliest >= result.getEarliestSequenceNumber()) fail(); } public void testPurgeNotificationsWithInitialNotificationMiss() throws Exception { int distance = 2; Map environment = new HashMap(); environment.put(MX4JRemoteConstants.NOTIFICATION_PURGE_DISTANCE, new Integer(distance)); RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(environment); // Add notifications (will be missed) NotificationListener listener = handler.getServerNotificationListener(); Notification notification = new Notification("dummy", this, 0); Integer listenerID = new Integer(1); int count = distance + 1; for (int i = 0; i < count; ++i) listener.handleNotification(notification, listenerID); // First fetch NotificationResult result = handler.fetchNotifications(-1, count + 1, 100); // Add notifications for (int i = 0; i < count; ++i) listener.handleNotification(notification, listenerID); // Fetch again: this call triggers purge of old notifications, which changes the earliest sequence number result = handler.fetchNotifications(result.getNextSequenceNumber(), count + 1, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), count + count); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, count); // Check that the earliest sequence number has changed long oldEarliest = result.getEarliestSequenceNumber(); result = handler.fetchNotifications(result.getNextSequenceNumber(), count + 1, 100); if (oldEarliest >= result.getEarliestSequenceNumber()) fail(); } public void testBufferOverflowWhileFetching() throws Exception { int bufferCapacity = 5; Map environment = new HashMap(); environment.put(MX4JRemoteConstants.NOTIFICATION_BUFFER_CAPACITY, new Integer(bufferCapacity)); RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(environment); // First Fetch NotificationResult result = handler.fetchNotifications(-1, bufferCapacity + 1, 100); // Add some notifications, but don't fill the buffer long count = bufferCapacity - 2; NotificationListener listener = handler.getServerNotificationListener(); Notification notification = new Notification("dummy", this, 0); Integer listenerID = new Integer(1); for (int i = 0; i < count; ++i) listener.handleNotification(notification, listenerID); // Fetch again result = handler.fetchNotifications(result.getNextSequenceNumber(), bufferCapacity + 1, 100); assertEquals(result.getEarliestSequenceNumber(), 0); assertEquals(result.getNextSequenceNumber(), count); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, count); // Add some notification overflowing the buffer by a number that will exceed the // next sequence number sent by the client. // The client will fetch with its own sequence number, but the server // has discarded that number already (it overflew), be sure the system it does // not screw up (IndexOutOfBoundsException) int overflow = 7; // Note that count == result.getNextSequenceNumber() always yield true at this point (see assertion above), // so we actually overflew the buffer by a quantity q == count + overflow (see assertion below). long overflowCount = (bufferCapacity - count) + result.getNextSequenceNumber() + overflow; for (int i = 0; i < overflowCount; ++i) listener.handleNotification(notification, listenerID); result = handler.fetchNotifications(result.getNextSequenceNumber(), bufferCapacity + 1, 100); // After algebraic semplification, overflowCount == bufferCapacity + overflow, so // the buffer is full, and we fetched all notifications assertEquals(count + overflow, result.getEarliestSequenceNumber()); assertEquals(count + overflow + bufferCapacity, result.getNextSequenceNumber()); assertNotNull(result.getTargetedNotifications()); assertEquals(result.getTargetedNotifications().length, bufferCapacity); } } mx4j-3.0.2/src/test/test/mx4j/server/BCELMBeanInvokerTest.java100644 0 0 22130 10513545721 21134 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.server; import java.lang.reflect.Method; import javax.management.MBeanServer; import javax.management.ObjectName; import mx4j.MX4JSystemKeys; import test.MX4JTestCase; import test.MutableInteger; /** * @version $Revision: 1.12 $ */ public class BCELMBeanInvokerTest extends MX4JTestCase { private int m_reps; private int m_calls; public BCELMBeanInvokerTest(String s) { super(s); } protected void setUp() throws Exception { m_reps = 10; m_calls = 50000; } protected void tearDown() throws Exception { super.tearDown(); } public void testReflectedAttributePerformance() throws Exception { String property = MX4JSystemKeys.MX4J_MBEAN_INVOKER; System.setProperty(property, "mx4j.server.CachingReflectionMBeanInvoker"); MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("BCEL:test=performance,type=reflection"); try { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); server.registerMBean(mbean, name); long[] results = new long[m_reps]; for (int i = 0; i < m_reps; ++i) { long start = System.currentTimeMillis(); for (int j = 0; j < m_calls; ++j) { server.getAttribute(name, "Test"); } long end = System.currentTimeMillis(); results[i] = end - start; System.out.println("Reflection result: " + results[i]); } if (integer.get() != m_calls * m_reps) { fail("MBean not called !"); } long reflectionAverage = 0; for (int i = 1; i < m_reps; ++i) { reflectionAverage += results[i]; } reflectionAverage = reflectionAverage / (m_reps - 1); System.out.println("Reflection Average for getAttribute = " + reflectionAverage); } finally { System.getProperties().remove(property); server.unregisterMBean(name); } } public void testReflectedOperationPerformance() throws Exception { String property = MX4JSystemKeys.MX4J_MBEAN_INVOKER; System.setProperty(property, "mx4j.server.CachingReflectionMBeanInvoker"); MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("BCEL:test=performance,type=reflection"); try { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); server.registerMBean(mbean, name); long[] results = new long[m_reps]; for (int i = 0; i < m_reps; ++i) { long start = System.currentTimeMillis(); for (int j = 0; j < m_calls; ++j) { server.invoke(name, "test", null, null); } long end = System.currentTimeMillis(); results[i] = end - start; System.out.println("Reflection result: " + results[i]); } if (integer.get() != m_calls * m_reps) { fail("MBean not called !"); } long reflectionAverage = 0; for (int i = 1; i < m_reps; ++i) { reflectionAverage += results[i]; } reflectionAverage = reflectionAverage / (m_reps - 1); System.out.println("Reflection Average for invoke = " + reflectionAverage); } finally { System.getProperties().remove(property); server.unregisterMBean(name); } } public void testBCELAttributePerformance() throws Exception { // Be sure we use the BCEL invoker System.getProperties().remove(MX4JSystemKeys.MX4J_MBEAN_INVOKER); MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("BCEL:test=performance,type=direct"); try { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); server.registerMBean(mbean, name); long[] results = new long[m_reps]; for (int i = 0; i < m_reps; ++i) { long start = System.currentTimeMillis(); for (int j = 0; j < m_calls; ++j) { server.getAttribute(name, "Test"); } long end = System.currentTimeMillis(); results[i] = end - start; System.out.println("Direct result: " + results[i]); } if (integer.get() != m_calls * m_reps) { fail("MBean not called !"); } long directAverage = 0; for (int i = 1; i < m_reps; ++i) { directAverage += results[i]; } directAverage = directAverage / (m_reps - 1); System.out.println("Direct Average for getAttribute = " + directAverage); } finally { server.unregisterMBean(name); } } public void testBCELOperationPerformance() throws Exception { // Be sure we use the BCEL invoker System.getProperties().remove(MX4JSystemKeys.MX4J_MBEAN_INVOKER); MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("BCEL:test=performance,type=direct"); try { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); server.registerMBean(mbean, name); long[] results = new long[m_reps]; for (int i = 0; i < m_reps; ++i) { long start = System.currentTimeMillis(); for (int j = 0; j < m_calls; ++j) { server.invoke(name, "test", null, null); } long end = System.currentTimeMillis(); results[i] = end - start; System.out.println("Direct result: " + results[i]); } if (integer.get() != m_calls * m_reps) { fail("MBean not called !"); } long directAverage = 0; for (int i = 1; i < m_reps; ++i) { directAverage += results[i]; } directAverage = directAverage / (m_reps - 1); System.out.println("Direct Average for invoke = " + directAverage); } finally { server.unregisterMBean(name); } } public void testPlainReflectionPerformance() throws Exception { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); Method test = mbean.getClass().getMethod("test", (Class[])null); int factor = 100; int calls = m_calls * factor; long[] results = new long[m_reps]; for (int i = 0; i < m_reps; ++i) { long start = System.currentTimeMillis(); for (int j = 0; j < calls; ++j) { test.invoke(mbean, (Object[])null); } long end = System.currentTimeMillis(); results[i] = end - start; System.out.println("Plain reflection: " + (results[i] / factor)); } if (integer.get() != calls * m_reps) { fail("MBean not called !"); } long directAverage = 0; for (int i = 1; i < m_reps; ++i) { directAverage += results[i]; } directAverage = directAverage / (m_reps - 1); System.out.println("Plain average = " + (directAverage / factor)); } public void testBCELPackagePrivate() throws Exception { // Be sure we use the BCEL invoker System.getProperties().remove(MX4JSystemKeys.MX4J_MBEAN_INVOKER); MBeanServer server = newMBeanServer(); ObjectName name = new ObjectName("BCEL:test=package,type=direct"); try { MutableInteger integer = new MutableInteger(0); BCELPerformance mbean = new BCELPerformance(integer); server.registerMBean(mbean, name); PackagePrivate arg = new PackagePrivate(); server.invoke(name, "testPackagePrivate", new Object[]{arg}, new String[]{arg.getClass().getName()}); if (integer.get() != 1) { fail("MBean not called !"); } } finally { server.unregisterMBean(name); } } public interface BCELPerformanceMBean { public void test(); public int getTest(); public void testPackagePrivate(PackagePrivate param); } class PackagePrivate { } public static class BCELPerformance implements BCELPerformanceMBean { private MutableInteger m_integer; public BCELPerformance(MutableInteger integer) { m_integer = integer; } public void test() { m_integer.set(m_integer.get() + 1); } public int getTest() { m_integer.set(m_integer.get() + 1); return 0; } public void testPackagePrivate(PackagePrivate param) { m_integer.set(m_integer.get() + 1); } } } mx4j-3.0.2/src/test/test/mx4j/server/MBeanPermissionTest.java100644 0 0 34201 10513545721 21223 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.server; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.management.MBeanPermission; import test.javax.management.PermissionTestCase; /** * @version $Revision: 1.19 $ */ public class MBeanPermissionTest extends PermissionTestCase { public MBeanPermissionTest(String s) { super(s); } public void testInvalidMBeanPermissionBecauseInvalidName() throws Exception { try { new MBeanPermission(null, null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("", null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission(" ", null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission(" ", "*"); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("", "*"); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } // Invalid ObjectName try { new MBeanPermission("[d?k=v]", "*"); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("[*]", "*"); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } } public void testInvalidMBeanPermissionBecauseInvalidActions() throws Exception { try { new MBeanPermission("*", null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("com.*[d:k=v]", null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("com.*[d:k=v]", null); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("com.*[d:k=v]", ""); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("com.*[d:k=v]", " "); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } try { new MBeanPermission("com.*[d:k=v]", " , "); fail("Invalid MBeanPermission"); } catch (IllegalArgumentException ignored) { } } public void testValidMBeanPermissionZero() throws Exception { MBeanPermission mbp1 = new MBeanPermission("*", "*"); MBeanPermission mbp2 = new MBeanPermission(" *", "*"); MBeanPermission mbp3 = new MBeanPermission(" *", "* "); MBeanPermission mbp4 = new MBeanPermission("*[*:*]", "*"); MBeanPermission mbp5 = new MBeanPermission("*#*[*:*]", "*"); // Test equality shouldBeEqual(mbp1, mbp2); shouldBeEqual(mbp2, mbp3); shouldBeEqual(mbp3, mbp4); shouldBeEqual(mbp4, mbp5); } public void testValidMBeanPermissionOne() throws Exception { MBeanPermission mbp1 = new MBeanPermission("[d:k=v]", "invoke"); MBeanPermission mbp2 = new MBeanPermission("*[d:k=v]", "invoke"); MBeanPermission mbp3 = new MBeanPermission("*#*[d:k=v]", "invoke"); shouldBeEqual(mbp1, mbp2); shouldBeEqual(mbp2, mbp3); } public void testValidMBeanPermissionTwo() throws Exception { MBeanPermission mbp1 = new MBeanPermission("com.package.MyClass", "getAttribute"); MBeanPermission mbp2 = new MBeanPermission("com.package.MyClass#*", "getAttribute"); MBeanPermission mbp3 = new MBeanPermission("com.package.MyClass#*[*:*]", "getAttribute"); shouldBeEqual(mbp1, mbp2); shouldBeEqual(mbp2, mbp3); } public void testValidMBeanPermissionThree() throws Exception { MBeanPermission mbp1 = new MBeanPermission("com.package.MyClass[d:k=v]", "setAttribute"); MBeanPermission mbp2 = new MBeanPermission("com.package.MyClass#*[d:k=v]", "setAttribute"); shouldBeEqual(mbp1, mbp2); } public void testValidMBeanPermissionFour() throws Exception { MBeanPermission mbp1 = new MBeanPermission("#Name[d:k=v]", "isInstanceOf"); MBeanPermission mbp2 = new MBeanPermission("*#Name[d:k=v]", "isInstanceOf"); shouldBeEqual(mbp1, mbp2); } public void testValidMBeanPermissionFive() throws Exception { MBeanPermission mbp1 = new MBeanPermission("-", "getMBeanInfo"); MBeanPermission mbp2 = new MBeanPermission("-#*[*:*]", "getMBeanInfo"); shouldBeEqual(mbp1, mbp2); } public void testValidMBeanPermissionSix() throws Exception { MBeanPermission mbp1 = new MBeanPermission("-#-", "getMBeanInfo"); MBeanPermission mbp2 = new MBeanPermission("-#-[*:*]", "getMBeanInfo"); shouldBeEqual(mbp1, mbp2); } public void testValidMBeanPermissionSeven() throws Exception { MBeanPermission mbp1 = new MBeanPermission("-#-[-]", "getMBeanInfo"); } public void testValidMBeanPermissionEight() throws Exception { MBeanPermission mbp1 = new MBeanPermission("com.package.MyClass#Attr[d:k=v]", "*"); MBeanPermission mbp2 = new MBeanPermission("com.package.MyClass#Attr[d:k=v]", "invoke,*"); shouldBeEqual(mbp1, mbp2); } public void testValidMBeanPermissionNine() throws Exception { new MBeanPermission("*[d:k=v]", "addNotificationListener, *"); new MBeanPermission("*[d:k1=v1,k2=v2]", "removeNotificationListener, *"); new MBeanPermission("mx4j.*", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo#*", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo$Inner#*", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo#*[*:*]", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo$Inner#*[*:*]", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "addNotificationListener, removeNotificationListener"); new MBeanPermission("mx4j.Foo$Inner#Bar[d:k=v]", "addNotificationListener, removeNotificationListener"); } public void testMBeanPermissionWildcardAlwaysImplies() throws Exception { MBeanPermission wild = new MBeanPermission("*", "*"); shouldImply(wild, wild); shouldImply(new MBeanPermission("*[*:*]", "*"), wild); shouldImply(wild, new MBeanPermission("*[*:*]", "*")); shouldImply(new MBeanPermission("*#*[*:*]", "*"), wild); shouldImply(wild, new MBeanPermission("*#*[*:*]", "*")); implies(wild, new MBeanPermission("com.*", "*")); shouldImply(wild, new MBeanPermission("com.package.MyClass", "*")); shouldImply(wild, new MBeanPermission("com.package.MyClass#Attribute", "*")); shouldImply(wild, new MBeanPermission("com.package.MyClass#Attribute[d:k=v]", "*")); shouldImply(wild, new MBeanPermission("com.package.MyClass#Attribute[d:k=v]", "getObjectInstance")); shouldImply(wild, new MBeanPermission("-#-[-]", "*")); } public void testMBeanPermissionNilCardIsAlwaysImplied() throws Exception { String action = "queryNames"; MBeanPermission nil = new MBeanPermission("-#-[-]", action); shouldImply(nil, nil); shouldImply(new MBeanPermission("com.package.MyClass#Attr[d:k=v]", action), nil); } public void testMBeanPermissionQueryMBeansImpliesQueryNames() throws Exception { shouldImply(new MBeanPermission("*", "queryMBeans"), new MBeanPermission("*", "queryNames")); shouldNotImply(new MBeanPermission("*", "queryMBeans"), new MBeanPermission("*", "queryNames, invoke")); } public void testMBeanPermissionShuffledActionsAreEquals() throws Exception { MBeanPermission mbp1 = new MBeanPermission("*", "addNotificationListener, removeNotificationListener"); MBeanPermission mbp2 = new MBeanPermission("*", "removeNotificationListener, addNotificationListener"); shouldBeEqual(mbp1, mbp2); } public void testMBeanPermissionImpliesOne() throws Exception { MBeanPermission implied = new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,k2=v2]", "invoke"); MBeanPermission all = new MBeanPermission("*", "*"); shouldImply(implied, implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k2=v2,k1=v1]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,k2=v2]", "invoke,getAttribute"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,k2=v2]", "setAttribute,invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,k2=v2]", "invoke,*"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,k2=v2]", "*"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k1=v1,*]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:k2=v2,*]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[domain:*]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[dom?in:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[do*in:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[*:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar[*:*]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar*[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#B*[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#*[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#Bar*", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#B*", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo#*", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo*#Bar[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.*#Bar[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("*#Bar[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("#Bar[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.*#Bar", "invoke"), implied); shouldImply(new MBeanPermission("*#Bar", "invoke"), implied); shouldImply(new MBeanPermission("#Bar", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.*", "invoke"), implied); shouldImply(new MBeanPermission("*", "invoke"), implied); shouldImply(new MBeanPermission("mx4j.Foo*#*[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(new MBeanPermission("[domain:k1=v1,k2=v2]", "invoke"), implied); shouldImply(all, implied); shouldImply(new MBeanPermission("[]", "*"), all); shouldImply(implied, new MBeanPermission(null, null, null, "invoke")); } public void testMBeanPermissionNotImpliesOne() throws Exception { MBeanPermission notImplied = new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "invoke, getObjectInstance"); // Different actions shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "getAttribute"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "getAttribute,setAttribute"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "invoke,setAttribute"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "setAttribute,getObjectInstance"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v]", "getObjectInstance,getAttribute"), notImplied); // Different objectname shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v1]", "invoke, getObjectInstance"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[d:k=v,k1=v1]", "invoke, getObjectInstance"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo#Bar[:k=v]", "invoke, getObjectInstance"), notImplied); // Different attribute shouldNotImply(new MBeanPermission("mx4j.Foo#Baz[d:k=v]", "invoke, getObjectInstance"), notImplied); // Different class shouldNotImply(new MBeanPermission("mx4j.Foo.Baz#Bar[d:k=v]", "invoke, getObjectInstance"), notImplied); shouldNotImply(new MBeanPermission("mx4j.Foo$Inner#Bar[d:k=v]", "invoke, getObjectInstance"), notImplied); shouldNotImply(new MBeanPermission("dummy.Foo#Bar[d:k=v]", "invoke, getObjectInstance"), notImplied); } public void testMBeanPermissionSerialization() throws Exception { MBeanPermission permission = new MBeanPermission("mx4j.Foo#Bar[domain:key=value]", "invoke"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(permission); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); MBeanPermission deserialized = (MBeanPermission)ois.readObject(); ois.close(); if (!(deserialized.equals(permission))) fail("Serialization/Deserialization failed"); } private void implies(MBeanPermission p1, MBeanPermission p2) { if (!imply(p1, p2)) fail("Permission " + p1 + " should imply Permission " + p2); } } mx4j-3.0.2/src/test/test/mx4j/server/MX4JMBeanServerTest.java100644 0 0 17507 10513545721 21016 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.server; import java.lang.reflect.Method; import java.net.URL; import java.util.Iterator; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.loading.MLet; import mx4j.MBeanDescriptionAdapter; import mx4j.MX4JSystemKeys; import mx4j.server.MBeanMetaData; import mx4j.server.MBeanRepository; import mx4j.server.interceptor.DefaultMBeanServerInterceptor; import mx4j.server.interceptor.MBeanServerInterceptor; import mx4j.server.interceptor.MBeanServerInterceptorConfigurator; import test.MX4JTestCase; import test.MutableInteger; /** * @version $Revision: 1.3 $ */ public class MX4JMBeanServerTest extends MX4JTestCase { public MX4JMBeanServerTest(String s) { super(s); } public void testCustomMBeanRepository() throws Exception { String property = MX4JSystemKeys.MX4J_MBEANSERVER_REPOSITORY; try { System.setProperty(property, MX4JMBeanServerTest.TestMBeanRepository.class.getName()); MBeanServer server = newMBeanServer(); Method method = server.getClass().getDeclaredMethod("getMBeanRepository", new Class[0]); method.setAccessible(true); Object repository = method.invoke(server, new Object[0]); if (!(repository instanceof TestMBeanRepository)) fail("Custom Repository does not work"); } finally { System.getProperties().remove(property); } } public void testContextClassLoaderOnMethodCalls() throws Exception { // Create the appropriate class loader hierarchy URL testCodebase = getClass().getProtectionDomain().getCodeSource().getLocation(); URL implCodebase = MBeanServer.class.getProtectionDomain().getCodeSource().getLocation(); MLet mlet = new MLet(new URL[]{testCodebase, implCodebase}, getClass().getClassLoader().getParent()); MBeanServer server = newMBeanServer(); // Register the MLet loader ObjectName loader = new ObjectName(":mbean=loader"); server.registerMBean(mlet, loader); // Be sure the context classloader interceptor is enabled server.setAttribute(ObjectName.getInstance("JMImplementation", "interceptor", "contextclassloader"), new Attribute("Enabled", Boolean.TRUE)); // Register the MBean ObjectName name = new ObjectName("Test:mbean=ccl"); server.createMBean("test.mx4j.server.MX4JMBeanServerTest$CCL", name, loader, null, null); server.invoke(name, "method", null, null); } public void testAddRemoveMBeanServerInterceptor() throws Exception { MBeanServer server = newMBeanServer(); ObjectName configurator = new ObjectName(MBeanServerInterceptorConfigurator.OBJECT_NAME); MutableInteger integer = new MutableInteger(0); TestMBeanServerInterceptor tester = new TestMBeanServerInterceptor(integer); server.invoke(configurator, "addInterceptor", new Object[]{tester}, new String[]{MBeanServerInterceptor.class.getName()}); server.getAttribute(configurator, "Running"); if (integer.get() != 1) fail("Interceptor not installed"); server.invoke(configurator, "clearInterceptors", null, null); server.getAttribute(configurator, "Running"); // Be sure the interceptor is not anymore in the chain if (integer.get() != 1) fail("Interceptor not removed"); } public void testRegisterRemoveMBeanServerInterceptor() throws Exception { MBeanServer server = newMBeanServer(); ObjectName configurator = new ObjectName(MBeanServerInterceptorConfigurator.OBJECT_NAME); MutableInteger integer = new MutableInteger(0); TestMBeanServerInterceptor tester = new TestMBeanServerInterceptor(integer); ObjectName name = new ObjectName("Interceptor:category=MBeanServer,type=Test"); server.invoke(configurator, "registerInterceptor", new Object[]{tester, name}, new String[]{MBeanServerInterceptor.class.getName(), ObjectName.class.getName()}); server.getMBeanInfo(configurator); if (integer.get() != 1) fail("Interceptor not installed"); // Let's check if the interceptor is registered, let's change something in it server.setAttribute(name, new Attribute("Enabled", Boolean.FALSE)); // Call again server.getMBeanInfo(configurator); if (integer.get() != 1) fail("Interceptor not registered"); AttributeList list = new AttributeList(); list.add(new Attribute("Enabled", Boolean.TRUE)); server.setAttributes(name, list); server.getMBeanInfo(configurator); if (integer.get() != 2) fail("Interceptor not enabled"); server.invoke(configurator, "clearInterceptors", null, null); server.getAttribute(configurator, "Running"); // Be sure the interceptor is not anymore in the chain if (integer.get() != 2) fail("Interceptor not removed"); } public void testMBeanDescription() throws Exception { MBeanServer server = newMBeanServer(); ObjectName name = ObjectName.getInstance(":mbean=description"); server.registerMBean(new Description(), name); MBeanInfo info = server.getMBeanInfo(name); assertEquals(info.getDescription(), new DescriptionMBeanDescription().getMBeanDescription()); } public interface DescriptionMBean { } public static class Description implements DescriptionMBean { } public static class DescriptionMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "test"; } } public static class TestMBeanServerInterceptor extends DefaultMBeanServerInterceptor { private MutableInteger m_integer; public TestMBeanServerInterceptor(MutableInteger integer) { m_integer = integer; } public String getType() { return "test"; } public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException { if (isEnabled()) m_integer.set(m_integer.get() + 1); return super.getAttribute(metadata, attribute); } public MBeanInfo getMBeanInfo(MBeanMetaData metadata) { if (isEnabled()) m_integer.set(m_integer.get() + 1); return super.getMBeanInfo(metadata); } } public static class TestMBeanRepository implements MBeanRepository { public MBeanMetaData get(ObjectName name) { return null; } public void put(ObjectName name, MBeanMetaData metadata) { } public void remove(ObjectName name) { } public int size() { return 0; } public Iterator iterator() { return null; } public Object clone() { return null; } } public interface CCLMBean { public void method(); } public static class CCL implements CCLMBean { public CCL() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String loaderClass = cl.getClass().getName(); if (!loaderClass.endsWith("MLet")) { throw new RuntimeException(); } } public void method() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String loaderClass = cl.getClass().getName(); if (!loaderClass.endsWith("MLet")) { throw new RuntimeException(); } } } } mx4j-3.0.2/src/test/test/mx4j/server/NoOpMBeanServerInterceptor.java100644 0 0 4653 10513545721 22504 0ustar 0 0 /* * © Copyright 2004 Hewlett-Packard */ package test.mx4j.server; import java.util.List; import javax.management.NotificationListener; import javax.management.NotificationFilter; import javax.management.ListenerNotFoundException; import javax.management.ReflectionException; import javax.management.MBeanException; import javax.management.MBeanRegistrationException; import javax.management.MBeanInfo; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.Attribute; import javax.management.InvalidAttributeValueException; import mx4j.server.interceptor.MBeanServerInterceptor; import mx4j.server.MBeanMetaData; /** * $Rev$ */ public class NoOpMBeanServerInterceptor implements MBeanServerInterceptor { public String getType() { return "noop"; } public void setChain(List interceptors) { } public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) { } public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException { } public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { } public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException { } public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException { } public MBeanInfo getMBeanInfo(MBeanMetaData metadata) { return null; } public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException { return null; } public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes) { return null; } public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes) { return null; } public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException { return null; } public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException { } } mx4j-3.0.2/src/test/test/mx4j/server/NotificationListenerMBeanServerInterceptorTest.java100644 0 0 43667 10513545721 26655 0ustar 0 0 /* * © Copyright 2004 Hewlett-Packard */ package test.mx4j.server; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Iterator; import javax.management.NotificationListener; import javax.management.Notification; import javax.management.ObjectName; import javax.management.MBeanInfo; import javax.management.ObjectInstance; import test.MX4JTestCase; import mx4j.server.interceptor.NotificationListenerMBeanServerInterceptor; import mx4j.server.interceptor.MBeanServerInterceptor; import mx4j.server.MBeanMetaData; import mx4j.server.MBeanInvoker; /** * $Rev$ */ public class NotificationListenerMBeanServerInterceptorTest extends MX4JTestCase { public NotificationListenerMBeanServerInterceptorTest(String name) { super(name); } /** * One listener, one MBean, one ObjectName */ public void testAddRemove1() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); ObjectName objectName = ObjectName.getInstance(":type=test"); MBeanMetaData metadata = new NotificationListenerMBeanMetaData(this, objectName); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata, listener, null, null); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); Object wrapper = ((Map.Entry)interceptor.getNotificationListenerWrappers().entrySet().iterator().next()).getValue(); assertEquals(1, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); assertEquals(1, interceptor.getObjectNames().size()); assertEquals(objectName, interceptor.getObjectNames().keySet().iterator().next()); interceptor.removeNotificationListener(metadata, listener, null, null); assertEquals(0, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener thrice, one MBean, one ObjectName */ public void testAddRemove2() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); ObjectName objectName = ObjectName.getInstance(":type=test"); MBeanMetaData metadata = new NotificationListenerMBeanMetaData(this, objectName); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata, listener, null, null); interceptor.addNotificationListener(metadata, listener, null, listener); Object handback = new Object(); interceptor.addNotificationListener(metadata, listener, null, handback); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); Object wrapper = ((Map.Entry)interceptor.getNotificationListenerWrappers().entrySet().iterator().next()).getValue(); assertEquals(3, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); assertEquals(1, interceptor.getObjectNames().size()); assertEquals(objectName, interceptor.getObjectNames().keySet().iterator().next()); interceptor.removeNotificationListener(metadata, listener, null, handback); assertEquals(2, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); assertEquals(1, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata, listener); assertEquals(0, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener, one MBean, two ObjectNames */ public void testAddRemove3() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata1 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); MBeanMetaData metadata2 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test2")); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata1, listener, null, null); interceptor.addNotificationListener(metadata2, listener, null, null); assertEquals(2, interceptor.getNotificationListenerWrappers().size()); assertEquals(2, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata1, listener, null, null); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata2, listener, null, null); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener, two MBeans, two ObjectNames */ public void testAddRemove4() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata1 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); MBeanMetaData metadata2 = new NotificationListenerMBeanMetaData(interceptor, ObjectName.getInstance(":type=test2")); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata1, listener, null, null); interceptor.addNotificationListener(metadata2, listener, null, null); assertEquals(2, interceptor.getNotificationListenerWrappers().size()); assertEquals(2, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata1, listener, null, null); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata2, listener, null, null); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * Two listeners, one MBean, one ObjectName */ public void testAddRemove5() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); ObjectName objectName = ObjectName.getInstance(":type=test1"); MBeanMetaData metadata = new NotificationListenerMBeanMetaData(this, objectName); NotificationListener listener1 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; NotificationListener listener2 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata, listener1, null, null); interceptor.addNotificationListener(metadata, listener2, null, null); assertEquals(2, interceptor.getNotificationListenerWrappers().size()); for (Iterator iterator = interceptor.getNotificationListenerWrappers().values().iterator(); iterator.hasNext();) { Object wrapper = iterator.next(); assertEquals(1, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); } assertEquals(1, interceptor.getObjectNames().size()); assertEquals(objectName, interceptor.getObjectNames().keySet().iterator().next()); interceptor.removeNotificationListener(metadata, listener1); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata, listener2); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * Two listeners, one MBean, two ObjectNames */ public void testAddRemove6() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata1 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); MBeanMetaData metadata2 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test2")); NotificationListener listener1 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; NotificationListener listener2 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata1, listener1, null, null); interceptor.addNotificationListener(metadata2, listener2, null, null); assertEquals(2, interceptor.getNotificationListenerWrappers().size()); for (Iterator iterator = interceptor.getNotificationListenerWrappers().values().iterator(); iterator.hasNext();) { Object wrapper = iterator.next(); assertEquals(1, interceptor.getNotificationListenerWrapperReferenceCount(wrapper)); } assertEquals(2, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata1, listener1); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.removeNotificationListener(metadata2, listener2); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener, one MBean, one ObjectName */ public void testAddUnregister1() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata, listener, null, null); interceptor.registration(metadata, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener twice, one MBean, one ObjectName */ public void testAddUnregister2() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata, listener, null, null); interceptor.addNotificationListener(metadata, listener, null, listener); interceptor.registration(metadata, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * One listener, one MBean, two ObjectNames */ public void testAddUnregister3() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata1 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); MBeanMetaData metadata2 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test2")); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata1, listener, null, null); interceptor.addNotificationListener(metadata2, listener, null, null); interceptor.registration(metadata1, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.registration(metadata2, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } /** * Two listeners, one MBean, two ObjectNames */ public void testAddUnregister4() throws Exception { NotificationListenerMBeanServerInterceptor interceptor = new NotificationListenerMBeanServerInterceptor(); interceptor.setEnabled(true); List chain = new ArrayList(); chain.add(interceptor); chain.add(new NoOpMBeanServerInterceptor()); interceptor.setChain(chain); MBeanMetaData metadata1 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test1")); MBeanMetaData metadata2 = new NotificationListenerMBeanMetaData(this, ObjectName.getInstance(":type=test2")); NotificationListener listener1 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; NotificationListener listener2 = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { } }; interceptor.addNotificationListener(metadata1, listener1, null, null); interceptor.addNotificationListener(metadata2, listener2, null, null); interceptor.registration(metadata1, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(1, interceptor.getNotificationListenerWrappers().size()); assertEquals(1, interceptor.getObjectNames().size()); interceptor.registration(metadata2, MBeanServerInterceptor.POST_DEREGISTER); assertEquals(0, interceptor.getNotificationListenerWrappers().size()); assertEquals(0, interceptor.getObjectNames().size()); } private class NotificationListenerMBeanMetaData implements MBeanMetaData { private final Object mbean; private final ObjectName objectName; public NotificationListenerMBeanMetaData(Object mbean, ObjectName objectName) { this.mbean = mbean; this.objectName = objectName; } public Object getMBean() { return mbean; } public ObjectName getObjectName() { return objectName; } public void setMBean(Object mbean) { } public void setClassLoader(ClassLoader loader) { } public ClassLoader getClassLoader() { return null; } public void setObjectName(ObjectName name) { } public void setMBeanInfo(MBeanInfo info) { } public MBeanInfo getMBeanInfo() { return null; } public void setMBeanInterface(Class management) { } public Class getMBeanInterface() { return null; } public void setMBeanStandard(boolean value) { } public boolean isMBeanStandard() { return false; } public void setMBeanDynamic(boolean value) { } public boolean isMBeanDynamic() { return false; } public void setMBeanInvoker(MBeanInvoker invoker) { } public MBeanInvoker getMBeanInvoker() { return null; } public ObjectInstance getObjectInstance() { return null; } } } mx4j-3.0.2/src/test/test/mx4j/timer/TimeQueueTest.java100644 0 0 3010 10513545721 17657 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.timer; import java.lang.reflect.Field; import mx4j.timer.TimeQueue; import mx4j.timer.TimeTask; import test.MX4JTestCase; /** * @version $Revision: 1.3 $ */ public class TimeQueueTest extends MX4JTestCase { public TimeQueueTest(String s) { super(s); } public void testStop() throws Exception { TimeQueue queue = new TimeQueue(); queue.start(); // Wait a while to let the thread start sleep(1000); final int sleep = 5000; // Post a task to simulate work TimeTask task = new TimeTask() { public void run() { sleep(sleep); } }; queue.schedule(task); // Wait for the task to be executed sleep(1000); // Stop the queue. This will cause the task above to interrupt, // but we set the flag again as would be in a normal task queue.stop(); // Wait until the task is finished; the TimeQueue should have cleaned up sleep(sleep); // I want to be sure the thread has really shutdown Field field = queue.getClass().getDeclaredField("thread"); field.setAccessible(true); Thread thread = (Thread)field.get(queue); if (thread != null && thread.isAlive()) fail("TimeQueue not stopped"); } } mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/http/HttpAdaptorTest.java100644 0 0 16744 10513545721 22701 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.adaptor.http; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import junit.framework.TestCase; import mx4j.tools.adaptor.http.HttpCommandProcessorAdaptor; import mx4j.tools.adaptor.http.HttpInputStream; import org.w3c.dom.Document; /** * Class HttpAdaptorTest, tests the basics of the HttpAdaptor class * * @version $Revision: 1.3 $ */ public class HttpAdaptorTest extends TestCase { protected MBeanServer server; protected ObjectName name; protected static final int DEFAULT_PORT = 9090; /** * Constructor requested by the JUnit framework */ public HttpAdaptorTest() { super("HTTPAdapter Test"); } /** * Constructor requested by the JUnit framework */ public HttpAdaptorTest(String name) { super(name); } public void setUp() { try { server = MBeanServerFactory.createMBeanServer("Http"); name = new ObjectName("Http:name=HttpAdaptor"); server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", name, null); // use another port. There is less proabablity of collision server.setAttribute(name, new Attribute("Port", new Integer(DEFAULT_PORT))); server.invoke(name, "start", null, null); } catch (Exception e) { e.printStackTrace(); } } public void tearDown() { waitToStop(); try { server.unregisterMBean(name); } catch (Exception e) { // ignore, it shouldn't happen } } public void testBasics() throws Exception { // test default parameters assertEquals(new Integer(DEFAULT_PORT), server.getAttribute(name, "Port")); assertEquals("localhost", server.getAttribute(name, "Host")); assertEquals("none", server.getAttribute(name, "AuthenticationMethod")); waitToStop(); // test changing parameters server.setAttribute(name, new Attribute("Port", new Integer(8000))); assertEquals(new Integer(8000), server.getAttribute(name, "Port")); server.setAttribute(name, new Attribute("Host", "1.1.1.1")); assertEquals("1.1.1.1", server.getAttribute(name, "Host")); server.setAttribute(name, new Attribute("AuthenticationMethod", "basic")); assertEquals("basic", server.getAttribute(name, "AuthenticationMethod")); boolean exception = false; try { server.setAttribute(name, new Attribute("AuthenticationMethod", "something")); } catch (Exception e) { exception = true; } assertTrue(exception); exception = false; try { // test both null server.invoke(name, "addAuthorization", new Object[]{null, null}, new String[]{"java.lang.String", "java.lang.String"}); } catch (Exception e) { exception = true; } assertTrue(exception); server.invoke(name, "addAuthorization", new Object[]{"mx4j", "mx4j"}, new String[]{"java.lang.String", "java.lang.String"}); waitToStop(); // test changing parameters when server running exception = false; try { server.setAttribute(name, new Attribute("Port", new Integer(8000))); } catch (Exception e) { exception = true; } assertTrue(true); exception = false; try { server.setAttribute(name, new Attribute("Host", "localhost")); } catch (Exception e) { exception = true; } assertTrue(true); exception = false; try { server.setAttribute(name, new Attribute("AuthenticationMethod", "digest")); } catch (Exception e) { exception = true; } assertTrue(true); } public void testAuthentication() throws Exception { String host = "localhost"; int port = DEFAULT_PORT; URL url = new URL("http://" + host + ":" + port + "/"); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); in.close(); waitToStop(); server.setAttribute(name, new Attribute("AuthenticationMethod", "basic")); server.invoke(name, "addAuthorization", new Object[]{"mx4j", "mx4j"}, new String[]{"java.lang.String", "java.lang.String"}); server.invoke(name, "start", null, null); url = new URL("http://" + host + ":" + port + "/"); connection = url.openConnection(); try { in = connection.getInputStream(); } catch (Exception e) { } finally { in.close(); } assertEquals(((HttpURLConnection)connection).getResponseCode(), 401); url = new URL("http://" + host + ":" + port + "/"); connection = url.openConnection(); connection.setRequestProperty("Authorization", "basic bXg0ajpteDRq"); in = connection.getInputStream(); in.close(); waitToStop(); server.setAttribute(name, new Attribute("AuthenticationMethod", "none")); } public void testAddCommandProcessor() throws Exception { String host = "localhost"; int port = DEFAULT_PORT; URLConnection connection = null; URL url = new URL("http://" + host + ":" + port + "/nonexistant"); server.invoke(name, "addCommandProcessor", new Object[]{"nonexistant", new DummyCommandProcessor()}, new String[]{"java.lang.String", "mx4j.tools.adaptor.http.HttpCommandProcessor"}); //connection.close(); connection = url.openConnection(); assertEquals(200, ((HttpURLConnection)connection).getResponseCode()); server.invoke(name, "removeCommandProcessor", new Object[]{"nonexistant"}, new String[]{"java.lang.String"}); //connection.close(); connection = url.openConnection(); assertEquals(404, ((HttpURLConnection)connection).getResponseCode()); server.invoke(name, "addCommandProcessor", new Object[]{"nonexistant", "test.mx4j.tools.adaptor.http.HttpAdaptorTest$DummyCommandProcessor"}, new String[]{"java.lang.String", "java.lang.String"}); //connection.close(); connection = url.openConnection(); assertEquals(200, ((HttpURLConnection)connection).getResponseCode()); } private void waitToStop() { try { while (((Boolean)server.getAttribute(name, "Active")).booleanValue()) { try { server.invoke(name, "stop", null, null); synchronized (this) { wait(1000); } } catch (Exception e) { continue; } } } catch (Exception e) { e.printStackTrace(); } } public static class DummyCommandProcessor extends HttpCommandProcessorAdaptor { public Document executeRequest(HttpInputStream in) throws IOException, JMException { return builder.newDocument(); } } } mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/http/HttpAdaptorXMLTest.java100644 0 0 142102 10513545721 23266 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.adaptor.http; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.Attribute; import javax.management.MBeanNotificationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import org.custommonkey.xmlunit.XMLTestCase; import org.custommonkey.xmlunit.XMLUnit; /** * Test of HttpAdapter XML results * * @version $Revision: 1.3 $ */ public class HttpAdaptorXMLTest extends XMLTestCase { protected MBeanServer server; protected ObjectName httpName, test1Name, test2Name, test3Name; protected String host = "localhost"; protected int port = 8080; TestClass test1 = new TestClass("t1"); TestClass test2 = new TestClass("t1"); TestClass2 test3 = new TestClass2("t3"); /** * Construct the test case */ public HttpAdaptorXMLTest(String name) { super(name); } public static interface TestClassMBean { public String getStr(); public Double getDouble(); public boolean isTrue(); public void setStr(String str); public Boolean aMethod(String string); public void anotherMethod(String string, int test); } public static class TestClass extends NotificationBroadcasterSupport implements TestClassMBean { private String str; public TestClass(String str) { this.str = str; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public Double getDouble() { return new Double(0); } public boolean isTrue() { return true; } public Boolean aMethod(String string) { return new Boolean(string.equals("true")); } public void anotherMethod(String string, int test) { this.str = string; } public MBeanNotificationInfo[] getNotificationInfo() { MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[1]; notifications[0] = new MBeanNotificationInfo(new String[]{"test1" , "test2"}, "name", "test"); return notifications; } } public static interface TestClass2MBean { public String getStr(); public String[] getStrArray(); public void setStrArray(String[] str); public Double getDouble(); public void setDouble(Double doubleValue); public void setStr(String str); public Map getMap(); public List getList(); } public static class TestClass2 extends NotificationBroadcasterSupport implements TestClass2MBean { private String str; private String[] strArray = new String[]{"a", "b", "c"}; private Map map = new HashMap(); private List list = new ArrayList(); private Double doubleValue = new Double(0); public TestClass2(String str) { this.str = str; list.add("1"); list.add("2"); map.put("1", new Integer(1)); map.put("2", new Integer(2)); } public String getStr() { return str; } public String[] getStrArray() { return strArray; } public void setStrArray(String[] str) { this.strArray = strArray; } public void setStr(String str) { this.str = str; } public void setDouble(Double doubleValue) { this.doubleValue = doubleValue; } public Double getDouble() { return doubleValue; } public Map getMap() { return map; } public List getList() { return list; } } public void setUp() { try { server = MBeanServerFactory.createMBeanServer("Http"); httpName = new ObjectName("Http:name=HttpAdaptor"); test1Name = new ObjectName("Test:name=test1"); test2Name = new ObjectName("Test:name=test2"); test3Name = new ObjectName("Test:name=test3"); server.createMBean("mx4j.tools.adaptor.http.HttpAdaptor", httpName, null); // customisations, if you have the 8080 port reserved String hostProperty = System.getProperty("test.http.host"); if (hostProperty != null) { host = hostProperty; } String portProperty = System.getProperty("test.http.port"); if (portProperty != null) { port = Integer.parseInt(portProperty); } server.setAttribute(httpName, new Attribute("Host", host)); server.setAttribute(httpName, new Attribute("Port", new Integer(port))); // add a couple of MBeans server.registerMBean(test1, test1Name); server.registerMBean(test2, test2Name); server.registerMBean(test3, test3Name); server.invoke(httpName, "start", null, null); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setControlParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); XMLUnit.setTestParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); } catch (Exception e) { e.printStackTrace(); } } public void tearDown() { try { while (((Boolean)server.getAttribute(httpName, "Active")).booleanValue()) { try { server.invoke(httpName, "stop", null, null); synchronized (this) { wait(1000); } } catch (Exception e) { continue; } } server.unregisterMBean(httpName); } catch (Exception e) { e.printStackTrace(); } } /** * Test the mbeans request */ public void testServer() throws Exception { // test raw mbeans request, no organization Reader stream = getReader(host, port, "server"); StringBuffer result = new StringBuffer(); int i = 0; while ((i = stream.read()) >= 0) { result.append((char)i); } String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(controlMBean, result.toString()); stream.close(); } /** * Test the mbeans request */ public void testServerAndFilters() throws Exception { // test raw mbeans request, no organization Reader stream = getReader(host, port, "server?instanceof=test.mx4j.tools.adaptor.http.HttpAdaptorXMLTest$TestClass"); String controlMBean = "\n" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); } public void testServerByDomain() throws Exception { // test raw mbeans request grouped by domain Reader stream = getReader(host, port, "serverbydomain"); String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); } public void testServerByDomainAndFilters() throws Exception { // test raw mbeans request grouped by domain Reader stream = getReader(host, port, "serverbydomain?instanceof=test.mx4j.tools.adaptor.http.HttpAdaptorXMLTest$TestClass"); String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream = getReader(host, port, "serverbydomain?querynames=*:*"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; stream = getReader(host, port, "serverbydomain?querynames=Test:*"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream = getReader(host, port, "serverbydomain?querynames=something"); controlMBean = "\n" + "" + "" + ""; } /** * Test the mbeans delete */ public void testDelete() throws Exception { try { // test raw mbeans request, no organization Reader stream = getReader(host, port, "delete?objectname=Test:name=test1"); String controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertTrue(!server.isRegistered(test1Name)); stream.close(); stream = getReader(host, port, "delete?objectname=Test:name=test5"); controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); } finally { server.registerMBean(test1, test1Name); } } /** * Test the operations invoke */ public void testInvoke() throws Exception { Reader stream = getReader(host, port, "invoke?objectname=Test:name=test1&operation=aMethod&type0=java.lang.String&value0=true"); String controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "invoke?objectname=Test:name=test1&operation=aMethod&type0=java.lang.String&value0=test"); controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); } /** * Test the set attribute request */ public void testSetAttribute() throws Exception { try { // test correct ser variable Reader stream = getReader(host, port, "setattribute?objectname=Test:name=test1&attribute=Str&value=t2"); String controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals("t2", server.getAttribute(test1Name, "Str")); server.setAttribute(test1Name, new Attribute("Str", "t1")); stream.close(); // test correct ser variable stream = getReader(host, port, "setattribute?attribute=Str&value=t2"); controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals("t1", server.getAttribute(test1Name, "Str")); // test correct ser variable stream = getReader(host, port, "setattribute?objectname=3&attribute=Str&value=t2"); controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals("t1", server.getAttribute(test1Name, "Str")); stream.close(); stream = getReader(host, port, "setattribute?objectname=Test:name=test1&attribute=Number&value=t2"); controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals("t1", server.getAttribute(test1Name, "Str")); stream.close(); } finally { server.setAttribute(test1Name, new Attribute("Str", "t1")); } } /** * Test the set attributes request */ public void testSetAttributes() throws Exception { try { // test with set one variable Reader stream = getReader(host, port, "setattributes?objectname=Test:name=test3&value_Str=t2&set_Str=Set"); String controlMBean = "\n" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals("t2", server.getAttribute(test3Name, "Str")); server.setAttribute(test3Name, new Attribute("Str", "t1")); stream.close(); // test with set all stream = getReader(host, port, "setattributes?objectname=Test:name=test3&value_Str=t2&value_Double=3&setall=Set"); controlMBean = "\n" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals(new Double(3), server.getAttribute(test3Name, "Double")); stream.close(); // test two variables stream = getReader(host, port, "setattributes?objectname=Test:name=test3&value_Str=t3&value_Double=4&set_Str=Set&set_Double=Set"); controlMBean = "\n" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals(new Double(4), server.getAttribute(test3Name, "Double")); assertEquals("t3", server.getAttribute(test3Name, "Str")); // test bug when setting a wrong value stream = getReader(host, port, "setattributes?objectname=Test:name=test3&value_Str=t3&value_Double=c4&set_Str=Set&set_Double=Set"); controlMBean = "\n" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); assertEquals(new Double(4), server.getAttribute(test3Name, "Double")); assertEquals("t3", server.getAttribute(test3Name, "Str")); } finally { server.setAttribute(test3Name, new Attribute("Str", "t1")); server.setAttribute(test3Name, new Attribute("Double", new Double(0))); } } public void testCreate() throws Exception { ObjectName name = new ObjectName("Http:name=create"); try { // test raw mbeans request grouped by domain Reader stream = getReader(host, port, "create?class=mx4j.tools.adaptor.http.HttpAdaptor&objectname=" + name.toString()); String controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); } finally { server.unregisterMBean(name); } } public void testEmpty() throws Exception { // test empty request Reader stream = getReader(host, port, "empty"); String controlMBean = "\n"; assertXMLEqual(new StringReader(controlMBean), stream); } /** * Test the mbeans request */ public void testSingleMBean() throws Exception { // test one mbean request Reader stream = getReader(host, port, "mbean?objectname=Test:name=test1"); String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); // Test with arrays/maps/collections stream = getReader(host, port, "mbean?objectname=Test:name=test3"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); // test isnull Object theMap = server.getAttribute(new ObjectName("Test:name=test3"), "StrArray"); try { server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", null)); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=StrArray&format=map"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; } finally { server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", theMap)); } } public void testSingleMBeanAndFilters() throws Exception { // test one mbean request Reader stream = getReader(host, port, "mbean?objectname=Test:name=test1&attributes=false"); String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "mbean?objectname=Test:name=test1&constructors=false"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "mbean?objectname=Test:name=test1&operations=false"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "mbean?objectname=Test:name=test1¬ifications=false"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "mbean?objectname=Test:name=test1¬ifications=false&attributes=false&operations=false&constructors=false"); controlMBean = "\n" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); } public void testConstructors() throws Exception { // test one constructors request Reader stream = getReader(host, port, "constructors?classname=mx4j.tools.adaptor.http.HttpAdaptor"); String controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream = getReader(host, port, "constructors?classname=mx4j.Something"); controlMBean = "\n" + ""; assertXMLEqual(new StringReader(controlMBean), stream); } /** * Test the get attribute request for arrays */ public void testGetAttribute() throws Exception { Reader stream = getReader(host, port, "getattribute?objectname=Test:name=test1&attribute=Str"); String controlMBean = "\n" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=StrArray&format=array"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=List&format=collection"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); stream.close(); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=Map&format=map"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + ""; assertXMLEqual(new StringReader(controlMBean), stream); // test isnull Object theArray = server.getAttribute(new ObjectName("Test:name=test3"), "StrArray"); try { server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", null)); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=StrArray&format=map"); controlMBean = "\n" + "" + "" + ""; } finally { server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", theArray)); } // test for bug #622693 String strArray[] = (String[])server.getAttribute(new ObjectName("Test:name=test3"), "StrArray"); String valueAt1 = strArray[1]; strArray[1] = null; try { server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", strArray)); stream = getReader(host, port, "getattribute?objectname=Test:name=test3&attribute=StrArray&format=map"); controlMBean = "\n" + "" + "" + "" + "" + "" + "" + "" + "" + ""; } finally { strArray[1] = valueAt1; server.setAttribute(new ObjectName("Test:name=test3"), new Attribute("StrArray", strArray)); } } public Reader getReader(String host, int port, String path) throws IOException, MalformedURLException { URL url = new URL("http://" + host + ":" + port + "/" + path); URLConnection connection = url.openConnection(); return new InputStreamReader(connection.getInputStream()); } } mx4j-3.0.2/src/test/test/mx4j/tools/config/ConfigurationLoaderTest.java100644 0 0 44001 10513545721 23224 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.config; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.net.Socket; import java.util.ArrayList; import java.util.Hashtable; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import mx4j.tools.config.ConfigurationException; import mx4j.tools.config.ConfigurationLoader; import mx4j.tools.config.DefaultConfigurationBuilder; import test.MX4JTestCase; /** * @version $Revision: 1.7 $ */ public class ConfigurationLoaderTest extends MX4JTestCase { public ConfigurationLoaderTest(String s) { super(s); } public void testMalformedXML() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); try { loader.startup(new StringReader(config)); fail(); } catch (ConfigurationException x) { } } public void testUnknownElement() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); try { loader.startup(new StringReader(config)); fail(); } catch (ConfigurationException x) { } } public void testEmptyConfiguration() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); } public void testEmptyStartup() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); } public void testEmptyShutdown() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); } public void testEmptyShutdownWithSocket() throws Exception { MBeanServer server = newMBeanServer(); int port = 8872; String config = "" + "" + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); sleep(1000); // Be sure we can connect to the socket Socket socket = new Socket((String)null, port); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); } public void testEmptyStartupAndShutdown() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); } public void testEmptyStartupAndShutdownWithSocket() throws Exception { MBeanServer server = newMBeanServer(); int port = 8872; String config = "" + "" + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); sleep(1000); // Be sure we can connect to the socket Socket socket = new Socket((String)null, port); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); } public void testWrongShutdownCommand() throws Exception { MBeanServer server = newMBeanServer(); int port = 8872; String config = "" + "" + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); sleep(1000); // Be sure we can connect to the socket Socket socket = new Socket((String)null, port); socket.close(); socket = new Socket((String)null, port); socket.getOutputStream().write("dummy".getBytes()); socket.close(); socket = new Socket((String)null, port); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); try { new Socket((String)null, port); fail(); } catch (IOException x) { } } public void testConfigurationLoaderAsMBean() throws Exception { MBeanServer server = newMBeanServer(); ConfigurationLoader loader = new ConfigurationLoader(); ObjectName loaderName = ObjectName.getInstance("configuration:service=loader"); server.registerMBean(loader, loaderName); int port = 8872; String config = "" + "" + " " + " " + ""; server.invoke(loaderName, "startup", new Object[]{new StringReader(config)}, new String[]{Reader.class.getName()}); sleep(1000); // Be sure we can connect to the socket Socket socket = new Socket((String)null, port); socket.close(); // Shutdown via JMX server.invoke(loaderName, "shutdown", null, null); sleep(2000); try { new Socket((String)null, port); fail(); } catch (IOException x) { } } public void testCallElementStaticInvocation() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); ArrayList list = MBeanServerFactory.findMBeanServer(null); assertEquals(list.size(), 1); MBeanServerFactory.releaseMBeanServer((MBeanServer)list.get(0)); } public void testCallElementWithObjectArgument() throws Exception { MBeanServer server = newMBeanServer(); String config = "" + "" + " " + " " + " " + " " + " " + " A String" + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); } public void testCallElementObjectInvocation() throws Exception { MBeanServer server = newMBeanServer(); String domain = "test"; String config = "" + "" + " " + " " + " " + " rmi" + " " + domain + "" + " 0" + " /path" + " " + " " + " " + " " + " " + " " + " " + " " + ""; ConfigurationLoader loader = new ConfigurationLoader(server); loader.startup(new StringReader(config)); ArrayList list = MBeanServerFactory.findMBeanServer(null); assertEquals(list.size(), 1); MBeanServer mbs = (MBeanServer)list.get(0); assertEquals(mbs.getDefaultDomain(), domain); MBeanServerFactory.releaseMBeanServer(mbs); } public void testCallElementMBeanServerGetAttribute() throws Exception { MBeanServer server = newMBeanServer(); String name = "JMImplementation:type=MBeanServerDelegate"; String config = "" + "" + " " + " " + " " + " " + " " + " " + " " + "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); Reader reader = new BufferedReader(new StringReader(config)); loader.startup(reader); ArrayList list = MBeanServerFactory.findMBeanServer(null); assertEquals(list.size(), 1); MBeanServer mbs = (MBeanServer)list.get(0); String id = (String)server.getAttribute(new ObjectName(name), "MBeanServerId"); assertEquals(id, mbs.getDefaultDomain()); MBeanServerFactory.releaseMBeanServer(mbs); } public void testCallElementMBeanServerOperation() throws Exception { MBeanServer server = newMBeanServer(); int shutdownPort = 8872; String name = "naming:type=rmiregistry"; String config = "" + "" + " " + " " + " 1099" + " " + " " + " " + " " + " " + " " + "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); Reader reader = new BufferedReader(new StringReader(config)); loader.startup(reader); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost"); InitialContext ctx = new InitialContext(env); ctx.list(""); sleep(1000); Socket socket = new Socket((String)null, shutdownPort); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); try { ctx.list(""); fail(); } catch (NamingException x) { } } public void testCallElementMBeanSetAttribute() throws Exception { MBeanServer server = newMBeanServer(); int shutdownPort = 8872; String name = "naming:type=rmiregistry"; String port = "1199"; String config = "" + "" + " " + " " + " " + " " + port + "" + " " + " " + " " + " " + " " + " " + "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); Reader reader = new BufferedReader(new StringReader(config)); loader.startup(reader); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory"); env.put(Context.PROVIDER_URL, "rmi://localhost:" + port); InitialContext ctx = new InitialContext(env); ctx.list(""); sleep(1000); Socket socket = new Socket((String)null, shutdownPort); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); try { ctx.list(""); fail(); } catch (NamingException x) { } } public void testRegisterUnregisterElements() throws Exception { MBeanServer server = newMBeanServer(); int port = 8872; String name = "connectors:protocol=rmi"; String config = "" + "" + " " + " " + " " + " service:jmx:rmi://localhost" + " " + " " + " " + " " + " " + " " + " " + " " + "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); Reader reader = new BufferedReader(new StringReader(config)); loader.startup(reader); sleep(1000); assertTrue(server.isRegistered(new ObjectName(name))); Socket socket = new Socket((String)null, port); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); assertTrue(!server.isRegistered(new ObjectName(name))); } public void testObjectElement() throws Exception { MBeanServer server = newMBeanServer(); int port = 8872; String id = "connector"; String name = "connectors:protocol=rmi"; String config = "" + "" + " " + " " + " " + " service:jmx:rmi://localhost" + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "" + ""; ConfigurationLoader loader = new ConfigurationLoader(server); Reader reader = new BufferedReader(new StringReader(config)); loader.startup(reader); sleep(1000); assertTrue(server.isRegistered(new ObjectName(name))); Boolean active = (Boolean)server.getAttribute(new ObjectName(name), "Active"); assertTrue(active.booleanValue()); Socket socket = new Socket((String)null, port); socket.getOutputStream().write(DefaultConfigurationBuilder.SHUTDOWN_COMMAND.getBytes()); socket.close(); sleep(2000); assertTrue(!server.isRegistered(new ObjectName(name))); } } ././@LongLink100644 0 0 162 10513545722 10256 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationCompleteMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationCompleteMBeanResourc100644 0 0 121 10513545721 30324 0ustar 0 0 #Default I18N descr=The default direct implementation complete MBean description ././@LongLink100644 0 0 162 10513545722 10256 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 122 10513545721 30277 0ustar 0 0 #Default I18N descr=The default direct implementation name only MBean description ././@LongLink100644 0 0 165 10513545722 10261 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources_en.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 122 10513545721 30277 0ustar 0 0 #English I18N descr=The English direct implementation name only MBean description ././@LongLink100644 0 0 165 10513545722 10261 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources_fr.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 120 10513545721 30275 0ustar 0 0 #French I18N descr=The French direct implementation name only MBean description ././@LongLink100644 0 0 171 10513545722 10256 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousConstructorsMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousConstructorsMBean100644 0 0 1314 10513545721 30414 0ustar 0 0 #Default I18N descr=The default subclassed ambiguous constructor MBean description cons.1=The no-args constructor cons.2=The Locale specific constructor cons.2.param.1=The locale cons.2.paramName.1=locale cons.3=The int constructor cons.3.param.1=a number cons.3.paramName=value cons.4=The two parameter constructor cons.4.param.1=a number cons.4.paramName.1=a cons.4.param.2=another number cons.4.paramName.2=b # In fact TWO 3 arg constructors are declared in the source # Only one is described here so should be considered ambiguous cons.5=The three parameter constructor cons.5.param.1=a number cons.5.paramName.1=a cons.5.param.2=another number cons.5.paramName.2=b cons.5.param.3=a string cons.5.paramName.3=s ././@LongLink100644 0 0 166 10513545722 10262 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousOperationMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousOperationMBeanRes100644 0 0 2075 10513545721 30323 0ustar 0 0 #Default I18N descr=The default subclassed ambiguous operation MBean description op.operation.1=a no parameter operation op.operation.2=an int operation op.operation.2.param.1=a number op.operation.2.paramName.1=value op.operation.3=an Object operation op.operation.3.param.1=an object op.operation.3.paramName.1=obj op.operation.4=an int[] operation op.operation.4.param.1=an array of int op.operation.4.paramName.1=intArray op.operation.5=an Object[] operation op.operation.5.param.1=an array of Object op.operation.5.paramName.1=objArray op.operation.6=a two parameter int,Object operation op.operation.6.param.1=a number op.operation.6.paramName.1=a op.operation.6.param.2=an object op.operation.6.paramName.2=obj # in fact there are 2 three parameter versions of operation. Only one is defined here. Should be ambiguous. op.operation.7=a three parameter int,int,int operation op.operation.7.param.1=a number op.operation.7.paramName.1=i op.operation.7.param.2=another number op.operation.7.paramName.2=j op.operation.7.param.3=yet another number op.operation.7.paramName.3=k ././@LongLink100644 0 0 154 10513545722 10257 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassCompleteMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassCompleteMBeanResources.pro100644 0 0 714 10513545721 30255 0ustar 0 0 #Default I18N descr=The default subclassed complete MBean description cons.1=The no-args constructor cons.2=The Locale specific constructor cons.2.param.1=The locale cons.2.paramName.1=locale attr.Attrib=The attribute description op.operation=The operation description op.operation.param.1=The first parameter for the operation op.operation.paramName.1=parameter1 op.operation.param.2=The second parameter for the operation op.operation.paramName.2=parameter2 ././@LongLink100644 0 0 154 10513545722 10257 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources.pro100644 0 0 107 10513545721 30223 0ustar 0 0 #Default I18N descr=The default subclassed name only MBean description ././@LongLink100644 0 0 157 10513545722 10262 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_en.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_en.100644 0 0 107 10513545721 30164 0ustar 0 0 #English I18N descr=The English subclassed name only MBean description ././@LongLink100644 0 0 157 10513545722 10262 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_fr.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_fr.100644 0 0 105 10513545721 30167 0ustar 0 0 #French I18N descr=The French subclassed name only MBean description ././@LongLink100644 0 0 154 10513545722 10257 Lustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassOverloadMBeanResources.propertiesmx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassOverloadMBeanResources.pro100644 0 0 4072 10513545721 30301 0ustar 0 0 #Default I18N descr=The default subclassed overloaded MBean description cons.1.sig=java.lang.Object cons.1=The Object constructor cons.1.param.1=an object cons.1.paramName.1=obj cons.2.sig=int cons.2=The int constructor cons.2.param.1=a number cons.2.paramName.1=value cons.3.sig=[I cons.3=The int[] constructor cons.3.param.1=an array of int cons.3.paramName.1=intArray cons.4.sig=[Ljava.lang.Object; cons.4=The Object[] constructor cons.4.param.1=an array of Object cons.4.paramName.1=objArray cons.5.sig=int,java.lang.Object cons.5=A two parameter int,Object constructor cons.5.param.1=a number cons.5.paramName.1=a cons.5.param.2=an object cons.5.paramName.2=b cons.6.sig= cons.6=The no-args constructor op.operation.1.sig= op.operation.1=a no parameter operation op.operation.2.sig=int op.operation.2=an int operation op.operation.2.param.1=a number op.operation.2.paramName.1=value op.operation.3.sig=java.lang.Object op.operation.3=an Object operation op.operation.3.param.1=an object op.operation.3.paramName.1=obj op.operation.4.sig=[I op.operation.4=an int[] operation op.operation.4.param.1=an array of int op.operation.4.paramName.1=intArray op.operation.5.sig=[Ljava.lang.Object; op.operation.5=an Object[] operation op.operation.5.param.1=an array of Object op.operation.5.paramName.1=objArray op.operation.6.sig=int,java.lang.Object op.operation.6=a two parameter int,Object operation op.operation.6.param.1=a number op.operation.6.paramName.1=a op.operation.6.param.2=an object op.operation.6.paramName.2=obj op.operation.7.sig=int,int,int op.operation.7=a three parameter int,int,int operation op.operation.7.param.1=a number op.operation.7.paramName.1=i op.operation.7.param.2=another number op.operation.7.paramName.2=j op.operation.7.param.3=yet another number op.operation.7.paramName.3=k op.operation.8.sig=int,int,java.lang.String op.operation.8=a three parameter int,int,String operation op.operation.8.param.1=a number op.operation.8.paramName.1=i op.operation.8.param.2=another number op.operation.8.paramName.2=j op.operation.8.param.3=a String op.operation.8.paramName.3=s mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport.java100644 0 0 17622 10513545721 22411 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.i18n; import java.util.Locale; import javax.management.NotCompliantMBeanException; import mx4j.tools.i18n.I18NStandardMBean; /** */ public class I18NStandardMBeanSupport { /** * No management interface and it is not a standard MBean */ public static class SubclassNotCompliant extends I18NStandardMBean { public SubclassNotCompliant() throws NotCompliantMBeanException { super(null); } } /** * A simple management interface. */ public interface FullManagement { public void setAttrib(int i); public void operation(int i, Object obj); } /** * A management interface have overloaded operations. */ public interface OverloadManagement { public void setAttrib(int i); public void operation(); public void operation(int i); public void operation(Object obj); public void operation(int[] array); public void operation(Object[] array); public void operation(int i, Object obj); public void operation(int i, int j, int k); public void operation(int i, int j, String s); } /** * A base subclass of I18NStandardMBean (for factorization). */ public static class BaseSubclass extends I18NStandardMBean { private int m_attrib = 0; protected BaseSubclass(Class mbeanInterface) throws NotCompliantMBeanException { super(mbeanInterface); } protected BaseSubclass(Class mbeanInterface, Locale locale) throws NotCompliantMBeanException { super(mbeanInterface, locale); } public void setAttrib(int i) { m_attrib = i; } public void operation(int i, Object obj) { } } /** * A base implementation NOT derrived from I18NStandardMBean. */ public static class BaseImplementation implements FullManagement { private int m_attrib = 0; public void setAttrib(int i) { m_attrib = i; } public void operation(int i, Object obj) { } } /** * An I18NStandardMBean subclass having just a global name decription. */ public static class SubclassNameOnly extends BaseSubclass implements FullManagement { public SubclassNameOnly() throws NotCompliantMBeanException { super(FullManagement.class); } public SubclassNameOnly(Locale locale) throws NotCompliantMBeanException { super(FullManagement.class, locale); } } /** * An I18NStandardMBean subclass having full descriptions. */ public static class SubclassComplete extends BaseSubclass implements FullManagement { public SubclassComplete(Locale locale) throws NotCompliantMBeanException { super(FullManagement.class, locale); } public SubclassComplete() throws NotCompliantMBeanException { super(FullManagement.class); } } /** * An I18NStandardMBean subclass having no bundle. */ public static class SubclassNoBundle extends BaseSubclass implements FullManagement { public SubclassNoBundle() throws NotCompliantMBeanException { super(FullManagement.class); } } /** * An I18NStandardMBean subclass having ambiguous constructors */ public static class SubclassAmbiguousConstructors extends BaseSubclass implements FullManagement { // desciption can be found based on number of parameters public SubclassAmbiguousConstructors() throws NotCompliantMBeanException { super(FullManagement.class); } // with no signature info in the bundle this cannot be distinguished from the Locale version public SubclassAmbiguousConstructors(Locale locale) throws NotCompliantMBeanException { super(FullManagement.class, locale); } // with no signature info in the bundle this cannot be distinguished from the Locale version public SubclassAmbiguousConstructors(int i) throws NotCompliantMBeanException { super(FullManagement.class); } // with no signature info in the bundle this cannot be distinguished from the Locale version public SubclassAmbiguousConstructors(String s) throws NotCompliantMBeanException { super(FullManagement.class); } // This can determined with no signature (2 args) public SubclassAmbiguousConstructors(int i, int j) throws NotCompliantMBeanException { super(FullManagement.class); } // of the two 3 arg constructors below only one is described in the bundle // BUT they should both still be considered ambiguous public SubclassAmbiguousConstructors(int i, int j, int k) throws NotCompliantMBeanException { super(FullManagement.class); } public SubclassAmbiguousConstructors(int i, int j, String s) throws NotCompliantMBeanException { super(FullManagement.class); } } /** * An I18NStandardMBean subclass overloaded constructors and operations. */ public static class SubclassOverload extends BaseSubclass implements OverloadManagement { // no arguments public SubclassOverload() throws NotCompliantMBeanException { super(OverloadManagement.class); } // one argument Object public SubclassOverload(Object obj) throws NotCompliantMBeanException { super(OverloadManagement.class); } // one argument int public SubclassOverload(int i) throws NotCompliantMBeanException { super(OverloadManagement.class); } // one argument int[] public SubclassOverload(int[] i) throws NotCompliantMBeanException { super(OverloadManagement.class); } // one argument Object[] public SubclassOverload(Object[] objs) throws NotCompliantMBeanException { super(OverloadManagement.class); } // 2 arguments public SubclassOverload(int a, Object b) throws NotCompliantMBeanException { super(OverloadManagement.class); } public void operation() { } public void operation(int i) { } public void operation(Object obj) { } public void operation(int[] array) { } public void operation(Object[] array) { } public void operation(int i, int j, int k) { } public void operation(int i, int j, String s) { } } /** * A subclass whose bundle will not specify sigs (so operations are ambiguous). */ public static class SubclassAmbiguousOperation extends BaseSubclass implements OverloadManagement { public SubclassAmbiguousOperation() throws NotCompliantMBeanException { super(OverloadManagement.class); } public void operation() { } public void operation(int i) { } public void operation(Object obj) { } public void operation(int[] array) { } public void operation(Object[] array) { } public void operation(int i, int j, int k) { } public void operation(int i, int j, String s) { } } /** * An I18N MBean implementation having just a global name decription. */ public static class ImplementationNameOnly extends BaseImplementation { } /** * An I18N MBean implementation having full decriptions. */ public static class ImplementationComplete extends BaseImplementation { } /** * An I18N MBean implementation having no bundle. */ public static class ImplementationNoBundle extends BaseImplementation { } } mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanTest.java100644 0 0 45553 10513545721 21660 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.i18n; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanFeatureInfo; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import junit.framework.TestCase; import mx4j.tools.i18n.I18NStandardMBean; /** * Tests for the translatable standard MBean extensions. */ public class I18NStandardMBeanTest extends TestCase { public I18NStandardMBeanTest(String s) { super(s); } public void setUp() { I18NStandardMBean.setDefaultLocale(null); setLocaleProp(""); // Hashtable does not accept null! } /** * Verify loading of correct resource bundle for subclassed I18NStandardMBeans. * Only use a single key (MBean decription) */ public void testSubclassSource() throws Exception { // No system property, standard locale with no I18N => default file setDefaultLocale(Locale.ITALY); // no I18N files for this I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassNameOnly(); MBeanInfo info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The default subclassed name only MBean description"); // Explicitly requested locale (overrides system default locale) setDefaultLocale(Locale.ENGLISH); mbean = new I18NStandardMBeanSupport.SubclassNameOnly(Locale.FRENCH); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The French subclassed name only MBean description"); // system default locale mbean = new I18NStandardMBeanSupport.SubclassNameOnly(); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The English subclassed name only MBean description"); // system property (overrides default locale) setLocaleProp("fr_FR"); mbean = new I18NStandardMBeanSupport.SubclassNameOnly(); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The French subclassed name only MBean description"); // static setLocale method (overrides default locale) I18NStandardMBean.setDefaultLocale(Locale.ENGLISH); mbean = new I18NStandardMBeanSupport.SubclassNameOnly(); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The English subclassed name only MBean description"); } /** * Verify loading of correct resource bundle for non subclassed MBeans. * Only use a single key (MBean decription) */ public void testImplementationSource() throws Exception { I18NStandardMBeanSupport.ImplementationNameOnly impl = new I18NStandardMBeanSupport.ImplementationNameOnly(); // No system property, standard locale with no I18N => default file setDefaultLocale(Locale.ITALY); // no I18N files for this I18NStandardMBean mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class); MBeanInfo info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The default direct implementation name only MBean description"); // Explicitly requested locale (overrides system default locale) setDefaultLocale(Locale.ENGLISH); mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class, Locale.FRENCH); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The French direct implementation name only MBean description"); // system default locale mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The English direct implementation name only MBean description"); // system property (overrides default locale) setLocaleProp("fr_FR"); mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The French direct implementation name only MBean description"); // static setLocale method (overrides default locale) I18NStandardMBean.setDefaultLocale(Locale.ENGLISH); mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class); info = mbean.getMBeanInfo(); assertEquals(info.getDescription(), "The English direct implementation name only MBean description"); } /** * Verify loading of all the keys. * Locale switching already tested above so just use a single locale here. * Only test "simple" constuctors and operations that do not require signatures. */ public void testAllKeys() throws Exception { I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassComplete(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK assertEquals(info.getDescription(), "The default subclassed complete MBean description"); MBeanAttributeInfo attrInfo = info.getAttributes()[0]; assertEquals(attrInfo.getDescription(), "The attribute description"); MBeanOperationInfo opInfo = info.getOperations()[0]; assertEquals(opInfo.getDescription(), "The operation description"); MBeanParameterInfo paramInfo = opInfo.getSignature()[0]; checkParam(paramInfo, "The first parameter for the operation", "parameter1"); paramInfo = opInfo.getSignature()[1]; checkParam(paramInfo, "The second parameter for the operation", "parameter2"); MBeanConstructorInfo[] cstrs = info.getConstructors(); assertEquals(cstrs.length, 2); //dumpConstructors(info); Map mapCstrForDesc = makeFeatureMap(cstrs); // no args constructor MBeanConstructorInfo cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The no-args constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 0); // Locale constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The Locale specific constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 1); paramInfo = cstr.getSignature()[0]; checkParam(paramInfo, "The locale", "locale"); } /** * Various tests of constructors that need to be destinguished by their signatures. */ public void testOverloadedConstructors() throws Exception { I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassOverload(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK //dumpConstructors(info); MBeanConstructorInfo[] cstrs = info.getConstructors(); assertEquals(cstrs.length, 6); Map mapCstrForDesc = makeFeatureMap(cstrs); // no args constructor MBeanConstructorInfo cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The no-args constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 0); // Object constuctor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The Object constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 1); checkParam(cstr.getSignature()[0], "an object", "obj"); // int constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The int constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 1); checkParam(cstr.getSignature()[0], "a number", "value"); // int[] constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The int[] constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 1); checkParam(cstr.getSignature()[0], "an array of int", "intArray"); // Object[] constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The Object[] constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 1); checkParam(cstr.getSignature()[0], "an array of Object", "objArray"); // int,Object constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("A two parameter int,Object constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 2); checkParam(cstr.getSignature()[0], "a number", "a"); checkParam(cstr.getSignature()[1], "an object", "b"); } /** * Various tests of ambiguous constructors */ public void testAmbiguousConstructors() throws Exception { System.out.println("****"); I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassAmbiguousConstructors(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK //dumpConstructors(info); MBeanConstructorInfo[] cstrs = info.getConstructors(); assertEquals(cstrs.length, 7); Map mapCstrForDesc = makeFeatureMap(cstrs); assertEquals(mapCstrForDesc.size(), 3); // 5 ambiguous mapped to same // no args constructor MBeanConstructorInfo cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The no-args constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 0); // Amiguous constuctors cstr = (MBeanConstructorInfo)mapCstrForDesc.get("ambiguous constructor"); assertNotNull(cstr); // int,Object constructor cstr = (MBeanConstructorInfo)mapCstrForDesc.get("The two parameter constructor"); assertNotNull(cstr); assertEquals(cstr.getSignature().length, 2); checkParam(cstr.getSignature()[0], "a number", "a"); checkParam(cstr.getSignature()[1], "another number", "b"); } /** * Various tests of operations that need to be destinguished by their signatures. */ public void testOverloadedOperations() throws Exception { I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassOverload(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK MBeanOperationInfo[] ops = info.getOperations(); //dumpOperations(info); assertEquals(ops.length, 8); Map mapOpsForDesc = makeFeatureMap(ops); // no args operation MBeanOperationInfo op = (MBeanOperationInfo)mapOpsForDesc.get("a no parameter operation"); assertNotNull(op); assertEquals(op.getSignature().length, 0); // int operation op = (MBeanOperationInfo)mapOpsForDesc.get("an int operation"); assertNotNull(op); assertEquals(op.getSignature().length, 1); checkParam(op.getSignature()[0], "a number", "value"); // Object operation op = (MBeanOperationInfo)mapOpsForDesc.get("an Object operation"); assertNotNull(op); assertEquals(op.getSignature().length, 1); checkParam(op.getSignature()[0], "an object", "obj"); // int[] operation op = (MBeanOperationInfo)mapOpsForDesc.get("an int[] operation"); assertNotNull(op); assertEquals(op.getSignature().length, 1); checkParam(op.getSignature()[0], "an array of int", "intArray"); // Object[] operation op = (MBeanOperationInfo)mapOpsForDesc.get("an Object[] operation"); assertNotNull(op); assertEquals(op.getSignature().length, 1); checkParam(op.getSignature()[0], "an array of Object", "objArray"); // int,Object operation op = (MBeanOperationInfo)mapOpsForDesc.get("a two parameter int,Object operation"); assertNotNull(op); assertEquals(op.getSignature().length, 2); checkParam(op.getSignature()[0], "a number", "a"); checkParam(op.getSignature()[1], "an object", "obj"); // int,int,int operation op = (MBeanOperationInfo)mapOpsForDesc.get("a three parameter int,int,int operation"); assertNotNull(op); assertEquals(op.getSignature().length, 3); checkParam(op.getSignature()[0], "a number", "i"); checkParam(op.getSignature()[1], "another number", "j"); checkParam(op.getSignature()[2], "yet another number", "k"); // int,int,String operation op = (MBeanOperationInfo)mapOpsForDesc.get("a three parameter int,int,String operation"); assertNotNull(op); assertEquals(op.getSignature().length, 3); checkParam(op.getSignature()[0], "a number", "i"); checkParam(op.getSignature()[1], "another number", "j"); checkParam(op.getSignature()[2], "a String", "s"); } /** * Various tests of ambiguous operations. */ public void testAmbiguousOperations() throws Exception { I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassAmbiguousOperation(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK //dumpOperations(info); MBeanOperationInfo[] ops = info.getOperations(); assertEquals(ops.length, 8); Map mapOpsForDesc = makeFeatureMap(ops); assertEquals(mapOpsForDesc.size(), 3); // 5 ambiguous mapped to same // no args operation MBeanOperationInfo op = (MBeanOperationInfo)mapOpsForDesc.get("a no parameter operation"); assertNotNull(op); assertEquals(op.getSignature().length, 0); // Ambiguous operation op = (MBeanOperationInfo)mapOpsForDesc.get("a two parameter int,Object operation"); assertNotNull(op); // int,Object operation op = (MBeanOperationInfo)mapOpsForDesc.get("a two parameter int,Object operation"); assertNotNull(op); assertEquals(op.getSignature().length, 2); checkParam(op.getSignature()[0], "a number", "a"); checkParam(op.getSignature()[1], "an object", "obj"); } /** * Tests missing translations (but bundle found). */ public void testPartialDesciptions() throws Exception { setDefaultLocale(Locale.ITALY); // no I18N files for this I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassNameOnly(); MBeanInfo info = mbean.getMBeanInfo(); info = mbean.getMBeanInfo(); // ensure cache OK assertEquals(info.getDescription(), "The default subclassed name only MBean description"); MBeanAttributeInfo attrInfo = info.getAttributes()[0]; assertEquals(attrInfo.getDescription(), "??(attr.Attrib)"); MBeanOperationInfo opInfo = info.getOperations()[0]; assertEquals(opInfo.getDescription(), "??(op.operation)"); MBeanParameterInfo paramInfo = opInfo.getSignature()[0]; checkParam(paramInfo, "??(op.operation.param.1)", "param1"); paramInfo = opInfo.getSignature()[1]; checkParam(paramInfo, "??(op.operation.param.2)", "param2"); MBeanConstructorInfo[] cstrs = info.getConstructors(); assertEquals(cstrs.length, 2); dumpConstructors(info); Map mapCstrForDesc = makeFeatureMap(cstrs); assertEquals(mapCstrForDesc.size(), 1); // ambiguous MBeanConstructorInfo cstr = (MBeanConstructorInfo)mapCstrForDesc.get("ambiguous constructor"); assertNotNull(cstr); } /** * Tests missing resource bundles. */ public void testMissingBundle() throws Exception { try { I18NStandardMBean mbean = new I18NStandardMBeanSupport.SubclassNoBundle(); assertTrue(false); } catch (MissingResourceException e) { } try { I18NStandardMBeanSupport.ImplementationNoBundle impl = new I18NStandardMBeanSupport.ImplementationNoBundle(); I18NStandardMBean mbean = new I18NStandardMBean(impl, I18NStandardMBeanSupport.FullManagement.class); MBeanInfo info = mbean.getMBeanInfo(); assertTrue(false); } catch (MissingResourceException e) { } } // create a feature description=>info mapping since order unknown private Map makeFeatureMap(MBeanFeatureInfo[] features) { Map mapFeatureForDesc = new HashMap(); // use map since co for (int i = 0; i < features.length; i++) { mapFeatureForDesc.put(features[i].getDescription(), features[i]); } return mapFeatureForDesc; } private void dumpConstructors(MBeanInfo info) { MBeanConstructorInfo[] consts = info.getConstructors(); System.out.println("NB cons = " + consts.length); for (int i = 0; i < consts.length; i++) { System.out.println("Cons " + i + ":" + consts[i].getDescription()); MBeanParameterInfo[] params = consts[i].getSignature(); for (int j = 0; j < params.length; j++) { MBeanParameterInfo p = params[j]; System.out.println(" Param " + j + ":" + p.getDescription() + " name=" + p.getName() + " type=" + p.getType()); } } } private void dumpOperations(MBeanInfo info) { MBeanOperationInfo[] ops = info.getOperations(); System.out.println("NB operations = " + ops.length); for (int i = 0; i < ops.length; i++) { System.out.println("Op " + i + ":" + ops[i].getDescription()); MBeanParameterInfo[] params = ops[i].getSignature(); for (int j = 0; j < params.length; j++) { MBeanParameterInfo p = params[j]; System.out.println(" Param " + j + ":" + p.getDescription() + " name=" + p.getName() + " type=" + p.getType()); } } } private void setLocaleProp(String s) { System.setProperty("mx4j.descriptionLocale", s); } private void setDefaultLocale(Locale locale) { Locale.setDefault(locale); } private void checkParam(MBeanParameterInfo paramInfo, String description, String name) { assertEquals(paramInfo.getDescription(), description); assertEquals(paramInfo.getName(), name); } } mx4j-3.0.2/src/test/test/mx4j/tools/jython/JythonRunnerTest.java100644 0 0 15236 10513545721 22011 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.jython; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectInstance; import javax.management.ObjectName; import junit.framework.TestCase; import mx4j.tools.jython.JythonRunner; /** * @version $Revision: 1.3 $ */ public class JythonRunnerTest extends TestCase { private MBeanServer svr; private JythonRunner jythonRunner; private ObjectName jythonName; private Int _int; private ObjectName intName; public interface IntMBean { int getValue(); void setValue(int value); ObjectInstance getMBeans(); void setMBeans(ObjectInstance value); ObjectInstance getInstances(); void setInstances(ObjectInstance value); void invocation(); void invocationWithString(String param); Long invocationWithLong(Long param); Number subtract(Number one, Number two); int subtractInts(int one, int two); } public class Int extends NotificationBroadcasterSupport implements IntMBean { private int value; private String param; private boolean invoked; private Number subtracted; private int subtractedInts; private Notification notification; private ObjectInstance mbean; private ObjectInstance instance; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public ObjectInstance getMBeans() { return mbean; } public void setMBeans(ObjectInstance mbeans) { this.mbean = mbeans; } public ObjectInstance getInstances() { return instance; } public void setInstances(ObjectInstance instance) { this.instance = instance; } public void invocation() { this.invoked = true; } public void invocationWithString(String param) { this.param = param; } public Long invocationWithLong(Long param) { return param; } public Number subtract(Number one, Number two) { if ((one.floatValue() - one.intValue()) == 0) { subtracted = new Integer(one.intValue() - two.intValue()); } else { subtracted = new Float(one.floatValue() - two.floatValue()); } return subtracted; } public int subtractInts(int one, int two) { subtractedInts = one - two; return subtractedInts; } } public JythonRunnerTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); svr = MBeanServerFactory.createMBeanServer(); jythonRunner = new JythonRunner(); jythonName = ObjectName.getInstance("tools", "type", "JythonRunner"); svr.registerMBean(jythonRunner, jythonName); _int = new Int(); intName = ObjectName.getInstance("test", "type", "Int"); svr.registerMBean(_int, intName); } public void testInvokeFromJython() { jythonRunner.setScript("import jarray\n" + "from java.lang import String,Long,Integer,Float\n" + "from javax.management import Attribute\n" + "o = ObjectName.getInstance(\"test\",\"type\",\"Int\")\n" + "server.setAttribute(o,Attribute(\"Value\",1))\n" + "server.invoke(o,\"invocation\",None,None)\n" + "params = ['parameter']\n" + "paramTypes = ['java.lang.String']\n" + "c = String().getClass()\n" + "aryParm = jarray.array(params,c)\n" + "aryType = jarray.array(paramTypes,c)\n" + "server.invoke(o,\"invocationWithString\",aryParm,aryType)\n"); jythonRunner.runScript(); assertTrue(_int.invoked); assertEquals(1, _int.value); assertEquals(_int.param, "parameter"); } public void testHelperJythonObjects() throws Exception { jythonRunner.setScript("from java.lang import String,Long,Integer,Float\n" + "from javax.management import Attribute\n" + "o = ObjectName.getInstance(\"test\",\"type\",\"Int\")\n" + "p = proxy(server,o)\n" + "p.invocationWithLong(Long(10000))\n" + "p.subtract(Float(2.1),Float(1.9))\n" + "p.subtract(Integer(3),Integer(1))\n" + "p.subtractInts(10,5)"); jythonRunner.runScript(); assertEquals(new Integer(2), _int.subtracted); assertEquals(5, _int.subtractedInts); } public void testListenerJythonScript() throws Exception { jythonRunner.setScript("o = ObjectName.getInstance(\"test\",\"type\",\"Int\")\n" + "p = Proxy(server,o)\n" + "p.Value=111"); jythonRunner.setObservedObject(intName); jythonRunner.setNotificationType("Type"); _int.sendNotification(new Notification("Type", "Source", 1L)); // Make sure notification is sent Thread.sleep(1000L); assertEquals(111, _int.getValue()); } public void testHelperFunctions() throws Exception { jythonRunner.setScript("import jarray\n" + "s = 'test.mx4j.tools.jython.JythonRunnerTest$Int'\n" + "o = ObjectName.getInstance(\"test\",\"type\",\"Int\")\n" + "p = Proxy(server,o)\n" + "p.MBeans=mbeans('test:type=Int')[0]\n" + "p.Instances=instances(s,'*:*')[0]"); jythonRunner.runScript(); ObjectInstance oinst = _int.instance; assertEquals(intName, oinst.getObjectName()); assertEquals("test.mx4j.tools.jython.JythonRunnerTest$Int", oinst.getClassName()); oinst = _int.mbean; assertEquals(intName, oinst.getObjectName()); assertEquals("test.mx4j.tools.jython.JythonRunnerTest$Int", oinst.getClassName()); } public void tearDown() throws Exception { svr.unregisterMBean(jythonName); super.tearDown(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/HTTPConnectorServerTestCase.java100644 0 0 13640 10513545721 23736 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote; import java.io.IOException; import java.util.Set; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorServerTestCase; /** * @version $Revision: 1.4 $ */ public abstract class HTTPConnectorServerTestCase extends JMXConnectorServerTestCase { public HTTPConnectorServerTestCase(String name) { super(name); } public void testTwoConnectorServersOneHTTPServerStart1Start2Invoke1Invoke2Stop1Stop2() throws Exception { JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url1 = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "one"); JMXServiceURL url2 = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "two"); JMXConnectorServer cntorServer1 = null; JMXConnectorServer cntorServer2 = null; try { cntorServer1 = JMXConnectorServerFactory.newJMXConnectorServer(url1, getEnvironment(), newMBeanServer()); cntorServer2 = JMXConnectorServerFactory.newJMXConnectorServer(url2, getEnvironment(), newMBeanServer()); cntorServer1.start(); sleep(5000); cntorServer2.start(); sleep(5000); // Make sure they work JMXConnector cntor1 = null; JMXConnector cntor2 = null; try { cntor1 = JMXConnectorFactory.connect(cntorServer1.getAddress(), getEnvironment()); cntor2 = JMXConnectorFactory.connect(cntorServer2.getAddress(), getEnvironment()); Set names = cntor1.getMBeanServerConnection().queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); names = cntor2.getMBeanServerConnection().queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); } finally { if (cntor2 != null) cntor2.close(); if (cntor1 != null) cntor1.close(); } } finally { if (cntorServer2 != null) cntorServer2.stop(); if (cntorServer1 != null) cntorServer1.stop(); } } public void testTwoConnectorServersOneHTTPServerStart1Start2Stop1Invoke1Invoke2Stop2() throws Exception { JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url1 = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "one"); JMXServiceURL url2 = new JMXServiceURL(temp.getProtocol(), temp.getHost(), temp.getPort(), "two"); JMXConnectorServer cntorServer1 = null; JMXConnectorServer cntorServer2 = null; try { cntorServer1 = JMXConnectorServerFactory.newJMXConnectorServer(url1, getEnvironment(), newMBeanServer()); cntorServer2 = JMXConnectorServerFactory.newJMXConnectorServer(url2, getEnvironment(), newMBeanServer()); cntorServer1.start(); sleep(5000); cntorServer2.start(); sleep(5000); // Make sure they work JMXConnector cntor1 = null; JMXConnector cntor2 = null; try { cntor1 = JMXConnectorFactory.connect(cntorServer1.getAddress(), getEnvironment()); cntor2 = JMXConnectorFactory.connect(cntorServer2.getAddress(), getEnvironment()); MBeanServerConnection conn1 = cntor1.getMBeanServerConnection(); Set names = conn1.queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); MBeanServerConnection conn2 = cntor2.getMBeanServerConnection(); names = conn2.queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); cntorServer1.stop(); try { conn1.queryNames(null, null); fail(); } catch (IOException ignored) { } names = conn2.queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); } catch (Exception x) { x.printStackTrace(); throw x; } finally { if (cntor2 != null) cntor2.close(); } } finally { if (cntorServer2 != null) cntorServer2.stop(); } } public void testConnectorServerOnDefaultHTTPPort() throws Exception { JMXServiceURL temp = createJMXConnectorServerAddress(); JMXServiceURL url = new JMXServiceURL(temp.getProtocol(), temp.getHost(), 80, temp.getURLPath()); JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, getEnvironment(), newMBeanServer()); try { cntorServer.start(); sleep(5000); JMXConnector cntor = JMXConnectorFactory.connect(cntorServer.getAddress(), getEnvironment()); try { MBeanServerConnection server = cntor.getMBeanServerConnection(); Set names = server.queryNames(null, null); assertNotNull(names); assertTrue(names.size() > 0); assertEquals(names.size(), server.getMBeanCount().intValue()); } finally { cntor.close(); } } finally { cntorServer.stop(); } } public void testStartWithProviderClassLoader() throws Exception { // Do nothing since messing with the context classloader confuses the web container } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/PasswordAuthenticatorTest.java100644 0 0 13656 10513545721 23665 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.security.Principal; import java.util.Set; import javax.security.auth.Subject; import mx4j.tools.remote.PasswordAuthenticator; import test.MX4JTestCase; /** * @version $Revision: 1.3 $ */ public class PasswordAuthenticatorTest extends MX4JTestCase { public PasswordAuthenticatorTest(String s) { super(s); } public void testAuthenticationWithNullCredentials() throws Exception { PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[0])); Object credentials = null; try { authenticator.authenticate(credentials); fail(); } catch (SecurityException x) { } } public void testAuthenticationWithBadCredentials() throws Exception { PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[0])); Object credentials = new Object(); try { authenticator.authenticate(credentials); fail(); } catch (SecurityException x) { } } public void testAuthenticationWithCredentialsNull() throws Exception { PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[0])); Object credentials = new String[2]; try { authenticator.authenticate(credentials); fail(); } catch (SecurityException x) { } } public void testAuthenticationWithUnknwonCredentials() throws Exception { PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{"user1", "password1"})); Object credentials = new String[]{"dummy", null}; try { authenticator.authenticate(credentials); fail(); } catch (SecurityException x) { } } public void testAuthenticationWithWrongCredentials() throws Exception { String user = "user1"; PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{user, "password1"})); Object credentials = new String[]{user, null}; try { authenticator.authenticate(credentials); fail(); } catch (SecurityException x) { } } public void testAuthenticationPlainSentClear() throws Exception { String user = "user1"; String password = "password1"; PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{user, password})); Object credentials = new String[]{user, password}; // Send the password in clear Subject subject = authenticator.authenticate(credentials); assertNotNull(subject); Set principals = subject.getPrincipals(); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertEquals(principal.getName(), user); } public void testAuthenticationPlainSentObfuscated() throws Exception { String user = "user1"; String password = "password1"; PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{user, password})); Object credentials = new String[]{user, PasswordAuthenticator.obfuscatePassword(password)}; // Send the password obfuscated Subject subject = authenticator.authenticate(credentials); assertNotNull(subject); Set principals = subject.getPrincipals(); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertEquals(principal.getName(), user); } public void testAuthenticationObfuscatedSentClear() throws Exception { String user = "user1"; String password = "password1"; PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{user, PasswordAuthenticator.obfuscatePassword(password)})); Object credentials = new String[]{user, password}; // Send the password in clear Subject subject = authenticator.authenticate(credentials); assertNotNull(subject); Set principals = subject.getPrincipals(); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertEquals(principal.getName(), user); } public void testAuthenticationObfuscatedSentObfuscated() throws Exception { String user = "user1"; String password = "password1"; PasswordAuthenticator authenticator = new PasswordAuthenticator(preparePasswords(new String[]{user, PasswordAuthenticator.obfuscatePassword(password)})); Object credentials = new String[]{user, PasswordAuthenticator.obfuscatePassword(password)}; // Send the password in clear Subject subject = authenticator.authenticate(credentials); assertNotNull(subject); Set principals = subject.getPrincipals(); assertEquals(principals.size(), 1); Principal principal = (Principal)principals.iterator().next(); assertEquals(principal.getName(), user); } private InputStream preparePasswords(String[] pairs) throws Exception { StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); for (int i = 0; i < pairs.length; i += 2) { String user = pairs[i]; String password = pairs[i + 1]; bw.write(user); bw.write(':'); bw.write(password); bw.newLine(); } bw.close(); return new BufferedInputStream(new ByteArrayInputStream(sw.toString().getBytes())); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/BurlapConnectorInvocationTest.java100644 0 0 1634 10513545721 25720 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.burlap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.3 $ */ public class BurlapConnectorInvocationTest extends JMXConnectorInvocationTestCase { public BurlapConnectorInvocationTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("burlap", null, 8080, "/burlap"); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/BurlapConnectorServerTest.java100644 0 0 1571 10513545721 25055 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.burlap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.mx4j.tools.remote.HTTPConnectorServerTestCase; /** * @version $ */ public class BurlapConnectorServerTest extends HTTPConnectorServerTestCase { public BurlapConnectorServerTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("burlap", null, 8080, "/burlap"); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/BurlapConnectorTest.java100644 0 0 2216 10513545721 23663 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.burlap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorTestCase; /** * @version $Revision: 1.4 $ */ public class BurlapConnectorTest extends JMXConnectorTestCase { public BurlapConnectorTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("burlap", null, 8080, "/burlap"); } public Map getEnvironment() { return new HashMap(); } public void testDefaultClassLoader() throws Exception { // No classloading magic is performed by the burlap protocol } public void testConnectWithProviderClassLoader() throws Exception { // No classloading magic is performed by the burlap protocol } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/BurlapNotificationsTest.java100644 0 0 2101 10513545721 24533 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.burlap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXNotificationsTestCase; /** * @version $ */ public class BurlapNotificationsTest extends JMXNotificationsTestCase { public BurlapNotificationsTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("burlap", null, 8080, "/burlap"); } public Map getEnvironment() { return new HashMap(); } public void testNonSerializableNotifications() throws Exception { // Burlap protocol does not see if the Object does not implement Serializable, // it tries anyway to serialize it } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/HessianConnectorInvocationTest.java100644 0 0 1641 10513545721 26230 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.hessian; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.3 $ */ public class HessianConnectorInvocationTest extends JMXConnectorInvocationTestCase { public HessianConnectorInvocationTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("hessian", null, 8080, "/hessian"); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/HessianConnectorServerTest.java100644 0 0 1607 10513545721 25367 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.hessian; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.mx4j.tools.remote.HTTPConnectorServerTestCase; /** * @version $Revision: 1.3 $ */ public class HessianConnectorServerTest extends HTTPConnectorServerTestCase { public HessianConnectorServerTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("hessian", null, 8080, "/hessian"); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/HessianConnectorTest.java100644 0 0 2204 10513545721 24172 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.hessian; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorTestCase; /** * @version $ */ public class HessianConnectorTest extends JMXConnectorTestCase { public HessianConnectorTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("hessian", null, 8080, "/hessian"); } public Map getEnvironment() { return new HashMap(); } public void testDefaultClassLoader() throws Exception { // No classloading magic is performed by the burlap protocol } public void testConnectWithProviderClassLoader() throws Exception { // No classloading magic is performed by the burlap protocol } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/HessianNotificationsTest.java100644 0 0 2125 10513545721 25053 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.hessian; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXNotificationsTestCase; /** * @version $Revision: 1.4 $ */ public class HessianNotificationsTest extends JMXNotificationsTestCase { public HessianNotificationsTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("hessian", null, 8080, "/hessian"); } public Map getEnvironment() { return new HashMap(); } public void testNonSerializableNotifications() throws Exception { // Burlap protocol does not see if the Object does not implement Serializable, // it tries anyway to serialize it } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/local/LocalConnectorInvocationTest.java100644 0 0 1613 10513545721 25327 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.local; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.3 $ */ public class LocalConnectorInvocationTest extends JMXConnectorInvocationTestCase { public LocalConnectorInvocationTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("local", "localhost", 0); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/local/LocalConnectorServerTest.java100644 0 0 1573 10513545721 24471 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.local; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorServerTestCase; /** * @version $Revision: 1.4 $ */ public class LocalConnectorServerTest extends JMXConnectorServerTestCase { public LocalConnectorServerTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("local", "localhost", 0); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/local/LocalConnectorTest.java100644 0 0 1762 10513545721 23302 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.local; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorTestCase; /** * @version $Revision: 1.5 $ */ public class LocalConnectorTest extends JMXConnectorTestCase { public LocalConnectorTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("local", "localhost", 0); } public Map getEnvironment() { return new HashMap(); } public void testDefaultClassLoader() throws Exception { // Nothing to test, the local connector does not handle classloading } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/proxy/RemoteMBeanProxyTest.java100644 0 0 20175 10513545721 23703 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.proxy; import java.io.IOException; import java.net.URL; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerDelegateMBean; import javax.management.MBeanServerInvocationHandler; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.loading.MLet; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.timer.Timer; import mx4j.tools.remote.proxy.RemoteMBeanProxy; import mx4j.util.Utils; import test.MX4JTestCase; import test.MutableObject; /** * @version $Revision: 1.6 $ */ public class RemoteMBeanProxyTest extends MX4JTestCase { public RemoteMBeanProxyTest(String s) { super(s); } public void testNotifications() throws Exception { // The remote MBeanServer MBeanServer remoteServer = newMBeanServer(); JMXServiceURL address1 = new JMXServiceURL("rmi", "localhost", 0); JMXConnectorServer connectorServer1 = JMXConnectorServerFactory.newJMXConnectorServer(address1, null, null); ObjectName connectorServerName1 = ObjectName.getInstance(":type=connector,protocol=" + address1.getProtocol()); remoteServer.registerMBean(connectorServer1, connectorServerName1); connectorServer1.start(); address1 = connectorServer1.getAddress(); ObjectName remoteDelegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); // The local MBeanServer MBeanServer localServer = newMBeanServer(); // The MBean proxy for the remote delegate JMXConnector cntor = JMXConnectorFactory.newJMXConnector(address1, null); RemoteMBeanProxy proxy = new RemoteMBeanProxy(remoteDelegateName, cntor, null, null); ObjectName proxyName = ObjectName.getInstance(":proxy=" + ObjectName.quote(remoteDelegateName.getCanonicalName())); localServer.registerMBean(proxy, proxyName); // Register a listener to the MBean proxy for the remote delegate final MutableObject holder = new MutableObject(null); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { synchronized (holder) { holder.set(notification); } } }; localServer.addNotificationListener(proxyName, listener, null, null); // Sleep to make sure the remote notifications threads started before we emit the notification sleep(1000); // Add an MBean to the remote MBeanServer: this will trigger a notification from the remote delegate, // that should be dispatched transparently the the listener above MLet remoteMLet = new MLet(); ObjectName remoteMLetName = ObjectName.getInstance(":type=mlet"); remoteServer.registerMBean(remoteMLet, remoteMLetName); synchronized (holder) { while (holder.get() == null) holder.wait(10); assertNotNull(holder.get()); holder.set(null); } // Remove the listener localServer.removeNotificationListener(proxyName, listener); // Unregister the MLet: this will trigger a notification remoteServer.unregisterMBean(remoteMLetName); assertNull(holder.get()); } public void testMultipleRemoteMBeanServers() throws Exception { // The 1st remote server MBeanServer remoteServer1 = newMBeanServer(); MLet mlet = new MLet(new URL[]{new URL("http", "host", 80, "/path")}); ObjectName remoteMLetName = ObjectName.getInstance(":type=mlet"); remoteServer1.registerMBean(mlet, remoteMLetName); JMXServiceURL address1 = new JMXServiceURL("rmi", "localhost", 0); JMXConnectorServer connectorServer1 = JMXConnectorServerFactory.newJMXConnectorServer(address1, null, null); ObjectName connectorServerName1 = ObjectName.getInstance(":type=connector,protocol=" + address1.getProtocol()); remoteServer1.registerMBean(connectorServer1, connectorServerName1); connectorServer1.start(); address1 = connectorServer1.getAddress(); // The 2nd remote server MBeanServer remoteServer2 = newMBeanServer(); Timer timer = new Timer(); ObjectName remoteTimerName = ObjectName.getInstance(":type=timer"); remoteServer2.registerMBean(timer, remoteTimerName); timer.start(); JMXServiceURL address2 = new JMXServiceURL("rmi", "localhost", 0); JMXConnectorServer connectorServer2 = JMXConnectorServerFactory.newJMXConnectorServer(address2, null, remoteServer2); connectorServer2.start(); address2 = connectorServer2.getAddress(); // The local server MBeanServer localServer = newMBeanServer(); RemoteMBeanProxy proxy1 = new RemoteMBeanProxy(remoteMLetName, address1, null, null); JMXConnector cntor = JMXConnectorFactory.connect(address2); RemoteMBeanProxy proxy2 = new RemoteMBeanProxy(remoteTimerName, cntor.getMBeanServerConnection()); ObjectName proxyName1 = ObjectName.getInstance(":proxy=" + ObjectName.quote(remoteMLetName.getCanonicalName())); ObjectName proxyName2 = ObjectName.getInstance(":proxy=" + ObjectName.quote(remoteTimerName.getCanonicalName())); localServer.registerMBean(proxy1, proxyName1); localServer.registerMBean(proxy2, proxyName2); JMXServiceURL address3 = new JMXServiceURL("local", "localhost", 0); JMXConnectorServer connectorServer3 = JMXConnectorServerFactory.newJMXConnectorServer(address3, null, localServer); connectorServer3.start(); address3 = connectorServer3.getAddress(); // The client JMXConnector connector = JMXConnectorFactory.connect(address3); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); // Tests URL[] urls = (URL[])mbsc.getAttribute(proxyName1, "URLs"); if (!Utils.arrayEquals(urls, mlet.getURLs())) fail(); if (!timer.isActive()) fail(); mbsc.invoke(proxyName2, "stop", null, null); if (timer.isActive()) fail(); } public void testJMXConnectorCloseOnDeregistration() throws Exception { // The remote MBeanServer MBeanServer remoteServer = newMBeanServer(); JMXServiceURL address = new JMXServiceURL("rmi", "localhost", 0); JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, null); ObjectName connectorServerName = ObjectName.getInstance(":type=connector,protocol=" + address.getProtocol()); remoteServer.registerMBean(connectorServer, connectorServerName); connectorServer.start(); address = connectorServer.getAddress(); ObjectName remoteDelegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); // The local MBeanServer MBeanServer localServer = newMBeanServer(); // The MBean proxy for the remote delegate JMXConnector cntor = JMXConnectorFactory.newJMXConnector(address, null); RemoteMBeanProxy proxy = new RemoteMBeanProxy(remoteDelegateName, cntor, null, null); ObjectName proxyName = ObjectName.getInstance(":proxy=" + ObjectName.quote(remoteDelegateName.getCanonicalName())); localServer.registerMBean(proxy, proxyName); // Be sure it works MBeanServerDelegateMBean mbean = (MBeanServerDelegateMBean)MBeanServerInvocationHandler.newProxyInstance(localServer, proxyName, MBeanServerDelegateMBean.class, true); String vendor = mbean.getImplementationVendor(); assertNotNull(vendor); // Unregister and be sure the connector is closed localServer.unregisterMBean(proxyName); try { cntor.getMBeanServerConnection(); fail(); } catch (IOException x) { } } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/SOAPConnectorInvocationTest.java100644 0 0 1622 10513545721 24707 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.soap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXConnectorInvocationTestCase; /** * @version $Revision: 1.4 $ */ public class SOAPConnectorInvocationTest extends JMXConnectorInvocationTestCase { public SOAPConnectorInvocationTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("soap", null, 8080, "/soap"); } public Map getEnvironment() { return new HashMap(); } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/SOAPConnectorServerTest.java100644 0 0 5102 10513545721 24041 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.soap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; import mx4j.tools.remote.http.jetty.JettyWebContainer; import org.apache.axis.transport.http.AxisServlet; import test.mx4j.tools.remote.HTTPConnectorServerTestCase; /** * @version $Revision: 1.9 $ */ public class SOAPConnectorServerTest extends HTTPConnectorServerTestCase { public SOAPConnectorServerTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("soap", null, 8080, "/soap"); } public Map getEnvironment() { return new HashMap(); } public void testExternalWebContainer() throws Exception { // Start Jetty, externally JettyWebContainer jetty = new JettyWebContainer(); try { JMXServiceURL url = new JMXServiceURL("soap", null, 8080, "/external"); jetty.start(url, null); jetty.deploy(AxisServlet.class.getName(), url, null); // A SOAPConnector JMXConnectorServer cntorServer = null; JMXConnector cntor = null; try { Map environment = new HashMap(); environment.put(HTTPConnectorServer.USE_EXTERNAL_WEB_CONTAINER, Boolean.TRUE); cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, newMBeanServer()); cntorServer.start(); // Check that it works cntor = JMXConnectorFactory.connect(cntorServer.getAddress()); MBeanServerConnection cntion = cntor.getMBeanServerConnection(); Set names = cntion.queryNames(null, null); assertNotNull(names); assertFalse(names.isEmpty()); } finally { if (cntor != null) cntor.close(); if (cntorServer != null) cntorServer.stop(); } } finally { jetty.stop(); } } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/SOAPConnectorTest.java100644 0 0 3660 10513545721 22661 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.soap; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import org.apache.axis.AxisFault; import test.javax.management.remote.JMXConnectorTestCase; /** * @version $Revision: 1.15 $ */ public class SOAPConnectorTest extends JMXConnectorTestCase { public SOAPConnectorTest(String name) { super(name); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("soap", null, 8080, "/soap"); } public Map getEnvironment() { return new HashMap(); } /** * The SOAPConnector does not handle gracefully the case of a SecurityException thrown by a * JMXAuthenticator. This is more an Axis problem, but for now we fix the test. */ protected void testJMXAuthenticatorConnect(JMXServiceURL url, Map environment) throws SecurityException, IOException { try { super.testJMXAuthenticatorConnect(url, environment); } catch (AxisFault x) { String name = x.getFaultString(); if (name.startsWith(SecurityException.class.getName())) throw new SecurityException(); throw x; } } /** * No default classloader for the SOAPConnector (at least not now). * It may be added later, but for now we fix the test. */ public void testDefaultClassLoader() throws Exception { // Do nothing } public void testConnectWithProviderClassLoader() throws Exception { // Do nothing since messing with the context classloader causes the connector server to fail its start } } mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/SOAPNotificationsTest.java100644 0 0 2106 10513545721 23532 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.remote.soap; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.remote.JMXServiceURL; import test.javax.management.remote.JMXNotificationsTestCase; /** * @version $Revision: 1.5 $ */ public class SOAPNotificationsTest extends JMXNotificationsTestCase { public SOAPNotificationsTest(String s) { super(s); } public JMXServiceURL createJMXConnectorServerAddress() throws MalformedURLException { return new JMXServiceURL("soap", null, 8080, "/soap"); } public Map getEnvironment() { return new HashMap(); } public void testNonSerializableNotifications() throws Exception { // SOAP serialization is always performed, // it does not care the fact that the object does not implement Serializable } } mx4j-3.0.2/src/test/test/mx4j/tools/stats/StatsMBeansTest.java100644 0 0 27000 10513545721 21343 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.tools.stats; import java.util.Date; import java.util.SortedMap; import javax.management.Attribute; import javax.management.AttributeChangeNotification; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import junit.framework.TestCase; import mx4j.tools.stats.PointTime; /** * Test the Statistics MBeans * * @version $Revision: 1.4 $ */ public class StatsMBeansTest extends TestCase { private MBeanServer server; /** * Constructor requested by the JUnit framework */ public StatsMBeansTest() { super("StatsMBeansTest Test"); } /** * Constructor requested by the JUnit framework */ public StatsMBeansTest(String name) { super(name); } public void setUp() { try { server = MBeanServerFactory.createMBeanServer("Stats"); } catch (Exception e) { e.printStackTrace(); } } public void tearDown() { try { MBeanServerFactory.releaseMBeanServer(server); } catch (Exception e) { e.printStackTrace(); } } public void testValueMBean() throws Exception { ObjectName name = new ObjectName("Domain:name=value"); try { server.createMBean("mx4j.tools.stats.ValueStatisticsRecorder", name, null); // Test that nothing happens if not started //Every time the value is set the statistics are updated server.setAttribute(name, new Attribute("Value", new Double(10))); server.setAttribute(name, new Attribute("Value", new Double(5))); server.setAttribute(name, new Attribute("Value", new Double(20))); assertEquals(new Long(0), server.getAttribute(name, "Max")); assertEquals(new Long(0), server.getAttribute(name, "Min")); assertEquals(new Long(0), server.getAttribute(name, "Average")); assertNull(server.getAttribute(name, "RecordingStart")); assertEquals(0, ((SortedMap)server.getAttribute(name, "Entries")).size()); // start it server.invoke(name, "start", null, null); //Every time the value is set the statistics are updated server.setAttribute(name, new Attribute("Value", new Double(10))); server.setAttribute(name, new Attribute("Value", new Double(5))); server.setAttribute(name, new Attribute("Value", new Double(20))); assertEquals(new Double(20), server.getAttribute(name, "Max")); assertEquals(new Double(5), server.getAttribute(name, "Min")); assertEquals(11.6, ((Double)server.getAttribute(name, "Average")).doubleValue(), 0.1); assertEquals(3, ((SortedMap)server.getAttribute(name, "Entries")).size()); Date start1 = (Date)server.getAttribute(name, "RecordingStart"); // start it server.invoke(name, "stop", null, null); server.invoke(name, "start", null, null); // Restart with longs server.setAttribute(name, new Attribute("Value", new Long(10))); server.setAttribute(name, new Attribute("Value", new Long(5))); server.setAttribute(name, new Attribute("Value", new Long(20))); assertEquals(new Long(20), server.getAttribute(name, "Max")); assertEquals(new Long(5), server.getAttribute(name, "Min")); assertEquals(11, ((Long)server.getAttribute(name, "Average")).longValue()); assertEquals(((SortedMap)server.getAttribute(name, "Entries")).size(), 3); Date start2 = (Date)server.getAttribute(name, "RecordingStart"); assertTrue(start1.equals(start2) || start1.before(start2)); SortedMap values = (SortedMap)server.getAttribute(name, "Entries"); PointTime point1 = (PointTime)values.firstKey(); PointTime point2 = (PointTime)values.lastKey(); assertTrue(point1.getDate().equals(point2.getDate()) || point1.getDate().before(point2.getDate())); // re start it server.invoke(name, "stop", null, null); server.invoke(name, "start", null, null); int maxSize = ((Integer)server.getAttribute(name, "MaxEntries")).intValue(); // set some random number for (int i = 0; i < maxSize * 2; i++) { server.setAttribute(name, new Attribute("Value", new Double(Math.random()))); } // min has to be higher than 0 assertTrue(((Double)server.getAttribute(name, "Min")).doubleValue() >= 0); // max has to be less than 1 assertTrue(((Double)server.getAttribute(name, "Max")).doubleValue() <= 1); //check than max size of entries has been kept assertEquals(((SortedMap)server.getAttribute(name, "Entries")).size(), maxSize); } finally { server.unregisterMBean(name); } } public void testNotificationMBean() throws Exception { ObjectName name = new ObjectName("Domain:name=notification"); ObjectName beanName = new ObjectName("Domain:name=observed"); try { server.createMBean("mx4j.tools.stats.NotificationStatisticsRecorder", name, null); Test t = new Test(); server.registerMBean(t, beanName); server.setAttribute(name, new Attribute("ObservedObject", beanName)); server.setAttribute(name, new Attribute("ObservedAttribute", "Value")); // Test that nothing happens if not started //Every time the value is set the statistics are updated server.setAttribute(beanName, new Attribute("Value", new Double(10))); server.setAttribute(beanName, new Attribute("Value", new Double(5))); server.setAttribute(beanName, new Attribute("Value", new Double(20))); assertEquals(new Long(0), server.getAttribute(name, "Max")); assertEquals(new Long(0), server.getAttribute(name, "Min")); assertEquals(new Long(0), server.getAttribute(name, "Average")); assertEquals(0, ((SortedMap)server.getAttribute(name, "Entries")).size()); // start it server.invoke(name, "start", null, null); //Every time the value is set the statistics are updated server.setAttribute(beanName, new Attribute("Value", new Double(10))); server.setAttribute(beanName, new Attribute("Value", new Double(5))); server.setAttribute(beanName, new Attribute("Value", new Double(20))); assertEquals(new Double(20), server.getAttribute(name, "Max")); assertEquals(new Double(5), server.getAttribute(name, "Min")); assertEquals(11.6, ((Double)server.getAttribute(name, "Average")).doubleValue(), 0.1); assertEquals(3, ((SortedMap)server.getAttribute(name, "Entries")).size()); // start it server.invoke(name, "stop", null, null); server.invoke(name, "start", null, null); // Restart with longs server.setAttribute(beanName, new Attribute("Value", new Double(10))); server.setAttribute(beanName, new Attribute("Value", new Double(15))); server.setAttribute(beanName, new Attribute("Value", new Double(20))); assertEquals(new Double(20), server.getAttribute(name, "Max")); assertEquals(new Double(10), server.getAttribute(name, "Min")); assertEquals(15, ((Double)server.getAttribute(name, "Average")).longValue()); assertEquals(((SortedMap)server.getAttribute(name, "Entries")).size(), 3); } finally { server.unregisterMBean(name); } } public synchronized void testTimedMBean() throws Exception { ObjectName name = new ObjectName("Domain:name=notification"); ObjectName beanName = new ObjectName("Domain:name=observed"); try { server.createMBean("mx4j.tools.stats.TimedStatisticsRecorder", name, null); Test t = new Test(); server.registerMBean(t, beanName); server.setAttribute(name, new Attribute("ObservedObject", beanName)); server.setAttribute(name, new Attribute("ObservedAttribute", "Value")); server.setAttribute(name, new Attribute("Granularity", new Long(1000))); // Test that nothing happens if not started //Every time the value is set the statistics are updated server.setAttribute(beanName, new Attribute("Value", new Double(10))); server.setAttribute(beanName, new Attribute("Value", new Double(5))); server.setAttribute(beanName, new Attribute("Value", new Double(20))); assertEquals(new Long(0), server.getAttribute(name, "Max")); assertEquals(new Long(0), server.getAttribute(name, "Min")); assertEquals(new Long(0), server.getAttribute(name, "Average")); assertEquals(0, ((SortedMap)server.getAttribute(name, "Entries")).size()); // start it server.invoke(name, "start", null, null); //Every time the value is set the statistics are updated server.setAttribute(beanName, new Attribute("Value", new Double(10))); Thread.currentThread().sleep(1500); server.setAttribute(beanName, new Attribute("Value", new Double(5))); Thread.currentThread().sleep(1500); server.setAttribute(beanName, new Attribute("Value", new Double(20))); Thread.currentThread().sleep(1500); assertEquals(new Double(20), server.getAttribute(name, "Max")); assertEquals(new Double(5), server.getAttribute(name, "Min")); // difficult to predict an exact value assertTrue(((Double)server.getAttribute(name, "Average")).longValue() > 5 && ((Double)server.getAttribute(name, "Average")).longValue() < 20); assertTrue(((SortedMap)server.getAttribute(name, "Entries")).size() >= 3); // start it server.invoke(name, "stop", null, null); server.invoke(name, "start", null, null); // Restart with longs server.setAttribute(beanName, new Attribute("Value", new Double(10))); Thread.currentThread().sleep(1500); server.setAttribute(beanName, new Attribute("Value", new Double(15))); Thread.currentThread().sleep(1500); server.setAttribute(beanName, new Attribute("Value", new Double(20))); Thread.currentThread().sleep(1500); assertEquals(new Double(20), server.getAttribute(name, "Max")); assertEquals(new Double(10), server.getAttribute(name, "Min")); // difficult to predict an exact value assertTrue(((Double)server.getAttribute(name, "Average")).longValue() >= 15 && ((Double)server.getAttribute(name, "Average")).longValue() <= 20); assertTrue(((SortedMap)server.getAttribute(name, "Entries")).size() >= 3); } finally { server.unregisterMBean(name); } } public interface TestMBean { public double getValue(); public void setValue(double value); } public class Test extends NotificationBroadcasterSupport implements TestMBean { private double value; public double getValue() { return value; } public void setValue(double value) { double oldValue = this.value; this.value = value; sendNotification(new AttributeChangeNotification(this, 0L, System.currentTimeMillis(), "test", "Value", Double.class.toString(), new Double(oldValue), new Double(value))); } } } mx4j-3.0.2/src/test/test/mx4j/util/WildcardMatchTest.java100644 0 0 1640 10513545721 20326 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package test.mx4j.util; import junit.framework.TestCase; import mx4j.util.Utils; /** * @version $Revision: 1.1 $ */ public class WildcardMatchTest extends TestCase { public void testSingleWildcard() { assertTrue(Utils.wildcardMatch("*", "")); assertTrue(Utils.wildcardMatch("*", "A")); assertTrue(Utils.wildcardMatch("*", "ABC")); } public void testTwoWildcards() { assertFalse(Utils.wildcardMatch("*D*", "")); assertTrue(Utils.wildcardMatch("*D*", "aaaaDbbb")); assertTrue(Utils.wildcardMatch("*D*", "aaaaD")); assertTrue(Utils.wildcardMatch("*D*", "Dbbb")); assertFalse(Utils.wildcardMatch("*D*", "aaabbb")); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/AdaptorServerSocketFactory.java100644 0 0 1456 10513545721 23266 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor; import java.io.IOException; import java.net.ServerSocket; /** * The ServerSocket factory interface.

* It allows to create ServerSocket for JMX adaptors * * @version $Revision: 1.3 $ */ public interface AdaptorServerSocketFactory { /** * Creates a new ServerSocket on the specified port, with the specified backlog and on the given host.
* The last parameter is useful for hosts with more than one IP address. */ public ServerSocket createServerSocket(int port, int backlog, String host) throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/PlainAdaptorServerSocketFactory.java100644 0 0 1275 10513545721 24251 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; /** * Creates plain ServerSockets. * * @version $Revision: 1.3 $ */ public class PlainAdaptorServerSocketFactory implements AdaptorServerSocketFactory { public ServerSocket createServerSocket(int port, int backlog, String host) throws IOException { return new ServerSocket(port, backlog, InetAddress.getByName(host)); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/CommandProcessorUtil.java100644 0 0 26370 10513545721 23121 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.lang.reflect.Constructor; import java.text.DateFormat; import java.text.ParseException; import java.util.Comparator; import java.util.Date; import javax.management.ObjectInstance; import javax.management.openmbean.OpenType; /** * Contains utilities common to CommandProcessor objects * * @version $Revision: 1.3 $ */ public class CommandProcessorUtil { // contains all date and date time format instances // for the current locale private static final DateFormat[] allFormats = new DateFormat[]{ DateFormat.getDateInstance(), DateFormat.getTimeInstance(), DateFormat.getDateTimeInstance(), // first pure date format DateFormat.getDateInstance(DateFormat.SHORT), DateFormat.getDateInstance(DateFormat.MEDIUM), DateFormat.getDateInstance(DateFormat.LONG), DateFormat.getDateInstance(DateFormat.FULL), // pure time format DateFormat.getTimeInstance(DateFormat.SHORT), DateFormat.getTimeInstance(DateFormat.MEDIUM), DateFormat.getTimeInstance(DateFormat.LONG), DateFormat.getTimeInstance(DateFormat.FULL), // combinations DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL), DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT), DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM), DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG), DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL), DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT), DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM), DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG), DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL), DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT), DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM), DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG), DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL) }; private static final String[] BASIC_TYPES = new String[]{ "int", "long", "short", "byte", "float", "double", "boolean" }; /** * Creates a parameter object of the given type containing a given value. * If the type is unknown null is returned * * @param parameterType Indicates the type of the parameter, for instance java.lang.String * @param parameterValue The value of the parameter as a String * @return an object of parameterType type and value parameterValue or null if the type is unknown * @throws Thrown in case there is a data conversion error */ protected static Object createParameterValue(String parameterType, String parameterValue) throws Exception { if (parameterType.equals("java.lang.String")) { return parameterValue; } else if (parameterType.equals("java.lang.Integer") || parameterType.equals("int")) { return Integer.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Long") || parameterType.equals("long")) { return Long.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Short") || parameterType.equals("short")) { return Short.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Byte") || parameterType.equals("byte")) { return Byte.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Float") || parameterType.equals("float")) { return Float.valueOf(parameterValue); } // changed java.lang.dobule to java.lang.double bronwen else if (parameterType.equals("java.lang.Double") || parameterType.equals("double")) { return Double.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Boolean") || parameterType.equals("boolean")) { return Boolean.valueOf(parameterValue); } else if (parameterType.equals("java.lang.Void")) { return Void.TYPE; } else if (parameterType.equals("java.util.Date")) { // this is tricky since Date can be written in many formats // will use the Date format with current locale and several // different formats Date value = null; for (int i = 0; i < allFormats.length; i++) { synchronized (allFormats[i]) { try { System.out.println(parameterValue + " " + allFormats[i]); value = allFormats[i].parse(parameterValue); // if succeful then break break; } catch (ParseException e) { // ignore, the format wasn't appropriate } } } if (value == null) { throw new ParseException("Not possible to parse", 0); } return value; } else if (parameterType.equals("java.lang.Number")) { Number value = null; // try first as a long try { value = Long.valueOf(parameterValue); } catch (NumberFormatException e) { } // if not try as a double if (value == null) { try { value = Double.valueOf(parameterValue); } catch (NumberFormatException e) { } } if (value == null) { throw new NumberFormatException("Not possible to parse"); } return value; } if (parameterType.equals("java.lang.Character") || parameterType.equals("char")) { if (parameterValue.length() > 0) { return new Character(parameterValue.charAt(0)); } else { throw new NumberFormatException("Can not initialize Character from empty String"); } } // tests whether the classes have a single string parameter value // constructor. That covers the classes // javax.management.ObjectName // java.math.BigInteger // java.math.BigDecimal Class cls = null; java.lang.reflect.Constructor ctor = null; try { cls = Class.forName(parameterType); ctor = cls.getConstructor(new Class[]{String.class}); return ctor.newInstance(new Object[]{parameterValue}); } catch (ClassNotFoundException cnfe) { // Can not find class. Not in our ClassLoader? /** @todo Ask the MBeanServer to instantiate this class??? */ throw new IllegalArgumentException("Invalid parameter type: " + parameterType); } catch (NoSuchMethodException nsme) { // No public String constructor. throw new IllegalArgumentException("Invalid parameter type: " + parameterType); } catch (Exception ex) { // Constructor might have thrown an exception? // Security Exception ? // IllegalAccessException? .... etc. // Just rethrow. We can do little here /** @todo Log the exception */ throw ex; } } /** * Checks if the given type is primitive of can be initialized from String.
* This is done by trying to load the class and checking if there is a public String * only constructor. * * @param parameterType Indicates the type of the parameter, for instance java.lang.String * @return true if the type is primitive or String initializable * @throws Thrown in case there is a data conversion error */ protected static boolean canCreateParameterValue(String parameterType) { int count = OpenType.ALLOWED_CLASSNAMES.length; for (int i = 0; i < count; i++) { if (OpenType.ALLOWED_CLASSNAMES[i].equals(parameterType)) { return true; } } count = BASIC_TYPES.length; for (int i = 0; i < count; i++) { if (BASIC_TYPES[i].equals(parameterType)) { return true; } } Class cls = null; try { cls = Class.forName(parameterType); cls.getConstructor(new Class[]{String.class}); // Yes we can load the class and it has a public String constructor. return true; } catch (ClassNotFoundException cnfe) { // Can not find class. Not in our ClassLoader? /** @todo Ask the MBeanServer to instantiate this class??? */ return false; } catch (NoSuchMethodException nsme) { // No public String constructor. return false; } catch (Exception ex) { // Constructor might have thrown an exception? // Security Exception ? // IllegalAccessException? .... etc. // Just rethrow. We can do little here /** @todo Log the exception */ return false; } } public static Comparator createObjectNameComparator() { return new ToStringComparator(); } public static Comparator createObjectInstanceComparator() { return new ObjectInstanceComparator(); } public static Comparator createConstructorComparator() { return new ConstructorComparator(); } public static Comparator createClassComparator() { return new ToStringComparator(); } private static class ToStringComparator implements Comparator { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } } private static class ObjectInstanceComparator implements Comparator { private ToStringComparator comp = new ToStringComparator(); public int compare(Object o1, Object o2) { ObjectInstance oi1 = (ObjectInstance)o1; ObjectInstance oi2 = (ObjectInstance)o2; return comp.compare(oi1.getObjectName(), oi2.getObjectName()); } } private static class ConstructorComparator implements Comparator { public int compare(Object o1, Object o2) { Constructor c1 = (Constructor)o1; Constructor c2 = (Constructor)o2; // sort them by the parameter types; Class[] params1 = c1.getParameterTypes(); Class[] params2 = c2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (!params1[i].equals(params2[i])) { return params2[i].toString().compareTo(params1[i].toString()); } } return 0; } else { return params1.length - params2.length; } } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ConstructorsCommandProcessor.java100644 0 0 7235 10513545721 24673 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.Arrays; import javax.management.JMException; import javax.management.loading.DefaultLoaderRepository; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * ConstructorsCommandProcessor, processes a request to query the available * constructors for a classname * * @version $Revision: 1.3 $ */ public class ConstructorsCommandProcessor extends HttpCommandProcessorAdaptor { public ConstructorsCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); String classname = in.getVariable("classname"); if (classname == null || classname.trim().length() == 0) { return createException(document, "", "classname parameter required"); } else { // look class in default classloader Class targetClass = null; try { targetClass = DefaultLoaderRepository.loadClass(classname); } catch (ClassNotFoundException e) { } try { if (targetClass == null) { targetClass = ClassLoader.getSystemClassLoader().loadClass(classname); } } catch (ClassNotFoundException e) { } try { if (targetClass == null) { targetClass = getClass().getClassLoader().loadClass(classname); } } catch (ClassNotFoundException e) { } if (targetClass == null) { return createException(document, classname, "class " + classname + " not found"); } Element root = document.createElement("Class"); root.setAttribute("classname", classname); document.appendChild(root); Constructor[] constructors = targetClass.getConstructors(); Arrays.sort(constructors, CommandProcessorUtil.createConstructorComparator()); for (int i = 0; i < constructors.length; i++) { System.out.println("Constructor " + constructors[i]); Element constructor = document.createElement("Constructor"); constructor.setAttribute("name", constructors[i].getName()); addParameters(constructor, document, constructors[i].getParameterTypes()); root.appendChild(constructor); } } return document; } protected void addParameters(Element node, Document document, Class[] parameters) { for (int j = 0; j < parameters.length; j++) { Element parameter = document.createElement("Parameter"); parameter.setAttribute("type", parameters[j].getName()); parameter.setAttribute("strinit", String.valueOf(CommandProcessorUtil.canCreateParameterValue(parameters[j].getName()))); // add id since order is relevant parameter.setAttribute("id", "" + j); node.appendChild(parameter); } } private Document createException(Document document, String classname, String message) { Element exceptionElement = document.createElement("Exception"); document.appendChild(exceptionElement); exceptionElement.setAttribute("classname", classname); exceptionElement.setAttribute("errorMsg", message); return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/CreateMBeanCommandProcessor.java100644 0 0 11332 10513545721 24302 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.management.JMException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * CreateMBeanCommandProcessor, processes a request for creating and registering * an MBean * * @version $Revision: 1.3 $ */ public class CreateMBeanCommandProcessor extends HttpCommandProcessorAdaptor { /** * Constructs a new CreateMBeanCommandProcessor */ public CreateMBeanCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("MBeanOperation"); document.appendChild(root); Element operationElement = document.createElement("Operation"); operationElement.setAttribute("name", "create"); root.appendChild(operationElement); String objectVariable = in.getVariable("objectname"); String classVariable = in.getVariable("class"); if (objectVariable == null || objectVariable.equals("") || classVariable == null || classVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } operationElement.setAttribute("objectname", objectVariable); List types = new ArrayList(); List values = new ArrayList(); int i = 0; boolean unmatchedParameters = false; boolean valid = false; do { String parameterType = in.getVariable("type" + i); String parameterValue = in.getVariable("value" + i); valid = (parameterType != null && parameterValue != null); if (valid) { types.add(parameterType); Object value = null; try { value = CommandProcessorUtil.createParameterValue(parameterType, parameterValue); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Parameter " + i + ": " + parameterValue + " cannot be converted to type " + parameterType); return document; } if (value != null) { values.add(value); } } if (parameterType == null ^ parameterValue == null) { unmatchedParameters = true; break; } i++; } while (valid); if (objectVariable == null || objectVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } if (unmatchedParameters) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "count of parameter types doesn't match count of parameter values"); return document; } ObjectName name = null; try { name = new ObjectName(objectVariable); } catch (MalformedObjectNameException e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Malformed object name"); return document; } if (server.isRegistered(name)) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "A MBean with name " + name + " is already registered"); return document; } else { try { if (types.size() > 0) { Object[] params = values.toArray(); String[] signature = new String[types.size()]; types.toArray(signature); server.createMBean(classVariable, name, null, params, signature); } else { server.createMBean(classVariable, name, null); } operationElement.setAttribute("result", "success"); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", e.getMessage()); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/DefaultProcessor.java100644 0 0 20300 10513545721 22254 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import mx4j.log.Log; import mx4j.log.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * DefaultPostProcessor doesn't alter the result, just publising the xml file * * @version $Revision: 1.4 $ */ public class DefaultProcessor implements ProcessorMBean { private final static String ENCODING = "UTF-8"; private boolean canonical = false; public String getName() { return "Default XML Processor"; } private Logger getLogger() { return Log.getLogger(getClass().getName()); } public void writeResponse(HttpOutputStream out, HttpInputStream in, Document document) throws IOException { out.setCode(HttpConstants.STATUS_OKAY); out.setHeader("Content-Type", "text/xml"); out.sendHeaders(); print(new PrintWriter(out), document); ByteArrayOutputStream o = new ByteArrayOutputStream(); print(new PrintWriter(o), document); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug(new String(o.toByteArray())); } public void writeError(HttpOutputStream out, HttpInputStream in, Exception e) throws IOException { if (e instanceof HttpException) { out.setCode(((HttpException)e).getCode()); out.setHeader("Content-Type", "text/xml"); out.sendHeaders(); print(new PrintWriter(out), ((HttpException)e).getResponseDoc()); } } public String preProcess(String path) { // The only special case. The root is routed to the the server request if (path.equals("/")) { path = "/server"; } return path; } public String notFoundElement(String path, HttpOutputStream out, HttpInputStream in) throws IOException, HttpException { // no processing. Unknown elements are not found throw new HttpException(HttpConstants.STATUS_NOT_FOUND, "Path " + path + " not found"); } // ripped from Xerces samples protected void print(PrintWriter out, Node node) { // is there anything to do? if (node == null) return; int type = node.getNodeType(); switch (type) { // print document case Node.DOCUMENT_NODE: { if (!canonical) { out.println(""); } NodeList children = node.getChildNodes(); for (int iChild = 0; iChild < children.getLength(); iChild++) { print(out, children.item(iChild)); } out.flush(); break; } // print element with attributes case Node.ELEMENT_NODE: { out.print('<'); out.print(node.getNodeName()); Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; out.print(' '); out.print(attr.getNodeName()); out.print("=\""); out.print(normalize(attr.getNodeValue())); out.print('"'); } out.print('>'); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { print(out, children.item(i)); } } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { if (canonical) { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { print(out, children.item(i)); } } } else { out.print('&'); out.print(node.getNodeName()); out.print(';'); } break; } // print cdata sections case Node.CDATA_SECTION_NODE: { if (canonical) { out.print(normalize(node.getNodeValue())); } else { out.print(""); } break; } // print text case Node.TEXT_NODE: { out.print(normalize(node.getNodeValue())); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { out.print(" 0) { out.print(' '); out.print(data); } out.println("?>"); break; } } // Close the element if (type == Node.ELEMENT_NODE) { out.print("'); } out.flush(); } /** * Returns a sorted list of attributes. * * @param attrs Description of Parameter * @return Description of the Returned Value */ protected Attr[] sortAttributes(NamedNodeMap attrs) { int len = (attrs != null) ? attrs.getLength() : 0; Attr array[] = new Attr[len]; for (int i = 0; i < len; ++i) array[i] = (Attr)attrs.item(i); Arrays.sort(array, new Comparator() { public int compare(Object o1, Object o2) { Attr attr1 = (Attr)o1; Attr attr2 = (Attr)o2; return attr1.getNodeName().compareTo(attr2.getNodeName()); } }); return array; } /** * Normalizes the given string. * * @param s Description of Parameter * @return Description of the Returned Value */ protected String normalize(String s) { StringBuffer str = new StringBuffer(); int len = (s != null) ? s.length() : 0; for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '<': { str.append("<"); break; } case '>': { str.append(">"); break; } case '&': { str.append("&"); break; } case '"': { str.append("""); break; } case '\'': { str.append("'"); break; } case '\r': case '\n': { if (canonical) { str.append("&#"); str.append(Integer.toString(ch)); str.append(';'); } else { str.append(ch); } break; } default: { str.append(ch); } } } return str.toString(); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/DeleteMBeanCommandProcessor.java100644 0 0 4725 10513545721 24271 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.management.JMException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * DeleteMBeanCommandProcessor, processes a request for unregistering an MBean * * @version $Revision: 1.3 $ */ public class DeleteMBeanCommandProcessor extends HttpCommandProcessorAdaptor { public DeleteMBeanCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("MBeanOperation"); document.appendChild(root); Element operationElement = document.createElement("Operation"); operationElement.setAttribute("operation", "delete"); root.appendChild(operationElement); String objectVariable = in.getVariable("objectname"); operationElement.setAttribute("objectname", objectVariable); if (objectVariable == null || objectVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } ObjectName name = null; try { name = new ObjectName(objectVariable); } catch (MalformedObjectNameException e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Malformed object name"); return document; } if (server.isRegistered(name)) { try { server.unregisterMBean(name); operationElement.setAttribute("result", "success"); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", e.getMessage()); } } else { if (name != null) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "MBean " + name + " not registered"); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/EmptyCommandProcessor.java100644 0 0 1664 10513545721 23261 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.management.JMException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * EmptyCommandProcessor, returns an empty xml tree * * @version $Revision: 1.3 $ */ public class EmptyCommandProcessor extends HttpCommandProcessorAdaptor { /** * Constructs a new EmptyCommandProcessor */ public EmptyCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("empty"); document.appendChild(root); return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/GetAttributeCommandProcessor.java100644 0 0 15247 10513545721 24610 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.management.JMException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * GetAttributeCommandProcessor, processes a request for getting one attribute * of a specific MBean. It also support some formats for types like Arrays * * @version $Revision: 1.4 $ */ public class GetAttributeCommandProcessor extends HttpCommandProcessorAdaptor { public GetAttributeCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); String name = in.getVariable("objectname"); String attributeVariable = in.getVariable("attribute"); String formatVariable = in.getVariable("format"); ObjectName objectName = null; MBeanAttributeInfo targetAttribute = null; // special case boolean validMBean = false; if (name != null) { objectName = new ObjectName(name); if (server.isRegistered(objectName)) { validMBean = true; } } if (validMBean && attributeVariable != null) { validMBean = false; MBeanInfo info = server.getMBeanInfo(objectName); MBeanAttributeInfo[] attributes = info.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(attributeVariable)) { targetAttribute = attributes[i]; validMBean = true; break; } } } } if (validMBean) { Element root = document.createElement("MBean"); document.appendChild(root); root.setAttribute("objectname", objectName.toString()); MBeanInfo info = server.getMBeanInfo(objectName); root.setAttribute("classname", info.getClassName()); root.setAttribute("description", info.getDescription()); Element attribute = document.createElement("Attribute"); attribute.setAttribute("name", attributeVariable); attribute.setAttribute("classname", targetAttribute.getType()); Object attributeValue = server.getAttribute(objectName, attributeVariable); attribute.setAttribute("isnull", (attributeValue == null) ? "true" : "false"); root.appendChild(attribute); if ("array".equals(formatVariable) && attributeValue.getClass().isArray()) { Element array = document.createElement("Array"); array.setAttribute("componentclass", attributeValue.getClass().getComponentType().getName()); int length = Array.getLength(attributeValue); array.setAttribute("length", "" + length); for (int i = 0; i < length; i++) { Element arrayElement = document.createElement("Element"); arrayElement.setAttribute("index", "" + i); if (Array.get(attributeValue, i) != null) { arrayElement.setAttribute("element", Array.get(attributeValue, i).toString()); arrayElement.setAttribute("isnull", "false"); } else { arrayElement.setAttribute("element", "null"); arrayElement.setAttribute("isnull", "true"); } array.appendChild(arrayElement); } attribute.appendChild(array); } else if ("collection".equals(formatVariable) && attributeValue instanceof Collection) { Collection collection = (Collection)attributeValue; Element collectionElement = document.createElement("Collection"); collectionElement.setAttribute("length", "" + collection.size()); Iterator i = collection.iterator(); int j = 0; while (i.hasNext()) { Element collectionEntry = document.createElement("Element"); collectionEntry.setAttribute("index", "" + j++); Object obj = i.next(); if (obj != null) { collectionEntry.setAttribute("elementclass", obj.getClass().getName()); collectionEntry.setAttribute("element", obj.toString()); } else { collectionEntry.setAttribute("elementclass", "null"); collectionEntry.setAttribute("element", "null"); } collectionElement.appendChild(collectionEntry); } attribute.appendChild(collectionElement); } else if ("map".equals(formatVariable) && attributeValue instanceof Map) { Map map = (Map)attributeValue; Element mapElement = document.createElement("Map"); mapElement.setAttribute("length", "" + map.size()); Iterator i = map.keySet().iterator(); int j = 0; while (i.hasNext()) { Element mapEntry = document.createElement("Element"); mapEntry.setAttribute("index", "" + j++); Object key = i.next(); Object entry = map.get(key); if (entry != null && key != null) { mapEntry.setAttribute("keyclass", key.getClass().getName()); mapEntry.setAttribute("key", key.toString()); mapEntry.setAttribute("elementclass", entry.getClass().getName()); mapEntry.setAttribute("element", entry.toString()); } else { mapEntry.setAttribute("keyclass", "null"); mapEntry.setAttribute("key", "null"); mapEntry.setAttribute("elementclass", "null"); mapEntry.setAttribute("element", "null"); } mapElement.appendChild(mapEntry); } attribute.appendChild(mapElement); } else { attribute.setAttribute("value", (attributeValue == null) ? "null" : attributeValue.toString()); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpAdaptor.java100644 0 0 70624 10513545721 21240 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import javax.management.JMException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.tools.adaptor.AdaptorServerSocketFactory; import mx4j.tools.adaptor.PlainAdaptorServerSocketFactory; import mx4j.util.Base64Codec; import org.w3c.dom.Document; /** * HttpAdaptor sets the basic adaptor listening for HTTP requests * * @version $Revision: 1.14 $ */ public class HttpAdaptor implements HttpAdaptorMBean, MBeanRegistration { private static final String VERSION = "3.0.2"; /** * Port to listen for connections */ private int port = 8080; /** * Host where to set the server socket */ private String host = "localhost"; /** * Target server */ private MBeanServer server; /** * Server socket */ private ServerSocket serverSocket; /** * Indicates whether the server is running */ private boolean alive; /** * Map of commands indexed by the request path */ private Map commands = new HashMap(); /** * Target processor */ private ProcessorMBean processor = null; /** * Target processor name */ private ObjectName processorName = null; /** * Default processor */ private ProcessorMBean defaultProcessor = new DefaultProcessor(); private String authenticationMethod = "none"; // Should be dependant on the server? private String realm = "MX4J"; private Map authorizations = new HashMap(); private AdaptorServerSocketFactory socketFactory = null; private ObjectName factoryName; private String processorClass; private Date startDate; private long requestsCount; private String[][] defaultCommandProcessors = { {"server", "mx4j.tools.adaptor.http.ServerCommandProcessor"}, {"serverbydomain", "mx4j.tools.adaptor.http.ServerByDomainCommandProcessor"}, {"mbean", "mx4j.tools.adaptor.http.MBeanCommandProcessor"}, {"setattributes", "mx4j.tools.adaptor.http.SetAttributesCommandProcessor"}, {"setattribute", "mx4j.tools.adaptor.http.SetAttributeCommandProcessor"}, {"getattribute", "mx4j.tools.adaptor.http.GetAttributeCommandProcessor"}, {"delete", "mx4j.tools.adaptor.http.DeleteMBeanCommandProcessor"}, {"invoke", "mx4j.tools.adaptor.http.InvokeOperationCommandProcessor"}, {"create", "mx4j.tools.adaptor.http.CreateMBeanCommandProcessor"}, {"constructors", "mx4j.tools.adaptor.http.ConstructorsCommandProcessor"}, {"relation", "mx4j.tools.adaptor.http.RelationCommandProcessor"}, {"empty", "mx4j.tools.adaptor.http.EmptyCommandProcessor"}}; private DocumentBuilder builder; /** * Default Constructor added so that we can have some additional * constructors as well. */ public HttpAdaptor() { } /** * Overloaded constructor to allow the port to be set. * The reason this was added was to allow the loading of this adaptor by * the dynamic loading service of the MBean server and have the port set * from a param in the mlet file. Example: (replaced lt & gt symbol with []) *
[mlet code="mx4j.tools.adaptor.http.HttpAdaptor" *
archive="mx4j.jar" *
name="Server:name=HttpAdaptor"] *
[arg type="int" value="12345"] *
[/mlet] *

*

This constructor uses the default host or the host must be set later. * * @param port The port on which the HttpAdaptor should listen */ public HttpAdaptor(int port) { this.port = port; } /** * Overloaded constructor to allow the host to be set. * The reason this was added was to allow the loading of this adaptor by * the dynamic loading service of the MBean server and have the host set * from a param in the mlet file. Example: (replaced lt & gt symbol with []) *
[mlet code="mx4j.tools.adaptor.http.HttpAdaptor" *
archive="mx4j.jar" *
name="Server:name=HttpAdaptor"] *
[arg type="java.lang.String" value="someserver.somehost.com"] *
[/mlet] *

*

This constructor uses the default port or the port must be set later. * * @param host The host on which the HttpAdaptor should listen */ public HttpAdaptor(String host) { this.host = host; } /** * Overloaded constructor to allow the port to be set. * The reason this was added was to allow the loading of this adaptor by * the dynamic loading service of the MBean server and have the port set * from a param in the mlet file. Example: (replaced lt & gt symbol with []) * NOTE that the port must come before the host in the arg list of the mlet *
[mlet code="mx4j.tools.adaptor.http.HttpAdaptor" *
archive="mx4j.jar" *
name="Server:name=HttpAdaptor"] *
[arg type="int" value="12345"] *
[arg type="java.lang.String" value="someserver.somehost.com"] *
[/mlet] * * @param port The port on which the HttpAdaptor should listen * @param host The host on which the HttpAdaptor should listen */ public HttpAdaptor(int port, String host) { this.port = port; this.host = host; } /** * Sets the value of the server's port * * @param port the new port's value */ public void setPort(int port) { if (alive) { throw new IllegalArgumentException("Not possible to change port with the server running"); } this.port = port; } /** * Returns the port where the server is running on. Default is 8080 * * @return HTTPServer's port */ public int getPort() { return port; } /** * Sets the host name where the server will be listening * * @param host Server's host */ public void setHost(String host) { if (alive) { throw new IllegalArgumentException("Not possible to change port with the server running"); } this.host = host; } /** * Return the host name the server will be listening to. If null the server * listen at the localhost * * @return the current hostname */ public String getHost() { return host; } /** * Sets the Authentication Method. * * @param method none/basic/digest */ public void setAuthenticationMethod(String method) { if (alive) { throw new IllegalArgumentException("Not possible to change authentication method with the server running"); } if (method == null || !(method.equals("none") || method.equals("basic") || method.equals("digest"))) { throw new IllegalArgumentException("Only accept methods none/basic/digest"); } this.authenticationMethod = method; } /** * Authentication Method * * @return authentication method */ public String getAuthenticationMethod() { return authenticationMethod; } /** * Sets the object which will post process the XML results. The last value set * between the setPostProcessor and setPostProcessorName will be the valid one * * @param processor a Post processor object */ public void setProcessor(ProcessorMBean processor) { this.processor = processor; this.processorName = null; } /** * Sets the classname of the object which will post process the XML results. The adaptor * will try to build the object and use the processor name ObjectName to register it * The class name has to implements mx4j.tools.adaptor.http.ProcessorMBean and be MBean * compliant * * @param processorClass a Post processor object */ public void setProcessorClass(String processorClass) { this.processorClass = processorClass; } /** * Sets the object name of the PostProcessor MBean. If ProcessorClass is set the processor * will be created * * @param processorName a Post processor object */ public void setProcessorNameString(String processorName) throws MalformedObjectNameException { this.processorName = new ObjectName(processorName); } /** * Sets the object name which will post process the XML result. The last value * set between the setPostProcessor and setPostProcessorName will be the valid * one. The MBean will be verified to be of instance HttpPostProcessor * * @param processorName The new processorName value */ public void setProcessorName(ObjectName processorName) { this.processor = null; this.processorName = processorName; } public ProcessorMBean getProcessor() { return this.processor; } public ObjectName getProcessorName() { return this.processorName; } /** * Sets the object which create the server sockets * * @param factory the socket factory */ public void setSocketFactory(AdaptorServerSocketFactory factory) { this.factoryName = null; this.socketFactory = factory; } /** * Sets the factory's object name which will create the server sockets * * @param factoryName the socket factory */ public void setSocketFactoryName(ObjectName factoryName) { this.socketFactory = null; this.factoryName = factoryName; } /** * Sets the factory's object name which will create the server sockets * * @param factoryName the socket factory */ public void setSocketFactoryNameString(String factoryName) throws MalformedObjectNameException { this.socketFactory = null; this.factoryName = new ObjectName(factoryName); } /** * Indicates whether the server's running * * @return The active value */ public boolean isActive() { return alive; } /** * Starting date * * @return The date when the server was started */ public Date getStartDate() { return startDate; } /** * Requests count * * @return The total of requests served so far */ public long getRequestsCount() { return requestsCount; } /** * Gets the HttpAdaptor version * * @return HttpAdaptor's version */ public String getVersion() { return VERSION; } /** * Adds a command processor object */ public void addCommandProcessor(String path, HttpCommandProcessor processor) { commands.put(path, processor); if (alive) { processor.setMBeanServer(server); processor.setDocumentBuilder(builder); } } /** * Adds a command processor object by class */ public void addCommandProcessor(String path, String processorClass) { try { HttpCommandProcessor processor = (HttpCommandProcessor)Class.forName(processorClass).newInstance(); addCommandProcessor(path, processor); } catch (Exception e) { Logger log = getLogger(); log.error("Exception creating Command Processor of class " + processorClass, e); } } /** * Removes a command processor object by class */ public void removeCommandProcessor(String path) { if (commands.containsKey(path)) { commands.remove(path); } } /** * Starts the server */ public void start() throws IOException { final Logger logger = getLogger(); if (server != null) { serverSocket = createServerSocket(); if (serverSocket == null) { logger.error("Server socket is null"); return; } if (processorClass != null && processorName != null) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Building processor class of type " + processorClass + " and name " + processorName); try { server.createMBean(processorClass, processorName, null); } catch (JMException e) { logger.error("Exception creating processor class", e); } } Iterator i = commands.values().iterator(); while (i.hasNext()) { HttpCommandProcessor processor = (HttpCommandProcessor)i.next(); processor.setMBeanServer(server); processor.setDocumentBuilder(builder); } if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("HttpAdaptor server listening on port " + port); alive = true; Thread serverThread = new Thread(new Runnable() { public void run() { if (logger.isEnabledFor(Logger.INFO)) logger.info("HttpAdaptor version " + VERSION + " started on port " + port); startDate = new Date(); requestsCount = 0; while (alive) { try { Socket client = null; client = serverSocket.accept(); if (!alive) { client.close(); break; } requestsCount++; new HttpClient(client).start(); } catch (InterruptedIOException e) { continue; } catch (IOException e) { continue; } catch (Exception e) { logger.warn("Exception during request processing", e); continue; } catch (Error e) { logger.error("Error during request processing", e); continue; } } try { serverSocket.close(); } catch (IOException e) { logger.warn("Exception closing the server", e); } serverSocket = null; alive = false; if (logger.isEnabledFor(Logger.INFO)) logger.info("HttpAdaptor version " + VERSION + " stopped on port " + port); } }); serverThread.start(); } else { if (logger.isEnabledFor(Logger.INFO)) logger.info("Start failed, no server target server has been set"); } } /** * Restarts the server. Useful when changing the Server parameters * * @deprecated as of RC 1 */ public void restart() throws IOException { stop(); start(); } /** * Stops the HTTP daemon */ public void stop() { try { if (alive) { alive = false; // force the close with a socket call new Socket(host, port); } } catch (IOException e) { getLogger().warn(e.getMessage()); } try { if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { getLogger().warn(e.getMessage()); } } /** * Adds an authorization pair as username/password */ public void addAuthorization(String username, String password) { if (username == null || password == null) { throw new IllegalArgumentException("username and passwords cannot be null"); } authorizations.put(username, password); } /** * Gathers some basic data */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { this.server = server; buildCommands(); return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws java.lang.Exception { // stop the server stop(); } public void postDeregister() { } private Logger getLogger() { return Log.getLogger(getClass().getName()); } private ServerSocket createServerSocket() throws IOException { if (socketFactory == null) { if (factoryName == null) { socketFactory = new PlainAdaptorServerSocketFactory(); return socketFactory.createServerSocket(port, 50, host); } else { try { return (ServerSocket)server.invoke(factoryName, "createServerSocket", new Object[]{new Integer(port), new Integer(50), host}, new String[]{"int", "int", "java.lang.String"}); } catch (Exception x) { Logger log = getLogger(); log.error("Exception invoking AdaptorServerSocketFactory via MBeanServer", x); } } } else { return socketFactory.createServerSocket(port, 50, host); } return null; } private boolean isUsernameValid(String username, String password) { if (authorizations.containsKey(username)) { return password.equals(authorizations.get(username)); } return false; } protected HttpCommandProcessor getProcessor(String path) { return (HttpCommandProcessor)commands.get(path); } /** * Build the commands */ protected void buildCommands() { Logger log = getLogger(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); for (int i = 0; i < defaultCommandProcessors.length; i++) { try { HttpCommandProcessor processor = (HttpCommandProcessor)Class.forName(defaultCommandProcessors[i][1]).newInstance(); commands.put(defaultCommandProcessors[i][0], processor); } catch (Exception e) { log.warn("Exception building command procesor", e); } } } catch (ParserConfigurationException e) { log.error("Exception building the Document Factories", e); } } protected void postProcess(HttpOutputStream out, HttpInputStream in, Document document) throws IOException, JMException { boolean processed = false; // inefficient but handles modifications at runtime if (processorName != null) { if (server.isRegistered(processorName) && server.isInstanceOf(processorName, "mx4j.tools.adaptor.http.ProcessorMBean")) { server.invoke(processorName, "writeResponse", new Object[]{out, in, document}, new String[]{"mx4j.tools.adaptor.http.HttpOutputStream", "mx4j.tools.adaptor.http.HttpInputStream", "org.w3c.dom.Document"}); processed = true; } else { Logger log = getLogger(); if (log.isEnabledFor(Logger.TRACE)) log.trace(processorName + " not found"); } } if (!processed && processor != null) { processor.writeResponse(out, in, document); processed = true; } if (!processed) { defaultProcessor.writeResponse(out, in, document); } } protected void findUnknownElement(String path, HttpOutputStream out, HttpInputStream in) throws IOException, JMException { boolean processed = false; // inefficient but handles modifications at runtime if (processorName != null) { if (server.isRegistered(processorName) && server.isInstanceOf(processorName, "mx4j.tools.adaptor.http.ProcessorMBean")) { server.invoke(processorName, "notFoundElement", new Object[]{path, out, in}, new String[]{"java.lang.String", "mx4j.tools.adaptor.http.HttpOutputStream", "mx4j.tools.adaptor.http.HttpInputStream"}); processed = true; } else { Logger log = getLogger(); if (log.isEnabledFor(Logger.TRACE)) log.trace(processorName + " not found"); } } if (!processed && processor != null) { processor.notFoundElement(path, out, in); processed = true; } if (!processed) { defaultProcessor.notFoundElement(path, out, in); } } protected String preProcess(String path) throws IOException, JMException { boolean processed = false; // inefficient but handles modifications at runtime if (processorName != null) { Logger log = getLogger(); if (log.isEnabledFor(Logger.TRACE)) log.trace("Preprocess using " + processorName); if (server.isRegistered(processorName) && server.isInstanceOf(processorName, "mx4j.tools.adaptor.http.ProcessorMBean")) { if (log.isEnabledFor(Logger.TRACE)) log.trace("Preprocessing"); path = (String)server.invoke(processorName, "preProcess", new Object[]{path}, new String[]{"java.lang.String"}); processed = true; } else { if (log.isEnabledFor(Logger.TRACE)) log.trace(processorName + " not found"); } } if (!processed && processor != null) { path = processor.preProcess(path); processed = true; } if (!processed) { path = defaultProcessor.preProcess(path); } return path; } protected void postProcess(HttpOutputStream out, HttpInputStream in, Exception e) throws IOException, JMException { boolean processed = false; // inefficient but handles modifications at runtime if (processorName != null) { if (server.isRegistered(processorName) && server.isInstanceOf(processorName, "mx4j.tools.adaptor.http.ProcessorMBean")) { server.invoke(processorName, "writeError", new Object[]{out, in, e}, new String[]{"mx4j.tools.adaptor.http.HttpOutputStream", "mx4j.tools.adaptor.http.HttpInputStream", "java.lang.Exception"}); processed = true; } else { Logger log = getLogger(); if (log.isEnabledFor(Logger.TRACE)) log.trace(processorName + " not found"); } } if (!processed && processor != null) { processor.writeError(out, in, e); processed = true; } if (!processed) { defaultProcessor.writeError(out, in, e); } } private class HttpClient extends Thread { private Socket client; HttpClient(Socket client) { this.client = client; } public boolean isValid(String authorizationString) { if (authenticationMethod.startsWith("basic")) { authorizationString = authorizationString.substring(5, authorizationString.length()); String decodeString = new String(Base64Codec.decodeBase64(authorizationString.getBytes())); if (decodeString.indexOf(":") > 0) { try { StringTokenizer tokens = new StringTokenizer(decodeString, ":"); String username = tokens.nextToken(); String password = tokens.nextToken(); return isUsernameValid(username, password); } catch (Exception e) { return false; } } } return false; } private boolean handleAuthentication(HttpInputStream in, HttpOutputStream out) throws IOException { if (authenticationMethod.equals("basic")) { String result = in.getHeader("authorization"); if (result != null) { if (isValid(result)) { return true; } throw new HttpException(HttpConstants.STATUS_FORBIDDEN, "Authentication failed"); } out.setCode(HttpConstants.STATUS_AUTHENTICATE); out.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); out.sendHeaders(); out.flush(); return false; } if (authenticationMethod.equals("digest")) { // not implemented } return true; } public void run() { Logger log = getLogger(); HttpInputStream httpIn = null; HttpOutputStream httpOut = null; try { // get input streams InputStream in = client.getInputStream(); httpIn = new HttpInputStream(in); httpIn.readRequest(); // Find a suitable command processor String path = httpIn.getPath(); String queryString = httpIn.getQueryString(); if (log.isEnabledFor(Logger.DEBUG)) log.debug("Request " + path + ((queryString == null) ? "" : ("?" + queryString))); String postPath = preProcess(path); if (!postPath.equals(path)) { if (log.isEnabledFor(Logger.DEBUG)) log.debug("Processor replaced path " + path + " with the path " + postPath); path = postPath; } OutputStream out = client.getOutputStream(); httpOut = new HttpOutputStream(out, httpIn); if (!handleAuthentication(httpIn, httpOut)) { return; } HttpCommandProcessor processor = getProcessor(path.substring(1, path.length())); if (processor == null) { if (log.isEnabledFor(Logger.DEBUG)) log.debug("No suitable command processor found, requesting from processor path " + path); findUnknownElement(path, httpOut, httpIn); } else { Document document = processor.executeRequest(httpIn); postProcess(httpOut, httpIn, document); } } catch (Exception ex) { log.warn("Exception during http request", ex); if (httpOut != null) { try { postProcess(httpOut, httpIn, ex); } catch (IOException e) { log.warn("IOException during http request", e); } catch (JMException e) { log.warn("JMException during http request", e); } catch (RuntimeException rte) { log.error("RuntimeException during http request", rte); } catch (Error er) { log.error("Error during http request ", er); } catch (Throwable t) { log.fatal("Throwable during http request ", t); } } } catch (Error ex) { log.error("Error during http request ", ex); } finally { try { if (httpOut != null) { httpOut.flush(); } } catch (IOException e) { log.warn("Exception during request processing", e); } finally { try { // always close the socket client.close(); } catch (IOException e) { log.info("Exception during socket close", e); } } } } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpAdaptorMBean.java100644 0 0 11444 10513545721 22136 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.Date; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import mx4j.tools.adaptor.AdaptorServerSocketFactory; /** * Management interface for the HttpAdaptor MBean. * * @version $Revision: 1.3 $ */ public interface HttpAdaptorMBean { /** * Sets the value of the server's port * * @param port the new port's value */ public void setPort(int port); /** * Returns the port where the server is running on. Default is 8080 * * @return HTTPServer's port */ public int getPort(); /** * Sets the host name where the server will be listening * * @param host Server's host */ public void setHost(java.lang.String host); /** * Return the host name the server will be listening to. If null the server listen at the localhost * * @return the current hostname */ java.lang.String getHost(); /** * Sets the Authentication Method. * * @param method none/basic/digest */ public void setAuthenticationMethod(String method); /** * Authentication Method * * @return authentication method */ public String getAuthenticationMethod(); /** * Sets the object which will post process the XML results. * The last value set between the setPostProcessor and setPostProcessorName will be the valid one * * @param processor a Post processor object */ public void setProcessor(ProcessorMBean processor); /** * Returns the Processor set by {@link #setProcessor} */ public ProcessorMBean getProcessor(); /** * Sets the classname of the object which will post process the XML results. * The adaptor will try to build the object and use the processor name ObjectName to register it. * The class name has to implements mx4j.tools.adaptor.http.ProcessorMBean and be MBean compliant * * @param processorClass a Post processor object */ public void setProcessorClass(String processorClass); /** * Sets the object name of the PostProcessor MBean. If ProcessorClass is set the processor will be created * * @param processorName a Post processor object */ public void setProcessorNameString(String processorName) throws MalformedObjectNameException; /** * Sets the object name which will post process the XML result. The last value set between the setPostProcessor and setPostProcessorName will be the valid one. The MBean will be verified to be of instance HttpPostProcessor * * @param processorName The new processorName value */ public void setProcessorName(ObjectName processorName); /** * Returns the ObjectName of the processor set by {@link #setProcessorName} */ public ObjectName getProcessorName(); /** * Sets the object which create the server sockets * * @param factory the socket factory */ public void setSocketFactory(AdaptorServerSocketFactory factory); /** * Sets the factory's object name which will create the server sockets * * @param factoryName the socket factory */ public void setSocketFactoryName(ObjectName factoryName); /** * Sets the factory's object name which will create the server sockets * * @param factoryName the socket factory */ public void setSocketFactoryNameString(String factoryName) throws MalformedObjectNameException; /** * Indicates whether the server's running * * @return The active value */ public boolean isActive(); /** * Starting date * * @return The date when the server was started */ public Date getStartDate(); /** * Requests count * * @return The total of requests served so far */ public long getRequestsCount(); /** * Gets the HttpAdaptor version * * @return HttpAdaptor's version */ public String getVersion(); /** * Adds a command processor object */ public void addCommandProcessor(String path, HttpCommandProcessor processor); /** * Adds a command processor object by class */ public void addCommandProcessor(String path, String processorClass); /** * Removes a command processor object by class */ public void removeCommandProcessor(String path); /** * Starts the server */ public void start() throws IOException; /** * Stops the HTTP daemon */ public void stop(); /** * Adds an authorization pair as username/password */ public void addAuthorization(String username, String password); } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpAdaptorMBeanDescription.java100644 0 0 16722 10513545721 24346 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Management interface descriptions for the HttpAdaptor MBean. * * @version $Revision: 1.3 $ */ public class HttpAdaptorMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "HttpAdaptor MBean"; } public String getConstructorDescription(Constructor ctor) { if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor()")) { return "Parameterless constructor"; } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int)")) { return "Constructor with a given port"; } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(java.lang.String)")) { return "Constructor with a given host"; } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int,java.lang.String)")) { return "Constructor with a given port and host"; } return super.getConstructorDescription(ctor); } public String getConstructorParameterName(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int)")) { switch (index) { case 0: return "port"; } } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(java.lang.String)")) { switch (index) { case 0: return "host"; } } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int,java.lang.String)")) { switch (index) { case 0: return "port"; case 1: return "host"; } } return super.getConstructorParameterName(ctor, index); } public String getConstructorParameterDescription(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int)")) { switch (index) { case 0: return "Listening port"; } } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(java.lang.String)")) { switch (index) { case 0: return "Listening host"; } } if (ctor.toString().equals("public mx4j.tools.adaptor.http.HttpAdaptor(int,java.lang.String)")) { switch (index) { case 0: return "Listening port"; case 1: return "Listening host"; } } return super.getConstructorParameterDescription(ctor, index); } public String getAttributeDescription(String attribute) { if (attribute.equals("AuthenticationMethod")) { return "Authentication method (none/basic/digest)"; } if (attribute.equals("ProcessorClass")) { return "PostProcessor MBean"; } if (attribute.equals("ProcessorNameString")) { return "PostProcessor MBean's object name as string"; } if (attribute.equals("Processor")) { return "PostProcessor MBean"; } if (attribute.equals("ProcessorName")) { return "PostProcessor MBean's object name"; } if (attribute.equals("SocketFactory")) { return "Server Socket factory"; } if (attribute.equals("SocketFactoryName")) { return "Server Socket factory's objectname"; } if (attribute.equals("SocketFactoryNameString")) { return "Server Socket factory's objectname as string"; } if (attribute.equals("Active")) { return "Indicates whether the server is active"; } if (attribute.equals("StartDate")) { return "Indicates the date when the server was started"; } if (attribute.equals("RequestsCount")) { return "Total of requested served so far"; } if (attribute.equals("Version")) { return "HttpAdaptor's version"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("addCommandProcessor")) { return "Adds a command processor object assigned to a given path"; } if (name.equals("addCommandProcessor")) { return "Adds a command processor object (given a classname) assigned to a given path"; } if (name.equals("removeCommandProcessor")) { return "Removes a command processor for a given path"; } if (name.equals("start")) { return "Starts the HttpAdaptor"; } if (name.equals("stop")) { return "Stops the HttpAdaptor"; } if (name.equals("addAuthorization")) { return "Adds an authorized pair name/password"; } return super.getOperationDescription(operation); } public String getOperationParameterName(Method method, int index) { String name = method.getName(); if (name.equals("addCommandProcessor")) { switch (index) { case 0: return "path"; case 1: return "processor"; } } if (name.equals("addCommandProcessor")) { switch (index) { case 0: return "path"; case 1: return "processorClass"; } } if (name.equals("removeCommandProcessor")) { switch (index) { case 0: return "path"; } } if (name.equals("addAuthorization")) { switch (index) { case 0: return "username"; case 1: return "password"; } } return super.getOperationParameterName(method, index); } public String getOperationParameterDescription(Method method, int index) { String name = method.getName(); if (name.equals("addCommandProcessor")) { switch (index) { case 0: return "Path assigned to the new command processor"; case 1: return "HttpCommandProcessor object"; } } if (name.equals("addCommandProcessor")) { switch (index) { case 0: return "Path assigned to the new command processor"; case 1: return "HttpCommandProcessor classname to be instantiated and assigned to the give path"; } } if (name.equals("removeCommandProcessor")) { switch (index) { case 0: return "Path to be removed"; } } if (name.equals("addAuthorization")) { switch (index) { case 0: return "Username"; case 1: return "Password"; } } return super.getOperationParameterDescription(method, index); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpCommandProcessor.java100644 0 0 2112 10513545721 23067 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.management.JMException; import javax.management.MBeanServer; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; /** * HttpCommandProcessor sets the structure of a command processor * * @version $Revision: 1.3 $ */ public interface HttpCommandProcessor { /** * Executes an HTTP request. It assumes the request is well formed * * @param out Input request * @return An XML Document * @throws IOException */ public Document executeRequest(HttpInputStream in) throws IOException, JMException; /** * Sets the target MBeanServer */ public void setMBeanServer(MBeanServer server); /** * Sets the Document Builder factory */ public void setDocumentBuilder(DocumentBuilder builder); } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpCommandProcessorAdaptor.java100644 0 0 2120 10513545721 24401 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.management.JMException; import javax.management.MBeanServer; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; /** * HttpCommandProcessor sets the structure of a command processor * * @version $Revision: 1.3 $ */ public abstract class HttpCommandProcessorAdaptor implements HttpCommandProcessor { protected MBeanServer server; protected DocumentBuilder builder; public abstract Document executeRequest(HttpInputStream in) throws IOException, JMException; /** * Sets the target MBeanServer */ public void setMBeanServer(MBeanServer server) { this.server = server; } /** * Sets the Document Builder factory */ public void setDocumentBuilder(DocumentBuilder builder) { this.builder = builder; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpConstants.java100644 0 0 3526 10513545721 21577 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; /** * Define constants for the HTTP request processing * * @version $Revision: 1.3 $ */ public class HttpConstants { /** * Server info header */ public final static String SERVER_INFO = "MX4J-HTTPD/1.0"; /** * HTTP implemented version */ public final static String HTTP_VERSION = "HTTP/1.0 "; /** * Get method header */ public final static String METHOD_GET = "GET"; /** * Post method header */ public final static String METHOD_POST = "POST"; /** * Status code OK */ public final static int STATUS_OKAY = 200; /** * Status code NO CONTENT */ public final static int STATUS_NO_CONTENT = 204; /** * Status code MOVED PERMANENTLY */ public final static int STATUS_MOVED_PERMANENTLY = 301; /** * Status code MOVED TEMPORARILY */ public final static int STATUS_MOVED_TEMPORARILY = 302; /** * Status code BAD REQUEST */ public final static int STATUS_BAD_REQUEST = 400; /** * Status code AUTHENTICATE */ public final static int STATUS_AUTHENTICATE = 401; /** * Status code FORBIDDEN */ public final static int STATUS_FORBIDDEN = 403; /** * Status code NOT FOUND */ public final static int STATUS_NOT_FOUND = 404; /** * Status code NOT ALLOWED */ public final static int STATUS_NOT_ALLOWED = 405; /** * Status code INTERNAL ERROR */ public final static int STATUS_INTERNAL_ERROR = 500; /** * Status code NOT IMPLEMENTED */ public final static int STATUS_NOT_IMPLEMENTED = 501; } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpException.java100644 0 0 3275 10513545721 21562 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * HttpException is emitted when an error parsing an HTTP request appears * * @version $Revision: 1.3 $ */ public class HttpException extends IOException { /** * Error code */ protected int code; /** * Constructor for the HttpException object * * @param code Error code * @param description Description */ public HttpException(int code, String description) { super(description); this.code = code; } /** * Return the exception code */ public int getCode() { return code; } public Document getResponseDoc() { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement("HttpException"); root.setAttribute("code", Integer.toString(code)); root.setAttribute("description", getMessage()); document.appendChild(root); return document; } catch (ParserConfigurationException e) { return null; } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpInputStream.java100644 0 0 25666 10513545721 22127 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.StringTokenizer; /** * HttpInputStream processes an HTTP request * * @version $Revision: 1.3 $ */ public class HttpInputStream extends BufferedInputStream { /** * Http method. only GET, POST implemented */ private String method; /** * Path of the request */ private String path; /** * Query string */ private String queryString; /** * Request version */ private float version; /** * Current headers */ private Map headers = new HashMap(); private Map variables = new HashMap(); /** * Constructs a new HttpInputStream * * @param in InputStream */ public HttpInputStream(InputStream in) { super(in); } /** * Returns the method of the request * * @return the method of the request GET/POST */ public String getMethod() { return method; } /** * Returns the path of the request * * @return the path of the request */ public String getPath() { return path; } /** * Returns the query string * * @return The queryString value */ public String getQueryString() { return queryString; } /** * Returns the version of the request * * @return The version value 1.0/1.1 */ public float getVersion() { return version; } /** * Returns a given header by name, assumes lower case * * @param name Name of the header * @return The header value */ public String getHeader(String name) { return (String)headers.get(name); } /** * Returns a given header by name, assumes lower case * * @param name Name of the header * @return The header value */ public Map getHeaders() { return headers; } /** * Reads the request parsing the headers * * @throws IOException Description of Exception */ public void readRequest() throws IOException { String request = readLine(); if (request == null) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, "Null query"); } // Parses the request StringTokenizer parts = new StringTokenizer(request); try { parseMethod(parts.nextToken()); parseRequest(parts.nextToken()); } catch (NoSuchElementException ex) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, request); } if (parts.hasMoreTokens()) { parseVersion(parts.nextToken()); } else { version = 0.9f; } if (version >= 1.0f) { readHeaders(); parseVariables(); } } /** * Reads an HTTP line * * @return A read line * @throws IOException Emmited in case of errors reading the stream */ public String readLine() throws IOException { StringBuffer line = new StringBuffer(64); line.delete(0, line.length()); int c; while (((c = read()) != -1) && (c != '\n') && (c != '\r')) { line.append((char)c); } if ((c == '\r') && ((c = read()) != '\n') && (c != -1)) { --pos; } if ((c == -1) && (line.length() == 0)) { return null; } else { return line.toString(); } } /** * Returns a map with the variables passed in the request. * * @return A map containing variables/value pairs. If a variable is *

* present only once in the request the value will be a String. *

* If it is present many times the variable will be a String[] */ public Map getVariables() { return variables; } /** * Returns one variable value. If the variable is present many times, the first *

* instance will be returned * * @return A String with the variable value */ public String getVariable(String name) { if (variables.containsKey(name)) { Object variable = variables.get(name); if (variable instanceof String) { return (String)variable; } else if (variable instanceof String[]) { return ((String[])variable)[0]; } } return null; } /** * Returns one variable values. * * @return A String array with all variable instances */ public String[] getVariableValues(String name) { if (variables.containsKey(name)) { Object variable = variables.get(name); if (variable instanceof String[]) { return (String[])variable; } else if (variable instanceof String) { String[] result = new String[1]; result[0] = (String)variable; return result; } } return null; } /** * Parses the request parameters */ protected void parseVariables() throws HttpException { try { // get request variables String variableHolder = ""; if (method.equals(HttpConstants.METHOD_POST) && "application/x-www-form-urlencoded".equals(headers.get("content-type")) && (headers.get("content-length") != null)) { if ("chunked".equals(headers.get("transfer-encoding"))) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, "Sorry I don't understand chunked requests"); } StringBuffer buffer = new StringBuffer(); int size = Integer.parseInt((String)headers.get("content-length")); mark(size); for (int i = 0; i < size; i++) { int j = read(); if (j >= 0) { buffer.append((char)j); } else { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, "Request not understood"); } } variableHolder = buffer.toString(); reset(); } else if (method.equals(HttpConstants.METHOD_GET)) { variableHolder = getQueryString(); } else { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, "Request not understood"); } StringTokenizer parser = new StringTokenizer(variableHolder, "&"); while (parser.hasMoreTokens()) { String command = parser.nextToken(); int equalIndex = command.indexOf('='); if (equalIndex > 0) { String variableName = URLDecoder.decode(command.substring(0, equalIndex)); String variableValue = URLDecoder.decode(command.substring(equalIndex + 1, command.length())); variableValue = new String(variableValue.getBytes(), "UTF-8"); if (variables.get(variableName) != null) { Object value = variables.get(variableName); String[] newValue = null; if (value instanceof String) { newValue = new String[2]; newValue[0] = variableValue; newValue[1] = (String)value; } else { String[] oldValue = (String[])value; newValue = new String[oldValue.length + 1]; System.arraycopy(oldValue, 0, newValue, 1, oldValue.length); newValue[0] = variableValue; } variables.put(variableName, newValue); } else { variables.put(variableName, variableValue); } } } } catch (Exception e) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, getQueryString()); } } /** * Parses the connection method. GET/POST are allowed * * @param method Description of Parameter * @throws HttpException Description of Exception */ protected void parseMethod(String method) throws HttpException { if (method.equals(HttpConstants.METHOD_GET)) { this.method = HttpConstants.METHOD_GET; } else if (method.equals(HttpConstants.METHOD_POST)) { this.method = HttpConstants.METHOD_POST; } else { throw new HttpException(HttpConstants.STATUS_NOT_IMPLEMENTED, method); } } /** * Parses the request * * @param request Request string * @throws HttpException Thrown if an error ocurr */ protected void parseRequest(String request) throws HttpException { if (!request.startsWith("/")) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, request); } int queryIdx = request.indexOf('?'); if (queryIdx == -1) { path = HttpUtil.canonicalizePath(request); queryString = ""; } else { path = HttpUtil.canonicalizePath(request.substring(0, queryIdx)); queryString = request.substring(queryIdx + 1); } } /** * Parses the request HttpConstants version * * @param verStr String containing the HTTP version * @throws HttpException */ protected void parseVersion(String verStr) throws HttpException { if (!verStr.startsWith("HTTP/")) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, verStr); } try { version = Float.valueOf(verStr.substring(5)).floatValue(); } catch (NumberFormatException ex) { throw new HttpException(HttpConstants.STATUS_BAD_REQUEST, verStr); } } /** * Reads the headers * * @throws IOException */ protected void readHeaders() throws IOException { String header; while (((header = readLine()) != null) && !header.equals("")) { int colonIdx = header.indexOf(':'); if (colonIdx != -1) { String name = header.substring(0, colonIdx); String value = header.substring(colonIdx + 1); headers.put(name.toLowerCase(), value.trim()); } } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpOutputStream.java100644 0 0 6621 10513545721 22276 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * HttpAdaptor sets the basic adaptor listening for HTTP requests * * @version $Revision: 1.3 $ */ public class HttpOutputStream extends BufferedOutputStream { /** * Answer code */ protected int code; /** * whether to send the headers */ protected boolean sendHeaders; /** * Headers to be sent */ protected Map headers = new HashMap(7); /** * Creates a new HttpOutputStream with a given OutputStream and an InputStream * * @param out The OutputStream normally associated with the output socket *

* stream of the incoming connection * @param in HttpInputStream containing the incoming request */ public HttpOutputStream(OutputStream out, HttpInputStream in) { super(out); code = HttpConstants.STATUS_OKAY; setHeader("Server", HttpConstants.SERVER_INFO); sendHeaders = (in.getVersion() >= 1.0); } /** * Sets the answer code * * @param code The new code value */ public void setCode(int code) { this.code = code; } /** * Sets a given header code * * @param attr The new header name * @param value The new header value */ public void setHeader(String attr, String value) { headers.put(attr, value); } /** * Sends the headers * * @return Description of the Returned Value * @throws IOException Description of Exception */ public boolean sendHeaders() throws IOException { if (sendHeaders) { StringBuffer buffer = new StringBuffer(512); buffer.append(HttpConstants.HTTP_VERSION); buffer.append(code); buffer.append(" "); buffer.append(HttpUtil.getCodeMessage(code)); buffer.append("\r\n"); Iterator attrs = headers.keySet().iterator(); int size = headers.size(); for (int i = 0; i < size; i++) { String attr = (String)attrs.next(); buffer.append(attr); buffer.append(": "); buffer.append(headers.get(attr)); buffer.append("\r\n"); } buffer.append("\r\n"); write(buffer.toString()); } return sendHeaders; } /** * Writes a given message line * * @param msg The message to be written * @throws IOException */ public void write(String msg) throws IOException { write(msg.getBytes("latin1")); } /** * Writes the content of the input stream to the output stream * * @param in The input stream * @throws IOException */ public void write(InputStream in) throws IOException { int n; int length = buf.length; while ((n = in.read(buf, count, length - count)) >= 0) { if ((count += n) >= length) { out.write(buf, count = 0, length); } } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/HttpUtil.java100644 0 0 7333 10513545721 20540 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; /** * Utility methods for the HTTP adaptor * * @version $Revision: 1.3 $ */ public class HttpUtil { /** * Gets a message apropriate for a give HTTP code * * @param code Reference Code * @return The result message * @see HttpConstants */ public static String getCodeMessage(int code) { switch (code) { case HttpConstants.STATUS_OKAY: return "OK"; case HttpConstants.STATUS_NO_CONTENT: return "No Content"; case HttpConstants.STATUS_MOVED_PERMANENTLY: return "Moved Permanently"; case HttpConstants.STATUS_MOVED_TEMPORARILY: return "Moved Temporarily"; case HttpConstants.STATUS_BAD_REQUEST: return "Bad Request"; case HttpConstants.STATUS_FORBIDDEN: return "Forbidden"; case HttpConstants.STATUS_NOT_FOUND: return "Not Found"; case HttpConstants.STATUS_NOT_ALLOWED: return "Method Not Allowed"; case HttpConstants.STATUS_INTERNAL_ERROR: return "Internal Server Error"; case HttpConstants.STATUS_AUTHENTICATE: return "Authentication requested"; case HttpConstants.STATUS_NOT_IMPLEMENTED: return "Not Implemented"; default: return "Unknown Code (" + code + ")"; } } /** * Makes a path canonical * * @param path Target path * @return The canonicalized path */ public static String canonicalizePath(String path) { char[] chars = path.toCharArray(); int length = chars.length; int idx; int odx = 0; while ((idx = indexOf(chars, length, '/', odx)) < length - 1) { int ndx = indexOf(chars, length, '/', idx + 1); int kill = -1; if (ndx == idx + 1) { kill = 1; } else if ((ndx >= idx + 2) && (chars[idx + 1] == '.')) { if (ndx == idx + 2) { kill = 2; } else if ((ndx == idx + 3) && (chars[idx + 2] == '.')) { kill = 3; while ((idx > 0) && (chars[--idx] != '/')) { ++kill; } } } if (kill == -1) { odx = ndx; } else if (idx + kill >= length) { length = odx = idx + 1; } else { length -= kill; System.arraycopy(chars, idx + 1 + kill, chars, idx + 1, length - idx - 1); odx = idx; } } return new String(chars, 0, length); } protected static int indexOf(char[] chars, int length, char chr, int from) { while ((from < length) && (chars[from] != chr)) { ++from; } return from; } /** * Returns whether a boolean variable is in the variables. It tries to find * it. If not found the the default is used. If found is tested to check if * it is true or 1 and the answer is true. * Otherwise is false */ public static boolean booleanVariableValue(HttpInputStream in, String variable, boolean defaultValue) { if (in.getVariables().containsKey(variable)) { String result = (String)in.getVariables().get(variable); return result.equals("true") || result.equals("1"); } return defaultValue; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/InvokeOperationCommandProcessor.java100644 0 0 15072 10513545721 25315 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * InvokeOperationCommandProcessor, processes a request for unregistering an MBean * * @version $Revision: 1.3 $ */ public class InvokeOperationCommandProcessor extends HttpCommandProcessorAdaptor { public InvokeOperationCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("MBeanOperation"); document.appendChild(root); Element operationElement = document.createElement("Operation"); operationElement.setAttribute("operation", "invoke"); root.appendChild(operationElement); String objectVariable = in.getVariable("objectname"); String operationVariable = in.getVariable("operation"); if (objectVariable == null || objectVariable.equals("") || operationVariable == null || operationVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } operationElement.setAttribute("objectname", objectVariable); List types = new ArrayList(); List values = new ArrayList(); int i = 0; boolean unmatchedParameters = false; boolean valid = false; do { String parameterType = in.getVariable("type" + i); String parameterValue = in.getVariable("value" + i); valid = (parameterType != null && parameterValue != null); if (valid) { types.add(parameterType); Object value = null; try { value = CommandProcessorUtil.createParameterValue(parameterType, parameterValue); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Parameter " + i + ": " + parameterValue + " cannot be converted to type " + parameterType); return document; } if (value != null) { values.add(value); } } if (parameterType == null ^ parameterValue == null) { unmatchedParameters = true; break; } i++; } while (valid); if (objectVariable == null || objectVariable.equals("") || operationVariable == null || operationVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } if (unmatchedParameters) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "count of parameter types doesn't match count of parameter values"); return document; } ObjectName name = null; try { name = new ObjectName(objectVariable); } catch (MalformedObjectNameException e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Malformed object name"); return document; } if (server.isRegistered(name)) { MBeanInfo info = server.getMBeanInfo(name); MBeanOperationInfo[] operations = info.getOperations(); boolean match = false; if (operations != null) { for (int j = 0; j < operations.length; j++) { if (operations[j].getName().equals(operationVariable)) { MBeanParameterInfo[] parameters = operations[j].getSignature(); if (parameters.length != types.size()) { continue; } Iterator k = types.iterator(); boolean signatureMatch = true; for (int p = 0; p < types.size(); p++) { if (!parameters[p].getType().equals(k.next())) { signatureMatch = false; break; } } match = signatureMatch; } if (match) { break; } } } if (!match) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Operation singature has no match in the MBean"); } else { try { Object[] params = values.toArray(); String[] signature = new String[types.size()]; types.toArray(signature); Object returnValue = server.invoke(name, operationVariable, params, signature); operationElement.setAttribute("result", "success"); if (returnValue != null) { operationElement.setAttribute("returnclass", returnValue.getClass().getName()); operationElement.setAttribute("return", returnValue.toString()); } else { operationElement.setAttribute("returnclass", null); operationElement.setAttribute("return", null); } } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", e.getMessage()); } } } else { if (name != null) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", new StringBuffer("MBean ").append(name).append(" not registered").toString()); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/MBeanCommandProcessor.java100644 0 0 22426 10513545721 23164 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import javax.management.JMException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ObjectName; import javax.management.modelmbean.ModelMBeanInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * MBeanCommandProcessor, processes a request for getting data about a MBean * * @version $Revision: 1.3 $ */ public class MBeanCommandProcessor extends HttpCommandProcessorAdaptor { public MBeanCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); String name = in.getVariable("objectname"); ObjectName objectName = null; if (name != null) { objectName = new ObjectName(name); if (!objectName.isPattern()) { // not a pattern - assume a single MBean if (server.isRegistered(objectName)) { Element mb = createMBeanElement(document, objectName, in); document.appendChild(mb); } } else { // A pattern - return all matching MBeans Set names = new TreeSet(CommandProcessorUtil.createObjectNameComparator()); names.addAll(server.queryNames(objectName, null)); Element root = document.createElement("Server"); root.setAttribute("pattern", objectName.toString()); for (Iterator it = names.iterator(); it.hasNext();) { Element mb = createMBeanElement(document, (ObjectName)it.next(), in); root.appendChild(mb); } document.appendChild(root); } } return document; } private Element createMBeanElement(Document document, ObjectName objectName, HttpInputStream in) throws JMException { Element root = document.createElement("MBean"); MBeanInfo info = server.getMBeanInfo(objectName); root.setAttribute("description", info.getDescription()); root.setAttribute("classname", info.getClassName()); root.setAttribute("objectname", objectName.toString()); if (info instanceof ModelMBeanInfo) { root.setAttribute("model", "true"); } if (HttpUtil.booleanVariableValue(in, "attributes", true)) { MBeanAttributeInfo[] attributes = info.getAttributes(); if (attributes != null) { SortedMap sortedAttributes = new TreeMap(); for (int i = 0; i < attributes.length; i++) { Element attribute = document.createElement("Attribute"); attribute.setAttribute("name", attributes[i].getName()); attribute.setAttribute("type", attributes[i].getType()); attribute.setAttribute("description", attributes[i].getDescription()); attribute.setAttribute("strinit", String.valueOf(CommandProcessorUtil.canCreateParameterValue(attributes[i].getType()))); if (attributes[i].isReadable() && attributes[i].isWritable()) { attribute.setAttribute("availability", "RW"); } if (attributes[i].isReadable() && !attributes[i].isWritable()) { attribute.setAttribute("availability", "RO"); } if (!attributes[i].isReadable() && attributes[i].isWritable()) { attribute.setAttribute("availability", "WO"); } try { Object attributeValue = server.getAttribute(objectName, attributes[i].getName()); attribute.setAttribute("isnull", (attributeValue == null) ? "true" : "false"); if (attributeValue != null) { attribute.setAttribute("value", attributeValue.toString()); if (attributeValue.getClass().isArray()) { attribute.setAttribute("aggregation", "array"); } if (attributeValue instanceof java.util.Collection) { attribute.setAttribute("aggregation", "collection"); } if (attributeValue instanceof java.util.Map) { attribute.setAttribute("aggregation", "map"); } } else { attribute.setAttribute("value", "null"); } } catch (JMException e) { attribute.setAttribute("value", e.getMessage()); } sortedAttributes.put(attributes[i].getName(), attribute); } Iterator keys = sortedAttributes.keySet().iterator(); while (keys.hasNext()) { root.appendChild((Element)sortedAttributes.get(keys.next())); } } } if (HttpUtil.booleanVariableValue(in, "constructors", true)) { MBeanConstructorInfo[] constructors = info.getConstructors(); if (constructors != null) { // How to order contructors? for (int i = 0; i < constructors.length; i++) { Element constructor = document.createElement("Constructor"); constructor.setAttribute("name", constructors[i].getName()); constructor.setAttribute("description", constructors[i].getDescription()); addParameters(constructor, document, constructors[i].getSignature()); root.appendChild(constructor); } } } if (HttpUtil.booleanVariableValue(in, "operations", true)) { MBeanOperationInfo[] operations = info.getOperations(); if (operations != null) { for (int i = 0; i < operations.length; i++) { Element operation = document.createElement("Operation"); operation.setAttribute("name", operations[i].getName()); operation.setAttribute("description", operations[i].getDescription()); operation.setAttribute("return", operations[i].getReturnType()); switch (operations[i].getImpact()) { case MBeanOperationInfo.UNKNOWN: operation.setAttribute("impact", "unknown"); break; case MBeanOperationInfo.ACTION: operation.setAttribute("impact", "action"); break; case MBeanOperationInfo.INFO: operation.setAttribute("impact", "info"); break; case MBeanOperationInfo.ACTION_INFO: operation.setAttribute("impact", "action_info"); break; } addParameters(operation, document, operations[i].getSignature()); root.appendChild(operation); } } } if (HttpUtil.booleanVariableValue(in, "notifications", true)) { MBeanNotificationInfo[] notifications = info.getNotifications(); if (notifications != null) { for (int i = 0; i < notifications.length; i++) { Element notification = document.createElement("Notification"); notification.setAttribute("name", notifications[i].getName()); notification.setAttribute("description", notifications[i].getDescription()); String[] types = notifications[i].getNotifTypes(); for (int j = 0; j < types.length; j++) { Element type = document.createElement("Type"); type.setAttribute("name", types[j]); notification.appendChild(type); } root.appendChild(notification); } } } return root; } protected void addParameters(Element node, Document document, MBeanParameterInfo[] parameters) { for (int j = 0; j < parameters.length; j++) { Element parameter = document.createElement("Parameter"); parameter.setAttribute("name", parameters[j].getName()); parameter.setAttribute("description", parameters[j].getDescription()); parameter.setAttribute("type", parameters[j].getType()); parameter.setAttribute("strinit", String.valueOf(CommandProcessorUtil.canCreateParameterValue(parameters[j].getType()))); // add id since order is relevant parameter.setAttribute("id", "" + j); node.appendChild(parameter); } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ProcessorMBean.java100644 0 0 4730 10513545721 21643 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import org.w3c.dom.Document; /** * Processor ManagementBean, just defines a generic description * * @version $Revision: 1.3 $ */ public interface ProcessorMBean { public String getName(); /** * The method will process the result string and produce an output. The * implementor is also responsible to set the mime type, response code and * send the headers before answering as follow: * * out.setCode(HttpConstants.STATUS_OKAY); * out.setHeader("Content-type", "text/html"); * out.sendHeaders(); * out.write("some text"); * * * @param out The output stream * @param in The input stream * @param document A document containing the data */ public void writeResponse(HttpOutputStream out, HttpInputStream in, Document document) throws IOException; /** * The method will process the result exception and produce output. The * implementor is also responsible to set the mime type, response code and * send the headers before answering as follow: * * out.setCode(HttpConstants.STATUS_OKAY); * out.setHeader("Content-type", "text/html"); * out.sendHeaders(); * out.write("some text"); * * * @param out The output stream * @param in The input stream * @param e The exception to be reported */ public void writeError(HttpOutputStream out, HttpInputStream in, Exception e) throws IOException; /** * Preprocess a path and return a replacement path. For instance the / path * could be replaced by the server path * * @param path The original path * @return the replacement path. If not modification the path param should * be returned */ public String preProcess(String path); /** * Let the processor load internally a not found element. This can be used * to load images, stylesheets and so on. If return is not null, the path is * processed * * @param path The request element * @param out The output stream * @param in The input stream */ public String notFoundElement(String path, HttpOutputStream out, HttpInputStream in) throws IOException, HttpException; } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ProcessorMBeanDescription.java100644 0 0 2654 10513545721 24052 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Description of the ProcessorMBean interface * * @version $Revision: 1.3 $ */ public class ProcessorMBeanDescription extends MBeanDescriptionAdapter { public String getAttributeDescription(String attribute) { if (attribute.equals("Name")) { return "Name of the ProcessorMBean"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { if (operation.getName().equals("writeResponse")) { return "The method process a xml result document into a suitable response"; } if (operation.getName().equals("writeError")) { return "The method process a xml error into a suitable response"; } if (operation.getName().equals("preProcess")) { return "Processes paths allowing for the replacement of a certain path with another"; } if (operation.getName().equals("notFoundElement")) { return "Method invoked when a path is not found"; } return super.getOperationDescription(operation); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/RelationCommandProcessor.java100644 0 0 17244 10513545721 23761 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.management.JMException; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.relation.RelationServiceMBean; import javax.management.relation.RoleInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * CreateMBeanCommandProcessor, processes a request for creating and registering * an MBean * * @version $Revision: 1.4 $ */ public class RelationCommandProcessor extends HttpCommandProcessorAdaptor { private ObjectName m_relationObjectName = null; private RelationServiceMBean m_proxy = null; public RelationCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("RelationServer"); document.appendChild(root); // check relationService is registered by finding its class if not return a default message if (!checkRelationServiceIsRegistered()) { Element defaultElement = document.createElement("default"); Text defaultNode = document.createTextNode("RelationService is not registered!"); defaultElement.appendChild(defaultNode); root.appendChild(defaultElement); return document; } m_proxy = (RelationServiceMBean)MBeanServerInvocationHandler.newProxyInstance(server, m_relationObjectName, RelationServiceMBean.class, true); // get all the defined relationTypeNames List allRelationNames = m_proxy.getAllRelationTypeNames(); addRelationTypeNames(root, document, allRelationNames); return document; } /** * put everything into a map as we need to maintain the correct relationTypeName to relationId * TODO: determine how to make relationService tab useful!! */ protected void addRelationTypeNames(Element node, Document document, List allRelationNames) throws JMException { Map namesMap = new HashMap(); Iterator i = allRelationNames.iterator(); while (i.hasNext()) { String name = (String)i.next(); List values = m_proxy.findRelationsOfType(name); if (namesMap.containsKey(name)) { ((List)namesMap.get(name)).add(values); } else { namesMap.put(name, values); } } // loop through the map assigning keys to Elements: values to child elements i = namesMap.keySet().iterator(); while (i.hasNext()) { String relationName = (String)i.next(); Element typeNameElement = document.createElement("relation-type-name"); typeNameElement.setAttribute("name", relationName); node.appendChild(typeNameElement); List infos = m_proxy.getRoleInfos(relationName); Iterator x = infos.iterator(); // build the metadata for the relationTypeName while (x.hasNext()) { // get the Relation meta-data for specified RelationTypeName RoleInfo roleInfo = (RoleInfo)x.next(); String roleName = roleInfo.getName(); String mbeanClassName = roleInfo.getRefMBeanClassName(); String description = roleInfo.getDescription(); int minDegree = roleInfo.getMinDegree(); int maxDegree = roleInfo.getMaxDegree(); boolean reading = roleInfo.isReadable(); boolean writing = roleInfo.isWritable(); // creating the element relation-meta-data Element roleInfoElement = document.createElement("relation-meta-data"); // create the roleName element and text node child of relation-meta-data Element roleNameElement = document.createElement("role-name"); Text roleNameNode = document.createTextNode(roleName); roleNameElement.appendChild(roleNameNode); roleInfoElement.appendChild(roleNameElement); // create the mbeanclass element child of relation-meta-data Element mbeanClassElement = document.createElement("mbean-classname"); Text mbeanClassNode = document.createTextNode(mbeanClassName); mbeanClassElement.appendChild(mbeanClassNode); roleInfoElement.appendChild(mbeanClassElement); // create the description element child of relation-meta-data Element descriptionElement = document.createElement("description"); if (description == null) description = "no description"; Text descriptionNode = document.createTextNode(description); descriptionElement.appendChild(descriptionNode); roleInfoElement.appendChild(descriptionElement); // create text node for min element Element minDegreeElement = document.createElement("min-degree"); Text minDegreeNode = document.createTextNode(Integer.toString(minDegree)); minDegreeElement.appendChild(minDegreeNode); roleInfoElement.appendChild(minDegreeElement); Element maxDegreeElement = document.createElement("max-degree"); Text maxDegreeNode = document.createTextNode(Integer.toString(maxDegree)); maxDegreeElement.appendChild(maxDegreeNode); roleInfoElement.appendChild(maxDegreeElement); Element readingElement = document.createElement("is-readable"); String readable = null; if (reading) readable = "true"; else readable = "false"; Text readingNode = document.createTextNode(readable); readingElement.appendChild(readingNode); roleInfoElement.appendChild(readingElement); Element writingElement = document.createElement("is-writable"); String writable = null; if (writing) writable = "true"; else writable = "false"; Text writingNode = document.createTextNode(writable); writingElement.appendChild(writingNode); roleInfoElement.appendChild(writingElement); typeNameElement.appendChild(roleInfoElement); } // get the list of relationIds (the values of the Map) List references = (List)namesMap.get(relationName); Iterator j = references.iterator(); while (j.hasNext()) { String relationId = (String)j.next(); Element idElement = document.createElement("relation-id"); Text idNode = document.createTextNode(relationId); idElement.appendChild(idNode); typeNameElement.appendChild(idElement); } } } // checks the relationService is registered protected boolean checkRelationServiceIsRegistered() { Set allMBeans = server.queryMBeans(null, null); for (Iterator i = allMBeans.iterator(); i.hasNext();) { ObjectInstance instance = (ObjectInstance)i.next(); if (instance.getClassName().equals("javax.management.relation.RelationService")) { // create a reference the the RelationService ObjetcName in order to create the proxy m_relationObjectName = instance.getObjectName(); return true; } } return false; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ServerByDomainCommandProcessor.java100644 0 0 6703 10513545721 25053 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * ServerByDomainCommandProcessor, processes a request for getting all the * MBeans of the current server grouped by domains * * @version $Revision: 1.3 $ */ public class ServerByDomainCommandProcessor extends HttpCommandProcessorAdaptor { public ServerByDomainCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("Server"); document.appendChild(root); String targetClass = in.getVariable("instanceof"); String queryNames = in.getVariable("querynames"); ObjectName query = null; if (queryNames != null) { try { query = new ObjectName(queryNames); } catch (MalformedObjectNameException e) { Element exceptionElement = document.createElement("Exception"); exceptionElement.setAttribute("errorMsg", e.getMessage()); root.appendChild(exceptionElement); return document; } } Set mbeans = server.queryMBeans(query, null); Iterator i = mbeans.iterator(); // this will order the domains Map domains = new TreeMap(); while (i.hasNext()) { ObjectInstance instance = (ObjectInstance)i.next(); ObjectName name = instance.getObjectName(); String domain = name.getDomain(); if (domains.containsKey(domain)) { ((Set)domains.get(domain)).add(name); } else { Set objects = new TreeSet(CommandProcessorUtil.createObjectNameComparator()); objects.add(name); domains.put(domain, objects); } } i = domains.keySet().iterator(); while (i.hasNext()) { String domain = (String)i.next(); Element domainElement = document.createElement("Domain"); root.appendChild(domainElement); domainElement.setAttribute("name", domain); Set names = (Set)domains.get(domain); Iterator j = names.iterator(); while (j.hasNext()) { ObjectName targetName = (ObjectName)j.next(); if (targetClass != null && !server.isInstanceOf(targetName, targetClass)) { continue; } Element mBeanElement = document.createElement("MBean"); mBeanElement.setAttribute("objectname", targetName.toString()); MBeanInfo info = server.getMBeanInfo(targetName); mBeanElement.setAttribute("description", info.getDescription()); mBeanElement.setAttribute("classname", info.getClassName()); domainElement.appendChild(mBeanElement); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ServerCommandProcessor.java100644 0 0 5306 10513545721 23426 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * ServerCommandProcessor, processes a request for getting all the * MBeans of the current server * * @version $Revision: 1.3 $ */ public class ServerCommandProcessor extends HttpCommandProcessorAdaptor { public ServerCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("Server"); document.appendChild(root); String classVariable = in.getVariable("instanceof"); String queryNames = in.getVariable("querynames"); Set mbeans = null; ObjectName query = null; if (queryNames != null) { try { query = new ObjectName(queryNames); mbeans = new TreeSet(CommandProcessorUtil.createObjectInstanceComparator()); mbeans.addAll(server.queryMBeans(query, null)); } catch (MalformedObjectNameException e) { Element exceptionElement = document.createElement("Exception"); exceptionElement.setAttribute("errorMsg", e.getMessage()); root.appendChild(exceptionElement); return document; } } else { mbeans = new TreeSet(CommandProcessorUtil.createObjectInstanceComparator()); mbeans.addAll(server.queryMBeans(null, null)); } Iterator i = mbeans.iterator(); while (i.hasNext()) { ObjectInstance instance = (ObjectInstance)i.next(); if (classVariable != null && !classVariable.equals(instance.getClassName())) { continue; } Element mBeanElement = document.createElement("MBean"); mBeanElement.setAttribute("objectname", instance.getObjectName().toString()); mBeanElement.setAttribute("classname", instance.getClassName()); MBeanInfo info = server.getMBeanInfo(instance.getObjectName()); mBeanElement.setAttribute("description", info.getDescription()); root.appendChild(mBeanElement); } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/SetAttributeCommandProcessor.java100644 0 0 10417 10513545721 24616 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * SetAttributeCommandProcessor, processes a request for setting one attribute * in one MBean * * @version $Revision: 1.3 $ */ public class SetAttributeCommandProcessor extends HttpCommandProcessorAdaptor { public SetAttributeCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("MBeanOperation"); document.appendChild(root); Element operationElement = document.createElement("Operation"); operationElement.setAttribute("operation", "setattribute"); root.appendChild(operationElement); String objectVariable = in.getVariable("objectname"); String attributeVariable = in.getVariable("attribute"); String valueVariable = in.getVariable("value"); if (objectVariable == null || objectVariable.equals("") || attributeVariable == null || attributeVariable.equals("") || valueVariable == null) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Incorrect parameters in the request"); return document; } operationElement.setAttribute("objectname", objectVariable); ObjectName name = null; try { name = new ObjectName(objectVariable); } catch (MalformedObjectNameException e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Malformed object name"); return document; } if (server.isRegistered(name)) { MBeanInfo info = server.getMBeanInfo(name); MBeanAttributeInfo[] attributes = info.getAttributes(); MBeanAttributeInfo targetAttribute = null; if (attributes != null) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(attributeVariable)) { targetAttribute = attributes[i]; break; } } } if (targetAttribute != null) { String type = targetAttribute.getType(); Object value = null; if (valueVariable != null) { try { value = CommandProcessorUtil.createParameterValue(type, valueVariable); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Value: " + valueVariable + " could not be converted to " + type); } if (value != null) { try { server.setAttribute(name, new Attribute(attributeVariable, value)); operationElement.setAttribute("result", "success"); } catch (Exception e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", e.getMessage()); } } } } else { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Attribute " + attributeVariable + " not found"); } } else { if (name != null) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "MBean " + name + " not registered"); } } return document; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/SetAttributesCommandProcessor.java100644 0 0 15204 10513545721 25000 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * SetAttributesCommandProcessor, processes a request for setting one or more attributes * in one MBean. it uses th facility of havin multiple submit buttons in a web page * if the set_all=Set variable is passed all attributes will be set, if a set_XXX varialbe * is passed only the specific attribute will be set * * @version $Revision: 1.3 $ */ public class SetAttributesCommandProcessor extends HttpCommandProcessorAdaptor { public SetAttributesCommandProcessor() { } public Document executeRequest(HttpInputStream in) throws IOException, JMException { Document document = builder.newDocument(); Element root = document.createElement("MBeanOperation"); document.appendChild(root); Element operationElement = document.createElement("Operation"); operationElement.setAttribute("operation", "setattributes"); root.appendChild(operationElement); String objectVariable = in.getVariable("objectname"); if (objectVariable == null || objectVariable.equals("")) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Missing objectname in the request"); return document; } operationElement.setAttribute("objectname", objectVariable); ObjectName name = null; try { name = new ObjectName(objectVariable); } catch (MalformedObjectNameException e) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "Malformed object name"); return document; } if (server.isRegistered(name)) { Map variables = in.getVariables(); if (variables.containsKey("setall")) { Iterator keys = variables.keySet().iterator(); SortedMap allAttributes = new TreeMap(); while (keys.hasNext()) { String key = (String)keys.next(); if (key.startsWith("value_")) { String attributeVariable = key.substring(6, key.length()); String valueVariable = in.getVariable(key); Element attributeElement = setAttribute(document, attributeVariable, valueVariable, name); allAttributes.put(attributeVariable, attributeElement); operationElement.appendChild(attributeElement); } } keys = allAttributes.keySet().iterator(); while (keys.hasNext()) { Element attributeElement = (Element)allAttributes.get(keys.next()); operationElement.appendChild(attributeElement); } } else { Iterator keys = variables.keySet().iterator(); SortedMap allAttributes = new TreeMap(); while (keys.hasNext()) { String key = (String)keys.next(); if (key.startsWith("set_")) { String attributeVariable = key.substring(4, key.length()); String valueVariable = in.getVariable("value_" + attributeVariable); Element attributeElement = setAttribute(document, attributeVariable, valueVariable, name); allAttributes.put(attributeVariable, attributeElement); } } keys = allAttributes.keySet().iterator(); while (keys.hasNext()) { Element attributeElement = (Element)allAttributes.get(keys.next()); operationElement.appendChild(attributeElement); } } //operationElement.setAttribute("result", "success"); } else { if (name != null) { operationElement.setAttribute("result", "error"); operationElement.setAttribute("errorMsg", "MBean " + name + " not registered"); } } return document; } private Element setAttribute(Document document, String attributeVariable, String valueVariable, ObjectName name) throws JMException { Element attributeElement = document.createElement("Attribute"); attributeElement.setAttribute("attribute", attributeVariable); MBeanInfo info = server.getMBeanInfo(name); MBeanAttributeInfo[] attributes = info.getAttributes(); MBeanAttributeInfo targetAttribute = null; if (attributes != null) { for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(attributeVariable)) { targetAttribute = attributes[i]; break; } } } if (targetAttribute != null) { String type = targetAttribute.getType(); Object value = null; if (valueVariable != null) { try { value = CommandProcessorUtil.createParameterValue(type, valueVariable); } catch (Exception e) { attributeElement.setAttribute("result", "error"); attributeElement.setAttribute("errorMsg", "Value: " + valueVariable + " could not be converted to " + type); } if (value != null) { try { server.setAttribute(name, new Attribute(attributeVariable, value)); attributeElement.setAttribute("result", "success"); attributeElement.setAttribute("value", valueVariable); } catch (Exception e) { attributeElement.setAttribute("result", "error"); attributeElement.setAttribute("errorMsg", e.getMessage()); } } } } else { attributeElement.setAttribute("result", "error"); attributeElement.setAttribute("errorMsg", "Attribute " + attributeVariable + " not found"); } return attributeElement; } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/XSLTProcessor.java100644 0 0 36054 10513545721 21477 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import javax.management.MBeanException; import javax.management.ReflectionException; import javax.management.RuntimeMBeanException; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import mx4j.log.Log; import mx4j.log.Logger; import org.w3c.dom.Document; /** * XSLTPostProcessor pass the document through an XSLT transformation * * @version $Revision: 1.8 $ */ public class XSLTProcessor implements ProcessorMBean, XSLTProcessorMBean, URIResolver { private String path = "mx4j/tools/adaptor/http/xsl"; private String defaultPage = "serverbydomain"; private TransformerFactory factory; private Map templatesCache = new HashMap(); private File root; private Map mimeTypes = new HashMap(); /** * Indicated whether the file are read from a file */ private boolean useJar = true; private volatile boolean useCache = true; private ClassLoader targetClassLoader = ClassLoader.getSystemClassLoader(); /** * The locale is set with the default as en_US since it is the * one bundled */ private Locale locale = new Locale("en", ""); public XSLTProcessor() { factory = TransformerFactory.newInstance(); factory.setURIResolver(this); mimeTypes.put(".gif", "image/gif"); mimeTypes.put(".jpg", "image/jpg"); mimeTypes.put(".png", "image/png"); mimeTypes.put(".tif", "image/tiff"); mimeTypes.put(".tiff", "image/tiff"); mimeTypes.put(".ico", "image/ico"); mimeTypes.put(".html", "text/html"); mimeTypes.put(".htm", "text/html"); mimeTypes.put(".txt", "text/plain"); mimeTypes.put(".xml", "text/xml"); mimeTypes.put(".xsl", "text/xsl"); mimeTypes.put(".css", "text/css"); mimeTypes.put(".js", "text/x-javascript"); mimeTypes.put(".jar", "application/java-archive"); } private Logger getLogger() { return Log.getLogger(getClass().getName()); } public void writeResponse(HttpOutputStream out, HttpInputStream in, Document document) throws IOException { Logger log = getLogger(); out.setCode(HttpConstants.STATUS_OKAY); out.setHeader("Content-Type", "text/html"); // added some caching attributes to force not to cache out.setHeader("Cache-Control", "no-cache"); out.setHeader("expires", "now"); out.setHeader("pragma", "no-cache"); out.sendHeaders(); Transformer transformer = null; String path = preProcess(in.getPath()); if (in.getVariable("template") != null) { transformer = createTransformer(in.getVariable("template") + ".xsl"); } else { transformer = createTransformer(path + ".xsl"); } if (transformer != null) { // added so that the document() function works transformer.setURIResolver(this); // The variables are passed to the XSLT as (param.name, value) Map variables = in.getVariables(); Iterator j = variables.keySet().iterator(); while (j.hasNext()) { String key = (String)j.next(); Object value = variables.get(key); if (value instanceof String) { transformer.setParameter("request." + key, value); } if (value instanceof String[]) { String[] allvalues = (String[])value; // not a good solution, only the first one is presented transformer.setParameter("request." + key, allvalues[0]); } } if (!variables.containsKey("locale")) { transformer.setParameter("request.locale", locale.toString()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); if (log.isEnabledFor(Logger.TRACE)) log.trace("transforming " + path); transformer.transform(new DOMSource(document), new StreamResult(output)); output.writeTo(out); } catch (TransformerException e) { log.error("Transformation exception ", e); } } else { log.warn("Transformer for path " + path + " not found"); } } protected Transformer createTransformer(String path) { Logger logger = getLogger(); try { synchronized (this) { if (useCache && templatesCache.containsKey(path)) { return ((Templates)templatesCache.get(path)).newTransformer(); } else { InputStream stream = getInputStream(path); if (stream != null) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Creating template for path " + path); Templates template = factory.newTemplates(new StreamSource(stream)); if (useCache) templatesCache.put(path, template); return template.newTransformer(); } else { if (logger.isEnabledFor(Logger.INFO)) logger.info("XSL template for path '" + path + "' not found"); } } } } catch (TransformerConfigurationException e) { logger.error("Exception during XSL template construction", e); } return null; } protected void processHttpException(HttpInputStream in, HttpOutputStream out, HttpException e) throws IOException { out.setCode(e.getCode()); out.setHeader("Content-Type", "text/html"); out.sendHeaders(); // hardcoded dir :-P Transformer transformer = createTransformer("error.xsl"); transformer.setURIResolver(this); Document doc = e.getResponseDoc(); if (doc != null) { try { if (!in.getVariables().containsKey("locale")) { transformer.setParameter("request.locale", locale.toString()); } ByteArrayOutputStream output = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc), new StreamResult(output)); output.writeTo(out); } catch (TransformerException ex) { Logger log = getLogger(); log.error("Exception during error output", ex); } } } public void writeError(HttpOutputStream out, HttpInputStream in, Exception e) throws IOException { Logger log = getLogger(); Exception t = e; if (e instanceof RuntimeMBeanException) { t = ((RuntimeMBeanException)e).getTargetException(); } if (log.isEnabledFor(Logger.DEBUG)) log.debug("Processing error " + t.getMessage()); if (t instanceof HttpException) { processHttpException(in, out, (HttpException)t); } else if ((t instanceof MBeanException) && (((MBeanException)t).getTargetException() instanceof HttpException)) { processHttpException(in, out, (HttpException)((MBeanException)t).getTargetException()); } else if ((t instanceof ReflectionException) && (((ReflectionException)t).getTargetException() instanceof HttpException)) { processHttpException(in, out, (HttpException)((ReflectionException)t).getTargetException()); } else { out.setCode(HttpConstants.STATUS_INTERNAL_ERROR); out.setHeader("Content-Type", "text/html"); out.sendHeaders(); } } public String preProcess(String path) { if (path.equals("/")) { path = "/" + defaultPage; } return path; } public String notFoundElement(String path, HttpOutputStream out, HttpInputStream in) throws IOException, HttpException { Logger log = getLogger(); File file = new File(this.path, path); if (log.isEnabledFor(Logger.DEBUG)) log.debug("Processing file request " + file); String name = file.getName(); int extensionIndex = name.lastIndexOf('.'); String mime = null; if (extensionIndex < 0) { log.warn("Filename has no extensions " + file.toString()); mime = "text/plain"; } else { String extension = name.substring(extensionIndex, name.length()); if (mimeTypes.containsKey(extension)) { mime = (String)mimeTypes.get(extension); } else { log.warn("MIME type not found " + extension); mime = "text/plain"; } } try { if (log.isEnabledFor(Logger.DEBUG)) log.debug("Trying to read file " + file); BufferedInputStream fileIn = new BufferedInputStream(getInputStream(path)); ByteArrayOutputStream outArray = new ByteArrayOutputStream(); BufferedOutputStream outBuffer = new BufferedOutputStream(outArray); int piece = 0; while ((piece = fileIn.read()) >= 0) { outBuffer.write(piece); } outBuffer.flush(); out.setCode(HttpConstants.STATUS_OKAY); out.setHeader("Content-type", mime); out.sendHeaders(); if (log.isEnabledFor(Logger.DEBUG)) log.debug("File output " + mime); outArray.writeTo(out); fileIn.close(); } catch (Exception e) { log.warn("Exception loading file " + file, e); throw new HttpException(HttpConstants.STATUS_NOT_FOUND, "file " + file + " not found"); } return null; } protected InputStream getInputStream(String path) { InputStream file = null; if (!useJar) { try { // load from a dir file = new FileInputStream(new File(this.root, path)); } catch (FileNotFoundException e) { Logger log = getLogger(); log.error("File not found", e); } } else { // load from a jar String targetFile = this.path; // workaround, should tought of somehting better if (path.startsWith("/")) { targetFile += path; } else { targetFile += "/" + path; } if (root != null) { file = targetClassLoader.getResourceAsStream(targetFile); } if (file == null) { ClassLoader cl = getClass().getClassLoader(); if (cl == null) { file = ClassLoader.getSystemClassLoader().getResourceAsStream(targetFile); } else { file = getClass().getClassLoader().getResourceAsStream(targetFile); } file = getClass().getClassLoader().getResourceAsStream(targetFile); } } return file; } public Source resolve(String href, String base) { StreamSource source = new StreamSource(getInputStream(href)); // this works with saxon7/saxon6.5.2/xalan source.setSystemId(href); return source; } public void setFile(String file) { if (file != null) { Logger log = getLogger(); File target = new File(file); if (!target.exists()) { log.warn("Target file " + file + " does not exist, defaulting to previous"); return; } if (target.isDirectory()) { useJar = false; if (log.isEnabledFor(Logger.DEBUG)) log.debug("Using " + file + " as the root dir"); this.root = target; return; } if (target.isFile() && (target.getName().endsWith(".jar") || (target.getName().endsWith(".zip")))) { try { URL url = target.toURL(); targetClassLoader = new URLClassLoader(new URL[]{url}); if (log.isEnabledFor(Logger.DEBUG)) log.debug("Using compressed file " + url + " as the root file"); this.root = target; useJar = true; } catch (MalformedURLException e) { log.warn("Unable to create class loader", e); } } else { log.warn("Target file " + file + " does not exist, defaulting to previous"); } } } public String getFile() { return (root != null) ? root.getName() : null; } public String getPathInJar() { return path; } public void setPathInJar(String path) { this.path = path; } public String getDefaultPage() { return defaultPage; } public void setDefaultPage(String defaultPage) { this.defaultPage = defaultPage; } public boolean isUseJar() { return useJar; } public boolean isUsePath() { return !useJar; } public void addMimeType(String extension, String type) { if (extension != null && type != null) { Logger log = getLogger(); if (log.isEnabledFor(Logger.DEBUG)) log.debug("Added MIME type " + type + " for extension " + extension); mimeTypes.put(extension, type); } } public void setUseCache(boolean useCache) { this.useCache = useCache; } public boolean isUseCache() { return useCache; } public String getName() { return "XSLT Processor"; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public void setLocaleString(String locale) { if (locale == null || locale.length() == 0) { this.locale = new Locale("en", ""); } else { // split locale based on underbar StringTokenizer tknzr = new StringTokenizer(locale, "_"); String language = tknzr.nextToken(); String country = ""; String variant = ""; if (tknzr.hasMoreTokens()) country = tknzr.nextToken(); if (tknzr.hasMoreTokens()) variant = tknzr.nextToken(); this.locale = new Locale(language, country, variant); } } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/XSLTProcessorMBean.java100644 0 0 4371 10513545721 22357 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.util.Locale; /** * Management interface for the XSLTProcessor MBean. * * @version $Revision: 1.3 $ */ public interface XSLTProcessorMBean extends ProcessorMBean { /** * Sets the jar/zip file or the directory where to find the XSL files * * @see #getFile */ public void setFile(String file); /** * Returns the jar/zip file or the directory where XSL files are loaded * * @see #setFile */ public String getFile(); /** * Returns the path of the XSL templates inside a jar file. * * @see #setPathInJar */ public String getPathInJar(); /** * Specifies the path of the XSL templates inside a jar file. * * @see #getPathInJar */ public void setPathInJar(String path); /** * Returns the default start page * * @see #setDefaultPage */ public String getDefaultPage(); /** * Sets the default start page, serverbydomain as a default * * @see #getDefaultPage */ public void setDefaultPage(String defaultPage); /** * Returns if the XSL files are contained in a jar/zip file. * * @see #isUsePath * @see #setFile */ boolean isUseJar(); /** * Returns if the XSL files are contained in a path. * * @see #isUseJar * @see #setFile */ boolean isUsePath(); /** * Maps a given extension with a specified MIME type */ public void addMimeType(String extension, String type); /** * Sets the caching of the XSL Templates. */ public void setUseCache(boolean useCache); /** * Returns if the XSL Templates are cached */ boolean isUseCache(); /** * Returns the Locale used to internationalize the output */ public Locale getLocale(); /** * Sets the locale used to internationalize the output */ public void setLocale(Locale locale); /** * Sets the locale used to internationalize the output, as a string */ public void setLocaleString(String locale); } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/XSLTProcessorMBeanDescription.java100644 0 0 5541 10513545721 24563 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.http; import java.lang.reflect.Method; /** * Management interface descriptions for the XSLTProcessor MBean. * * @version $Revision: 1.3 $ */ public class XSLTProcessorMBeanDescription extends ProcessorMBeanDescription { public String getMBeanDescription() { return "XSLTPostProcessor which passes the XML message from the HttpAdaptor through a XSL transformation"; } public String getAttributeDescription(String attribute) { if (attribute.equals("File")) { return "The jar/zip file or the directory where to find the XSL files"; } if (attribute.equals("PathInJar")) { return "The path of the XSL templates inside a jar file"; } if (attribute.equals("DefaultPage")) { return "The default start page"; } if (attribute.equals("UseJar")) { return "Indicates whether XSL files are contained in an external jar/zip file"; } if (attribute.equals("UsePath")) { return "Indicates whether XSL files are contained in an external path"; } if (attribute.equals("UseCache")) { return "Indicates whether the XSL Templates are cached"; } if (attribute.equals("Locale")) { return "The locale used to internationalize the output"; } if (attribute.equals("LocaleString")) { return "Sets the locale used to internationalize the output, as a string"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("addMimeType")) { return "Adds a MIME type to the default list"; } return super.getOperationDescription(operation); } public String getOperationParameterName(Method method, int index) { String name = method.getName(); if (name.equals("addMimeType")) { switch (index) { case 0: return "extension"; case 1: return "mimeType"; } } return super.getOperationParameterName(method, index); } public String getOperationParameterDescription(Method method, int index) { String name = method.getName(); if (name.equals("addMimeType")) { switch (index) { case 0: return "The extension of the file"; case 1: return "The MIME type for the extension"; } } return super.getOperationParameterDescription(method, index); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/about.xsl100644 0 0 13140 10513545721 20601 0ustar 0 0 stylesheet.css text/css about.title
about

about.main.url about.main.title MX4J

about.main.url2 about.main.line1 JMX

about.main.implementation

about.main.implementationversion

about.main.serverid

mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/common.xsl100644 0 0 41436 10513545721 20770 0ustar 0 0 en <xsl:call-template name="str"> <xsl:with-param name="id"> <xsl:value-of select="$head.title"/> </xsl:with-param> </xsl:call-template>
common.title
common.subtitle
common.logo common.logo.gif common.site common.logo.width common.logo.height {$str.logo}

 
fronttab backtab fronttab backtab fronttab backtab fronttab backtab fronttab backtab fronttab backtab fronttab backtab
common.tabs.serverview common.tabs.serverview common.tabs.mbeanview common.tabs.timerview common.tabs.monitorview common.tabs.relationview common.tabs.mletview common.tabs.about
common.serverview.return 1 common.mbeanview.return common true false true false - - - {0} {1}
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/constructors.xsl100644 0 0 23721 10513545721 22245 0ustar 0 0 stylesheet.css text/css constructors.title

constructors.parameters.title

constructors.parameters.id
constructors.parameters.type
constructors.parameters.value
true false true true false constructors.parameters.unknowntype
clearline darkline true false
constructors.constructors.intro
constructors.constructors.objectnameinput
constructors.constructors.createnew
constructors.error.exception
mbean
constructors.main.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/create.xsl100644 0 0 5715 10513545721 20723 0ustar 0 0 stylesheet.css text/css create.title
create.operation.title
create.operation.success create.operation.error
mbean
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/delete.xsl100644 0 0 5363 10513545721 20721 0ustar 0 0 stylesheet.css text/css delete.title
delete.operation.title
delete.operation.success delete.operation.error
mbean
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/emptymbean.xsl100644 0 0 5477 10513545721 21626 0ustar 0 0 stylesheet.css text/css emptymbean.title
mbean
emptymbean.title
emptymbean.querycontructors emptymbean.query
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/error.xsl100644 0 0 4555 10513545721 20612 0ustar 0 0 stylesheet.css text/css error.title
error.title
error.httpexception.code
error.httpexception.message
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/favicon.ico100644 0 0 2576 10513545721 21053 0ustar 0 0 h( €€€@ûÇû»û}ý»ýÛýëùqõxè}_}¿}_lïU÷9û}ÿmx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/identity.xsl100644 0 0 1367 10513545721 21310 0ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/invoke.xsl100644 0 0 10162 10513545721 20763 0ustar 0 0 stylesheet.css text/css invoke.title
invoke.operation.title
invoke.operation.success
invoke.operation.success.result invoke.operation.success.noresult
invoke.operation.success.error
mbean
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/logo.gif100644 0 0 4127 10513545721 20353 0ustar 0 0 GIF89aÊZ÷iov00ƒ;;‰PP–[[£pp©{{°¼››Ã°°Ð»»ÖÐÐãÛÛéððöûûý!ùÿ,ÊZ@ÿÿ H° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç €)Aü‡²%•,[.Ð2%Æ(À$yòåΘ>kªÔˆòe͈8[êlH¥Ç¦N „ @$Ì“OV­u ‚£\Q0ôŸIŸ  ,Pð+©[€™­ÁJ˜‹æÛ5»Ž„*®@¼( “ô[Va–Š öl˜w"M«ýæôèö/\­žAºå ´`Ê`ª]:1iËÆ+CWlJÚ°mÕ`slª{¤k!ßN¼¸ñãÈ“+_μ¹óçУ;w˜d`Ù’wô+=aÍȃ¯Ûÿô˜mCÄ2'¢ìݽ`M»¢Ó L=»kÒæ#¢ß M4 Йm í„ØAT×Ppu†E¦aDk­…Ð@!`ë­|þɇP‡Þ¹tVQ‡€ü §L"2¤™O4Õ¶Pe¹õi[eDLj‘¸’Ž­ÀžB<&¤ÕŠY“  C&¶gå•Xf©å–\véå—`†)æ˜d–i&BxM RS ¤ÕGŒaÜí×"IpwáuAÅ$–5m§x#iGe ¹Õ¦–'AéQĄҟQEç¯EtQŽ’4!]é¹UXÀÚjê]ZP€Q÷ §ªrÿ4'AN¾úÐiLF‘ª(nÔf1îkG½ÔR¤ᤠ¥=ùÏI”J4`…{Ù6,‡¯~zë«×æXS´ 9˜ØuXúž@Z!Ë™V‹úºiATé¥P7`¢ÖÙ{[•ùª›Pˆ‘êþŽ,DÕdÚ‘55¿ Ü—pÑÔ®{-[¢ Íù–Ʃں¦Ä% ‘¹&7ä$dzœP­(œªÀ$%å2€43Eò¼S«&D0›*ìÏ*o×cDç+$¼;CèìJZÝüOÀgVmõÕXg­õÖ\wíõ×`‡-öØd—möÙh§­öÚl·  c=VÄïJ·Ÿ°™.Ö3AÊQܬÐYjV÷F⎥¡Ô~‡mÎÝæwG–J­Ñ›/7j"7ntl×]|"Ž%‚>å^št¹„„~ÄlÑÝ*9ø•N˜S„ÄòùfI#ô•äí¡—ÿ{FÁ½äšçšNÚº±r!løF¤ÿ/¨úþ$ñÊ«ôÛ=Ïq5‘¥ ÇDâ?QSø’¦œêŠ~QŸ•ª»w„×Rß{4+L4)Ø·*ª ¯"èQú"-‚È0ã ‹ ’Â8Õœfua‘Ïë"â§eîpÔÈÝ”·êµ%‚º ÌNMíNp¡Ê1¢'ƒDpR B¡ÁÄr‘»Àº¡ ƒ2íY=F$ŠüŠEφMÜÖÞ0'–à­&€ 9g¿Š§‚Ç[Ƣȼ˜f…1Ÿaä!òŒ`¼ØÓÈq¡qWO„K`ÒALâ½nƒTq¡ÎþÄ>òT'Ä»âšÞ4±~)ß É¡Û€æt”"v¢x.¤l’>"#¶ð–Èò †Œs¼Ýâ1Àeäz?Ñ¡D–Æê )3D׿ôÒ#^¦²T<”Šèâ#Êù&‰LëŸô\YžèޤþzY¼]R‘šIJÓÅ4BÓgû‚ã,‹iP¤y š4C9'!ó#63Ì~¢U Ø‰œúa&’Ôè"âÀˆIÀ;ǙǑ8 Jè À@ÝÖ¥ CCÌ%C'JÑŠZô¢ͨF7ÊÑŽzô£\ ;mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/mbean.xsl100644 0 0 44145 10513545721 20562 0ustar 0 0 stylesheet.css text/css mbean.title
true false true true false mbean.parameters.unknown
mbean.operations.title
mbean.operations.invoke clearline darkline true false
mbean.operations.name
mbean.operations.returntype
mbean.operations.description
mbean.operations.parameter
mbean.operations.parameterid mbean.operations.parametername mbean.operations.parameterdescription mbean.operations.parameterclass
clearline darkline
mbean.constructors.class
mbean.constructors.description
mbean.constructors.parameter
mbean.constructors.parameterid mbean.constructors.parametername mbean.constructors.parameterdescription mbean.constructors.parameterclass
mbean.constructors.objectname
mbean.constructors.create
mbean
mbean.mbean.title
mbean.mbean.description
mbean.mbean.attributes
mbean.mbean.constructors
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/mbean_attributes.xsl100644 0 0 41147 10513545721 23027 0ustar 0 0 mbean_attributes.array.view mbean_attributes.array.null mbean_attributes.collection.view mbean_attributes.collection.null mbean_attributes.map.view mbean_attributes.map.null mbean_attributes.compositedata.view mbean_attributes.compositedata.null mbean_attributes.tabulardata.view mbean_attributes.tabulardata.null none true false true false true false true mbean_attributes.form.unknowntype mbean_attributes.submit.set javax.management.ObjectName mbean_attributes.WO.readonly mbean_attributes.RO.readonly clearline darkline
mbean_attributes.attribute.name
mbean_attributes.attribute.description
mbean_attributes.attribute.type
mbean_attributes.attribute.value
mbean_attributes.attribute.newvalue
mbean_attributes.attribute.arrayof mbean_attributes.attribute.arrayof boolean char float double byte short int long
mbean_attributes.attribute.setall
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/mlet.xsl100644 0 0 6131 10513545721 20412 0ustar 0 0 stylesheet.css text/css mlet.title
darkline clearline mlet.mbean.unregister mlet
mlet.main.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/monitor.xsl100644 0 0 15206 10513545721 21163 0ustar 0 0 stylesheet.css text/css monitor.title
darkline clearline monitor.mbean.unregister monitor monitor.main.createstring.button monitor.main.creategauge.button monitor.main.createcounter.button
monitor.main.title
monitor.main.createstring.label
monitor.main.creategauge.label
monitor.main.createcounter.label
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/monitor_create.xsl100644 0 0 11047 10513545721 22505 0ustar 0 0 stylesheet.css text/css monitor_create.title monitor_create.operation.stringmonitor monitor_create.operation.gaguemonitor monitor_create.operation.countermonitor monitor_create.operation.mbeanview
monitor_create.operation.title
monitor_create.operation.success monitor_create.operation.error
timer
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/relation.xsl100644 0 0 17055 10513545721 21315 0ustar 0 0 stylesheet.css text/css relation.title
relation.typename.title
relation.metadata.title
relation.relationids.title
darkline clearline
relation.rolename.title relation.classname.title
relation.description.title relation.mindegree.title
relation.maxdegree.title relation.readable.title relation.writable.title
darkline clearline
relation
relation.inprogress
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/server.xsl100644 0 0 7006 10513545721 20761 0ustar 0 0 stylesheet.css text/css server.title darkline clearline server.unregister server
server.mbeans.title
server.filter.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/serverbydomain.xsl100644 0 0 13626 10513545721 22531 0ustar 0 0 stylesheet.css text/css serverbydomain.title serverbydomain.error.query serverbydomain.domain.label darkline clearline

serverbydomain.mbean.unregister

server serverbydomain.server.query
serverbydomain.server.title
serverbydomain.server.filter
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/setattribute.xsl100644 0 0 7125 10513545721 22174 0ustar 0 0 stylesheet.css text/css setattribute.title darkline clearline
setattribute.operation.title
setattribute.operation.success setattribute.operation.error
mbean
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/setattributes.xsl100644 0 0 7641 10513545721 22362 0ustar 0 0 stylesheet.css text/css setattributes.title darkline clearline
setattributes.operation.title
setattributes.operation.success
setattributes.operation.error
mbean
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/strings_en.xml100644 0 0 26560 10513545721 21646 0ustar 0 0 MX4J/Http Adaptor JMX Management Console Server view MBean view Timers Monitors Relations MLet About Return to server view Built using {0} HttpAdaptor Return to MBean view logo.gif 100 50 mx4j.sourceforge.net MX4J - Agent View Exception during query: {0} Domain: {0} MBean By Domain: Filter: Query Unregister MBean - View Query constructors for class: query MX4J - MBean View Unknown type Operations Name Return type Description Parameters id Name Description Class Invoke Class ObjectName: Description Parameters id Name Description Class Create new MBean {0} Description {0} Attributes Constructors Name Description Type Value New Value Array of {0} Set all Read-only attribute Write-only attribute set Unknown type View array View map View collection Array is null Map is null Collection is null MX4J - MBean View MBean operation: set attributes on MBean {0} Attribute {0} set to {1} Exception during set attribute {0}, message: {1} MX4J - Exception Error during request Code: {0} Message: {0} ObjectName: Create new Constructor for class {0} MX4J - MBean Constructor's View Constructors for class {0} Exception: {0} Parameters id type value Unkown type MX4J - MBean View MBean successfully created Error during MBean creation, message: {0} MBean operation: create MBean of class {0} and object name {1} MX4J - MBean View MBean delete, objectname {0} MBean successfully deleted Error during MBean deletion, message: {0} MX4J - Timer Service Timers by Domain: ObjectName: New timer Unregister Timers for domain: {0} ObjectName MX4J - Timer Creation Timer creation with object name {0} Timer created Exception during timer creation, message: {0} Configure timer MX4J - Array View MBean {0} Array attribute {0} of type {1} Index Value first previous next last MX4J - Collection View MBean {0} Collection of class {0} on attribute {1} Index Value class Value first previous next last MX4J - Map View MBean {0} Map of class {0} on attribute {1} Key Key class Value class Value first previous next last MX4J - Monitor Service Unregister Monitors By Domain ObjectName: New StringMonitor ObjectName: New GaugeMonitor ObjectName: New CounterMonitor MX4J - Monitor creation creation with object name {0} Monitor type {0} successfully created Exception during {0} creation, mesage: {1} Configure Monitor StringMonitor GaugeMonitor CounterMonitor MX4J - MLet Service MX4J - MLet Service Mlet: (Not yet implemented) MX4J - MBean View MBean operation: invoke method {0} on MBean {1} Invocation successful Result value:
{0}
No result Error during MBean operation invocation
Message: {0}
MX4J - About {0} - HttpAdaptor http://mx4j.sourceforge.net http://www.javasoft.com/jmx Built based on the {0} specification JMX Implementation: Implementation Version: MBeanServer ID: MX4J - Relation Service RelationTypeName: Relation Type metaData: RelationIds: Role Name: MBeanClass: Description: Min Degree: Max Degree: Readable: Writable: relation Relation Service: (In Progress) MX4J - Agent View Unregister MBeans: Filter: MX4J - MBean View MBean operation: set attribute {0} on MBean {1} Attribute {0} set to {1} Error during set attribute, message: {0}
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/stylesheet.css100644 0 0 7136 10513545721 21632 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. * Author: Carlos Quiroz * Revision: $Revision: 1.2 $ */ body { background: white; color: black; font-family: tahoma,verdana,helvetica,arial,sans-serif; margin-top: 5px; margin-left: 5px; margin-right: 5px; margin-bottom: 5px; } /* Footer class */ div.footer { font-weight: bold; text-align: center; } /* Tabs styles */ td.fronttab { background: rgb(220,220,220); color: black; padding-left: 10px; padding-right: 10px; padding-bottom: 3px; font-size: small; } td.backtab { background: rgb(240,240,240); color: black; height: 25px; padding-left: 10px; padding-right: 10px; font-size: small; } a.tabs { color: black; text-decoration: none; font-size: small; } /* End of tabs styles */ /* Header styles */ td.darker { background: rgb(57,128,144); height: 18px; } td.topheading { background: rgb(183,187,184); color: black; font-weight: bold; padding-left: 10px; } /* End of Header styles */ td.domainline { background: rgb(220,220,220); color: black; padding-left: 10px; } td.page_title { background: rgb(220,220,220); color: black; padding-left: 10px; padding-right: 10px; padding-top: 2px; padding-bottom: 2px; font-weight: bold; } div.subtitle { font-size: smaller; } /* Server by domain styles */ td.serverbydomain_domainline { background: rgb(200,200,200); color: black; padding-left: 10px; font-weight: bold; } tr.clearline { background: rgb(255,255,255); color: black; padding-left: 10px; padding-right: 10px; padding-top: 2px; padding-bottom: 2px; } tr.darkline { background: rgb(240,240,240); color: black; padding-left: 10px; padding-right: 10px; } td.serverbydomain_row { font-size: x-small; padding-left: 10px; } /* MBean section title */ td.mbeans { background: rgb(183,187,184); } p.darklinebottom { background: rgb(240,240,240); color: black; height: 20px; padding-left: 10px; font-weight: bold; } div.tableheader { font-weight: bold; padding-top: 2px; padding-bottom: 2px; font-size: small } td.mbean_row { font-size: x-small; padding-left: 1px; } td.attributes_setall { padding-right: 20px; padding-top: 5px; padding-bottom: 5px; } /* MBean section title */ td.mbeans { background: rgb(183,187,184); color: black; height: 20px; padding-left: 10px; padding-right: 10px; font-weight: bold; } div.tableheader { font-weight: bold; padding-top: 2px; padding-bottom: 2px; font-size: small } td.mbean_row { font-size: x-small; padding-left: 1px; } td.aggregationrow { font-size: small; padding-left: 1px; } td.constructorrow { font-size: small; padding-left: 1px; } td.attributes_setall { padding-right: 20px; padding-top: 5px; padding-bottom: 5px; } tr.about { background: rgb(220,220,220); } h1.about { padding-left: 20px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px; font-size: xx-large; background: rgb(220,220,220); color: black; } h2.about { padding-left: 20px; padding-right: 20px; padding-top: 15px; padding-bottom: 15px; font-size: x-large; background: rgb(220,220,220); color: black; } h3.about { padding-left: 20px; padding-right: 20px; padding-top: 15px; padding-bottom: 15px; font-size: large; background: rgb(220,220,220); color: black; } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/timer.xsl100644 0 0 11523 10513545721 20612 0ustar 0 0 stylesheet.css text/css timer.title timer.domain.title
timer.domain.objectname
darkline clearline timer.mbean.unregister timer
timer.main.title
timer.main.createlabel timer.main.createbutton
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/timer_create.xsl100644 0 0 6472 10513545721 22124 0ustar 0 0 stylesheet.css text/css timer_create.title timer_create.operation.mbeanview
timer_create.operation.title
timer_create.operation.success timer_create.operation.error
timer
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewarray.xsl100644 0 0 13041 10513545721 21500 0ustar 0 0 stylesheet.css text/css viewarray.title 30 0 mbean clearline darkline getattribute?objectname= &attribute= &format=array&template=viewarray&locale= viewarray.main
viewarray.main.title
viewarray.main.arraytitle
viewarray.main.index
viewarray.main.value
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewcollection.xsl100644 0 0 14304 10513545721 22520 0ustar 0 0 stylesheet.css text/css viewcollection.title 30 0 mbean clearline darkline getattribute?objectname= &attribute= &format=collection&template=viewcollection&locale= viewcollection.main
viewcollection.main.title
viewcollection.main.viewcollectiontitle
viewcollection.main.index
viewcollection.main.value
viewcollection.main.valueclass
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewmap.xsl100644 0 0 15447 10513545721 21153 0ustar 0 0 stylesheet.css text/css viewmap.title 30 0 mbean clearline darkline getattribute?objectname= &attribute= &format=map&template=viewmap&locale= viewmap.main
viewmap.main.title
viewmap.main.viewmaptitle
viewmap.main.key
viewmap.main.keyclass
viewmap.main.value
viewmap.main.valueclass
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/xalan-ext.xsl100644 0 0 2311 10513545721 21346 0ustar 0 0 No encode function available mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/SSLAdaptorServerSocketFactory.java100644 0 0 22336 10513545721 24471 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.ssl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.security.UnrecoverableKeyException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import com.sun.net.ssl.KeyManagerFactory; import com.sun.net.ssl.SSLContext; import com.sun.net.ssl.TrustManagerFactory; import mx4j.log.Log; import mx4j.log.Logger; /** * TODO: Fix this class to avoid hardcoding Sun's provider, since it will not work with IBM's JDK. * This MBean creates SSLServerSocket instances.

* It can be configured to use a specific keystore and SSL protocol version to create SSLServerSockets * that will use the keystore information to encrypt data.
*

* A keystore can be created with this command: *

 * keytool -genkey -v -keystore store.key -storepass storepwd -keypass keypwd -dname "CN=Simone Bordet, OU=Project Administrator, O=MX4J, L=Torino, S=TO, C=IT" -validity 365
 * 
* or with this minimal command (that will prompt you for further information): *
 * keytool -genkey -keystore store.key
 * 
*

* A keystore may contains more than one entry, but only the first entry will be used * for encryption, no matter which is the alias for that entry. *

* Following the first example of generation of the keystore, this MBean must be instantiated and then setup by * invoking the following methods: *

    *
  • {@link #setKeyStoreName}("store.key"); *
  • {@link #setKeyStorePassword}("storepwd"); *
  • {@link #setKeyManagerPassword}("keypwd"); *
* before {@link #createServerSocket} is called. * * @version $Revision: 1.5 $ */ public class SSLAdaptorServerSocketFactory implements SSLAdaptorServerSocketFactoryMBean { static { addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } private String m_keyStoreType = "JKS"; private String m_trustStoreType = "JKS"; private String m_keyStoreName; private String m_trustStoreName; private String m_keyStorePassword; private String m_trustStorePassword; private String m_keyManagerAlgorithm = "SunX509"; private String m_trustManagerAlgorithm = "SunX509"; private String m_keyManagerPassword; private String m_sslProtocol = "TLS"; public static void addProvider(Provider provider) { Security.addProvider(provider); } public void setKeyStoreType(String keyStoreType) { if (keyStoreType == null || keyStoreType.trim().length() == 0) { throw new IllegalArgumentException("Invalid KeyStore type"); } m_keyStoreType = keyStoreType; } public void setTrustStoreType(String trustStoreType) { if (trustStoreType == null || trustStoreType.trim().length() == 0) { throw new IllegalArgumentException("Invalid TrustStore type"); } m_trustStoreType = trustStoreType; } public void setKeyStoreName(String name) { if (name == null || name.trim().length() == 0) { throw new IllegalArgumentException("Invalid KeyStore name"); } m_keyStoreName = name; } public void setTrustStoreName(String name) { if (name == null || name.trim().length() == 0) { throw new IllegalArgumentException("Invalid TrustStore name"); } m_trustStoreName = name; } public void setKeyStorePassword(String password) { if (password == null || password.trim().length() == 0) { throw new IllegalArgumentException("Invalid KeyStore password"); } m_keyStorePassword = password; } public void setTrustStorePassword(String password) { if (password == null || password.trim().length() == 0) { throw new IllegalArgumentException("Invalid TrustStore password"); } m_trustStorePassword = password; } public void setKeyManagerAlgorithm(String algorithm) { if (algorithm == null || algorithm.trim().length() == 0) { throw new IllegalArgumentException("Invalid KeyManager algorithm"); } m_keyManagerAlgorithm = algorithm; } public void setTrustManagerAlgorithm(String algorithm) { if (algorithm == null || algorithm.trim().length() == 0) { throw new IllegalArgumentException("Invalid TrustManager algorithm"); } m_trustManagerAlgorithm = algorithm; } public void setKeyManagerPassword(String password) { if (password == null || password.trim().length() == 0) { throw new IllegalArgumentException("Invalid KeyManager password"); } m_keyManagerPassword = password; } public void setSSLProtocol(String protocol) { if (protocol == null || protocol.trim().length() == 0) { throw new IllegalArgumentException("Invalid SSL protocol"); } m_sslProtocol = protocol; } /** * Returns a SSLServerSocket on the given port. */ public ServerSocket createServerSocket(int port, int backlog, String host) throws IOException { if (m_keyStoreName == null) { throw new IOException("KeyStore file name cannot be null"); } if (m_keyStorePassword == null) { throw new IOException("KeyStore password cannot be null"); } Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("Creating SSLServerSocket"); logger.trace("\tKeyStore " + m_keyStoreName + ", type " + m_keyStoreType); logger.trace("\tKeyManager algorithm is " + m_keyManagerAlgorithm); logger.trace("\tTrustStore " + m_trustStoreName + ", type " + m_trustStoreType); logger.trace("\tTrustManager algorithm is " + m_trustManagerAlgorithm); logger.trace("\tSSL protocol version is " + m_sslProtocol); } try { KeyStore keystore = KeyStore.getInstance(m_keyStoreType); InputStream keyStoreStream = getClass().getClassLoader().getResourceAsStream(m_keyStoreName); // Must check for nullity, otherwise a new empty keystore is created by KeyStore.load if (keyStoreStream == null) { // Let's look at the file system, maybe that the name provided is in fact a file path File fle = new java.io.File(m_keyStoreName); if (fle.exists()) keyStoreStream = new FileInputStream(fle); } if (keyStoreStream == null) throw new IOException("Cannot find KeyStore " + m_keyStoreName); keystore.load(keyStoreStream, m_keyStorePassword.toCharArray()); try { keyStoreStream.close(); } catch (IOException x) { } KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(m_keyManagerAlgorithm); // Use the keystore password as default if not given keyFactory.init(keystore, m_keyManagerPassword == null ? m_keyStorePassword.toCharArray() : m_keyManagerPassword.toCharArray()); TrustManagerFactory trustFactory = null; if (m_trustStoreName != null) { // User specified a trust store, retrieve it if (m_trustStorePassword == null) { throw new IOException("TrustStore password cannot be null"); } KeyStore trustStore = KeyStore.getInstance(m_trustStoreType); InputStream trustStoreStream = getClass().getClassLoader().getResourceAsStream(m_trustStoreName); // Check for nullity if (trustStoreStream == null) { throw new IOException("Cannot find TrustStore " + m_trustStoreName); } trustStore.load(trustStoreStream, m_trustStorePassword.toCharArray()); trustFactory = TrustManagerFactory.getInstance(m_trustManagerAlgorithm); trustFactory.init(trustStore); } SSLContext context = SSLContext.getInstance(m_sslProtocol); // Below call does not handle TrustManagers, needed when server must authenticate clients. context.init(keyFactory.getKeyManagers(), trustFactory == null ? null : trustFactory.getTrustManagers(), null); SSLServerSocketFactory ssf = context.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket)ssf.createServerSocket(port, backlog, InetAddress.getByName(host)); return serverSocket; } catch (IOException x) { logger.error("", x); throw x; } catch (UnrecoverableKeyException x) { // Wrong password for the key logger.error("Probably a bad key password", x); throw new IOException("Probably a bad key password: " + x.toString()); } catch (Exception x) { logger.error("Unexpected exception", x); throw new IOException(x.toString()); } } private Logger getLogger() { return Log.getLogger(getClass().getName()); } } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/SSLAdaptorServerSocketFactoryMBean.java100644 0 0 4516 10513545721 25354 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.ssl; import mx4j.tools.adaptor.AdaptorServerSocketFactory; /** * Management interface for the SSL ServerSocket factory * * @version $Revision: 1.3 $ */ public interface SSLAdaptorServerSocketFactoryMBean extends AdaptorServerSocketFactory { /** * Sets the type of the keystore, by default is "JKS". */ public void setKeyStoreType(String keyStoreType); /** * Sets the type of the truststore, by default is "JKS". */ public void setTrustStoreType(String trustStoreType); /** * Sets the name of the keystore; if the keystore is of type JKS, then this is a file name, that will be * resolved by the ClassLoader of this class, via getResourceAsStream. */ public void setKeyStoreName(String name); /** * Sets the name of the truststore; if the truststore is of type JKS, then this is a file name, that will be * resolved by the ClassLoader of this class, via getResourceAsStream. */ public void setTrustStoreName(String name); /** * Sets the password to access the keystore specified by {@link #setKeyStoreName}.

* It correspond to the value of the -storepass option of keytool. */ public void setKeyStorePassword(String password); /** * Sets the password to access the truststore specified by {@link #setTrustStoreName}.

* It correspond to the value of the -storepass option of keytool. */ public void setTrustStorePassword(String password); /** * Sets the key manager algorithm, by default is "SunX509". */ public void setKeyManagerAlgorithm(String algorithm); /** * Sets the trust manager algorithm, by default is "SunX509". */ public void setTrustManagerAlgorithm(String algorithm); /** * Sets the password to access the key present in the keystore.

* It correspond to the value of the -keypass option of keytool; if not specified, the KeyStore password is taken. */ public void setKeyManagerPassword(String password); /** * Sets the SSL protocol version, by default is "TLS". */ public void setSSLProtocol(String protocol); } mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/SSLAdaptorServerSocketFactoryMBeanDescription.java100644 0 0 6435 10513545721 27562 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.adaptor.ssl; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * @version $Revision: 1.3 $ */ public class SSLAdaptorServerSocketFactoryMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "Factory for SSLServerSockets used by adaptors"; } public String getConstructorDescription(Constructor ctor) { return "Creates a new SSLServerSocket factory for adaptors"; } public String getAttributeDescription(String attribute) { if (attribute.equals("KeyStoreType")) { return "The type of the keystore, default is 'JKS'"; } if (attribute.equals("TrustStoreType")) { return "The type of the truststore, default is 'JKS'"; } if (attribute.equals("KeyStoreName")) { return "The keystore name"; } if (attribute.equals("TrustStoreName")) { return "The truststore name"; } if (attribute.equals("KeyStorePassword")) { return "The keystore password"; } if (attribute.equals("TrustStorePassword")) { return "The truststore password"; } if (attribute.equals("KeyManagerAlgorithm")) { return "The key algorithm, default is 'SunX509'"; } if (attribute.equals("TrustManagerAlgorithm")) { return "The trust algorithm, default is 'SunX509'"; } if (attribute.equals("KeyManagerPassword")) { return "The key password"; } if (attribute.equals("SSLProtocol")) { return "The SSL protocol version, default is 'TLS'"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("createServerSocket")) { return "Creates a new SSLServerSocket"; } return super.getOperationDescription(operation); } public String getOperationParameterName(Method method, int index) { String name = method.getName(); if (name.equals("createServerSocket")) { switch (index) { case 0: return "port"; case 1: return "backlog"; case 2: return "host"; } } return super.getOperationParameterName(method, index); } public String getOperationParameterDescription(Method method, int index) { String name = method.getName(); if (name.equals("createServerSocket")) { switch (index) { case 0: return "The port on which the SSLServerSocket listens for incoming connections"; case 1: return "The backlog for this SSLServerSocket"; case 2: return "The host name or IP address on which the SSLServerSocket is opened"; } } return super.getOperationParameterDescription(method, index); } } mx4j-3.0.2/src/tools/mx4j/tools/config/ConfigurationBuilder.java100644 0 0 2223 10513545721 21726 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.config; import java.util.List; import javax.management.MBeanServer; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; /** * @version $Revision: 1.3 $ */ public interface ConfigurationBuilder { public static interface Node { public void setAttributes(NamedNodeMap attributes) throws ConfigurationException; public void setText(String text); public java.lang.Object configure(MBeanServer server) throws ConfigurationException; public Node getParent(); public void setParent(Node parent); public List getChildren(); public void addChild(Node child); } public static interface ObjectsHolder { public Object getObject(String key); public Object putObject(String key, Object value); public boolean containsKey(String key); } public Node createConfigurationNode(Element node) throws ConfigurationException; } mx4j-3.0.2/src/tools/mx4j/tools/config/ConfigurationException.java100644 0 0 3337 10513545721 22305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.config; import java.io.PrintStream; import java.io.PrintWriter; /** * @version $Revision: 1.3 $ */ public class ConfigurationException extends Exception { private Throwable cause; public ConfigurationException() { this(null, null); } public ConfigurationException(String message) { this(message, null); } public ConfigurationException(Throwable cause) { this(null, cause); } public ConfigurationException(String message, Throwable cause) { super(message); this.cause = cause; } public Throwable getCause() { return cause; } public void printStackTrace() { if (cause == null) { super.printStackTrace(); } else { synchronized (System.err) { System.err.println(this); cause.printStackTrace(); } } } public void printStackTrace(PrintStream stream) { if (cause == null) { super.printStackTrace(stream); } else { synchronized (stream) { stream.println(this); cause.printStackTrace(stream); } } } public void printStackTrace(PrintWriter writer) { if (cause == null) { super.printStackTrace(writer); } else { synchronized (writer) { writer.println(this); cause.printStackTrace(writer); } } } } mx4j-3.0.2/src/tools/mx4j/tools/config/ConfigurationLoader.java100644 0 0 10432 10513545721 21567 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.config; import java.io.Reader; import java.util.ArrayList; import java.util.List; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * @version $Revision: 1.3 $ */ public class ConfigurationLoader implements ConfigurationLoaderMBean, MBeanRegistration { private MBeanServer server; private ConfigurationBuilder builder; private ConfigurationBuilder.Node root; public ConfigurationLoader() { this(null, new DefaultConfigurationBuilder()); } public ConfigurationLoader(ConfigurationBuilder builder) { this(null, builder); } public ConfigurationLoader(MBeanServer server) { this(server, new DefaultConfigurationBuilder()); } public ConfigurationLoader(MBeanServer server, ConfigurationBuilder builder) { this.server = server; if (builder == null) throw new IllegalArgumentException("ConfigurationBuilder cannot be null"); this.builder = builder; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; return name; } public void postRegister(Boolean registered) { } public void preDeregister() throws Exception { } public void postDeregister() { } public void startup(Reader source) throws ConfigurationException { if (server == null) throw new ConfigurationException("Cannot startup the configuration, MBeanServer is not specified"); try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); InputSource src = new InputSource(source); Document document = documentBuilder.parse(src); Element xmlRoot = document.getDocumentElement(); root = builder.createConfigurationNode(xmlRoot); parse(xmlRoot, root); root.configure(server); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } public void shutdown() throws ConfigurationException { root.configure(null); } private void parse(Element xmlNode, ConfigurationBuilder.Node node) throws ConfigurationException { NamedNodeMap attributes = xmlNode.getAttributes(); if (attributes != null && attributes.getLength() > 0) { node.setAttributes(attributes); } List elements = getChildrenElements(xmlNode); if (elements != null) { for (int i = 0; i < elements.size(); ++i) { Element xmlChild = (Element)elements.get(i); ConfigurationBuilder.Node child = builder.createConfigurationNode(xmlChild); node.addChild(child); parse(xmlChild, child); } } String value = getNodeValue(xmlNode); node.setText(value); } private List getChildrenElements(Element xmlNode) { NodeList xmlChildren = xmlNode.getChildNodes(); if (xmlChildren == null) return null; ArrayList children = new ArrayList(); for (int i = 0; i < xmlChildren.getLength(); ++i) { Node xmlChild = xmlChildren.item(i); if (xmlChild.getNodeType() == Node.ELEMENT_NODE) children.add(xmlChild); } return children; } private String getNodeValue(Element xmlNode) { NodeList xmlChildren = xmlNode.getChildNodes(); if (xmlChildren == null) return null; for (int i = 0; i < xmlChildren.getLength(); ++i) { Node xmlChild = xmlChildren.item(i); if (xmlChild.getNodeType() == Node.TEXT_NODE) { return xmlChild.getNodeValue(); } } return null; } } mx4j-3.0.2/src/tools/mx4j/tools/config/ConfigurationLoaderMBean.java100644 0 0 771 10513545721 22437 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.config; import java.io.Reader; /** * @version $Revision: 1.3 $ */ public interface ConfigurationLoaderMBean { public void startup(Reader reader) throws ConfigurationException; public void shutdown() throws ConfigurationException; } mx4j-3.0.2/src/tools/mx4j/tools/config/DefaultConfigurationBuilder.java100644 0 0 60135 10513545721 23261 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.config; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Logger; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; /** * @version $Revision: 1.8 $ */ public class DefaultConfigurationBuilder implements ConfigurationBuilder { public static final String SHUTDOWN_COMMAND = "shutdown"; public static final String RESTART_COMMAND = "restart"; private static final String NULL = "null"; public Node createConfigurationNode(Element node) throws ConfigurationException { String loweredName = node.getNodeName().toLowerCase(); StringBuffer buffer = new StringBuffer(loweredName); buffer.replace(0, 1, loweredName.substring(0, 1).toUpperCase()); String className = getClass().getName() + "$" + buffer.toString(); try { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Creating configuration node " + className); return (ConfigurationBuilder.Node)getClass().getClassLoader().loadClass(className).newInstance(); } catch (Exception x) { throw new ConfigurationException(x); } } private static Logger getLogger() { return Log.getLogger(DefaultConfigurationBuilder.class.getName()); } public abstract static class AbstractNode implements Node { private String text; private Node parent; private List children; public void setText(String text) { this.text = text; } public void setParent(Node parent) { this.parent = parent; } public void addChild(Node child) { if (children == null) children = new ArrayList(); child.setParent(this); children.add(child); } protected String getText() { return text; } public Node getParent() { return parent; } public List getChildren() { return children; } public void setAttributes(NamedNodeMap attributes) throws ConfigurationException { Logger logger = getLogger(); for (int i = 0; i < attributes.getLength(); ++i) { org.w3c.dom.Node attribute = attributes.item(i); String name = attribute.getNodeName(); String value = attribute.getNodeValue(); String setterName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); try { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Calling " + setterName + " with " + value + " on " + this); Method setter = getClass().getMethod(setterName, new Class[]{String.class}); setter.invoke(this, new java.lang.Object[]{value}); } catch (InvocationTargetException x) { throw new ConfigurationException(x.getTargetException()); } catch (Exception x) { throw new ConfigurationException(x); } } } } public static class Configuration extends AbstractNode implements ObjectsHolder, Runnable { private Map objects; private int port = -1; private MBeanServer server; private Thread thread; public void setPort(String portString) { this.port = Integer.parseInt(portString); } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { if (server != null) { this.server = server; return startup(server); } else { return shutdown(this.server); } } private java.lang.Object startup(MBeanServer server) throws ConfigurationException { Logger logger = getLogger(); List children = getChildren(); if (children != null) { for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); if (child instanceof DefaultConfigurationBuilder.Startup) child.configure(server); } } if (port > 0) { thread = new Thread(this, "Configuration Shutdown"); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Starting " + thread.getName() + " Thread on port " + port); thread.start(); } return null; } private java.lang.Object shutdown(MBeanServer server) throws ConfigurationException { Logger logger = getLogger(); List children = getChildren(); if (children != null) { for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); if (child instanceof DefaultConfigurationBuilder.Shutdown) child.configure(server); } } if (port > 0) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Stopping " + thread.getName() + " Thread on port " + port); thread.interrupt(); } return null; } public void run() { Logger logger = getLogger(); ServerSocket server = null; try { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Started " + thread.getName() + " Thread on port " + port); server = new ServerSocket(port, 50, InetAddress.getByName(null)); server.setSoTimeout(1000); byte[] buffer = new byte[64]; StringBuffer command = new StringBuffer(); while (!thread.isInterrupted()) { Socket client = null; try { client = server.accept(); } catch (InterruptedIOException x) { continue; } if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Client connected " + client); InputStream is = new BufferedInputStream(client.getInputStream()); command.setLength(0); int read = -1; while ((read = is.read(buffer)) >= 0) command.append(new String(buffer, 0, read)); String cmd = command.toString(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Got command '" + cmd + "'"); if (SHUTDOWN_COMMAND.equals(cmd)) { try { configure(null); break; } catch (ConfigurationException x) { if (logger.isEnabledFor(Logger.WARN)) logger.warn("Bad configuration for shutdown", x); } } } } catch (Exception x) { if (logger.isEnabledFor(Logger.INFO)) logger.info("Caught Exception in " + thread.getName() + " Thread, exiting", x); } finally { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Stopped " + thread.getName() + " Thread on port " + port); try { if (server != null) server.close(); } catch (IOException x) { } } } public java.lang.Object getObject(String key) { if (objects == null) return null; return objects.get(key); } public java.lang.Object putObject(String key, java.lang.Object value) { if (objects == null) objects = new HashMap(); return objects.put(key, value); } public boolean containsKey(String key) { if (objects == null) return false; return objects.containsKey(key); } } public static class Startup extends AbstractNode { public java.lang.Object configure(MBeanServer server) throws ConfigurationException { List children = getChildren(); if (children != null) { for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); child.configure(server); } } return null; } } public static class Shutdown extends AbstractNode { public java.lang.Object configure(MBeanServer server) throws ConfigurationException { List children = getChildren(); if (children != null) { for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); child.configure(server); } } return null; } } public static class Object extends AbstractNode { private String id; public void setObjectid(String id) { this.id = id; } public String getObjectid() { return id; } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { List children = getChildren(); java.lang.Object result = null; if (children != null && children.size() > 0) { Node child = (Node)children.get(0); result = child.configure(server); } putObject(this, id, result); return result; } } public static class New extends AbstractNode { private String classname; public void setClassname(String classname) { this.classname = classname; } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { try { Class cls = loadClass(classname); Constructor ctor = cls.getConstructor(getMethodSignature(this)); return ctor.newInstance(getMethodArguments(this, server)); } catch (InvocationTargetException x) { throw new ConfigurationException(x.getTargetException()); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } } public static class Arg extends AbstractNode { private static final String OBJECT_TYPE = "object"; private static final String STRING_TYPE = "string"; private static final String BOOLEAN_TYPE = "boolean"; private static final String BYTE_TYPE = "byte"; private static final String CHAR_TYPE = "char"; private static final String DOUBLE_TYPE = "double"; private static final String FLOAT_TYPE = "float"; private static final String INT_TYPE = "int"; private static final String LONG_TYPE = "long"; private static final String SHORT_TYPE = "short"; private String type; private String refobjectid; public void setType(String type) { this.type = type; } public void setRefobjectid(String refobjectid) { this.refobjectid = refobjectid; } public Class getJavaType() throws ConfigurationException { if (STRING_TYPE.equalsIgnoreCase(type)) return String.class; if (OBJECT_TYPE.equalsIgnoreCase(type)) return java.lang.Object.class; if (BOOLEAN_TYPE.equalsIgnoreCase(type)) return boolean.class; if (BYTE_TYPE.equalsIgnoreCase(type)) return byte.class; if (CHAR_TYPE.equalsIgnoreCase(type)) return char.class; if (DOUBLE_TYPE.equalsIgnoreCase(type)) return double.class; if (FLOAT_TYPE.equalsIgnoreCase(type)) return float.class; if (INT_TYPE.equalsIgnoreCase(type)) return int.class; if (LONG_TYPE.equalsIgnoreCase(type)) return long.class; if (SHORT_TYPE.equalsIgnoreCase(type)) return short.class; return loadClass(type); } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { if (refobjectid != null) return getObject(this, refobjectid); List children = getChildren(); if (children != null && children.size() > 0) { Node child = (Node)children.get(0); return child.configure(server); } String text = getText(); if (text == null || NULL.equals(text)) return null; if (STRING_TYPE.equalsIgnoreCase(type)) return text; if (OBJECT_TYPE.equalsIgnoreCase(type)) return text; if (BOOLEAN_TYPE.equalsIgnoreCase(type)) return Boolean.valueOf(text); if (BYTE_TYPE.equalsIgnoreCase(type)) return Byte.valueOf(text); if (CHAR_TYPE.equalsIgnoreCase(type)) return new Character(text.length() < 1 ? 0 : text.charAt(0)); if (DOUBLE_TYPE.equalsIgnoreCase(type)) return Double.valueOf(text); if (FLOAT_TYPE.equalsIgnoreCase(type)) return Float.valueOf(text); if (INT_TYPE.equalsIgnoreCase(type)) return Integer.valueOf(text); if (LONG_TYPE.equalsIgnoreCase(type)) return Long.valueOf(text); if (SHORT_TYPE.equalsIgnoreCase(type)) return Short.valueOf(text); try { Constructor ctor = getJavaType().getConstructor(new Class[]{String.class}); return ctor.newInstance(new java.lang.Object[]{text}); } catch (InvocationTargetException x) { throw new ConfigurationException(x.getTargetException()); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } } public static class Register extends AbstractNode { private ObjectName objectname; public void setObjectname(String name) throws MalformedObjectNameException { if (name != null && !NULL.equals(name)) this.objectname = ObjectName.getInstance(name); } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { List children = getChildren(); if (children != null && children.size() > 0) { Node child = (Node)children.get(0); try { return server.registerMBean(child.configure(server), objectname); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } return null; } } public static class Unregister extends AbstractNode { private ObjectName objectname; public void setObjectname(String name) throws MalformedObjectNameException { this.objectname = ObjectName.getInstance(name); } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { try { server.unregisterMBean(objectname); return null; } catch (Exception x) { throw new ConfigurationException(x); } } } public static class Create extends AbstractNode { private String classname; private ObjectName objectname; private String loadername; public void setClassname(String classname) { this.classname = classname; } public void setObjectname(String name) throws MalformedObjectNameException { if (name != null && !NULL.equals(name)) this.objectname = ObjectName.getInstance(name); } public void setLoadername(String name) throws MalformedObjectNameException { this.loadername = name; } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { try { if (loadername != null) { ObjectName loader = null; if (!NULL.equals(loadername)) loader = ObjectName.getInstance(loadername); return server.createMBean(classname, objectname, loader, getMethodArguments(this, server), getJMXMethodSignature(this)); } else { return server.createMBean(classname, objectname, getMethodArguments(this, server), getJMXMethodSignature(this)); } } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } } public static class Call extends AbstractNode { private String classname; private ObjectName objectname; private String refobjectid; private String method; private String operation; private String attribute; public void setClassname(String classname) { this.classname = classname; } public void setObjectname(String name) throws MalformedObjectNameException { if (name != null && !NULL.equals(name)) this.objectname = ObjectName.getInstance(name); } public void setRefobjectid(String refid) { this.refobjectid = refid; } public void setMethod(String method) { this.method = method; } public void setOperation(String operation) { this.operation = operation; } public void setAttribute(String attribute) { this.attribute = attribute; } public java.lang.Object configure(MBeanServer server) throws ConfigurationException { if (classname != null) { // Static call Class cls = loadClass(classname); try { Method mthd = cls.getMethod(method, getMethodSignature(this)); return mthd.invoke(null, getMethodArguments(this, server)); } catch (InvocationTargetException x) { throw new ConfigurationException(x.getTargetException()); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } else { if (objectname != null) { // JMX call if (operation != null) { try { return server.invoke(objectname, operation, getMethodArguments(this, server), getJMXMethodSignature(this)); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } else if (attribute != null) { try { List children = getChildren(); if (children == null || children.size() < 1) { return server.getAttribute(objectname, attribute); } else { java.lang.Object arg = getMethodArguments(this, server)[0]; server.setAttribute(objectname, new Attribute(attribute, arg)); return null; } } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } else { throw new ConfigurationException("Missing 'attribute' or 'operation' attribute in JMX call"); } } else { // Standard call java.lang.Object target = null; if (refobjectid != null) { target = getObject(this, refobjectid); if (target == null) throw new ConfigurationException("Could not find object with id " + refobjectid); try { Method mthd = target.getClass().getMethod(method, getMethodSignature(this)); return mthd.invoke(target, getMethodArguments(this, server)); } catch (InvocationTargetException x) { throw new ConfigurationException(x.getTargetException()); } catch (ConfigurationException x) { throw x; } catch (Exception x) { throw new ConfigurationException(x); } } else { throw new ConfigurationException("Missing 'refobjectid' attribute in call element"); } } } } } private static Class[] getMethodSignature(Node node) throws ConfigurationException { List children = node.getChildren(); if (children == null) return null; ArrayList signature = new ArrayList(); for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); if (child instanceof Arg) { Arg arg = (Arg)child; signature.add(arg.getJavaType()); } } return (Class[])signature.toArray(new Class[signature.size()]); } private static String[] getJMXMethodSignature(Node node) throws ConfigurationException { Class[] signature = getMethodSignature(node); if (signature == null) return null; ArrayList jmxSignature = new ArrayList(); for (int i = 0; i < signature.length; ++i) { jmxSignature.add(signature[i].getName()); } return (String[])jmxSignature.toArray(new String[jmxSignature.size()]); } private static java.lang.Object[] getMethodArguments(Node node, MBeanServer server) throws ConfigurationException { List children = node.getChildren(); if (children == null) return null; ArrayList arguments = new ArrayList(); for (int i = 0; i < children.size(); ++i) { Node child = (Node)children.get(i); if (child instanceof Arg) { Arg arg = (Arg)child; arguments.add(arg.configure(server)); } } return arguments.toArray(); } private static Class loadClass(String className) throws ConfigurationException { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException x) { throw new ConfigurationException(x); } } private static java.lang.Object getObject(Node node, String key) { while (node != null) { if (node instanceof ObjectsHolder) { ObjectsHolder holder = (ObjectsHolder)node; if (holder.containsKey(key)) return holder.getObject(key); } node = node.getParent(); } return null; } private static void putObject(Node node, String key, java.lang.Object value) { while (node != null) { if (node instanceof ObjectsHolder) { ObjectsHolder holder = (ObjectsHolder)node; holder.putObject(key, value); } node = node.getParent(); } } } mx4j-3.0.2/src/tools/mx4j/tools/i18n/I18NStandardMBean.java100644 0 0 72227 10513545721 20220 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.i18n; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import java.util.StringTokenizer; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.NotCompliantMBeanException; import javax.management.StandardMBean; /** * An extension of StandardMBean to support internationalization.

*

* The I18N information is taken from a property bundle named MyImplMBeanResources * where "MyImpl" is the fully qualified class implementing the MBean.

* These bundles are nested following the class hierachy of the implementation * class. This means that a superclass of the real implementing class can * define the resource bundle for the common attributes and operations. *

* The resource bundle naming rules defined by {@link java.util.ResourceBundle} * are used; in particular :

    *
  • If a class called MyPackage.MyImplMBeanResources_localInfo exists it is used (programmatic methd) *
  • Otherwise the file called MyPackage.MyImplMBeanResources_localInfo.properties is used. *
*

* localInfo consists of one or more sections of "language_country_variant" (eg en_GB or fr_FR). *

* The locale to be used is determined by one of the following mechanisms (in this order)

    *
  • The locale object explicitly passed to the constructor (if not null) *
  • The static method {@link #setDefaultLocale} *
  • The system property "mx4j.descriptionLocale" *
  • The current system default locale *
*

* The bundle should contain keys as described below : *

Global bean description

* The global bean description is given by the single key "descr":
 * descr=The MBean Description
 * 
*

*

Attributes

* Attribute desciptions are given by keys of form "attr.Name" where Name * is the attribute name (the method name minus the get/set prefix) :
 * attr.Counter=The counter
 * 
*

*

Constructors

*

Non ambiguous case

* All constructors having a different number of arguments may be described in this way:
 * cons.N=desciption of constructor N
 * cons.N.param.1=Description of first parameter of constructor N
 * cons.N.paramName.1=paramName1
 * cons.N.param.2=Description of first parameter of constructor N
 * cons.N.paramName.2=paramName2
 * 
* Where N is a sequential number starting at one. *

*

Ambiguous case

* Where several constructors exist with the same number of arguments an explicit * signature must be given. The signature is a comma separated list of class descriptions * (as returned by {@link java.lang.Class#getName} and has the key cons.N.sig :
 * cons.N.sig=int,java.lang.Object
 * cons.N.param.1=The int parameter
 * cons.N.param.2=The Object parameter
 * 
*

*

Operations

*

No overloading

* When no overloaded versions of an operation exist (same method name but different parameters) * the simplest case shown below can be used :
 * op.operationName=The description
 * op.operationName.param.1=The first parameter
 * op.operationName.paramName.1=param1
 * 
*

*

Non ambiguous overloading case

* When operation overloading is used but the overloaded versions differ in the number * of parameters the format below can be used :
 * op.operationName.1=The first version of operationName
 * op.operationName.1.param.1=parameter for first version
 * op.operationName.1.paramName.1=param1
 * op.operationName.2=The second version of operationName
 * op.operationName.2.paramName.1=param1
 * op.operationName.2.param.1=first parameter for second version
 * op.operationName.2.param.2=second parameter for second version
 * op.operationName.2.paramName.2=param2
 * 
*

*

Ambiguous overloading case

* When operations with the same name have the same number of arguments an explicit * signature must be used :
 * op.operationName.1.sig=int
 * op.operationName.1=The first version of operationName (takes int)
 * op.operationName.1.param.1=parameter for first version
 * op.operationName.1.paramName.1=param1
 * op.operationName.2.sig=java.lang.Object
 * op.operationName.2=The second version of operationName (take Object)
 * op.operationName.2.paramName.1=param1
 * op.operationName.2.param.1=first parameter for second version
 * 
*

*

Restrictions

* Parameter names must only contain characters allowed in a Java identifier * (in particular spaces are not allowed). This is required by the JMX specifications. * No such restrictions exist for the other descriptions. *

*

Behaviour with missing data

* If no resource bunde exists for the MBean a java.util.MissingResourceException * will be thrown by the constructor.

*

* If the resouce bundle is found but the bean description, constructor description or * parameter name is missing the String "??(key)" will be returned instead (eg * "??(op.myOperation)".

*

* If a paramName key is missing (for constructor or operation) the version normally * given by StandardMBean is used (generally "pN").

*

* If a non ambiguous description cannot be determined the fixed (non translatable) * descriptions "ambiguous constructor", "parameter for ambiguous constructor", * "ambiguous operation", "parameter for ambiguous operation" are returned. */ public class I18NStandardMBean extends StandardMBean { private static final String IDPROP_DEFAULT_LOCALE = "mx4j.descriptionLocale"; private static final String RESOURCE_SUFFIX = "MBeanResources"; private static final String KEY_DESCR = "descr"; private static final String KEY_CONS = "cons"; private static final String KEY_ATTR = "attr"; private static final String KEY_OP = "op"; private static final String KEY_PARAM = "param"; private static final String KEY_PARAM_NAME = "paramName"; private static final String KEY_SIG = "sig"; private static Locale g_defaultLocale = null; private NestedResourceBundle m_bundle; private Map m_mapConstructorSignatureToResourceIndex; private Map m_mapConstructorParamCountToResourceIndex; private Map m_mapConstructorToResourceIndex = new HashMap(); private Map m_mapOperationNameToSignatures = new HashMap(); private Map m_mapOperationNameToParamCounts = new HashMap(); private Set m_setAmbiguousConstructors = new HashSet(); private Set m_setAmbiguousOperations = new HashSet(); /** * Makes an I18NStandardMBean for the default locale with a separate implementation class. * * @see javax.management.StandardMBean#StandardMBean(java.lang.Object, java.lang.Class) */ public I18NStandardMBean(Object implementation, Class mbeanInterface) throws NotCompliantMBeanException { this(implementation, mbeanInterface, null); } /** * Makes an I18NStandardMBean for the given locale with a separate implementation class. * * @see javax.management.StandardMBean#StandardMBean(java.lang.Object, java.lang.Class) */ public I18NStandardMBean(Object implementation, Class mbeanInterface, Locale locale) throws NotCompliantMBeanException { super(implementation, mbeanInterface); setupBundle(implementation, locale); } /** * Makes a I18NStandardMBean for the default locale implemented by a subclass. * * @see javax.management.StandardMBean#StandardMBean(java.lang.Class) */ protected I18NStandardMBean(Class mbeanInterface) throws NotCompliantMBeanException { super(mbeanInterface); setupBundle(this, null); } /** * Makes a I18NStandardMBean for the given locale implemented by a subclass. * * @see javax.management.StandardMBean#StandardMBean(java.lang.Class) */ protected I18NStandardMBean(Class mbeanInterface, Locale locale) throws NotCompliantMBeanException { super(mbeanInterface); setupBundle(this, locale); } private void setupBundle(Object implementation, Locale locale) { // calculate the effective locale: if (locale == null) { locale = g_defaultLocale; } if (locale == null) { locale = getLocaleFromSystemProperties(); } // create bundle NestedResourceBundle cur = null; MissingResourceException ex = null; for (Class c = implementation.getClass(); c != null; c = c.getSuperclass()) { String bundleName = c.getName() + RESOURCE_SUFFIX; try { ResourceBundle b = ResourceBundle.getBundle(bundleName, locale); NestedResourceBundle nb = new NestedResourceBundle(b); if (cur == null) { m_bundle = nb; } else { cur.setParent(nb); } cur = nb; } catch (MissingResourceException e) { if (m_bundle == null) ex = e; // save first exception } } if (m_bundle == null) { ex.fillInStackTrace(); throw ex; } } // Obtain the default locale from system properties private Locale getLocaleFromSystemProperties() { Locale locale = Locale.getDefault(); String stdLocale = System.getProperty(IDPROP_DEFAULT_LOCALE); if (stdLocale != null && stdLocale.length() > 0) { StringTokenizer st = new StringTokenizer(stdLocale, "_"); switch (st.countTokens()) { case 2: locale = new Locale(st.nextToken(), st.nextToken()); break; case 3: locale = new Locale(st.nextToken(), st.nextToken(), st.nextToken()); break; default : throw new IllegalArgumentException("Invalid locale in " + IDPROP_DEFAULT_LOCALE + ":" + stdLocale); } } return locale; } /** * Set the locale which will be used for future I18NStandardMBeans.

* The locale specified can be overridden on a per class basis via the * constructors but overrides other means of setting the Locale (system properties).

*

* Changing the locale has no effect on already constructed MBeans. * * @param locale the Locale for future MBeans */ public static void setDefaultLocale(Locale locale) { g_defaultLocale = locale; } /** * Initialise internal data structures.

* This method is always called first during getMBeanInfo processing. * We use this to avoid keeping all our internal Maps in memory too long. * * @see javax.management.StandardMBean#getCachedMBeanInfo */ protected MBeanInfo getCachedMBeanInfo() { MBeanInfo info = super.getCachedMBeanInfo(); if (info == null) { // only setup if we are going to be called! m_mapConstructorToResourceIndex = new HashMap(); m_mapOperationNameToSignatures = new HashMap(); m_mapOperationNameToParamCounts = new HashMap(); m_setAmbiguousConstructors = new HashSet(); m_setAmbiguousOperations = new HashSet(); m_mapConstructorSignatureToResourceIndex = getSignatureMap(KEY_CONS); m_mapConstructorParamCountToResourceIndex = getParamCountMap(KEY_CONS); } return info; } /** * Once the MBeanInfo has been obtained discard our caches. * * @see javax.management.StandardMBean#cacheMBeanInfo(javax.management.MBeanInfo) */ protected void cacheMBeanInfo(MBeanInfo info) { super.cacheMBeanInfo(info); m_mapConstructorToResourceIndex = null; m_mapOperationNameToSignatures = null; m_mapOperationNameToParamCounts = null; m_setAmbiguousConstructors = null; m_setAmbiguousOperations = null; m_mapConstructorSignatureToResourceIndex = null; m_mapConstructorParamCountToResourceIndex = null; } /* * Initialises internal structures based on available constructors.

* Return value is supplied by superclass.

* * For all the constructors :

    *
  • Create a map of MBeanConstructorInfo=>resource bundle index for explicit signatures *
  • Create list of "ambiguous" constructors based on number of arguments. *
* Note we assume that this metthod will be called BEFORE the constructor related * getDesciption methods. The spec does not say anything about this. */ protected MBeanConstructorInfo[] getConstructors(MBeanConstructorInfo[] cstrs, Object impl) { Map argCountToCstr = new HashMap(); for (int i = 0; i < cstrs.length; i++) { MBeanConstructorInfo ci = cstrs[i]; MBeanParameterInfo[] params = ci.getSignature(); // update potentially ambiguous constructors (same number of arguments) Integer count = new Integer(params.length); Object first = argCountToCstr.get(count); if (first != null) { // already have a constructor with this number of args m_setAmbiguousConstructors.add(first); // Set so no duplication m_setAmbiguousConstructors.add(ci); // this one is ambiguous too } else { argCountToCstr.put(count, ci); } // update signature=>resource index mapping (if explicit signature provided) String sig = makeSignatureString(params); Integer idx = (Integer)m_mapConstructorSignatureToResourceIndex.get(sig); if (idx != null) { m_mapConstructorToResourceIndex.put(ci, idx); } } return super.getConstructors(cstrs, impl); } /** * Obtain global description for MBean.

* Taken from "descr" key in resource bundle.

*

* Also performs internal initialisations requiring the MBeanInfo obtained * by introspection. Therefore the superclass must call this method BEFORE * the other hooks. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanInfo) */ protected String getDescription(MBeanInfo info) { findAmbiguousOperations(info); // assume called first return getValueFromBundle(KEY_DESCR); } /** * Obtain the constructor description.

* Taken from "cons.N" key in resource bundle.

*

* Maybe "ambiguous constructor" if correct index cannot be determined by * an explicit signature or parameter counts. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanConstructorInfo) */ protected String getDescription(MBeanConstructorInfo cstr) { int idx = getConstructorIndex(cstr); if (idx < 1) { return "ambiguous constructor"; } return getValueFromBundle(KEY_CONS + "." + idx); } /** * Obtain the constructor parameter description.

* Taken from "cons.N.param.seq" key in resource bundle.

*

* Maybe "parameter for ambiguous constructor" if correct index cannot be determined by * an explicit signature or parameter counts. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanConstructorInfo, javax.management.MBeanParameterInfo, int) */ protected String getDescription(MBeanConstructorInfo cstr, MBeanParameterInfo param, int seq) { int idx = getConstructorIndex(cstr); if (idx < 1) { return "parameter for ambiguous constructor"; } return getValueFromBundle(KEY_CONS + "." + idx + ".param." + (seq + 1)); } /** * Obtain constructor parameter name.

* Taken from "cons.N.paramName.seq" key in resource bundle.

*

* If this key does not exist or if the correct index N cannot be determined by * an explicit signature or parameter counts the superclass method is called. * * @see javax.management.StandardMBean#getParameterName(javax.management.MBeanConstructorInfo, javax.management.MBeanParameterInfo, int) */ protected String getParameterName(MBeanConstructorInfo cstr, MBeanParameterInfo param, int seq) { int idx = getConstructorIndex(cstr); String name = null; if (idx >= 1) { name = getValueOrNullFromBundle(KEY_CONS + "." + idx + ".paramName." + (seq + 1)); } if (name == null) { name = super.getParameterName(cstr, param, seq); } return name; } /** * Obtain the attribute description.

* Taken from the "attr.attributeName" key in resource bundle. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanAttributeInfo) */ protected String getDescription(MBeanAttributeInfo attr) { return getValueFromBundle(KEY_ATTR + "." + attr.getName()); } /** * Obtain the operation description.

* Taken from the "op.operationName.N" or the "op.operationName" * key in the resource bundle.

* May be "ambiguous operation" if the correct key cannot be determined by * signature or parameter counts. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanOperationInfo) */ protected String getDescription(MBeanOperationInfo op) { try { return getValueFromBundle(getOperationKey(op)); } catch (IllegalStateException e) { return e.getMessage(); } } /** * Obtain the operation parameter description.

* Taken from the "op.operationName.N.param.M" or the "op.operationName.param" * key in the resource bundle.

* May be "parameter for ambiguous operation" if the correct key cannot be determined by * signature or parameter counts. * * @see javax.management.StandardMBean#getDescription(javax.management.MBeanOperationInfo, javax.management.MBeanParameterInfo, int) */ protected String getDescription(MBeanOperationInfo op, MBeanParameterInfo param, int seq) { try { return getValueFromBundle(getOperationKey(op) + "." + KEY_PARAM + "." + (seq + 1)); } catch (IllegalStateException e) { return "parameter for " + e.getMessage(); } } /** * Obtain operation parameter name.

* Taken from the "op.operationName.N.paramName.M" or the "op.operationName.paramName.M" * key in the resource bundle.

*

* If this key does not exist or if the correct index N cannot be determined by * an explicit signature or parameter counts the superclass method is called. * * @see javax.management.StandardMBean#getParameterName(javax.management.MBeanOperationInfo, javax.management.MBeanParameterInfo, int) */ protected String getParameterName(MBeanOperationInfo op, MBeanParameterInfo param, int seq) { String name = null; try { name = getValueOrNullFromBundle(getOperationKey(op) + "." + KEY_PARAM_NAME + "." + (seq + 1)); } catch (IllegalStateException e) { } if (name == null) { name = super.getParameterName(op, param, seq); } return name; } /* * Obtain 1 based index of constructor in resource bundle. * First look for a signature match (.sig in bundle) * If not found and constuctor is potentially ambiguous (another constructor with the same number of params exists) return -1 * If not found try a parameter number match. * If parameter number match is ambiguous return -1 * If no match found return 0 */ private int getConstructorIndex(MBeanConstructorInfo cons) { Integer idx = (Integer)m_mapConstructorToResourceIndex.get(cons); if (idx != null) { return idx.intValue(); } // do multiple constuctors with the same arg count exist? if (m_setAmbiguousConstructors.contains(cons)) return -1; // no signature match - try using parameter count int nbParams = cons.getSignature().length; idx = (Integer)m_mapConstructorParamCountToResourceIndex.get(new Integer(nbParams)); if (idx != null) { return idx.intValue(); } return 0; } /* * Obtain the root bundle key for the given operation. * If a matching signature entry exists for this operation * is of form : "op.operationName.N" * otherwise it is of form "op.operationName" * where N is the index of the matching signature. * If the operation is ambiguous throw an IllegalStateException. */ private String getOperationKey(MBeanOperationInfo op) { String operationName = op.getName(); // lookup by signature Map sigMap = getOperationSignatureMap(operationName); MBeanParameterInfo[] params = op.getSignature(); String sig = makeSignatureString(params); Integer idx = (Integer)sigMap.get(sig); StringBuffer sbRet = new StringBuffer(KEY_OP + "."); sbRet.append(operationName); if (idx == null) { if (m_setAmbiguousOperations.contains(op)) { throw new IllegalStateException("ambiguous operation"); } // no direct signature mapping, try matching by parameter counts Map countMap = getOperationParamCountMap(operationName); idx = (Integer)countMap.get(new Integer(params.length)); if (idx != null && idx.intValue() < 1) { throw new IllegalStateException("ambiguous operation"); } } if (idx != null) { sbRet.append("."); sbRet.append(idx); } return sbRet.toString(); } /* * Initialise the set m_setAmbiguousOperations with those operations * that have the same name and same number of parameters. */ private void findAmbiguousOperations(MBeanInfo info) { // obtain potentially ambiguous operations (same name, same number parameters) MBeanOperationInfo[] ops = info.getOperations(); Map mapNameToArgCountMap = new HashMap(); for (int i = 0; i < ops.length; i++) { MBeanOperationInfo op = ops[i]; String name = op.getName(); Map argCountToOp = (Map)mapNameToArgCountMap.get(name); if (argCountToOp == null) { argCountToOp = new HashMap(); mapNameToArgCountMap.put(name, argCountToOp); } Integer count = new Integer(op.getSignature().length); Object first = argCountToOp.get(count); if (first != null) { // already have an operation with this number of args m_setAmbiguousOperations.add(first); // Set so no duplication m_setAmbiguousOperations.add(op); // this one is ambiguous too } else { argCountToOp.put(count, op); } } } /* * Obtain Map of operation signature=>resource bundle index. * Use lazy instantiation and caching. * The entries in resource bundle have form : * op.operationName.1.sig=xxx * op.operationName.2.sig=yyy * * The above example would give xxx=>1, yyy=>2 */ private Map getOperationSignatureMap(String operationName) { // look up in cache Map m = (Map)m_mapOperationNameToSignatures.get(operationName); if (m != null) { return m; } // construct map m = getSignatureMap(KEY_OP + "." + operationName); m_mapOperationNameToSignatures.put(operationName, m); // cache return m; } /* * Obtain Map of parameter count =>resource bundle index for the given operation * Use lazy instantiation and caching. */ private Map getOperationParamCountMap(String operationName) { // look up in cache Map m = (Map)m_mapOperationNameToParamCounts.get(operationName); if (m != null) { return m; } // construct map m = getParamCountMap(KEY_OP + "." + operationName); m_mapOperationNameToParamCounts.put(operationName, m); // cache return m; } /* * Obtain a Map of parameter count => Integer index from resource bundle * The entries in resource bundle have form : * prefix.1.param.1=xxx * prefix.1.param.2=yyy * prefix.2.param.1=zzz * * The above example would give 2=>1, 1=>2 (index1 has 2 parameter, index 2 has 1 parameter) * If there are duplicate parameter counts map to -1 */ private Map getParamCountMap(String prefix) { int nb; Map m = new HashMap(); for (int i = 1; ; i++) { String key = prefix + "." + i; String sig = getValueOrNullFromBundle(key); if (sig == null) { break; } nb = 0; for (int j = 1; ; j++) { key = prefix + "." + i + "." + KEY_PARAM + "." + j; if (getValueOrNullFromBundle(key) != null) { nb = j; } else { break; } } Integer nbObj = new Integer(nb); int idx = m.containsKey(nbObj) ? -1 : i; m.put(nbObj, new Integer(idx)); } return m; } /* * Create a map of signature string=>Integer index from resource bundle. * The entries in resource bundle have form : * prefix.1.sig=signature1 * prefix.2.sig=signature2 * .. * The list stops at the first non existant index. * The signatures are comma separated types of the form returned by * Class.getName(), eg: java.lang.Object,Z,[Z; */ private Map getSignatureMap(String prefix) { Map m = new HashMap(); for (int i = 1; ; i++) { String key = prefix + "." + i + "." + KEY_SIG; String sig = getValueOrNullFromBundle(key); if (sig == null) { break; } m.put(sig, new Integer(i)); } return m; } // create a comma separated list of signatures. private String makeSignatureString(MBeanParameterInfo[] params) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < params.length; i++) { if (i > 0) { sb.append(","); } sb.append(params[i].getType()); } return sb.toString(); } private String getValueFromBundle(String key) { String value; try { value = m_bundle.getString(key); } catch (MissingResourceException e) { value = "??(" + key + ")"; } return value; } private String getValueOrNullFromBundle(String key) { String value = null; try { value = m_bundle.getString(key); } catch (MissingResourceException e) { } return value; } private static class NestedResourceBundle extends ResourceBundle { private ResourceBundle _impl; NestedResourceBundle(ResourceBundle impl) { _impl = impl; } void setParent(NestedResourceBundle parent) { super.setParent(parent); } /* (non-Javadoc) * @see java.util.ResourceBundle#handleGetObject(java.lang.String) */ protected Object handleGetObject(String key) { try { return _impl.getString(key); } catch (MissingResourceException e) { return null; // Resource bundle will ask parent } } /* (non-Javadoc) * @see java.util.ResourceBundle#getKeys() */ public Enumeration getKeys() { // obtain union of all keys in bundle hierachy (no doublons) HashSet hs = new HashSet(); addEnumeration(hs, _impl.getKeys()); if (parent != null) { addEnumeration(hs, parent.getKeys()); } return Collections.enumeration(hs); } private void addEnumeration(Collection col, Enumeration e) { while (e.hasMoreElements()) { col.add(e.nextElement()); } } } } mx4j-3.0.2/src/tools/mx4j/tools/jython/JythonRunner.java100644 0 0 21070 10513545721 20344 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.jython; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Logger; import org.python.core.Py; import org.python.core.PyCode; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; /** * This MBean enables you to run scripts written in jython. Scripts can be run * using the managed operation runScript or by listening notifcations from * another MBean. To us it you need to install jython 2.1 or higher from * <a href="http://www.jython.org">here</a> *

* If you want to use a jython library remember to add the jython jar to the * classpath in the right location or modify the python.path address *

* The scripts have always the "server" embedded variable which points * to the current server. It also automatically import some JMX modules as: *

*

    *
  • from javax.management import * *
  • from javax.management.loading import * *
* * @version $Revision: 1.9 $ */ public class JythonRunner implements JythonRunnerMBean, NotificationListener, MBeanRegistration { private MBeanServer server = null; private ObjectName targetMBeanName, objectName; private String notificationName; private boolean useText = true; private boolean useCache = false; private String scriptText; private URL scriptFile; private PyCode cache = null; private static PythonInterpreter interpreter; public void handleNotification(Notification notification, Object handback) { if (notificationName != null && !notification.getType().equals(notificationName)) return; Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification " + notification + " hit, sending message"); runScript(); } private Logger getLogger() { return Log.getLogger(getClass().getName()); } /** * Executes a given script. If useText is true the text passed will be run as a script * otherwise the script will be loaded from the URL an executed */ public void runScript() { PythonInterpreter interp = getPythonInterpreter(); interp.set("server", server); String script = null; if (useText) { script = scriptText; } else { try { script = loadStream(scriptFile.openStream()); } catch (IOException e) { Logger log = getLogger(); log.error("Exception during url opening", e); } } interp.exec(script); } public static PythonInterpreter getPythonInterpreter() { if (interpreter == null) { interpreter = new PythonInterpreter(); PySystemState sys = Py.getSystemState(); sys.add_package("javax.management"); sys.add_package("javax.management.loading"); sys.add_package("javax.management.modelmbean"); sys.add_package("javax.management.monitor"); sys.add_package("javax.management.openmbean"); sys.add_package("javax.management.remote"); sys.add_package("javax.management.remote.rmi"); sys.add_package("javax.management.relation"); sys.add_package("javax.management.timer"); try { String script = loadStream(JythonRunner.class.getClassLoader().getResourceAsStream("mx4j/tools/jython/jmxUtils.py")); interpreter.exec(script); } catch (IOException e) { e.printStackTrace(); } } return interpreter; } protected static String loadStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); buffer.append("\n"); } return buffer.toString(); } /** * Gets the specific notification type being listened */ public String getNotificationType() { return notificationName; } /** * Sets the notification being listed. If null any notification will trigger * the execution of the script. Otherwise only notifications matching notificationName * will trigger it */ public void setNotificationType(String notificationName) { this.notificationName = notificationName; } /** * Sets the object being observed by this MBean. The MBean will register * itself as a listener of targetMBeanName */ public void setObservedObject(ObjectName targetMBeanName) { this.targetMBeanName = targetMBeanName; registerListener(); } /** * Gets the object being observed by this MBean */ public ObjectName getObservedObject() { return targetMBeanName; } /** * Indicates wether to use the script given in the ScripText variable or * the one given in the script File. */ public boolean getUseText() { return this.useText; } /** * Sets the content of the script. If you want to use a file, use ScriptFile * instead. */ public void setScript(String text) { this.scriptText = text; this.useText = true; } /** * Returns the script as text. */ public String getScript() { return this.scriptText; } /** * Returns the URL pointing to the script source */ public URL getScriptURL() { return scriptFile; } /** * Sets the script source as URL. If the cache script variable is true * the file will be loaded only once, otherwise everytime the script is * executed */ public void setScriptURL(URL file) { this.scriptFile = file; this.useText = false; } /** * Returns whether the script should be kept in the cache. If true, no further * attempts to read the script will be done afterwards. By default is false */ public boolean getCacheScript() { return useCache; } /** * Sets whether the script should be kept in the cache. If true, no further * attempts to read the script will be done afterwards. By default is false */ public void setCacheScript(boolean useCache) { this.useCache = useCache; } /** * Gathers some basic data */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { this.server = server; this.objectName = name; return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws java.lang.Exception { unregisterListener(); } public void postDeregister() { } protected void registerListener() { try { if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster")) { server.addNotificationListener(targetMBeanName, this, new MessageFilter(), null); } } catch (InstanceNotFoundException e) { Logger log = getLogger(); log.error("Exception during notification registration", e); } } protected void unregisterListener() { try { if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster")) { server.removeNotificationListener(targetMBeanName, this); } } catch (InstanceNotFoundException e) { Logger log = getLogger(); log.error("Exception during notification unregistration", e); } catch (ListenerNotFoundException e) { } } private class MessageFilter implements NotificationFilter { public boolean isNotificationEnabled(Notification notification) { return notificationName == null || (notification.getType() != null && notification.getType().equals(notificationName)); } } } mx4j-3.0.2/src/tools/mx4j/tools/jython/JythonRunnerMBean.java100644 0 0 4645 10513545721 21240 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.jython; import java.net.URL; import javax.management.ObjectName; /** * Management interface for the JythonRunner MBean. * * @version $Revision: 1.6 $ */ public interface JythonRunnerMBean { /** * Executes a given script. * If useText is true the text passed will be run as a script otherwise * the script will be loaded from the URL an executed */ public void runScript(); /** * Gets the specific notification type being listened */ public String getNotificationType(); /** * Sets the notification type being listened. * If null any notification will trigger the execution of the script. * Otherwise only notifications matching notificationName will trigger it */ public void setNotificationType(String notificationName); /** * Sets the object being observed by this MBean. * The MBean will register itself as a listener of targetMBeanName */ public void setObservedObject(ObjectName targetMBeanName); /** * Gets the object being observed by this MBean */ public ObjectName getObservedObject(); /** * Indicates wether to use the script given in the ScripText variable or the one given in the script File. */ public boolean getUseText(); /** * Sets the content of the script. If you want to use a file, use ScriptFile instead. */ public void setScript(String text); /** * Returns the script as text. */ public String getScript(); /** * Returns the URL pointing to the script source */ public URL getScriptURL(); /** * Sets the script source as URL. If the cache script variable is true the file will be loaded only once, otherwise everytime the script is executed */ public void setScriptURL(URL file); /** * Returns whether the script should be kept in the cache. * If true, no further attempts to read the script will be done afterwards. By default is false */ public boolean getCacheScript(); /** * Sets whether the script should be kept in the cache. If true, no further attempts to read the script will be done afterwards. By default is false */ public void setCacheScript(boolean useCache); } mx4j-3.0.2/src/tools/mx4j/tools/jython/JythonRunnerMBeanDescription.java100644 0 0 3276 10513545721 23443 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.jython; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Management interface descriptions for the JythonRunner MBean. * * @version $Revision: 1.7 $ */ public class JythonRunnerMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "Runs a jython script for management purposes"; } public String getAttributeDescription(String attribute) { if (attribute.equals("NotificationType")) { return "The Notification type that triggers the script execution"; } if (attribute.equals("ObservedObject")) { return "The ObjectName being observed"; } if (attribute.equals("UseText")) { return "Indicates wether a text based or file based script is used"; } if (attribute.equals("Script")) { return "The script text"; } if (attribute.equals("ScriptURL")) { return "The script's URL"; } if (attribute.equals("CacheScript")) { return "Indicates whether the script is read every time or only once"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("runScript")) { return "Runs the jython script"; } return super.getOperationDescription(operation); } } mx4j-3.0.2/src/tools/mx4j/tools/jython/jmxUtils.py100644 0 0 12353 10513545721 17231 0ustar 0 0 """ Copyright (C) MX4J. All rights reserved. This software is distributed under the terms of the MX4J License version 1.0. See the terms of the MX4J License in the documentation provided with this software. author Carlos Quiroz version $Revision: 1.1 $ Adapted by Martin Fuzzey for testing use. For this we need to communicate with a REMOTE server (the orignal code always ran in the same process as the JMX server and was intended to be used as helpers for python scripts in the python MBean """ import sys,java sys.add_package("javax.management") sys.add_package("javax.management.loading"); sys.add_package("javax.management.modelmbean"); sys.add_package("javax.management.monitor"); sys.add_package("javax.management.openmbean"); sys.add_package("javax.management.relation"); sys.add_package("javax.management.remote"); sys.add_package("javax.management.remote.rmi"); sys.add_package("javax.management.timer"); from javax.management import * from javax.management.loading import * from javax.management.modelmbean import * from javax.management.monitor import * from javax.management.openmbean import * from javax.management.relation import * from javax.management.remote import * from javax.management.remote.rmi import * from javax.management.timer import * class ServerConnection: def __init__(self, connection) : self.server = connection def createProxy(self, objectname) : """ Creates a proxy for the named MBean in this server. The objectname may either be an instance of javax.management.ObjectName or a string The MBeans attributes and methods may be then accessed directly as in : proxy = server.createProxy("myDomain:myType=toto") print "val=",proxy.val proxy.doSomething() """ if (isinstance(objectname, ObjectName) == 0) : objectname = ObjectName(objectname) return Proxy(self.server, objectname) def getMBeanNames(self, query="*:*"): """ Returns a list of all the available MBeans in the server. The optional query parameter will filter the list by objectname """ names = [] for n in self.server.queryNames(ObjectName(query), None) : names.append(n) ;# To python collection return names def getInstanceNames(self, classname, query="*:*"): """ Returns a list of all the available MBeans in the server which are instances of classname. It accepts a query parameter to filter by objectname """ return [x for x in self.getMBeanNames(query) if self.server.isInstanceOf(x, classname)] class OperationProxy: def __init__(self, server, objectname, opInfo): self.server = server self.objectname = objectname self.operation = opInfo.name self.sig = [] for s in opInfo.signature : self.sig.append(s.type) def invoke(self, *args): if (len(args) != len(self.sig)) : raise "argument list / sig mismatch" + str(args) + str(self.sig) # Manually map Boolean nargs = [] for i in range(len(args)) : arg = args[i] if (self.sig[i] == "boolean") : arg = java.lang.Boolean(arg) nargs.append(arg) return self.server.invoke(self.objectname, self.operation, nargs, self.sig) class Proxy: def __init__(self, server, objectname): # Need the syntax below to avoid infinite recursion betweed setattr + getattr self.__dict__["server"] = server self.__dict__["objectname"] = objectname info = self.server.getMBeanInfo(objectname) for o in info.operations: self.__dict__[o.name] = OperationProxy(self.server, objectname, o).invoke # print "op:", o.name def __getattr__(self, name): return self.server.getAttribute(self.objectname, name) def __setattr__(self, name, value): from javax.management import Attribute return self.server.setAttribute(self.objectname, Attribute(name, value)) def __repr__(self): return "Proxy of MBean: %s " % (self.__dict__["objectname"], ) def invoke(self, name, arguments=None, types=None): return self.server.invoke(self.objectname, name, arguments, types) def addListener(self, l, filter=None, handback=None) : self.server.addNotificationListener(self.objectname, l, filter, handback) class proxy (Proxy): # For backwards compatibility pass def mbeans(query=None): """ Returns a list of all the available MBeans in the server. The optional query parameter will filter the list by objectname """ if query: return server.queryMBeans(ObjectName(query), None) else: return server.queryMBeans(None, None) def instances(classname, query=None): """ Returns a list of all the available MBeans in the server which are instances of classname. It accepts a query parameter to filter by objectname """ return [x for x in mbeans(query) if server.isInstanceOf(x.getObjectName(),classname)] mx4j-3.0.2/src/tools/mx4j/tools/jython/mx4j.py100644 0 0 3557 10513545721 16262 0ustar 0 0 """ Copyright (C) MX4J. All rights reserved. This software is distributed under the terms of the MX4J License version 1.0. See the terms of the MX4J License in the documentation provided with this software. author Carlos Quiroz version $Revision: 1.3 $ """ from javax.management import * from javax.management.monitor import * from javax.management.timer import * from javax.management.loading import * from javax.management.relation import * from javax.management.modelmbean import * class OperationProxy: def __init__(self, objectname, operation): self.objectname = objectname self.operation = operation def invoke(self, **kw): server.invoke(self.objectname, self.operation, None, None) class proxy: def __init__(self, objectname): self.__dict__["objectname"] = objectname info = server.getMBeanInfo(objectname) for o in info.operations: self.__dict__[o.name] = OperationProxy(objectname, o.name).invoke def __getattr__(self, name): return server.getAttribute(self.objectname, name) def __setattr__(self, name, value): from javax.management import Attribute return server.setAttribute(self.objectname, Attribute(name, value)) def __repr__(self): return "Proxy of MBean: %s " % (self.__dict__["objectname"], ) def invoke(self, name, arguments=None, types=None): return server.invoke(self.objectname, name, arguments, types) def mbeans(query=None): """ Returns a list of all the available MBeans in the server. The optional query parameter will filter the list by objectname """ return server.getQueryMBeans(ObjectName(query), None) def instances(classname, query=None): """ Returns a list of all the available MBeans in the server which are instances of classname. It accepts a query parameter to filter by objectname """ return [x for x in mbeans(query) if server.isInstanceOf(classname)] mx4j-3.0.2/src/tools/mx4j/tools/mail/SMTP.java100644 0 0 31134 10513545721 16073 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.mail; import java.text.DateFormat; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Logger; /** * This MBean is meant to send a mail given certain situation. It may be used to listen to a monitor * or timer and send a mail. *

* To use it you need to add to your classpath the mail.jar from the JavaMail API and the activation.jar * from the Java Activation Framework. *

* Besides you need to configure all the required fields, at least the serverHost and To fields and if your server * requires login also the serverUsername and serverPassword fields *

* The subject and content fields are subject to keyword expansions, i.e. some keyworks put between $ signs will * be exapnded this can be used to give a more informative message. The current available expansions are *

* $date$ -> Current date formatted with locale format * $time$ -> Current tim formatted with locale format * $datetime$ -> Current date and time formatted with locale format * $notification$ -> Notification type * $observed$ -> ObjectName of the observed object * $objectname$ -> This MBean's objectname * * @version $Revision: 1.7 $ */ public class SMTP implements SMTPMBean, NotificationListener, MBeanRegistration { private MBeanServer server = null; private ObjectName targetMBeanName, objectName; private String notificationName; private Properties sessionProperties = new Properties(); private Session session; private String content = "Empty default mail"; private String mimeType = "text/plain"; private String subject = "Empty Subject"; private String fromAddress = "noreply"; private String fromName = "MX4J default"; private String toAddresses = null; private String ccAddresses = null; private String bccAddresses = null; private String serverHost; private String serverPassword; private String serverUserName; private int serverPort = 25; private int timeout = 10000; private boolean doLogin; private Object sessionLock = new Object(); public void handleNotification(Notification notification, Object handback) { if (notificationName != null && !notification.getType().equals(notificationName)) return; Logger log = getLogger(); log.debug("Notification " + notification + " hit, sending message"); sendMail(); } private Logger getLogger() { return Log.getLogger(getClass().getName()); } public void sendMail() { // send the message in an independet thread not to stop the MBeanServer execution flow new Thread(new Runnable() { public void run() { if (validState()) { Logger logger = getLogger(); synchronized (sessionLock) { createSession(); try { MimeMessage message = new MimeMessage(session); message.setContent(doKeywordExpansion(content), mimeType); message.setSubject(doKeywordExpansion(subject)); Address from = new InternetAddress(fromAddress, fromName); message.setFrom(from); message.setReplyTo(new Address[]{from}); if (toAddresses != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses)); } if (ccAddresses != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses)); } if (bccAddresses != null) { message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses)); } Transport transport = session.getTransport("smtp"); if (doLogin) { transport.connect(serverHost, serverPort, serverUserName, serverPassword); } else { transport.connect(); } message.saveChanges(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending message"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Message sent"); } catch (Exception e) { logger.error("Exception during message sending ", e); } } } } }).start(); } private String doKeywordExpansion(String source) { StringBuffer sourceCopy = new StringBuffer(); int index = -1; int lastIndex = 0; int length = source.length(); while ((index = source.indexOf("$", lastIndex)) > 0) { sourceCopy.append(source.substring(lastIndex, index)); if (index >= (length - 1)) { break; } lastIndex = ++index; if (source.charAt(index) == '$') { sourceCopy.append('$'); lastIndex++; } if (source.startsWith("date$", index)) { sourceCopy.append(DateFormat.getDateInstance().format(new Date())); lastIndex += 5; } if (source.startsWith("time$", index)) { sourceCopy.append(DateFormat.getTimeInstance().format(new Date())); lastIndex += 5; } if (source.startsWith("datetime$", index)) { sourceCopy.append(DateFormat.getDateTimeInstance().format(new Date())); lastIndex += 9; } if (source.startsWith("observed$", index)) { if (targetMBeanName != null) { sourceCopy.append(targetMBeanName); lastIndex += 9; } } if (source.startsWith("objectname$", index)) { if (objectName != null) { sourceCopy.append(objectName); lastIndex += 11; } } if (source.startsWith("notification$", index)) { if (notificationName != null) { sourceCopy.append(notificationName); lastIndex += 13; } } } sourceCopy.append(source.substring(lastIndex, length)); return sourceCopy.toString(); } /** * Sanity check */ private boolean validState() { return serverHost != null && toAddresses != null && (!doLogin || (serverUserName != null || serverPassword != null)); } private void createSession() { synchronized (sessionLock) { if (session == null) { sessionProperties.setProperty("mail.smtp.host", serverHost); sessionProperties.setProperty("mail.smtp.port", Integer.toString(serverPort)); sessionProperties.setProperty("mail.smtp.timeout", Integer.toString(timeout)); sessionProperties.setProperty("mail.smtp.connectiontimeout", Integer.toString(timeout)); sessionProperties.setProperty("mail.smtp.sendpartial", "true"); session = Session.getInstance(sessionProperties, null); } } } public String getBCC() { return bccAddresses; } public void setBCC(String bccAddresses) { this.bccAddresses = bccAddresses; } public void setCC(String ccAddresses) { this.ccAddresses = ccAddresses; } public String getCC() { return ccAddresses; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public void setServerHost(String host) { synchronized (sessionLock) { this.serverHost = host; session = null; } } public String getServerHost() { return this.serverHost; } public void setServerPort(int port) { synchronized (sessionLock) { this.serverPort = port; session = null; } } public int getServerPort() { return this.serverPort; } public void setServerUsername(String username) { this.serverUserName = username; } public String getServerUsername() { return this.serverUserName; } public void setServerPassword(String password) { this.serverPassword = password; } public void setLoginToServer(boolean login) { this.doLogin = login; } public boolean isLoginToServer() { return this.doLogin; } public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getNotificationName() { return notificationName; } public void setNotificationName(String notificationName) { this.notificationName = notificationName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public void setTimeout(int timeout) { synchronized (sessionLock) { this.timeout = timeout; session = null; } } public int getTimeout() { return timeout; } public void setObservedObject(ObjectName targetMBeanName) { this.targetMBeanName = targetMBeanName; registerListener(); } public ObjectName getObservedObject() { return targetMBeanName; } public String getTo() { return toAddresses; } public void setTo(String toAddresses) { this.toAddresses = toAddresses; } /** * Gathers some basic data */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { this.server = server; this.objectName = name; return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws java.lang.Exception { unregisterListener(); } public void postDeregister() { } protected void registerListener() { try { if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster")) { server.addNotificationListener(targetMBeanName, this, new MessageFilter(), null); } } catch (InstanceNotFoundException e) { Logger log = getLogger(); log.error("Exception during notification registration", e); } } protected void unregisterListener() { try { if (targetMBeanName != null && server.isInstanceOf(targetMBeanName, "javax.management.NotificationBroadcaster")) { server.removeNotificationListener(targetMBeanName, this); } } catch (InstanceNotFoundException e) { Logger log = getLogger(); log.error("Exception during notification unregistration", e); } catch (ListenerNotFoundException e) { } } private class MessageFilter implements NotificationFilter { public boolean isNotificationEnabled(Notification notification) { return notificationName == null || (notification.getType() != null && notification.getType().equals(notificationName)); } } } mx4j-3.0.2/src/tools/mx4j/tools/mail/SMTPMBean.java100644 0 0 12161 10513545721 16775 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.mail; import javax.management.ObjectName; /** * Management Interface of a SMTP MBean. *

* This MBean is meant to send a mail given certain situation. It may be used to listen to a monitor * or timer and send a mail. *

* To use it you need to add to your classpath the mail.jar from the JavaMail API and the activation.jar * from the Java Activation Framework. *

* Besides you need to configure all the required fields, at least the serverHost and To fields and if your server * requires login also the serverUsername and serverPassword fields *

* The subject and content fields are subject to keyword expansions, i.e. some keyworks put between $ signs will * be exapnded this can be used to give a more informative message. The current available expansions are *

* $date$ -> Current date formatted with locale format * $time$ -> Current tim formatted with locale format * $datetime$ -> Current date and time formatted with locale format * $notification$ -> Notification type * $observed$ -> ObjectName of the observed object * $objectname$ -> This MBean's objectname * * @version $Revision: 1.4 $ */ public interface SMTPMBean { /** * Gets the MBean's objectname which is being listened */ public ObjectName getObservedObject(); /** * Sets the observed object. It is expected that the observed MBean is a NotificationBroadcster * On the contrary the MBean will not be listening to events */ public void setObservedObject(ObjectName targetMBeanName); /** * Returns the notification which will trigger the mail sending */ public String getNotificationName(); /** * Sets the notification name which will trigger the mail sending. If it is null any notification * will trigger a mail */ public void setNotificationName(String notificationName); /** * Gets the server's host as name or IP */ public String getServerHost(); /** * Sets the server's host, it can be set as name or IP */ public void setServerHost(String host); /** * Sets the server's port. */ public void setServerPort(int port); /** * Gets the server's port, by default is 25 */ public int getServerPort(); /** * Sets server's username, use with setLoginToServer(true) */ public void setServerUsername(String username); /** * Gets the username to log to the server */ public String getServerUsername(); /** * Sets server's passowrd, use with setLoginToServer(true) and setServerUsername */ public void setServerPassword(String password); /** * Sets whether to login to the SMTP server */ public void setLoginToServer(boolean login); /** * Indicates whether login to the SMTP server will be attpemted */ public boolean isLoginToServer(); /** * Sets the send timeout, by default it is 10 secs */ public void setTimeout(int timeout); /** * Returns the timeout used when sending mails */ public int getTimeout(); /** * Gets the from address attached to mails */ public String getFromAddress(); /** * Sets the form address set to mail */ public void setFromAddress(String fromAddress); /** * Gets the from name presented on the mail */ public String getFromName(); /** * Sets the from name presented on the mail */ public void setFromName(String fromName); /** * Gets the MIME type set to the mail */ public String getMimeType(); /** * Sets the MIME type, by default it is text/plain */ public void setMimeType(String mimeType); /** * Gets a comma separated list of addresses set in the TO field */ public String getTo(); /** * Sets a comma separated list of address which will go in the TO mail field */ public void setTo(String toAddresses); /** * Gets a comma separated list of addresses set in the BCC field */ public String getBCC(); /** * Sets a comma separated list of address which will go in the BCC mail field */ public void setBCC(String bccAddresses); /** * Gets a comma separated list of addresses set in the CC field */ public String getCC(); /** * Sets a comma separated list of address which will go in the CC mail field */ public void setCC(String ccAddresses); /** * Gets the mail subject */ public String getSubject(); /** * Sets the mail's subject, by default is Empty subject. The subject field can contain keyword expansion */ public void setSubject(String subject); /** * Returns the content of the mail */ public String getContent(); /** * Sets the content of the mail */ public void setContent(String content); /** * This will directly execute the send mail. It can be used to manually testing the MBean or direct execution */ public void sendMail(); } mx4j-3.0.2/src/tools/mx4j/tools/naming/CosNamingService.java100644 0 0 15617 10513545721 21046 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.security.AccessController; import java.security.PrivilegedAction; import mx4j.log.Log; import mx4j.log.Logger; /** * An MBean that wraps tnameserv.

* Calling {@link #start} will start tnameserv in a separate process via * {@link java.lang.Runtime#exec(String) Runtime.exec(String command)}. * * @version $Revision: 1.13 $ */ public class CosNamingService implements CosNamingServiceMBean { private int m_port; private volatile boolean m_running; private Process m_process; private InputStreamConsumer m_output; private InputStreamConsumer m_error; private volatile Exception exception; /** * Creates a new instance of CosNamingService with the default port (900). */ public CosNamingService() { this(900); } /** * Creates a new instance of CosNamingService with the specified port. */ public CosNamingService(int port) { m_port = port; } /** * Sets the port on which tnameserv listens for incoming connections. * * @see #getPort */ public void setPort(int port) { m_port = port; } /** * Returns the port on which tnameserv listens for incoming connections * * @see #setPort */ public int getPort() { return m_port; } /** * Returns whether this MBean has been started and not yet stopped. * * @see #start */ public boolean isRunning() { return m_running; } /** * Starts this MBean: tnameserv can now accept incoming calls * * @see #stop * @see #isRunning */ public synchronized void start() throws Exception { if (isRunning()) return; final Logger logger = getLogger(); // We start another thread because Process.waitFor() blocks until the process is destroyed. Thread thread = new Thread(new Runnable() { public void run() { String home = getJavaHomeBin(); String command = (home == null ? "" : home) + "tnameserv -ORBInitialPort " + getPort(); try { m_process = Runtime.getRuntime().exec(command); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Process created: " + m_process); } catch (IOException x) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Could not create process", x); exception = x; return; } m_output = new InputStreamConsumer(m_process.getInputStream()); m_error = new InputStreamConsumer(m_process.getErrorStream()); m_output.start(); m_error.start(); m_running = true; try { // Blocks until the process is destroyed int result = m_process.waitFor(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Exit value for tnameserv is: " + result); // If we're still running after waitFor() returns, means stop() has not been called // so the process has returned unexpectedly, we signal this by setting the exception if (isRunning()) { stop(); if (logger.isEnabledFor(Logger.INFO)) logger.info("Unexpected death of tnameserv process (maybe the port " + getPort() + " is already in use)"); exception = new IOException("Unexpected death of tnameserv process " + m_process); } } catch (InterruptedException x) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Process tnameserv has been interrupted", x); stop(); } } }, "CosNamingService Thread"); thread.setDaemon(true); thread.start(); // Nothing better than wait for a while for the process to check if it is really started Thread.sleep(500); // Check if the process is still alive; it is not fool proof since // the sleep above may not have been enough. try { m_process.exitValue(); // The process exited unexpectedly throw new IOException("Unexpected death of tnameserv process " + m_process); } catch (IllegalThreadStateException ignored) { // There are good chances that the process is still running, go on if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Process tnameserv is alive"); } // Double check that the process is still running, since we're not fool proof if (!isRunning() && exception != null) throw exception; if (logger.isEnabledFor(Logger.TRACE)) logger.trace("CosNamingService started"); } private String getJavaHomeBin() { String home = (String)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("java.home"); } }); if (home != null && !home.endsWith(File.separator)) home += File.separator; if (home != null) home += "bin" + File.separator; return home; } /** * Stops this MBean: tnameserv cannot accept anymore incoming calls * * @see #start */ public synchronized void stop() { if (!isRunning()) return; m_running = false; m_output.interrupt(); m_error.interrupt(); m_process.destroy(); } private Logger getLogger() { return Log.getLogger(getClass().getName()); } private class InputStreamConsumer extends Thread { private final InputStream m_stream; private final byte[] m_buffer = new byte[128]; public InputStreamConsumer(InputStream stream) { super("Stream Consumer Thread"); m_stream = new BufferedInputStream(stream); setDaemon(true); } public void run() { Logger logger = getLogger(); while (!isInterrupted()) { try { int read = -1; while ((read = m_stream.read(m_buffer)) >= 0) { if (logger.isEnabledFor(Logger.INFO)) logger.info(new String(m_buffer, 0, read)); } } catch (InterruptedIOException x) { Thread.currentThread().interrupt(); break; } catch (IOException x) { if (logger.isEnabledFor(Logger.INFO)) logger.info("Error while consuming process stream", x); break; } } } } } mx4j-3.0.2/src/tools/mx4j/tools/naming/CosNamingServiceMBean.java100644 0 0 2162 10513545721 21720 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; /** * Management interface for the CosNamingService MBean. * * @version $Revision: 1.4 $ */ public interface CosNamingServiceMBean { /** * Sets the port on which tnameserv listens for incoming connections. * * @see #getPort */ public void setPort(int port); /** * Returns the port on which tnameserv listens for incoming connections * * @see #setPort */ public int getPort(); /** * Returns whether this MBean has been started and not yet stopped. * * @see #start */ public boolean isRunning(); /** * Starts this MBean: tnameserv can now accept incoming calls * * @see #stop * @see #isRunning */ public void start() throws Exception; /** * Stops this MBean: tnameserv cannot accept anymore incoming calls * * @see #start */ public void stop(); } mx4j-3.0.2/src/tools/mx4j/tools/naming/CosNamingServiceMBeanDescription.java100644 0 0 5261 10513545721 24127 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Management interface descriptions for the CosNamingService MBean. * * @version $Revision: 1.3 $ */ public class CosNamingServiceMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "MBean that wraps tnameserv"; } public String getConstructorDescription(Constructor ctor) { if (ctor.toString().equals("public mx4j.tools.naming.CosNamingService()")) { return "Creates a new instance of CosNamingService with the default port (900)"; } if (ctor.toString().equals("public mx4j.tools.naming.CosNamingService(int)")) { return "Creates a new instance of CosNamingService with the specified port"; } return super.getConstructorDescription(ctor); } public String getConstructorParameterName(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.naming.CosNamingService(int)")) { switch (index) { case 0: return "port"; } } return super.getConstructorParameterName(ctor, index); } public String getConstructorParameterDescription(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.naming.CosNamingService(int)")) { switch (index) { case 0: return "The port on which tnameserv will listen for incoming connections"; } } return super.getConstructorParameterDescription(ctor, index); } public String getAttributeDescription(String attribute) { if (attribute.equals("Port")) { return "The port on which tnameserv listens for incoming connections"; } if (attribute.equals("Running")) { return "The running status of this MBean"; } if (attribute.equals("Delay")) { return "The delay (ms) for the start() and stop() methods"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("start")) { return "Starts tnameserv"; } if (name.equals("stop")) { return "Stops tnameserv"; } return super.getOperationDescription(operation); } } mx4j-3.0.2/src/tools/mx4j/tools/naming/NamingService.java100644 0 0 4310 10513545721 20345 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; /** * An MBean that wraps rmiregistry.

* Calling {@link #start} will launch rmiregistry in the same JVM; this way * rmiregistry will have in its classpath the same classes the JVM has. * * @version $Revision: 1.11 $ */ public class NamingService implements NamingServiceMBean { private int m_port; private Registry m_registry; private boolean m_running; /** * Creates a new instance of NamingService with the default rmiregistry port (1099). */ public NamingService() { this(Registry.REGISTRY_PORT); } /** * Creates a new instance of NamingService with the specified port. */ public NamingService(int port) { setPort(port); } public void setPort(int port) { if (isRunning()) throw new IllegalStateException("NamingService is running, cannot change the port"); m_port = port; } public int getPort() { return m_port; } public boolean isRunning() { return m_running; } public void start() throws RemoteException { if (!isRunning()) { m_registry = LocateRegistry.createRegistry(getPort()); m_running = true; } } public void stop() throws NoSuchObjectException { if (isRunning()) { m_running = !UnicastRemoteObject.unexportObject(m_registry, true); } } public String[] list() throws RemoteException { if (!isRunning()) throw new IllegalStateException("NamingService is not running"); return m_registry.list(); } public void unbind(String name) throws RemoteException, NotBoundException { if (!isRunning()) throw new IllegalStateException("NamingService is not running"); m_registry.unbind(name); } } mx4j-3.0.2/src/tools/mx4j/tools/naming/NamingServiceMBean.java100644 0 0 3353 10513545721 21256 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; /** * Management interface for the NamingService MBean. * * @version $Revision: 1.7 $ */ public interface NamingServiceMBean { /** * Sets the port on which rmiregistry listens for incoming connections. * Can be called only if this service is not {@link #isRunning() running}. * * @see #getPort */ public void setPort(int port); /** * Returns the port on which rmiregistry listens for incoming connections * * @see #setPort */ public int getPort(); /** * Returns whether this MBean has been started and not yet stopped. * * @see #start */ public boolean isRunning(); /** * Starts this MBean: rmiregistry can now accept incoming calls * * @see #stop * @see #isRunning */ public void start() throws RemoteException; /** * Stops this MBean: rmiregistry cannot accept anymore incoming calls * * @see #start */ public void stop() throws NoSuchObjectException; /** * Returns an array of the names bound in the rmiregistry * * @see java.rmi.registry.Registry#list() */ public String[] list() throws RemoteException; /** * Removes the binding for the specified name in the rmiregistry * * @see java.rmi.registry.Registry#unbind(String) */ public void unbind(String name) throws RemoteException, NotBoundException; } mx4j-3.0.2/src/tools/mx4j/tools/naming/NamingServiceMBeanDescription.java100644 0 0 5066 10513545721 23465 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.naming; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Management interface descriptions for the NamingService MBean. * * @version $Revision: 1.3 $ */ public class NamingServiceMBeanDescription extends MBeanDescriptionAdapter { public String getMBeanDescription() { return "MBean that wraps rmiregistry"; } public String getConstructorDescription(Constructor ctor) { if (ctor.toString().equals("public mx4j.tools.naming.NamingService()")) { return "Creates a new instance of NamingService with the default rmiregistry port (1099)"; } if (ctor.toString().equals("public mx4j.tools.naming.NamingService(int)")) { return "Creates a new instance of NamingService with the specified port"; } return super.getConstructorDescription(ctor); } public String getConstructorParameterName(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.naming.NamingService(int)")) { switch (index) { case 0: return "port"; } } return super.getConstructorParameterName(ctor, index); } public String getConstructorParameterDescription(Constructor ctor, int index) { if (ctor.toString().equals("public mx4j.tools.naming.NamingService(int)")) { switch (index) { case 0: return "The port on which rmiregistry will listen for incoming connections"; } } return super.getConstructorParameterDescription(ctor, index); } public String getAttributeDescription(String attribute) { if (attribute.equals("Port")) { return "The port on which rmiregistry listens for incoming connections"; } if (attribute.equals("Running")) { return "The running status of this MBean"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { String name = operation.getName(); if (name.equals("start")) { return "Starts rmiregistry"; } if (name.equals("stop")) { return "Stops rmiregistry"; } return super.getOperationDescription(operation); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/AbstractConnection.java100644 0 0 1644 10513545721 21427 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; /** * Implementation of the Connection interface, to be used on the server-side end of the connection. * * @version $Revision: 1.4 $ */ public abstract class AbstractConnection implements Connection { private final String connectionId; private final ConnectionManager manager; protected AbstractConnection(String connectionId, ConnectionManager manager) { this.connectionId = connectionId; this.manager = manager; } public void close() throws IOException { manager.closeConnection(this); } public String getConnectionId() throws IOException { return connectionId; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/AbstractConnectionManager.java100644 0 0 16626 10513545721 22750 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.lang.ref.WeakReference; import java.security.AccessControlContext; import java.security.AccessController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnectorServer; import javax.security.auth.Subject; import mx4j.remote.MX4JRemoteUtils; /** * Implementation of the ConnectionManager interface that implements emission of connection notifications, * authentication, and proper closing of connections. * * @version $Revision: 1.8 $ */ public abstract class AbstractConnectionManager implements ConnectionManager { private AbstractJMXConnectorServer server; private final Map environment; private final AccessControlContext context; private final Map connections = new HashMap(); private volatile boolean closed; /** * Called by subclasses. * * @param server The JMXConnectorServer that will emit connection notifications * @param environment The environment passed when the JMXConnectorServer is created. */ protected AbstractConnectionManager(AbstractJMXConnectorServer server, Map environment) { this.server = server; this.environment = environment; this.context = AccessController.getContext(); } protected void setJMXConnectorServer(AbstractJMXConnectorServer server) { this.server = server; } /** * Implemented using the template method pattern, it handles authentication, creation of the connection ID, * emission of connection notification of type "opened". * * @see #doConnect * @see #authenticate * @see #createConnectionID */ public synchronized Connection connect(Object credentials) throws IOException, SecurityException { if (isClosed()) throw new IOException("This connection manager is already closed " + this); Subject subject = authenticate(credentials); String connectionId = createConnectionID(subject); Connection client = doConnect(connectionId, subject); WeakReference weak = new WeakReference(client); synchronized (connections) { connections.put(connectionId, weak); } server.connectionOpened(connectionId, "Connection opened " + client, null); return client; } /** * Returns a connection ID as specified by JSR 160. * * @param subject The authenticated Subject */ protected String createConnectionID(Subject subject) { return MX4JRemoteUtils.createConnectionID(getProtocol(), null, -1, subject); } /** * Template method to be implemented by subclasses; must return the server-side part of * a connection. * When an remote invocation arrives, it will lookup the corrispondent server-side part * of the connection and delegate the call to it. The server-side part of the connection * must then (eventually) call the MBeanServer to satisfy the request. * * @param connectionId The connection ID for connection that is returned * @param subject The authenticated Subject * @return The server-side part of a connection (with the given connection ID) * @throws IOException If the connection cannot be created */ protected abstract Connection doConnect(String connectionId, Subject subject) throws IOException; /** * Implemented using the template method pattern * * @see #doClose * @see #closeConnection */ public synchronized void close() throws IOException { if (isClosed()) return; closed = true; doClose(); closeConnections(); } /** * Closes this ConnectionManager but not the connections it manages * * @throws IOException If this ConnectionManager cannot be closed */ protected abstract void doClose() throws IOException; private void closeConnections() throws IOException { IOException clientException = null; synchronized (connections) { while (!connections.isEmpty()) { // Create the iterator every time, since closeConnection() may modify the Map Iterator entries = connections.entrySet().iterator(); Map.Entry entry = (Map.Entry)entries.next(); WeakReference weak = (WeakReference)entry.getValue(); Connection connection = (Connection)weak.get(); if (connection == null) { // Already GC'ed entries.remove(); continue; } else { try { connection.close(); } catch (IOException x) { if (clientException == null) clientException = x; } } } } if (clientException != null) throw clientException; } /** * Implemented using the template method pattern, handles the emission of the connection notification * of type "closed". * This method is called both when closing the connector server and when closing a connector. * * @see #doCloseConnection */ public void closeConnection(Connection connection) throws IOException { String connectionID = connection.getConnectionId(); WeakReference weak = null; synchronized (connections) { weak = (WeakReference)connections.remove(connectionID); } // Someone may have called stop() and closed all connections in the meanwhile if (weak == null) return; Connection client = (Connection)weak.get(); if (connection != client) throw new IOException("Could not find active connection " + connection + ", expecting " + client); doCloseConnection(connection); server.connectionClosed(connectionID, "Closed connection " + connection, null); } /** * Closes the given Connection. */ protected abstract void doCloseConnection(Connection connection) throws IOException; /** * Returns whether the {@link #close} method has been called. */ protected boolean isClosed() { return closed; } /** * Returns the environment passed when creating the JMXConnectorServer */ protected Map getEnvironment() { return environment; } /** * Returns a security context at the moment of creation of this ConnectionManager. * This security context is the restricting context that should be used when a call * from a remote client is invoked in a doPrivileged() block. */ protected AccessControlContext getSecurityContext() { return context; } /** * Authenticates a Subject with the given credentials, by looking up a JMXAuthenticator * in the environment returned by {@link #getEnvironment}. */ protected Subject authenticate(Object credentials) throws IOException, SecurityException { Map environment = getEnvironment(); if (environment != null) { JMXAuthenticator authenticator = (JMXAuthenticator)environment.get(JMXConnectorServer.AUTHENTICATOR); if (authenticator != null) { return authenticator.authenticate(credentials); } } return null; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/AbstractJMXConnector.java100644 0 0 12742 10513545721 21662 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.io.Serializable; import java.util.Map; import javax.management.ListenerNotFoundException; import javax.management.MBeanServerConnection; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.remote.JMXConnector; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import mx4j.remote.ConnectionNotificationEmitter; /** * Abstract implementation of the JMXConnector interface. * It gives support for emitting connection notifications and implements JMXConnector methods * using the template method pattern. * * @version $Revision: 1.8 $ */ public abstract class AbstractJMXConnector implements JMXConnector, Serializable { /** * @serial */ private final JMXServiceURL address; private transient boolean connected; private transient boolean closed; private transient ConnectionNotificationEmitter emitter; /** * Creates a new JMXConnector that will connect to the given JMXServiceURL */ protected AbstractJMXConnector(JMXServiceURL address) throws IOException { if (address == null) throw new IOException("JMXServiceURL cannot be null"); this.address = address; } /** * Returns the JMXServiceURL this JMXConnector will connect to. */ protected JMXServiceURL getAddress() { return address; } public void connect() throws IOException, SecurityException { connect(null); } public void connect(Map environment) throws IOException, SecurityException { synchronized (this) { if (isConnected()) return; if (isClosed()) throw new IOException("This connector has already been closed"); doConnect(environment); connected = true; } sendConnectionNotificationOpened(); } protected abstract void doConnect(Map environment) throws IOException, SecurityException; public void close() throws IOException { synchronized (this) { if (isClosed()) return; closed = true; connected = false; doClose(); } sendConnectionNotificationClosed(); } /** * Template method to be implemented by subclasses to close this JMXConnector */ protected abstract void doClose() throws IOException; public MBeanServerConnection getMBeanServerConnection() throws IOException { return getMBeanServerConnection(null); } public MBeanServerConnection getMBeanServerConnection(Subject delegate) throws IOException { if (!isConnected()) throw new IOException("Connection has not been established"); return doGetMBeanServerConnection(delegate); } /** * Template method to be implemented by subclasses to return an MBeanServerConnection * for the given delegate subject. * This method should return an MBeanServerConnection that delegates method calls to a * {@link JMXConnection} (or an equivalent client side connection object). * The JMXConnection object to which calls are delegated can in turn be a chain of * objects that decorate the call performing some other operation; the final object in * the chain is the one that really communicates with the server side, and it is normally * called ClientInvoker. */ protected abstract MBeanServerConnection doGetMBeanServerConnection(Subject delegate) throws IOException; public void addConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { getConnectionNotificationEmitter().addNotificationListener(listener, filter, handback); } public void removeConnectionNotificationListener(NotificationListener listener) throws ListenerNotFoundException { getConnectionNotificationEmitter().removeNotificationListener(listener); } public void removeConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { getConnectionNotificationEmitter().removeNotificationListener(listener, filter, handback); } private void sendConnectionNotificationOpened() { getConnectionNotificationEmitter().sendConnectionNotificationOpened(); } protected void sendConnectionNotificationClosed() { getConnectionNotificationEmitter().sendConnectionNotificationClosed(); } /** * Creates a notification emitter used to emit connection notifications. * This method is called once per JMXConnector. */ protected ConnectionNotificationEmitter createConnectionNotificationEmitter() { return new ConnectionNotificationEmitter(this); } protected ConnectionNotificationEmitter getConnectionNotificationEmitter() { synchronized (this) { if (emitter == null) emitter = createConnectionNotificationEmitter(); } return emitter; } /** * Returns whether the {@link #connect} or {@link #connect(Map)} method has been called on this JMXConnector. */ protected synchronized boolean isConnected() { return connected; } /** * Returns whether the {@link #close} method has been called. */ protected synchronized boolean isClosed() { return closed; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/AbstractJMXConnectorServer.java100644 0 0 7730 10513545721 23032 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.util.Collections; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXServiceURL; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.remote.MX4JRemoteUtils; /** * Extends the implementation of JMXConnectorServer by implementing most * JMXConnectorServer methods following the JSR 160 specification and delegating * implementation specific operations using the template method pattern. * * @version $Revision: 1.8 $ * @see ConnectionManager */ public abstract class AbstractJMXConnectorServer extends JMXConnectorServer { private JMXServiceURL url; private final Map environment; private volatile boolean active; private volatile boolean stopped; public AbstractJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) { super(server); this.url = url; this.environment = environment; } public synchronized JMXServiceURL getAddress() { return url; } /** * Sets the JMXServiceURL that represent the address of this JMXConnectorServer */ protected synchronized void setAddress(JMXServiceURL url) { this.url = url; } public synchronized Map getAttributes() { Map env = MX4JRemoteUtils.removeNonSerializableEntries(getEnvironment()); return Collections.unmodifiableMap(env); } /** * Returns the environment Map as is, without removing non-serializable entries like {@link #getAttributes} does. */ protected synchronized Map getEnvironment() { return environment; } public boolean isActive() { return active; } /** * Returns whether the {@link #stop} method of this JMXConnectorServer has been called. */ protected boolean isStopped() { return stopped; } public synchronized void start() throws IOException, IllegalStateException { Logger logger = getLogger(); if (isActive()) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("This JMXConnectorServer has already been started"); return; } if (isStopped()) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("This JMXConnectorServer has already been stopped"); throw new IOException("This RMIConnectorServer has already been stopped"); } doStart(); active = true; if (logger.isEnabledFor(Logger.INFO)) logger.info("JMXConnectorServer started at: " + getAddress()); } /** * Template method implemented by subclasses to start this JMXConnectorServer */ protected abstract void doStart() throws IOException, IllegalStateException; public synchronized void stop() throws IOException { if (!isActive() || isStopped()) return; stopped = true; active = false; doStop(); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.INFO)) logger.info("JMXConnectorServer stopped at: " + getAddress()); } /** * Template method implemented by subclasses to stop this JMXConnectorServer */ protected abstract void doStop() throws IOException; protected Logger getLogger() { return Log.getLogger(getClass().getName()); } public void connectionOpened(String connectionId, String message, Object userData) { super.connectionOpened(connectionId, message, userData); } public void connectionClosed(String connectionId, String message, Object userData) { super.connectionClosed(connectionId, message, userData); } public void connectionFailed(String connectionId, String message, Object userData) { super.connectionFailed(connectionId, message, userData); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/AbstractServerInvoker.java100644 0 0 14645 10513545721 22161 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServerConnection; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.security.auth.Subject; /** * This class implements partially the JMXConnection interface to forward the calls * to an MBeanServerConnection object (hence the name 'invoker'). * It does not handle nor unmarshalling of arguments (and all related classloading * problems), nor remote notification mechanisms of any sort, which are left * to subclasses, which will implement them in a protocol specific way. * This class is the server-side counterpart of {@link JMXConnectionMBeanServerConnection} * * @version $Revision: 1.4 $ */ public abstract class AbstractServerInvoker implements JMXConnection { private final MBeanServerConnection server; protected AbstractServerInvoker(MBeanServerConnection server) { this.server = server; } protected MBeanServerConnection getServer() { return server; } public ObjectInstance createMBean(String className, ObjectName name, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return getServer().createMBean(className, name, (Object[])params, signature); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return getServer().createMBean(className, name, loaderName, (Object[])params, signature); } public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException { getServer().unregisterMBean(name); } public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException { return getServer().getObjectInstance(name); } public Set queryMBeans(ObjectName name, Object query, Subject delegate) throws IOException { return getServer().queryMBeans(name, (QueryExp)query); } public Set queryNames(ObjectName name, Object query, Subject delegate) throws IOException { return getServer().queryNames(name, (QueryExp)query); } public boolean isRegistered(ObjectName name, Subject delegate) throws IOException { return getServer().isRegistered(name); } public Integer getMBeanCount(Subject delegate) throws IOException { return getServer().getMBeanCount(); } public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { return getServer().getAttribute(name, attribute); } public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { return getServer().getAttributes(name, attributes); } public void setAttribute(ObjectName name, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { getServer().setAttribute(name, (Attribute)attribute); } public AttributeList setAttributes(ObjectName name, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { return getServer().setAttributes(name, (AttributeList)attributes); } public Object invoke(ObjectName name, String operationName, Object params, String[] signature, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { return getServer().invoke(name, operationName, (Object[])params, signature); } public String getDefaultDomain(Subject delegate) throws IOException { return getServer().getDefaultDomain(); } public String[] getDomains(Subject delegate) throws IOException { return getServer().getDomains(); } public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { return getServer().getMBeanInfo(name); } public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException { return getServer().isInstanceOf(name, className); } public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { getServer().addNotificationListener(name, listener, (NotificationFilter)filter, handback); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getServer().removeNotificationListener(name, listener); } public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getServer().removeNotificationListener(name, listener, (NotificationFilter)filter, handback); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/Connection.java100644 0 0 1466 10513545721 17745 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; /** * Represents a connection between a client and a server. * A connection has normally a client end and a server end. Both ends will be implemented in * a protocol specific way by JSR 160 protocol provider implementations. * * @version $Revision: 1.4 $ */ public interface Connection { /** * Closes this connection */ public void close() throws IOException; /** * Returns the connection ID as specified by JSR 160 specification */ public String getConnectionId() throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/ConnectionManager.java100644 0 0 3705 10513545721 21236 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; /** * A ConnectionManager is a server-side object that acts as the factory for new connections and * manages the authentication details. * A JMXConnectorServer delegates a ConnectionManager for the creation of connections, and a * ConnectionManager interacts with the JMXConnectorServer to emit connection notifications. * It is the first object contacted by a remote client to obtain a client-specific connection, that is, * a connection with a specific connection ID. * * @version $Revision: 1.4 $ */ public interface ConnectionManager { /** * Factory method that creates connections that are specific to the client that invoked this method. * * @param credentials The credentials sent by the client to authenticate a subject. * @return A new client-specific connection. * @throws IOException If the connection cannot be created. * @throws SecurityException If the authentication fails. */ public Connection connect(Object credentials) throws IOException, SecurityException; /** * Returns the protocol used by the corrispondent JMXConnectorServer. */ public String getProtocol(); /** * Closes this ConnectionManager and all the opened connections it manages. * * @see #closeConnection */ public void close() throws IOException; /** * Closes the given Connection. * This method is called by the connection manager when it is closing the connections it manages, * or as a consequence of the fact that the client end of the connection has been closed. * * @see Connection#close * @see #close */ public void closeConnection(Connection connection) throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/JMXConnection.java100644 0 0 12122 10513545721 20333 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.util.Set; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.security.auth.Subject; /** * @version $Revision: 1.3 $ */ public interface JMXConnection { public void close() throws IOException; public ObjectInstance createMBean(String className, ObjectName name, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException; public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException; public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException; public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException; public Set queryMBeans(ObjectName name, Object query, Subject delegate) throws IOException; public Set queryNames(ObjectName name, Object query, Subject delegate) throws IOException; public boolean isRegistered(ObjectName name, Subject delegate) throws IOException; public Integer getMBeanCount(Subject delegate) throws IOException; public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException; public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException; public void setAttribute(ObjectName name, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException; public AttributeList setAttributes(ObjectName name, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException; public Object invoke(ObjectName name, String operationName, Object params, String[] signature, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException; public String getDefaultDomain(Subject delegate) throws IOException; public String[] getDomains(Subject delegate) throws IOException; public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException; public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException; public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException; public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/JMXConnectionHandler.java100644 0 0 20365 10513545721 21641 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.util.Set; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.security.auth.Subject; /** * This handler manages the operations related to the connection itself, such as * {@link #close}, {@link #getConnectionId}. *

* It is important that this object is the outermost wrapper of the Connection objects * returned by {@link mx4j.tools.remote.ConnectionManager#connect} * * @version $Revision: 1.3 $ */ public abstract class JMXConnectionHandler extends AbstractConnection implements JMXConnection { private final JMXConnection connection; private volatile boolean closed; public JMXConnectionHandler(JMXConnection connection, ConnectionManager manager, String connectionId) { super(connectionId, manager); this.connection = connection; } /** * Overridden to allow nested connections to close and release their resources and, afterwards, * to close this connection with the JSR 160 semantic provided by the superclass. */ public void close() throws IOException { if (isClosed()) return; closed = true; getConnection().close(); super.close(); } protected boolean isClosed() { return closed; } protected JMXConnection getConnection() { return connection; } public ObjectInstance createMBean(String className, ObjectName name, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().createMBean(className, name, params, signature, delegate); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().createMBean(className, name, loaderName, params, signature, delegate); } public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); getConnection().unregisterMBean(name, delegate); } public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getObjectInstance(name, delegate); } public Set queryMBeans(ObjectName name, Object query, Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().queryMBeans(name, query, delegate); } public Set queryNames(ObjectName name, Object query, Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().queryNames(name, query, delegate); } public boolean isRegistered(ObjectName name, Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().isRegistered(name, delegate); } public Integer getMBeanCount(Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getMBeanCount(delegate); } public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getAttribute(name, attribute, delegate); } public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getAttributes(name, attributes, delegate); } public void setAttribute(ObjectName name, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); getConnection().setAttribute(name, attribute, delegate); } public AttributeList setAttributes(ObjectName name, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().setAttributes(name, attributes, delegate); } public Object invoke(ObjectName name, String operationName, Object params, String[] signature, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().invoke(name, operationName, params, signature, delegate); } public String getDefaultDomain(Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getDefaultDomain(delegate); } public String[] getDomains(Subject delegate) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getDomains(delegate); } public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().getMBeanInfo(name, delegate); } public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return getConnection().isInstanceOf(name, className, delegate); } public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); getConnection().addNotificationListener(name, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); getConnection().removeNotificationListener(name, listener, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); getConnection().removeNotificationListener(name, listener, filter, handback, delegate); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/JMXConnectionMBeanServerConnection.java100644 0 0 16503 10513545721 24454 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.IOException; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServerConnection; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.security.auth.Subject; /** * Abstract implementation of an adapter that converts MBeanServerConnection calls * to JMXConnection calls. * It does not handle nor marshalling nor remote notifications, which are left to * subclasses. * This is the client side counterpart of {@link AbstractServerInvoker} * * @version $Revision: 1.3 $ */ public abstract class JMXConnectionMBeanServerConnection implements MBeanServerConnection { private final JMXConnection connection; private final Subject delegate; protected JMXConnectionMBeanServerConnection(JMXConnection connection, Subject delegate) { this.connection = connection; this.delegate = delegate; } protected JMXConnection getConnection() { return connection; } protected Subject getDelegateSubject() { return delegate; } public MBeanInfo getMBeanInfo(ObjectName objectName) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { return getConnection().getMBeanInfo(objectName, getDelegateSubject()); } public boolean isInstanceOf(ObjectName objectName, String className) throws InstanceNotFoundException, IOException { return getConnection().isInstanceOf(objectName, className, getDelegateSubject()); } public String[] getDomains() throws IOException { return getConnection().getDomains(getDelegateSubject()); } public String getDefaultDomain() throws IOException { return getConnection().getDefaultDomain(getDelegateSubject()); } public ObjectInstance createMBean(String className, ObjectName objectName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return createMBean(className, objectName, null, null); } public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return getConnection().createMBean(className, objectName, args, parameters, getDelegateSubject()); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return createMBean(className, objectName, loaderName, null, null); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return getConnection().createMBean(className, objectName, loaderName, args, parameters, getDelegateSubject()); } public void unregisterMBean(ObjectName objectName) throws InstanceNotFoundException, MBeanRegistrationException, IOException { getConnection().unregisterMBean(objectName, getDelegateSubject()); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { return getConnection().getAttribute(objectName, attribute, getDelegateSubject()); } public void setAttribute(ObjectName objectName, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { getConnection().setAttribute(objectName, attribute, getDelegateSubject()); } public AttributeList getAttributes(ObjectName objectName, String[] attributes) throws InstanceNotFoundException, ReflectionException, IOException { return getConnection().getAttributes(objectName, attributes, getDelegateSubject()); } public AttributeList setAttributes(ObjectName objectName, AttributeList attributes) throws InstanceNotFoundException, ReflectionException, IOException { return getConnection().setAttributes(objectName, attributes, getDelegateSubject()); } public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { return getConnection().invoke(objectName, methodName, args, parameters, getDelegateSubject()); } public Integer getMBeanCount() throws IOException { return getConnection().getMBeanCount(getDelegateSubject()); } public boolean isRegistered(ObjectName objectName) throws IOException { return getConnection().isRegistered(objectName, getDelegateSubject()); } public ObjectInstance getObjectInstance(ObjectName objectName) throws InstanceNotFoundException, IOException { return getConnection().getObjectInstance(objectName, getDelegateSubject()); } public Set queryMBeans(ObjectName patternName, QueryExp filter) throws IOException { return getConnection().queryMBeans(patternName, filter, getDelegateSubject()); } public Set queryNames(ObjectName patternName, QueryExp filter) throws IOException { return getConnection().queryNames(patternName, filter, getDelegateSubject()); } public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, IOException { getConnection().addNotificationListener(observed, listener, filter, handback, getDelegateSubject()); } public void removeNotificationListener(ObjectName observed, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getConnection().removeNotificationListener(observed, listener, getDelegateSubject()); } public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getConnection().removeNotificationListener(observed, listener, filter, handback, getDelegateSubject()); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/PasswordAuthenticator.java100644 0 0 21755 10513545721 22226 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXPrincipal; import javax.security.auth.Subject; import mx4j.util.Base64Codec; /** * Implementation of the JMXAuthenticator interface to be used on server side * to secure access to {@link javax.management.remote.JMXConnectorServer JMXConnectorServer}s.
* Usage: *

 * JMXAuthenticator authenticator = new PasswordAuthenticator(new File("users.properties"));
 * Map environment = new HashMap();
 * environment.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
 * JMXServiceURL address = new JMXServiceURL("rmi", "localhost", 0);
 * MBeanServer server = ...;
 * JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, environment, server);
 * 
* The format of the users.properties file is that of a standard properties file:
* <user>=<password>
* where <password> can be stored in 2 ways: *
    *
  • Clear text: the password is written in clear text
  • *
  • Obfuscated text: the password is obfuscated
  • *
* The obfuscated form can be obtained running this class as a main class: *
 * java -cp mx4j-remote.jar mx4j.tools.remote.PasswordAuthenticator
 * 
* and following the instructions printed on the console. The output will be a string that should be * copy/pasted as the password into the properties file.
* The obfuscated password is obtained by digesting the clear text password using a * {@link java.security.MessageDigest} algorithm, and then by Base64-encoding the resulting bytes.
*
* On client side, you are allowed to connect to a server side secured with the PasswordAuthenticator * only if you provide the correct credentials: *
 * String[] credentials = new String[2];
 * // The user will travel as clear text
 * credentials[0] = "user";
 * // You may send the password in clear text, but it's better to obfuscate it
 * credentials[1] = PasswordAuthenticator.obfuscatePassword("password");
 * Map environment = new HashMap();
 * environment.put(JMXConnector.CREDENTIALS, credentials);
 * JMXServiceURL address = ...;
 * JMXConnector cntor = JMXConnectorFactory.connect(address, environment);
 * 
* Note that {@link #obfuscatePassword(java.lang.String,java.lang.String) obfuscating} the passwords only works if the server side has been * setup with the PasswordAuthenticator. * However, the PasswordAuthenticator can be used with other JSR 160 implementations, such as Sun's reference * implementation. * * @version $Revision: 1.3 $ */ public class PasswordAuthenticator implements JMXAuthenticator { private static final String LEFT_DELIMITER = "OBF("; private static final String RIGHT_DELIMITER = "):"; /** * Runs this class as main class to obfuscate passwords. * When no arguments are provided, it prints out the usage. * * @see #obfuscatePassword(java.lang.String,java.lang.String) */ public static void main(String[] args) throws Exception { if (args.length == 1) { if (!"-help".equals(args[0])) { printPassword("MD5", args[0]); return; } } else if (args.length == 3) { if ("-alg".equals(args[0])) { printPassword(args[1], args[2]); return; } } printUsage(); } private static void printPassword(String algorithm, String input) { String password = obfuscatePassword(input, algorithm); System.out.println(password); } private static void printUsage() { System.out.println(); System.out.println("Usage: java -cp /mx4j-tools.jar mx4j.tools.remote.PasswordAuthenticator "); System.out.println("Where is one of the following:"); System.out.println(" -help Prints this message"); System.out.println(" -alg Specifies the digest algorithm (default is MD5)"); System.out.println(); } /** * Obfuscates the given password using MD5 as digest algorithm * * @see #obfuscatePassword(java.lang.String,java.lang.String) */ public static String obfuscatePassword(String password) { return obfuscatePassword(password, "MD5"); } /** * Obfuscates the given password using the given digest algorithm.
* Obfuscation consists of 2 steps: first the clear text password is {@link java.security.MessageDigest#digest digested} * using the specified algorithm, then the resulting bytes are Base64-encoded.
* For example, the obfuscated version of the password "password" is "OBF(MD5):X03MO1qnZdYdgyfeuILPmQ==" * or "OBF(SHA-1):W6ph5Mm5Pz8GgiULbPgzG37mj9g=".
* OBF stands for "obfuscated", in parenthesis the algorithm used to digest the password. */ public static String obfuscatePassword(String password, String algorithm) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] digestedBytes = digest.digest(password.getBytes()); byte[] obfuscatedBytes = Base64Codec.encodeBase64(digestedBytes); return LEFT_DELIMITER + algorithm + RIGHT_DELIMITER + new String(obfuscatedBytes); } catch (NoSuchAlgorithmException x) { throw new SecurityException("Could not find digest algorithm " + algorithm); } } private Map passwords; /** * Creates a new PasswordAuthenticator that reads user/password pairs from the specified properties file. * The file format is described in the javadoc of this class. * * @see #obfuscatePassword */ public PasswordAuthenticator(File passwordFile) throws IOException { this(new FileInputStream(passwordFile)); } /** * Creates a new PasswordAuthenticator that reads user/password pairs from the specified InputStream. * The file format is described in the javadoc of this class. * * @see #obfuscatePassword */ public PasswordAuthenticator(InputStream is) throws IOException { passwords = readPasswords(is); } private Map readPasswords(InputStream is) throws IOException { Properties properties = new Properties(); try { properties.load(is); } finally { is.close(); } return new HashMap(properties); } public Subject authenticate(Object credentials) throws SecurityException { if (!(credentials instanceof String[])) throw new SecurityException("Bad credentials"); String[] creds = (String[])credentials; if (creds.length != 2) throw new SecurityException("Bad credentials"); String user = creds[0]; String password = creds[1]; if (password == null) throw new SecurityException("Bad password"); if (!passwords.containsKey(user)) throw new SecurityException("Unknown user " + user); String storedPassword = (String)passwords.get(user); if (!isPasswordCorrect(password, storedPassword)) throw new SecurityException("Bad password"); Set principals = new HashSet(); principals.add(new JMXPrincipal(user)); return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); } private boolean isPasswordCorrect(String password, String storedPassword) { if (password.startsWith(LEFT_DELIMITER)) { if (storedPassword.startsWith(LEFT_DELIMITER)) { return password.equals(storedPassword); } else { String algorithm = getAlgorithm(password); String obfuscated = obfuscatePassword(storedPassword, algorithm); return password.equals(obfuscated); } } else { if (storedPassword.startsWith(LEFT_DELIMITER)) { // Password was sent in clear, bad practice String algorithm = getAlgorithm(storedPassword); String obfuscated = obfuscatePassword(password, algorithm); return obfuscated.equals(storedPassword); } else { return password.equals(storedPassword); } } } private String getAlgorithm(String obfuscatedPassword) { try { return obfuscatedPassword.substring(LEFT_DELIMITER.length(), obfuscatedPassword.indexOf(RIGHT_DELIMITER)); } catch (IndexOutOfBoundsException x) { throw new SecurityException("Bad password"); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/SubjectInvoker.java100644 0 0 5520 10513545721 20576 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessControlContext; import java.security.PrivilegedExceptionAction; import java.util.Map; import javax.management.remote.JMXServerErrorException; import javax.security.auth.Subject; import mx4j.remote.MX4JRemoteUtils; /** * @version $Revision: 1.4 $ */ public abstract class SubjectInvoker implements InvocationHandler { private final Object target; private final Subject subject; private final AccessControlContext context; private Map environment; protected SubjectInvoker(Object target, Subject subject, AccessControlContext context, Map environment) { this.target = target; this.subject = subject; this.context = context; this.environment = environment; } protected boolean isPlainInvoke(Method method) { String methodName = method.getName(); // java.lang.Object methods if ("toString".equals(methodName)) return true; if ("hashCode".equals(methodName)) return true; if ("equals".equals(methodName)) return true; return false; } protected Object handleSpecialInvoke(Object target, Method method, Object[] args) throws Exception { throw new NoSuchMethodException(method.toString()); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (isPlainInvoke(method)) return chain(target, method, args); if (method.getParameterTypes()[args.length - 1] == Subject.class) { Subject delegate = (Subject)args[args.length - 1]; return subjectInvoke(target, method, args, delegate); } else { return handleSpecialInvoke(target, method, args); } } protected Object subjectInvoke(final Object proxy, final Method method, final Object[] args, Subject delegate) throws Exception { return MX4JRemoteUtils.subjectInvoke(subject, delegate, context, environment, new PrivilegedExceptionAction() { public Object run() throws Exception { return chain(proxy, method, args); } }); } protected Object chain(Object proxy, Method method, Object[] args) throws Exception { try { return method.invoke(proxy, args); } catch (InvocationTargetException x) { Throwable t = x.getTargetException(); if (t instanceof Exception) throw (Exception)t; throw new JMXServerErrorException("Error thrown during invocation", (Error)t); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/CauchoClientInvoker.java100644 0 0 7442 10513545721 23007 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.net.URLConnection; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.tools.remote.http.HTTPClientInvoker; import mx4j.tools.remote.http.HTTPConnection; /** * @version $Revision: 1.4 $ */ public abstract class CauchoClientInvoker extends HTTPClientInvoker { private final String endpoint; private final HTTPConnection service; public CauchoClientInvoker(String endpoint) { this.endpoint = endpoint; CauchoServiceProxy proxy = new CauchoServiceProxy(); service = (HTTPConnection)Proxy.newProxyInstance(proxy.getClass().getClassLoader(), new Class[]{HTTPConnection.class}, proxy); } protected HTTPConnection getService() { return service; } protected abstract CauchoInput createCauchoInput(InputStream stream); protected abstract CauchoOutput createCauchoOutput(OutputStream stream); private class CauchoServiceProxy implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { URLConnection connection = new URL(endpoint).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); OutputStream os = new BufferedOutputStream(connection.getOutputStream()); try { CauchoOutput output = createCauchoOutput(os); startCall(output); writeHeaders(output); writeMethod(output, method); writeArguments(output, args); completeCall(output); os.flush(); InputStream is = new BufferedInputStream(connection.getInputStream()); try { CauchoInput input = createCauchoInput(is); input.startReply(); Object result = input.readObject(null); input.completeReply(); return result; } catch (Throwable x) { Logger logger = Log.getLogger(CauchoClientInvoker.class.getName()); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("", x); throw x; } finally { is.close(); } } finally { os.close(); } } private void startCall(CauchoOutput output) throws IOException { output.startCall(); } private void writeHeaders(CauchoOutput output) throws IOException { output.writeHeader(CauchoService.CONNECTION_ID_HEADER_NAME); output.writeObject(getConnectionId()); } private void writeMethod(CauchoOutput output, Method method) throws IOException { String methodName = mangleMethodName(method); output.writeMethod(methodName); } private String mangleMethodName(Method method) { return CauchoService.mangleMethodName(method); } private void writeArguments(CauchoOutput output, Object[] args) throws IOException { if (args != null) for (int i = 0; i < args.length; ++i) output.writeObject(args[i]); } private void completeCall(CauchoOutput output) throws IOException { output.completeCall(); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/CauchoInput.java100644 0 0 2035 10513545721 21323 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho; import java.io.IOException; /** * @version $ */ public interface CauchoInput { public void startCall() throws IOException; public void completeCall() throws IOException; public String readHeader() throws IOException; public String readMethod() throws IOException; /** * Reads and returns an object of the given class, * or a generic object if the class is null. */ public Object readObject(Class cls) throws IOException; /** * Starts reading a reply of a previous call; if the call threw an exception, * the exception is read and re-thrown, otherwise the result of the call * can be read using {@link #readObject}. */ public void startReply() throws Exception; public void completeReply() throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/CauchoOutput.java100644 0 0 1463 10513545721 21530 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho; import java.io.IOException; /** * @version $ */ public interface CauchoOutput { public void startCall() throws IOException; public void completeCall() throws IOException; public void startReply() throws IOException; public void completeReply() throws IOException; public void writeHeader(String header) throws IOException; public void writeMethod(String methodName) throws IOException; public void writeObject(Object object) throws IOException; public void writeFault(Throwable fault) throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/CauchoService.java100644 0 0 3336 10513545721 21631 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho; import java.lang.reflect.Method; import mx4j.tools.remote.http.HTTPService; /** * @version $ */ public class CauchoService extends HTTPService { static final String CONNECTION_ID_HEADER_NAME = "connectionContext"; private static ThreadLocal connectionContext = new ThreadLocal(); private final String protocol; public CauchoService(String protocol) { this.protocol = protocol; } protected String getProtocol() { return protocol; } protected String findRequestURL() { ConnectionContext context = (ConnectionContext)connectionContext.get(); return context == null ? null : context.url; } protected String findConnectionId() { ConnectionContext context = (ConnectionContext)connectionContext.get(); return context == null ? null : context.connectionId; } static void setConnectionContext(String url, String connectionId) { connectionContext.set(new ConnectionContext(url, connectionId)); } static void resetConnectionContext() { connectionContext.set(null); } static String mangleMethodName(Method method) { return method.getName() + "__" + method.getParameterTypes().length; } private static class ConnectionContext { private String url; private String connectionId; private ConnectionContext(String url, String connectionId) { this.url = url; this.connectionId = connectionId; } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/CauchoServlet.java100644 0 0 11013 10513545721 21664 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mx4j.tools.remote.http.HTTPConnection; /** * @version $Revision: 1.4 $ */ public abstract class CauchoServlet extends HttpServlet { private Map methods; public void init() throws ServletException { methods = new HashMap(); mapMethods(HTTPConnection.class, methods); } protected void mapMethods(Class cls, Map methods) { Method[] mthds = cls.getMethods(); for (int i = 0; i < mthds.length; ++i) { Method mthd = mthds[i]; String key = mangleMethodName(mthd); methods.put(key, mthd); } } protected Method findMethod(String methodName) { return (Method) methods.get(methodName); } protected String mangleMethodName(Method method) { return CauchoService.mangleMethodName(method); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!"POST".equalsIgnoreCase(request.getMethod())) throw new ServletException("Caucho protocol requires POST"); BufferedInputStream is = new BufferedInputStream(request.getInputStream(), 48); CauchoInput input = createCauchoInput(is); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream(), 48); CauchoOutput output = createCauchoOutput(bos); invoke(request, input, output); bos.flush(); } protected abstract CauchoInput createCauchoInput(InputStream stream); protected abstract CauchoOutput createCauchoOutput(OutputStream stream); protected abstract Object getService(); protected void invoke(HttpServletRequest request, CauchoInput input, CauchoOutput output) throws IOException { input.startCall(); Map headers = readHeaders(input); String methodName = input.readMethod(); Method method = findMethod(methodName); if (method == null) { output.startReply(); NoSuchMethodException x = new NoSuchMethodException(methodName); output.writeFault(x); output.completeReply(); } else { Object[] values = readArguments(input, method); input.completeCall(); Object result = null; try { result = invoke(request.getRequestURL().toString(), getService(), method, headers, values); } catch (Throwable x) { output.startReply(); output.writeFault(x); output.completeReply(); return; } output.startReply(); output.writeObject(result); output.completeReply(); } } protected Map readHeaders(CauchoInput input) throws IOException { Map headers = new HashMap(); String header = null; while ((header = input.readHeader()) != null) headers.put(header, input.readObject(null)); return headers; } protected Object[] readArguments(CauchoInput input, Method method) throws IOException { Class[] types = method.getParameterTypes(); Object[] values = new Object[types.length]; for (int i = 0; i < types.length; ++i) values[i] = input.readObject(types[i]); return values; } protected Object invoke(String url, Object target, Method method, Map headers, Object[] values) throws Exception { if (target == null) throw new IOException("Service is not available"); String connectionId = (String) headers.get(CauchoService.CONNECTION_ID_HEADER_NAME); CauchoService.setConnectionContext(url, connectionId); try { return method.invoke(target, values); } catch (InvocationTargetException x) { Throwable t = x.getTargetException(); if (t instanceof Exception) throw (Exception) t; throw (Error) t; } finally { CauchoService.resetConnectionContext(); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/BurlapCauchoInput.java100644 0 0 3165 10513545721 23763 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.burlap; import java.io.IOException; import java.io.InputStream; import com.caucho.burlap.io.BurlapInput; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.serialization.JMXSerializerFactory; /** * @version $Revision: 1.4 $ */ class BurlapCauchoInput implements CauchoInput { private final BurlapInput input; BurlapCauchoInput(InputStream stream) { this.input = new BurlapInput(); input.setSerializerFactory(new JMXSerializerFactory()); input.init(stream); } public void startCall() throws IOException { input.readCall(); } public void completeCall() throws IOException { input.completeCall(); } public void startReply() throws Exception { try { input.startReply(); } catch (Throwable x) { if (x instanceof Exception) throw (Exception) x; throw (Error) x; } } public void completeReply() throws IOException { input.completeReply(); } public String readHeader() throws IOException { return input.readHeader(); } public String readMethod() throws IOException { return input.readMethod(); } public Object readObject(Class cls) throws IOException { if (cls == null || cls == Object.class) return input.readObject(); return input.readObject(cls); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/BurlapCauchoOutput.java100644 0 0 3147 10513545721 24164 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.burlap; import java.io.IOException; import java.io.OutputStream; import com.caucho.burlap.io.BurlapOutput; import mx4j.tools.remote.caucho.CauchoOutput; import mx4j.tools.remote.caucho.serialization.JMXSerializerFactory; /** * @version $Revision: 1.3 $ */ class BurlapCauchoOutput implements CauchoOutput { private final BurlapOutput output; BurlapCauchoOutput(OutputStream stream) { this.output = new BurlapOutput(); output.setSerializerFactory(new JMXSerializerFactory()); output.init(stream); } public void startReply() throws IOException { output.startReply(); } public void completeReply() throws IOException { output.completeReply(); } public void startCall() throws IOException { output.startCall(); } public void completeCall() throws IOException { output.completeCall(); } public void writeHeader(String header) throws IOException { output.writeHeader(header); } public void writeMethod(String methodName) throws IOException { output.writeMethod(methodName); } public void writeObject(Object object) throws IOException { output.writeObject(object); } public void writeFault(Throwable fault) throws IOException { output.writeFault(fault.getClass().getName(), fault.getMessage(), fault); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/BurlapClientInvoker.java100644 0 0 1616 10513545721 24314 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.burlap; import java.io.InputStream; import java.io.OutputStream; import mx4j.tools.remote.caucho.CauchoClientInvoker; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.CauchoOutput; /** * @version $Revision: 1.3 $ */ public class BurlapClientInvoker extends CauchoClientInvoker { public BurlapClientInvoker(String endpoint) { super(endpoint); } protected CauchoInput createCauchoInput(InputStream stream) { return new BurlapCauchoInput(stream); } protected CauchoOutput createCauchoOutput(OutputStream stream) { return new BurlapCauchoOutput(stream); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/BurlapServlet.java100644 0 0 2345 10513545721 23164 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.burlap; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.CauchoOutput; import mx4j.tools.remote.caucho.CauchoService; import mx4j.tools.remote.caucho.CauchoServlet; /** * @version $ */ public class BurlapServlet extends CauchoServlet { private CauchoService service; public void init() throws ServletException { super.init(); service = createService(); } protected CauchoService createService() { return new CauchoService("burlap"); } public void destroy() { this.service = null; } protected Object getService() { return service; } protected CauchoInput createCauchoInput(InputStream stream) { return new BurlapCauchoInput(stream); } protected CauchoOutput createCauchoOutput(OutputStream stream) { return new BurlapCauchoOutput(stream); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/SSLBurlapServlet.java100644 0 0 1015 10513545721 23537 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.burlap; import mx4j.tools.remote.caucho.CauchoService; /** * @version $Revision: 1.1 $ */ public class SSLBurlapServlet extends BurlapServlet { protected CauchoService createService() { return new CauchoService("burlap+ssl"); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/HessianCauchoInput.java100644 0 0 3132 10513545721 24267 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.hessian; import java.io.IOException; import java.io.InputStream; import com.caucho.hessian.io.HessianInput; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.serialization.JMXSerializerFactory; /** * @version $Revision: 1.3 $ */ class HessianCauchoInput implements CauchoInput { private final HessianInput input; HessianCauchoInput(InputStream stream) { this.input = new HessianInput(); input.setSerializerFactory(new JMXSerializerFactory()); input.init(stream); } public void startCall() throws IOException { input.readCall(); } public void completeCall() throws IOException { input.completeCall(); } public void startReply() throws Exception { try { input.startReply(); } catch (Throwable x) { if (x instanceof Exception) throw (Exception)x; throw (Error)x; } } public void completeReply() throws IOException { input.completeReply(); } public String readHeader() throws IOException { return input.readHeader(); } public String readMethod() throws IOException { return input.readMethod(); } public Object readObject(Class cls) throws IOException { return cls == null ? input.readObject() : input.readObject(cls); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/HessianCauchoOutput.java100644 0 0 4331 10513545721 24472 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.hessian; import java.io.IOException; import java.io.OutputStream; import com.caucho.hessian.io.HessianOutput; import mx4j.tools.remote.caucho.CauchoOutput; import mx4j.tools.remote.caucho.serialization.JMXSerializerFactory; /** * @version $Revision: 1.3 $ */ class HessianCauchoOutput implements CauchoOutput { private final OutputStream stream; private final HessianOutput output; HessianCauchoOutput(OutputStream stream) { this.stream = stream; this.output = new HessianOutput(); output.setSerializerFactory(new JMXSerializerFactory()); output.init(stream); } public void startReply() throws IOException { output.startReply(); } public void completeReply() throws IOException { output.completeReply(); } /** * A bug in the Hessian protocol requires this hack: headers cannot be written using * HessianOutput, since the HessianOutput.startCall() already writes the method name, * while HessianInput expects the headers before the method name * * @see #writeMethod */ public void startCall() throws IOException { stream.write(99); stream.write(0); stream.write(1); } public void completeCall() throws IOException { output.completeCall(); } public void writeHeader(String header) throws IOException { output.writeHeader(header); } /** * Same hack as {@link #startCall}: this method is missing from HessianOutput */ public void writeMethod(String methodName) throws IOException { stream.write(109); int len = methodName.length(); stream.write(len >> 8); stream.write(len); output.printString(methodName, 0, len); } public void writeObject(Object object) throws IOException { output.writeObject(object); } public void writeFault(Throwable fault) throws IOException { output.writeFault(fault.getClass().getName(), fault.getMessage(), fault); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/HessianClientInvoker.java100644 0 0 1604 10513545721 24623 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.hessian; import java.io.InputStream; import java.io.OutputStream; import mx4j.tools.remote.caucho.CauchoClientInvoker; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.CauchoOutput; /** * @version $ */ public class HessianClientInvoker extends CauchoClientInvoker { public HessianClientInvoker(String endpoint) { super(endpoint); } protected CauchoInput createCauchoInput(InputStream stream) { return new HessianCauchoInput(stream); } protected CauchoOutput createCauchoOutput(OutputStream stream) { return new HessianCauchoOutput(stream); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/HessianServlet.java100644 0 0 2371 10513545721 23475 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.hessian; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import mx4j.tools.remote.caucho.CauchoInput; import mx4j.tools.remote.caucho.CauchoOutput; import mx4j.tools.remote.caucho.CauchoService; import mx4j.tools.remote.caucho.CauchoServlet; /** * @version $Revision: 1.4 $ */ public class HessianServlet extends CauchoServlet { private CauchoService service; public void init() throws ServletException { super.init(); service = createService(); } protected CauchoService createService() { return new CauchoService("hessian"); } public void destroy() { this.service = null; } protected Object getService() { return service; } protected CauchoInput createCauchoInput(InputStream stream) { return new HessianCauchoInput(stream); } protected CauchoOutput createCauchoOutput(OutputStream stream) { return new HessianCauchoOutput(stream); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/SSLHessianServlet.java100644 0 0 1021 10513545721 24046 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.hessian; import mx4j.tools.remote.caucho.CauchoService; /** * @version $Revision: 1.1 $ */ public class SSLHessianServlet extends HessianServlet { protected CauchoService createService() { return new CauchoService("hessian+ssl"); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/serialization/JMXDeserializer.java100644 0 0 2221 10513545721 24754 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.serialization; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.Deserializer; /** * @version $ */ class JMXDeserializer extends Deserializer { private Class type; JMXDeserializer(Class type) { this.type = type; } public Class getType() { return type; } public Object readMap(AbstractHessianInput in) throws IOException { try { byte[] bytes = in.readBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Object result = ois.readObject(); ois.close(); return result; } catch (ClassNotFoundException x) { throw new IOException(x.toString()); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/serialization/JMXSerializer.java100644 0 0 1640 10513545721 24447 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.serialization; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import com.caucho.hessian.io.AbstractHessianOutput; import com.caucho.hessian.io.Serializer; /** * @version $Revision: 1.3 $ */ class JMXSerializer extends Serializer { public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { out.writeMapBegin(obj.getClass().getName()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); out.writeBytes(baos.toByteArray()); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/serialization/JMXSerializerFactory.java100644 0 0 2137 10513545721 26001 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.caucho.serialization; import com.caucho.hessian.io.Deserializer; import com.caucho.hessian.io.Serializer; import com.caucho.hessian.io.SerializerFactory; /** * @version $Revision: 1.4 $ */ public class JMXSerializerFactory extends SerializerFactory { protected Serializer getDefaultSerializer(Class cls) { if (!cls.getName().startsWith("javax.management.")) return super.getDefaultSerializer(cls); return new JMXSerializer(); } protected Deserializer getDefaultDeserializer(Class cls) { if (!cls.getName().startsWith("javax.management.")) return super.getDefaultDeserializer(cls); // A bug in the Hessian protocol requires JMX exception to be treated as normal objects if (Throwable.class.isAssignableFrom(cls)) return super.getDefaultDeserializer(cls); return new JMXDeserializer(cls); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPClientInvoker.java100644 0 0 15535 10513545721 22123 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.Set; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; /** * @version $Revision: 1.3 $ */ public abstract class HTTPClientInvoker implements HTTPConnection { private String connectionId; protected abstract HTTPConnection getService(); public String connect(Object credentials) throws IOException, SecurityException { connectionId = getService().connect(credentials); return connectionId; } public void close() throws IOException { getService().close(); } public String getConnectionId() throws IOException { return connectionId; } public ObjectInstance createMBean(String className, ObjectName name, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return getService().createMBean(className, name, params, signature, delegate); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return getService().createMBean(className, name, loaderName, params, signature, delegate); } public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException { getService().unregisterMBean(name, delegate); } public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException { return getService().getObjectInstance(name, delegate); } public Set queryMBeans(ObjectName name, Object query, Subject delegate) throws IOException { return getService().queryMBeans(name, query, delegate); } public Set queryNames(ObjectName name, Object query, Subject delegate) throws IOException { return getService().queryNames(name, query, delegate); } public boolean isRegistered(ObjectName name, Subject delegate) throws IOException { return getService().isRegistered(name, delegate); } public Integer getMBeanCount(Subject delegate) throws IOException { return getService().getMBeanCount(delegate); } public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { return getService().getAttribute(name, attribute, delegate); } public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { return getService().getAttributes(name, attributes, delegate); } public void setAttribute(ObjectName name, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { getService().setAttribute(name, attribute, delegate); } public AttributeList setAttributes(ObjectName name, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { return getService().setAttributes(name, attributes, delegate); } public Object invoke(ObjectName name, String operationName, Object params, String[] signature, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { return getService().invoke(name, operationName, params, signature, delegate); } public String getDefaultDomain(Subject delegate) throws IOException { return getService().getDefaultDomain(delegate); } public String[] getDomains(Subject delegate) throws IOException { return getService().getDomains(delegate); } public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { return getService().getMBeanInfo(name, delegate); } public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException { return getService().isInstanceOf(name, className, delegate); } public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { getService().addNotificationListener(name, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getService().removeNotificationListener(name, listener, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getService().removeNotificationListener(name, listener, filter, handback, delegate); } public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException { return getService().addNotificationListener(name, filter, delegate); } public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getService().removeNotificationListeners(name, listenerIDs, delegate); } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { return getService().fetchNotifications(clientSequenceNumber, maxNotifications, timeout); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnection.java100644 0 0 4026 10513545721 21417 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.ObjectName; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; import mx4j.tools.remote.JMXConnection; /** * @version $Revision: 1.3 $ */ public interface HTTPConnection extends JMXConnection { /** * This method is called when a call initiated by {@link javax.management.remote.JMXConnector#connect} * arrives on server side. For HTTP connections, the socket is handled by the web container, but * the remote procedure call that arrives along with the HTTP request is parsed and then (normally) * forwarded to a JavaBean (that will implement this interface). * Implementations of this method will normally call {@link mx4j.tools.remote.ConnectionManager#connect}. * * @param credentials The credential for authentication * @return The connection id for the newly created connection * @throws IOException If a communication problem occurs * @throws SecurityException If the authentication fails */ public String connect(Object credentials) throws IOException, SecurityException; public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException; public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnectionHandler.java100644 0 0 4147 10513545721 22721 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.ObjectName; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; import mx4j.tools.remote.ConnectionManager; import mx4j.tools.remote.JMXConnection; import mx4j.tools.remote.JMXConnectionHandler; /** * @version $Revision: 1.4 $ */ public class HTTPConnectionHandler extends JMXConnectionHandler implements HTTPConnection { public HTTPConnectionHandler(JMXConnection connection, ConnectionManager manager, String connectionId) { super(connection, manager, connectionId); } public String connect(Object credentials) throws IOException, SecurityException { throw new Error("Method connect() must not be forwarded to the invocation chain"); } public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); return ((HTTPConnection)getConnection()).addNotificationListener(name, filter, delegate); } public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); ((HTTPConnection)getConnection()).removeNotificationListeners(name, listenerIDs, delegate); } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { if (isClosed()) throw new IOException("Connection has been closed"); return ((HTTPConnection)getConnection()).fetchNotifications(clientSequenceNumber, maxNotifications, timeout); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnectionMBeanServerConnection.java100644 0 0 7634 10513545721 25541 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.security.auth.Subject; import mx4j.remote.NotificationTuple; import mx4j.remote.RemoteNotificationClientHandler; import mx4j.tools.remote.JMXConnection; import mx4j.tools.remote.JMXConnectionMBeanServerConnection; /** * Implementation of an adapter that converts MBeanServerConnection calls * to HTTPConnection calls. * It handles remote notifications, but it does not handle unmarshalling of * arguments (and all related classloading problems). * NotificationFilters are always invoked on client side. * * @version $Revision: 1.4 $ */ public class HTTPConnectionMBeanServerConnection extends JMXConnectionMBeanServerConnection { private final RemoteNotificationClientHandler notificationHandler; public HTTPConnectionMBeanServerConnection(JMXConnection connection, Subject delegate, RemoteNotificationClientHandler notificationHandler) { super(connection, delegate); this.notificationHandler = notificationHandler; } public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, IOException { NotificationTuple tuple = new NotificationTuple(observed, listener, filter, handback); // Filters are always invoked on client side, for now tuple.setInvokeFilter(true); if (notificationHandler.contains(tuple)) return; Integer id = ((HTTPConnection)getConnection()).addNotificationListener(observed, null, getDelegateSubject()); notificationHandler.addNotificationListener(id, tuple); } public void removeNotificationListener(ObjectName observed, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException { Integer[] ids = notificationHandler.getNotificationListeners(new NotificationTuple(observed, listener)); if (ids == null) throw new ListenerNotFoundException("Could not find listener " + listener); try { ((HTTPConnection)getConnection()).removeNotificationListeners(observed, ids, getDelegateSubject()); notificationHandler.removeNotificationListeners(ids); } catch (InstanceNotFoundException x) { notificationHandler.removeNotificationListeners(ids); throw x; } catch (ListenerNotFoundException x) { notificationHandler.removeNotificationListeners(ids); throw x; } } public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException { Integer id = notificationHandler.getNotificationListener(new NotificationTuple(observed, listener, filter, handback)); if (id == null) throw new ListenerNotFoundException("Could not find listener " + listener + " with filter " + filter + " and handback " + handback); Integer[] ids = new Integer[]{id}; try { ((HTTPConnection)getConnection()).removeNotificationListeners(observed, ids, getDelegateSubject()); notificationHandler.removeNotificationListeners(ids); } catch (InstanceNotFoundException x) { notificationHandler.removeNotificationListeners(ids); throw x; } catch (ListenerNotFoundException x) { notificationHandler.removeNotificationListeners(ids); throw x; } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnectionManager.java100644 0 0 4122 10513545721 22707 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.Map; import javax.management.MBeanServerConnection; import javax.security.auth.Subject; import mx4j.remote.DefaultRemoteNotificationServerHandler; import mx4j.remote.RemoteNotificationServerHandler; import mx4j.tools.remote.AbstractConnectionManager; import mx4j.tools.remote.AbstractJMXConnectorServer; import mx4j.tools.remote.Connection; /** * @version $Revision: 1.4 $ */ public class HTTPConnectionManager extends AbstractConnectionManager { private final MBeanServerConnection mbeanServerConnection; private final String protocol; public HTTPConnectionManager(AbstractJMXConnectorServer server, String protocol, Map environment) { super(server, environment); this.mbeanServerConnection = server.getMBeanServer(); this.protocol = protocol; } public String getProtocol() { return protocol; } protected Connection doConnect(String connectionId, Subject subject) throws IOException { RemoteNotificationServerHandler notificationHandler = new DefaultRemoteNotificationServerHandler(getEnvironment()); HTTPConnection invoker = new HTTPServerInvoker(mbeanServerConnection, notificationHandler); HTTPConnection subjectInvoker = HTTPSubjectInvoker.newInstance(invoker, subject, getSecurityContext(), getEnvironment()); Connection handler = new HTTPConnectionHandler(subjectInvoker, this, connectionId); return handler; } /** * HTTPConnectionManager does not really manages connections, * so this method does nothing by default */ protected void doClose() throws IOException { } /** * HTTPConnectionManager does not really manages connections, * so this method does nothing by default */ protected void doCloseConnection(Connection connection) throws IOException { } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnector.java100644 0 0 6464 10513545721 21262 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import mx4j.remote.ConnectionNotificationEmitter; import mx4j.remote.ConnectionResolver; import mx4j.remote.HeartBeat; import mx4j.remote.RemoteNotificationClientHandler; import mx4j.tools.remote.AbstractJMXConnector; /** * @version $ */ public class HTTPConnector extends AbstractJMXConnector { private transient HTTPConnection connection; private transient String connectionId; private transient HeartBeat heartbeat; private transient RemoteNotificationClientHandler notificationHandler; public HTTPConnector(JMXServiceURL address, Map environment) throws IOException { super(address); } protected void doConnect(Map environment) throws IOException, SecurityException { JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); HTTPConnection temp = (HTTPConnection)resolver.lookupClient(address, environment); connection = (HTTPConnection)resolver.bindClient(temp, environment); Object credentials = environment == null ? null : environment.get(CREDENTIALS); connectionId = connection.connect(credentials); this.heartbeat = createHeartBeat(connection, getConnectionNotificationEmitter(), environment); this.notificationHandler = createRemoteNotificationClientHandler(connection, getConnectionNotificationEmitter(), heartbeat, environment); this.heartbeat.start(); this.notificationHandler.start(); } protected HeartBeat createHeartBeat(HTTPConnection connection, ConnectionNotificationEmitter emitter, Map environment) { return new HTTPHeartBeat(connection, emitter, environment); } protected RemoteNotificationClientHandler createRemoteNotificationClientHandler(HTTPConnection connection, ConnectionNotificationEmitter emitter, HeartBeat heartbeat, Map environment) { return new HTTPRemoteNotificationClientHandler(connection, emitter, heartbeat, environment); } protected MBeanServerConnection doGetMBeanServerConnection(Subject delegate) throws IOException { return new HTTPConnectionMBeanServerConnection(getHTTPConnection(), delegate, getRemoteNotificationClientHandler()); } protected void doClose() throws IOException { if (notificationHandler != null) notificationHandler.stop(); if (heartbeat != null) heartbeat.stop(); if (connection != null) connection.close(); } public String getConnectionId() throws IOException { return connectionId; } protected HTTPConnection getHTTPConnection() { return connection; } protected RemoteNotificationClientHandler getRemoteNotificationClientHandler() { return notificationHandler; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPConnectorServer.java100644 0 0 11270 10513545721 22460 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXServiceURL; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.remote.ConnectionResolver; import mx4j.tools.remote.AbstractJMXConnectorServer; import mx4j.tools.remote.ConnectionManager; /** * @version $Revision: 1.5 $ */ public class HTTPConnectorServer extends AbstractJMXConnectorServer { /** * MX4J's implementation uses this property to specify a String that points to the configuration * resource used to configure the HTTP server for JSR 160 connectors that use HTTP as transport. * For Jetty, the default HTTP server, this can be a URL or a relative path (in this latter case * the resource must be in classpath). */ public static final String WEB_CONTAINER_CONFIGURATION = "jmx.remote.x.http.server.configuration"; public static final String USE_EXTERNAL_WEB_CONTAINER = "jmx.remote.x.http.use.external.web.container"; public static final String EMBEDDED_WEB_CONTAINER_CLASS = "jmx.remote.x.http.embedded.web.container.class"; private static Map instances = new HashMap(); private WebContainer webContainer; private ConnectionManager connectionManager; public HTTPConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) { super(url, environment, server); } protected void doStart() throws IOException, IllegalStateException { MBeanServer server = getMBeanServer(); if (server == null) throw new IllegalStateException("This JMXConnectorServer is not attached to an MBeanServer"); JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); Map environment = getEnvironment(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); webContainer = (WebContainer)resolver.createServer(address, environment); setAddress(resolver.bindServer(webContainer, address, environment)); connectionManager = createConnectionManager(this, address, environment); // Here is where we give to clients the possibility to access us register(getAddress(), connectionManager); } protected ConnectionManager createConnectionManager(AbstractJMXConnectorServer server, JMXServiceURL url, Map environment) { return new HTTPConnectionManager(server, url.getProtocol(), environment); } private void register(JMXServiceURL url, ConnectionManager manager) throws IOException { synchronized (HTTPConnectorServer.class) { // TODO: must use weak references to connection managers, otherwise they're not GC'ed // TODO: in case the connector server is not stopped cleanly if (instances.get(url) != null) throw new IOException("A JMXConnectorServer is already serving at address " + url); instances.put(url, manager); } } private void unregister(JMXServiceURL url) throws IOException { synchronized (HTTPConnectorServer.class) { Object removed = instances.remove(url); if (removed == null) throw new IOException("No JMXConnectorServer is present for address " + url); } } static ConnectionManager find(JMXServiceURL address) { synchronized (HTTPConnectorServer.class) { ConnectionManager manager = (ConnectionManager)instances.get(address); if (manager != null) return manager; Logger logger = Log.getLogger(HTTPConnectorServer.class.getName()); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Known HTTPConnectorServers bound at " + instances.keySet()); return null; } } protected void doStop() throws IOException { JMXServiceURL url = getAddress(); unregister(url); if (connectionManager != null) { connectionManager.close(); connectionManager = null; } String protocol = url.getProtocol(); Map environment = getEnvironment(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); resolver.unbindServer(webContainer, url, environment); resolver.destroyServer(webContainer, url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPHeartBeat.java100644 0 0 1510 10513545721 21152 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.Map; import mx4j.remote.AbstractHeartBeat; import mx4j.remote.ConnectionNotificationEmitter; /** * @version $Revision: 1.3 $ */ public class HTTPHeartBeat extends AbstractHeartBeat { private final HTTPConnection connection; public HTTPHeartBeat(HTTPConnection connection, ConnectionNotificationEmitter emitter, Map environment) { super(emitter, environment); this.connection = connection; } protected void pulse() throws IOException { connection.getDefaultDomain(null); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPRemoteNotificationClientHandler.java100644 0 0 2167 10513545721 25563 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.Map; import javax.management.remote.NotificationResult; import mx4j.remote.AbstractRemoteNotificationClientHandler; import mx4j.remote.ConnectionNotificationEmitter; import mx4j.remote.HeartBeat; /** * @version $Revision: 1.3 $ */ public class HTTPRemoteNotificationClientHandler extends AbstractRemoteNotificationClientHandler { private final HTTPConnection connection; public HTTPRemoteNotificationClientHandler(HTTPConnection connection, ConnectionNotificationEmitter emitter, HeartBeat heartbeat, Map environment) { super(emitter, heartbeat, environment); this.connection = connection; } protected NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) throws IOException { return connection.fetchNotifications(sequence, maxNumber, timeout); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPResolver.java100644 0 0 17274 10513545721 21152 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.remote.ConnectionResolver; /** * @version $Revision: 1.4 $ */ public abstract class HTTPResolver extends ConnectionResolver { protected static final String DEFAULT_WEB_CONTAINER_CLASS = "mx4j.tools.remote.http.jetty.JettyWebContainer"; // TODO: maybe worth to use weak references to hold web containers private static Map webContainers = new HashMap(); private static Map deployedURLs = new HashMap(); private static final WebContainer EXTERNAL_WEB_CONTAINER = new ExternalWebContainer(); public Object bindClient(Object client, Map environment) throws IOException { return client; } protected String getEndpoint(JMXServiceURL address, Map environment) { String transport = getEndpointProtocol(environment); return transport + getEndpointPath(address); } protected String getEndpointProtocol(Map environment) { return "http"; } private String getEndpointPath(JMXServiceURL url) { String address = url.toString(); String prefix = "service:jmx:" + url.getProtocol(); return address.substring(prefix.length()); } public Object createServer(JMXServiceURL url, Map environment) throws IOException { WebContainer result = null; boolean useExternalWebContainer = environment == null ? false : Boolean.valueOf(String.valueOf(environment.get(HTTPConnectorServer.USE_EXTERNAL_WEB_CONTAINER))).booleanValue(); if (!useExternalWebContainer) { // Create and start an embedded web container String webContainerClassName = environment == null ? null : (String)environment.get(HTTPConnectorServer.EMBEDDED_WEB_CONTAINER_CLASS); // Not present, by default use Jetty if (webContainerClassName == null || webContainerClassName.length() == 0) webContainerClassName = DEFAULT_WEB_CONTAINER_CLASS; result = findWebContainer(url, webContainerClassName); if (result == null) { result = createWebContainer(url, webContainerClassName, environment); if (result != null) result.start(url, environment); } // Nothing present, give up if (result == null) throw new IOException("Could not start embedded web container"); } return result; } private WebContainer findWebContainer(JMXServiceURL url, String webContainerClassName) { String key = createWebContainerKey(url, webContainerClassName); return (WebContainer)webContainers.get(key); } private String createWebContainerKey(JMXServiceURL url, String webContainerClassName) { return new StringBuffer(webContainerClassName).append("|").append(url.getHost()).append("|").append(url.getPort()).toString(); } public JMXServiceURL bindServer(Object server, JMXServiceURL url, Map environment) throws IOException { WebContainer webContainer = (WebContainer)server; if (!isDeployed(webContainer, url)) { if (webContainer != null) webContainer.deploy(getServletClassName(), url, environment); if (!hasDeployed(webContainer)) { // The jmxconnector web service has never been deployed, deploy it now deploy(url, environment); } addDeployed(webContainer, url); } return url; } protected abstract String getServletClassName(); protected void deploy(JMXServiceURL address, Map environment) throws IOException { } public void unbindServer(Object server, JMXServiceURL address, Map environment) throws IOException { WebContainer webContainer = (WebContainer)server; if (isDeployed(webContainer, address)) { // First undeploy the jmxconnector web service, then undeploy the webContainer: otherwise the service cannot be undeployed removeDeployed(webContainer, address); if (!hasDeployed(webContainer)) { undeploy(address, environment); } if (webContainer != null) webContainer.undeploy(getServletClassName(), address, environment); } } protected void undeploy(JMXServiceURL address, Map environment) throws IOException { } public void destroyServer(Object server, JMXServiceURL url, Map environment) throws IOException { WebContainer webContainer = (WebContainer)server; if (webContainer != null && !hasDeployed(webContainer)) { // No more deployed stuff here, shutdown also the web container String key = createWebContainerKey(url, server.getClass().getName()); WebContainer container = (WebContainer)webContainers.remove(key); if (webContainer != container) throw new IOException("Trying to stop the wrong web container: " + server + " should be: " + container); webContainer.stop(); } } protected WebContainer createWebContainer(JMXServiceURL url, String webContainerClassName, Map environment) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (environment != null) { Object cl = environment.get(JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER); if (cl instanceof ClassLoader) loader = (ClassLoader)cl; } try { WebContainer webContainer = (WebContainer)loader.loadClass(webContainerClassName).newInstance(); String key = createWebContainerKey(url, webContainerClassName); webContainers.put(key, webContainer); return webContainer; } catch (Exception x) { } return null; } private boolean isDeployed(WebContainer webContainer, JMXServiceURL url) { if (webContainer == null) webContainer = EXTERNAL_WEB_CONTAINER; Set urls = (Set)deployedURLs.get(webContainer); if (urls == null) return false; return urls.contains(url); } private boolean hasDeployed(WebContainer webContainer) { if (webContainer == null) webContainer = EXTERNAL_WEB_CONTAINER; Set urls = (Set)deployedURLs.get(webContainer); if (urls == null) return false; return !urls.isEmpty(); } private void addDeployed(WebContainer webContainer, JMXServiceURL url) { if (webContainer == null) webContainer = EXTERNAL_WEB_CONTAINER; Set urls = (Set)deployedURLs.get(webContainer); if (urls == null) { urls = new HashSet(); deployedURLs.put(webContainer, urls); } urls.add(url); } private void removeDeployed(WebContainer webContainer, JMXServiceURL url) { if (webContainer == null) webContainer = EXTERNAL_WEB_CONTAINER; Set urls = (Set)deployedURLs.get(webContainer); if (urls != null) { urls.remove(url); if (urls.isEmpty()) deployedURLs.remove(webContainer); } } private static class ExternalWebContainer implements WebContainer { public void start(JMXServiceURL url, Map environment) throws IOException { } public void stop() throws IOException { } public void deploy(String servletClassName, JMXServiceURL url, Map environment) throws IOException { } public void undeploy(String servletClassName, JMXServiceURL url, Map environment) { } public String toString() { return "External WebContainer"; } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPServerInvoker.java100644 0 0 6366 10513545721 22135 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanServerConnection; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; import mx4j.remote.NotificationTuple; import mx4j.remote.RemoteNotificationServerHandler; import mx4j.tools.remote.AbstractServerInvoker; /** * Implementation of the HTTPConnector interface that forwards the calls * to an MBeanServerConnection object. * It handles remote notifications, but it does not handle unmarshalling of * arguments (and all related classloading problems). * * @version $Revision: 1.3 $ */ public class HTTPServerInvoker extends AbstractServerInvoker implements HTTPConnection { private final RemoteNotificationServerHandler notificationHandler; public HTTPServerInvoker(MBeanServerConnection server, RemoteNotificationServerHandler handler) { super(server); this.notificationHandler = handler; } public String connect(Object credentials) throws IOException, SecurityException { return null; } public void close() throws IOException { NotificationTuple[] tuples = notificationHandler.close(); for (int i = 0; i < tuples.length; ++i) { NotificationTuple tuple = tuples[i]; try { getServer().removeNotificationListener(tuple.getObjectName(), tuple.getNotificationListener(), tuple.getNotificationFilter(), tuple.getHandback()); } catch (InstanceNotFoundException ignored) { } catch (ListenerNotFoundException ignored) { } } } public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException { Integer id = notificationHandler.generateListenerID(name, null); NotificationListener listener = notificationHandler.getServerNotificationListener(); getServer().addNotificationListener(name, listener, null, id); notificationHandler.addNotificationListener(id, new NotificationTuple(name, listener, null, id)); return id; } public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { for (int i = 0; i < listenerIDs.length; ++i) { Integer id = listenerIDs[i]; NotificationTuple tuple = notificationHandler.removeNotificationListener(id); getServer().removeNotificationListener(name, tuple.getNotificationListener(), tuple.getNotificationFilter(), tuple.getHandback()); } } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { return notificationHandler.fetchNotifications(clientSequenceNumber, maxNotifications, timeout); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPService.java100644 0 0 27040 10513545721 20741 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXServiceURL; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.tools.remote.Connection; import mx4j.tools.remote.ConnectionManager; /** * @version $Revision: 1.4 $ */ public abstract class HTTPService implements HTTPConnection { private final Map connections = new HashMap(); protected Logger getLogger() { return Log.getLogger(getClass().getName()); } public String connect(Object credentials) throws IOException, SecurityException { JMXServiceURL address = findJMXServiceURL(); // Lookup the ConnectionManager ConnectionManager connectionManager = HTTPConnectorServer.find(address); if (connectionManager == null) throw new IOException("Could not find ConnectionManager. Make sure a HTTPConnectorServer is in classloader scope and bound at this address " + address); Connection connection = connectionManager.connect(credentials); addConnection(connection); return connection.getConnectionId(); } protected JMXServiceURL findJMXServiceURL() throws MalformedURLException { String url = findRequestURL(); JMXServiceURL temp = new JMXServiceURL("service:jmx:" + url); int port = temp.getPort(); if ("http".equals(temp.getProtocol()) && port == 0) { // Default HTTP port, set it to 80 port = 80; } else if ("https".equals(temp.getProtocol()) && port == 0) { // Default HTTPS port, set it to 443 port = 443; } return new JMXServiceURL(getProtocol(), temp.getHost(), port, temp.getURLPath()); } protected abstract String findRequestURL(); protected abstract String getProtocol(); protected void addConnection(Connection connection) throws IOException { String connectionId = connection.getConnectionId(); synchronized (this) { if (connections.containsKey(connectionId)) throw new IOException("Connection '" + connection + "' already connected"); connections.put(connectionId, connection); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Added connection '" + connectionId + "', known connections are " + connections.keySet()); } } protected void removeConnection(Connection connection) throws IOException { String connectionId = connection.getConnectionId(); synchronized (this) { if (!connections.containsKey(connectionId)) throw new IOException("Connection '" + connection + "' unknown"); connections.remove(connectionId); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Removed connection '" + connectionId + "', known connections are " + connections.keySet()); } } protected Connection findConnection() throws IOException { String connectionId = findConnectionId(); synchronized (this) { Connection connection = (Connection)connections.get(connectionId); if (connection != null) return connection; Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Unknown connection '" + connectionId + "', known connections are " + connections.keySet()); throw new IOException("Connection ID '" + connectionId + "' unknown"); } } protected abstract String findConnectionId(); public void close() throws IOException { Connection connection = findConnection(); removeConnection(connection); connection.close(); } public String getConnectionId() throws IOException { Connection connection = findConnection(); return connection.getConnectionId(); } public ObjectInstance createMBean(String className, ObjectName name, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.createMBean(className, name, params, signature, delegate); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params, String[] signature, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.createMBean(className, name, loaderName, params, signature, delegate); } public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.unregisterMBean(name, delegate); } public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getObjectInstance(name, delegate); } public Set queryMBeans(ObjectName name, Object query, Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.queryMBeans(name, query, delegate); } public Set queryNames(ObjectName name, Object query, Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.queryNames(name, query, delegate); } public boolean isRegistered(ObjectName name, Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.isRegistered(name, delegate); } public Integer getMBeanCount(Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getMBeanCount(delegate); } public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getAttribute(name, attribute, delegate); } public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getAttributes(name, attributes, delegate); } public void setAttribute(ObjectName name, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.setAttribute(name, attribute, delegate); } public AttributeList setAttributes(ObjectName name, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.setAttributes(name, attributes, delegate); } public Object invoke(ObjectName name, String operationName, Object params, String[] signature, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.invoke(name, operationName, params, signature, delegate); } public String getDefaultDomain(Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getDefaultDomain(delegate); } public String[] getDomains(Subject delegate) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getDomains(delegate); } public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.getMBeanInfo(name, delegate); } public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.isInstanceOf(name, className, delegate); } public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.addNotificationListener(name, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.removeNotificationListener(name, listener, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.removeNotificationListener(name, listener, filter, handback, delegate); } public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.addNotificationListener(name, filter, delegate); } public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { HTTPConnection connection = (HTTPConnection)findConnection(); connection.removeNotificationListeners(name, listenerIDs, delegate); } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { HTTPConnection connection = (HTTPConnection)findConnection(); return connection.fetchNotifications(clientSequenceNumber, maxNotifications, timeout); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/HTTPSubjectInvoker.java100644 0 0 2772 10513545721 22263 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.AccessControlContext; import java.util.Map; import javax.security.auth.Subject; import mx4j.tools.remote.SubjectInvoker; /** * @version $Revision: 1.5 $ */ public class HTTPSubjectInvoker extends SubjectInvoker { public static HTTPConnection newInstance(HTTPConnection target, Subject subject, AccessControlContext context, Map environment) { HTTPSubjectInvoker handler = new HTTPSubjectInvoker(target, subject, context, environment); return (HTTPConnection)Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[]{HTTPConnection.class}, handler); } private HTTPSubjectInvoker(HTTPConnection target, Subject subject, AccessControlContext context, Map environment) { super(target, subject, context, environment); } protected boolean isPlainInvoke(Method method) { boolean plain = super.isPlainInvoke(method); if (plain) return plain; String methodName = method.getName(); // HTTPConnection methods that do not require the delegate subject if ("fetchNotifications".equals(methodName)) return true; if ("close".equals(methodName)) return true; return false; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/WebContainer.java100644 0 0 2161 10513545721 21176 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http; import java.io.IOException; import java.util.Map; import javax.management.remote.JMXServiceURL; /** * An Interface for the Web Container so that we can plug in any web container. * * @version $Revision: 1.3 $ */ public interface WebContainer { /** * Starts the web container */ public void start(JMXServiceURL url, Map environment) throws IOException; /** * Stops the web container */ public void stop() throws IOException; /** * Deploys the given servlet class mapping it to the URL specified by the given JMXServiceURL. */ public void deploy(String servletClassName, JMXServiceURL url, Map environment) throws IOException; /** * Undeploys the servlet mapped to the URL specified by the given JMXServiceURL. */ public void undeploy(String servletClassName, JMXServiceURL url, Map environment); } mx4j-3.0.2/src/tools/mx4j/tools/remote/http/jetty/JettyWebContainer.java100644 0 0 11707 10513545721 23403 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.http.jetty; import java.io.IOException; import java.util.Map; import javax.management.remote.JMXServiceURL; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.tools.remote.http.HTTPConnectorServer; import mx4j.tools.remote.http.WebContainer; import org.mortbay.http.HttpListener; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.ServletHandler; import org.mortbay.jetty.servlet.ServletHttpContext; /** * Jetty's implementation of WebContainer interface * * @version $Revision: 1.6 $ */ public class JettyWebContainer implements WebContainer { private final Server server; public JettyWebContainer() { server = new Server(); } protected Logger getLogger() { return Log.getLogger(getClass().getName()); } protected Server getServer() { return server; } public void start(JMXServiceURL url, Map environment) throws IOException { try { configure(url, environment); getServer().start(); } catch (IOException x) { throw x; } catch (Exception x) { throw new IOException(x.toString()); } } private void configure(JMXServiceURL url, Map environment) throws IOException { Logger logger = getLogger(); if (environment != null) { Object config = environment.get(HTTPConnectorServer.WEB_CONTAINER_CONFIGURATION); if (config instanceof String) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Configuring Jetty with configuration " + config); getServer().configure((String)config); // Be sure there is at least one listener on the port specified by the JMXServiceURL HttpListener[] listeners = getServer().getListeners(); if (listeners != null) { boolean found = false; for (int i = 0; i < listeners.length; ++i) { HttpListener listener = listeners[i]; if (listener.getPort() == url.getPort()) { found = true; break; } } if (!found) throw new IOException("No listener configured with configuration " + config + " matches JMXServiceURL " + url); // Configured successfully, return if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Configured Jetty successfully with configuration " + config); return; } else { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Jetty configuration " + config + " does not have any listener"); } } else { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Skipping Jetty configuration " + config + " (must be a String)"); } } configureListener(url, environment); } protected void configureListener(JMXServiceURL url, Map environment) throws IOException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Configuring Jetty with a default listener on port " + url.getPort()); String host = url.getHost(); if (host == null) host = ""; getServer().addListener(host + ":" + url.getPort()); } public void stop() throws IOException { try { getServer().stop(); } catch (InterruptedException x) { Thread.currentThread().interrupt(); } } public void deploy(String servletClassName, JMXServiceURL url, Map environment) throws IOException { try { String urlPattern = resolveServletMapping(url); ServletHttpContext context = (ServletHttpContext)getServer().getContext("/"); context.addServlet(urlPattern, servletClassName); // TODO: be sure an undeployed url is not restarted ! if (!context.isStarted()) context.start(); } catch (Exception x) { throw new IOException(x.toString()); } } public void undeploy(String servletName, JMXServiceURL url, Map environment) { String urlPattern = resolveServletMapping(url); ServletHttpContext context = (ServletHttpContext)getServer().getContext("/"); ServletHandler handler = context.getServletHandler(); handler.getServletMap().remove(urlPattern); } private String resolveServletMapping(JMXServiceURL url) { String path = url.getURLPath(); String urlPattern = null; if (path.endsWith("/")) urlPattern = path + "*"; else urlPattern = path + "/*"; if (!urlPattern.startsWith("/")) urlPattern = "/" + urlPattern; return urlPattern; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnection.java100644 0 0 2516 10513545721 22007 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.security.auth.Subject; import mx4j.tools.remote.JMXConnection; /** * @version $Revision: 1.6 $ */ public interface LocalConnection extends JMXConnection { public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException; public void removeNotificationListener(ObjectName observed, NotificationListener listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnectionHandler.java100644 0 0 4066 10513545721 23307 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.security.auth.Subject; import mx4j.tools.remote.JMXConnectionHandler; /** * @version $Revision: 1.3 $ */ class LocalConnectionHandler extends JMXConnectionHandler implements LocalConnection { LocalConnectionHandler(String connectionId, LocalConnectionManager manager, LocalConnection target) { super(target, manager, connectionId); } public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); ((LocalConnection)getConnection()).addNotificationListener(observed, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); ((LocalConnection)getConnection()).removeNotificationListener(observed, listener, delegate); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (isClosed()) throw new IOException("Connection has been closed"); ((LocalConnection)getConnection()).removeNotificationListener(observed, listener, filter, handback, delegate); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnectionMBeanServerConnection.java100644 0 0 17353 10513545721 26146 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.MBeanServerConnection; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.security.auth.Subject; /** * @version $Revision: 1.3 $ */ class LocalConnectionMBeanServerConnection implements MBeanServerConnection { private final LocalConnection connection; private final Subject delegate; LocalConnectionMBeanServerConnection(LocalConnection connection, Subject delegate) { this.connection = connection; this.delegate = delegate; } public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, IOException { connection.addNotificationListener(observed, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName observed, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException { connection.removeNotificationListener(observed, listener, delegate); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException { connection.removeNotificationListener(observed, listener, filter, handback, delegate); } public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, IOException { connection.addNotificationListener(observed, listener, filter, handback, delegate); } public void removeNotificationListener(ObjectName observed, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException { connection.removeNotificationListener(observed, listener, delegate); } public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException, IOException { connection.removeNotificationListener(observed, listener, filter, handback, delegate); } public MBeanInfo getMBeanInfo(ObjectName objectName) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { return connection.getMBeanInfo(objectName, delegate); } public boolean isInstanceOf(ObjectName objectName, String className) throws InstanceNotFoundException, IOException { return connection.isInstanceOf(objectName, className, delegate); } public String[] getDomains() throws IOException { return connection.getDomains(delegate); } public String getDefaultDomain() throws IOException { return connection.getDefaultDomain(delegate); } public ObjectInstance createMBean(String className, ObjectName objectName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return connection.createMBean(className, objectName, null, null, delegate); } public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return connection.createMBean(className, objectName, args, parameters, delegate); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return connection.createMBean(className, objectName, loaderName, null, null, delegate); } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return connection.createMBean(className, objectName, loaderName, args, parameters, delegate); } public void unregisterMBean(ObjectName objectName) throws InstanceNotFoundException, MBeanRegistrationException, IOException { connection.unregisterMBean(objectName, delegate); } public Object getAttribute(ObjectName objectName, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { return connection.getAttribute(objectName, attribute, delegate); } public void setAttribute(ObjectName objectName, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { connection.setAttribute(objectName, attribute, delegate); } public AttributeList getAttributes(ObjectName objectName, String[] attributes) throws InstanceNotFoundException, ReflectionException, IOException { return connection.getAttributes(objectName, attributes, delegate); } public AttributeList setAttributes(ObjectName objectName, AttributeList attributes) throws InstanceNotFoundException, ReflectionException, IOException { return connection.setAttributes(objectName, attributes, delegate); } public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { return connection.invoke(objectName, methodName, args, parameters, delegate); } public Integer getMBeanCount() throws IOException { return connection.getMBeanCount(delegate); } public boolean isRegistered(ObjectName objectName) throws IOException { return connection.isRegistered(objectName, delegate); } public ObjectInstance getObjectInstance(ObjectName objectName) throws InstanceNotFoundException, IOException { return connection.getObjectInstance(objectName, delegate); } public Set queryMBeans(ObjectName patternName, QueryExp filter) throws IOException { return connection.queryMBeans(patternName, filter, delegate); } public Set queryNames(ObjectName patternName, QueryExp filter) throws IOException { return connection.queryNames(patternName, filter, delegate); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnectionManager.java100644 0 0 2654 10513545721 23305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import java.util.Map; import javax.management.MBeanServer; import javax.security.auth.Subject; import mx4j.tools.remote.AbstractConnectionManager; import mx4j.tools.remote.Connection; /** * @version $Revision: 1.7 $ */ class LocalConnectionManager extends AbstractConnectionManager { private final MBeanServer mbeanServer; LocalConnectionManager(LocalConnectorServer server, Map environment) { super(server, environment); this.mbeanServer = server.getMBeanServer(); } public String getProtocol() { return "local"; } public Connection doConnect(String connectionId, Subject subject) throws IOException { LocalConnection serverInvoker = new LocalServerInvoker(mbeanServer); LocalConnection subjectInvoker = LocalSubjectInvoker.newInstance(serverInvoker, subject, getSecurityContext(), getEnvironment()); return new LocalConnectionHandler(connectionId, this, subjectInvoker); } protected void doClose() throws IOException { // Yes, do nothing } protected void doCloseConnection(Connection connection) throws IOException { // Yes, do nothing } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnector.java100644 0 0 3724 10513545721 21644 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import mx4j.remote.ConnectionResolver; import mx4j.tools.remote.AbstractJMXConnector; import mx4j.tools.remote.Connection; import mx4j.tools.remote.ConnectionManager; /** * @version $Revision: 1.9 $ */ public class LocalConnector extends AbstractJMXConnector { private transient Connection connection; public LocalConnector(JMXServiceURL url, Map environment) throws IOException { super(url); } protected void doConnect(Map environment) throws IOException, SecurityException { JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); ConnectionManager server = (ConnectionManager)resolver.lookupClient(address, environment); server = (ConnectionManager)resolver.bindClient(server, environment); Object credentials = environment == null ? null : environment.get(CREDENTIALS); connection = server.connect(credentials); } protected void doClose() throws IOException { connection.close(); } protected MBeanServerConnection doGetMBeanServerConnection(Subject delegate) throws IOException { return new LocalConnectionMBeanServerConnection((LocalConnection)connection, delegate); } public String getConnectionId() throws IOException { return connection.getConnectionId(); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalConnectorServer.java100644 0 0 7464 10513545721 23040 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXServiceURL; import mx4j.remote.ConnectionResolver; import mx4j.tools.remote.AbstractJMXConnectorServer; /** * @version $Revision: 1.8 $ */ public class LocalConnectorServer extends AbstractJMXConnectorServer { private static Map instances = new HashMap(); public static LocalConnectionManager find(JMXServiceURL url) { synchronized (LocalConnectorServer.class) { return (LocalConnectionManager)instances.get(url); } } private MBeanServer mbeanServer; private LocalConnectionManager connectionManager; public LocalConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) { super(url, environment, server); } public MBeanServer getMBeanServer() { return mbeanServer; } protected void doStart() throws IOException { JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); Map environment = getEnvironment(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); MBeanServer realServer = null; MBeanServer server = super.getMBeanServer(); MBeanServer resolvedServer = (MBeanServer)resolver.createServer(address, environment); if (resolvedServer == null) { if (server == null) throw new IllegalStateException("This LocalConnectorServer is not attached to an MBeanServer"); realServer = server; } else { if (server == null) { realServer = resolvedServer; } else { if (server != resolvedServer) throw new IllegalStateException("This LocalConnectorServer cannot be attached to 2 MBeanServers"); realServer = server; } } this.mbeanServer = realServer; connectionManager = new LocalConnectionManager(this, environment); setAddress(resolver.bindServer(realServer, address, environment)); // Here is where we give to clients the possibility to access us register(getAddress(), connectionManager); } private void register(JMXServiceURL url, LocalConnectionManager manager) throws IOException { synchronized (LocalConnectorServer.class) { if (instances.get(url) != null) throw new IOException("A LocalConnectorServer is already serving at address " + url); instances.put(url, manager); } } protected void doStop() throws IOException { connectionManager.close(); JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); Map environment = getEnvironment(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); MBeanServer server = getMBeanServer(); resolver.unbindServer(server, address, environment); resolver.destroyServer(server, address, environment); unregister(address); } private void unregister(JMXServiceURL url) throws IOException { synchronized (LocalConnectorServer.class) { Object removed = instances.remove(url); if (removed == null) throw new IOException("No LocalConnectorServer is present for address " + url); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalServerInvoker.java100644 0 0 6053 10513545721 22514 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.management.InstanceNotFoundException; import javax.management.ListenerNotFoundException; import javax.management.MBeanServer; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.security.auth.Subject; import mx4j.remote.NotificationTuple; import mx4j.tools.remote.AbstractServerInvoker; /** * @version $Revision: 1.3 $ */ class LocalServerInvoker extends AbstractServerInvoker implements LocalConnection { private final Set listeners = new HashSet(); LocalServerInvoker(MBeanServer server) { super(server); } public void close() throws IOException { NotificationTuple[] tuples = null; synchronized (listeners) { tuples = (NotificationTuple[])listeners.toArray(new NotificationTuple[listeners.size()]); listeners.clear(); } for (int i = 0; i < tuples.length; i++) { NotificationTuple tuple = tuples[i]; try { getServer().removeNotificationListener(tuple.getObjectName(), tuple.getNotificationListener(), tuple.getNotificationFilter(), tuple.getHandback()); } catch (InstanceNotFoundException ignored) { } catch (ListenerNotFoundException ignored) { } } } public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { NotificationTuple tuple = new NotificationTuple(observed, listener, filter, handback); synchronized (listeners) { listeners.add(tuple); } getServer().addNotificationListener(observed, listener, filter, handback); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { NotificationTuple tuple = new NotificationTuple(observed, listener); synchronized (listeners) { listeners.remove(tuple); } getServer().removeNotificationListener(observed, listener); } public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { NotificationTuple tuple = new NotificationTuple(observed, listener, filter, handback); synchronized (listeners) { listeners.remove(tuple); } getServer().removeNotificationListener(observed, listener, filter, handback); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/local/LocalSubjectInvoker.java100644 0 0 2671 10513545721 22647 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.local; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.AccessControlContext; import java.util.Map; import javax.security.auth.Subject; import mx4j.tools.remote.SubjectInvoker; /** * @version $Revision: 1.4 $ */ class LocalSubjectInvoker extends SubjectInvoker { static LocalConnection newInstance(LocalConnection target, Subject subject, AccessControlContext context, Map environment) { LocalSubjectInvoker handler = new LocalSubjectInvoker(target, subject, context, environment); return (LocalConnection)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[]{LocalConnection.class}, handler); } private LocalSubjectInvoker(LocalConnection target, Subject subject, AccessControlContext context, Map environment) { super(target, subject, context, environment); } protected boolean isPlainInvoke(Method method) { boolean plain = super.isPlainInvoke(method); if (plain) return plain; String methodName = method.getName(); // LocalConnection methods that does not require the delegate subject if ("close".equals(methodName)) return true; return false; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ClientProvider.java100644 0 0 1741 10513545721 23712 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.burlap; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnector; /** * @version $Revision: 1.5 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"burlap".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ServerProvider.java100644 0 0 2114 10513545721 23735 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.burlap; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * @version $Revision: 1.5 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"burlap".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ssl/ClientProvider.java100644 0 0 1751 10513545721 24514 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.burlap.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnector; /** * @version $Revision: 1.2 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"burlap+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ssl/ServerProvider.java100644 0 0 2124 10513545721 24537 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.burlap.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * @version $Revision: 1.2 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"burlap+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ClientProvider.java100644 0 0 1743 10513545721 24061 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.hessian; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnector; /** * @version $Revision: 1.5 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"hessian".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ServerProvider.java100644 0 0 2116 10513545721 24104 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.hessian; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * @version $Revision: 1.5 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"hessian".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ssl/ClientProvider.java100644 0 0 1753 10513545721 24663 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.hessian.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnector; /** * @version $Revision: 1.2 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"hessian+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ssl/ServerProvider.java100644 0 0 2126 10513545721 24706 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.hessian.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * @version $Revision: 1.2 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"hessian+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/local/ClientProvider.java100644 0 0 1742 10513545721 23520 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.local; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.local.LocalConnector; /** * @version $Revision: 1.4 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"local".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new LocalConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/local/ServerProvider.java100644 0 0 2115 10513545721 23543 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.local; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.local.LocalConnectorServer; /** * @version $Revision: 1.4 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"local".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new LocalConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ClientProvider.java100644 0 0 2002 10513545721 23356 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.soap; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.soap.SOAPConnector; /** * SOAP Connector Client Provider * * @version $Revision: 1.6 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"soap".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new SOAPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ServerProvider.java100644 0 0 2155 10513545721 23417 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.soap; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * SOAP Connector Server Provider * * @version $Revision: 1.6 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"soap".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ssl/ClientProvider.java100644 0 0 1745 10513545721 24174 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.soap.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.soap.SOAPConnector; /** * @version $Revision: 1.2 $ */ public class ClientProvider implements JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException { String protocol = url.getProtocol(); if (!"soap+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new SOAPConnector(url, environment); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ssl/ServerProvider.java100644 0 0 2120 10513545721 24210 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.provider.soap.ssl; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerProvider; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.http.HTTPConnectorServer; /** * @version $Revision: 1.2 $ */ public class ServerProvider implements JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { String protocol = url.getProtocol(); if (!"soap+ssl".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this); return new HTTPConnectorServer(url, environment, server); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/proxy/RemoteMBeanProxy.java100644 0 0 15771 10513545721 22253 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.proxy; import java.io.IOException; import java.util.Map; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; /** * @version $Revision: 1.4 $ */ public class RemoteMBeanProxy implements DynamicMBean, NotificationEmitter, MBeanRegistration { private final ObjectName remoteObjectName; private final JMXConnector connector; private final MBeanServerConnection connection; public RemoteMBeanProxy(ObjectName remoteObjectName, JMXServiceURL url, Map environment, Subject delegate) throws IOException { this(remoteObjectName, JMXConnectorFactory.newJMXConnector(url, environment), environment, delegate); } public RemoteMBeanProxy(ObjectName remoteObjectName, JMXConnector connector, Map environment, Subject delegate) throws IOException { this.remoteObjectName = remoteObjectName; this.connector = connector; this.connector.connect(environment); this.connection = connector.getMBeanServerConnection(delegate); } public RemoteMBeanProxy(ObjectName remoteObjectName, MBeanServerConnection connection) { this.remoteObjectName = remoteObjectName; this.connector = null; this.connection = connection; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { JMXConnector cntor = getJMXConnector(); if (cntor != null) cntor.close(); } public void postDeregister() { } protected ObjectName getRemoteObjectName() { return remoteObjectName; } protected MBeanServerConnection getMBeanServerConnection() { return connection; } protected JMXConnector getJMXConnector() { return connector; } public MBeanInfo getMBeanInfo() { try { return getMBeanServerConnection().getMBeanInfo(getRemoteObjectName()); } catch (Exception x) { throw new RemoteMBeanProxyException(x); } } public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { try { return getMBeanServerConnection().getAttribute(getRemoteObjectName(), attribute); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { try { getMBeanServerConnection().setAttribute(getRemoteObjectName(), attribute); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public AttributeList getAttributes(String[] attributes) { try { return getMBeanServerConnection().getAttributes(getRemoteObjectName(), attributes); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (ReflectionException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public AttributeList setAttributes(AttributeList attributes) { try { return getMBeanServerConnection().setAttributes(getRemoteObjectName(), attributes); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (ReflectionException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException { try { return getMBeanServerConnection().invoke(getRemoteObjectName(), method, arguments, params); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public MBeanNotificationInfo[] getNotificationInfo() { return getMBeanInfo().getNotifications(); } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { try { getMBeanServerConnection().addNotificationListener(getRemoteObjectName(), listener, filter, handback); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { try { getMBeanServerConnection().removeNotificationListener(getRemoteObjectName(), listener); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { try { getMBeanServerConnection().removeNotificationListener(getRemoteObjectName(), listener, filter, handback); } catch (InstanceNotFoundException x) { throw new RemoteMBeanProxyException(x); } catch (IOException x) { throw new RemoteMBeanProxyException(x); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/proxy/RemoteMBeanProxyException.java100644 0 0 1645 10513545721 24105 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.proxy; import javax.management.JMRuntimeException; /** * @version $Revision: 1.3 $ */ public class RemoteMBeanProxyException extends JMRuntimeException { private final Exception exception; public RemoteMBeanProxyException() { this(null, null); } public RemoteMBeanProxyException(String message) { this(message, null); } public RemoteMBeanProxyException(Exception exception) { this(null, exception); } public RemoteMBeanProxyException(String message, Exception exception) { super(message); this.exception = exception; } public Throwable getCause() { return exception; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/Resolver.java100644 0 0 1633 10513545721 22571 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.burlap; import java.io.IOException; import java.util.Map; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.caucho.burlap.BurlapClientInvoker; import mx4j.tools.remote.caucho.burlap.BurlapServlet; import mx4j.tools.remote.http.HTTPResolver; /** * @version $Revision: 1.1 $ */ public class Resolver extends HTTPResolver { public Object lookupClient(JMXServiceURL url, Map environment) throws IOException { String endpoint = getEndpoint(url, environment); return new BurlapClientInvoker(endpoint); } protected String getServletClassName() { return BurlapServlet.class.getName(); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/ssl/Resolver.java100644 0 0 1243 10513545721 23367 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.burlap.ssl; import java.util.Map; import mx4j.tools.remote.caucho.burlap.SSLBurlapServlet; /** * @version $Revision: 1.1 $ */ public class Resolver extends mx4j.tools.remote.resolver.burlap.Resolver { protected String getEndpointProtocol(Map environment) { return "https"; } protected String getServletClassName() { return SSLBurlapServlet.class.getName(); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/Resolver.java100644 0 0 1642 10513545721 22736 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.hessian; import java.io.IOException; import java.util.Map; import javax.management.remote.JMXServiceURL; import mx4j.tools.remote.caucho.hessian.HessianClientInvoker; import mx4j.tools.remote.caucho.hessian.HessianServlet; import mx4j.tools.remote.http.HTTPResolver; /** * @version $Revision: 1.1 $ */ public class Resolver extends HTTPResolver { public Object lookupClient(JMXServiceURL url, Map environment) throws IOException { String endpoint = getEndpoint(url, environment); return new HessianClientInvoker(endpoint); } protected String getServletClassName() { return HessianServlet.class.getName(); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/ssl/Resolver.java100644 0 0 1250 10513545721 23532 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.hessian.ssl; import java.util.Map; import mx4j.tools.remote.caucho.hessian.SSLHessianServlet; /** * @version $Revision: 1.1 $ */ public class Resolver extends mx4j.tools.remote.resolver.hessian.Resolver { protected String getEndpointProtocol(Map environment) { return "https"; } protected String getServletClassName() { return SSLHessianServlet.class.getName(); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/local/Resolver.java100644 0 0 7164 10513545721 22403 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.local; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.remote.JMXServiceURL; import mx4j.remote.ConnectionResolver; import mx4j.tools.remote.local.LocalConnectorServer; /** * @version $Revision: 1.1 $ */ public class Resolver extends ConnectionResolver { private static final String ID_CONTEXT = "/id/"; private static int connectorID; private final Map mbeanServerIds = new HashMap(); public Object createServer(JMXServiceURL url, Map environment) throws IOException { String connectorID = findConnectorID(url); if (connectorID == null) return null; String mbeanServerId = findMBeanServerId(connectorID); if (mbeanServerId == null) return null; List servers = MBeanServerFactory.findMBeanServer(mbeanServerId); if (servers.size() == 1) return servers.get(0); return null; } private String findConnectorID(JMXServiceURL url) { String path = url.getURLPath(); if (path == null || !path.startsWith(ID_CONTEXT)) return null; return path.substring(ID_CONTEXT.length()); } private String findMBeanServerId(String connectorID) { synchronized (mbeanServerIds) { return (String)mbeanServerIds.get(connectorID); } } public JMXServiceURL bindServer(Object server, JMXServiceURL url, Map environment) throws IOException { String connectorID = findConnectorID(url); if (connectorID == null) connectorID = generateConnectorID(); MBeanServer mbeanServer = (MBeanServer)server; try { String mbeanServerId = (String)mbeanServer.getAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), "MBeanServerId"); synchronized (mbeanServerIds) { String existing = findMBeanServerId(connectorID); if (existing != null && !existing.equals(mbeanServerId)) throw new IOException("LocalConnectorServer with ID " + connectorID + " is already attached to MBeanServer with ID " + existing); mbeanServerIds.put(connectorID, mbeanServerId); } } catch (JMException x) { throw new IOException("Cannot retrieve MBeanServer ID " + x.toString()); } return new JMXServiceURL(url.getProtocol(), url.getHost(), url.getPort(), ID_CONTEXT + connectorID); } private String generateConnectorID() { synchronized (Resolver.class) { return String.valueOf(++connectorID); } } public void unbindServer(Object server, JMXServiceURL address, Map environment) throws IOException { String connectorID = findConnectorID(address); if (connectorID == null) throw new IOException("Unknown LocalConnectorServer ID: " + address); synchronized (mbeanServerIds) { mbeanServerIds.remove(connectorID); } } public void destroyServer(Object server, JMXServiceURL url, Map environment) throws IOException { } public Object lookupClient(JMXServiceURL url, Map environment) throws IOException { return LocalConnectorServer.find(url); } public Object bindClient(Object client, Map environment) throws IOException { return client; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/Resolver.java100644 0 0 7565 10513545721 22260 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.soap; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.management.remote.JMXServiceURL; import mx4j.log.Logger; import mx4j.tools.remote.http.HTTPResolver; import mx4j.tools.remote.soap.SOAPClientInvoker; import org.apache.axis.client.AdminClient; import org.apache.axis.client.Service; import org.apache.axis.configuration.FileProvider; import org.apache.axis.transport.http.AxisServlet; import org.apache.axis.utils.Options; /** * @version $Revision: 1.1 $ */ public class Resolver extends HTTPResolver { private static final String SERVER_DEPLOY_WSDD = "server-deploy.wsdd"; private static final String SERVER_UNDEPLOY_WSDD = "server-undeploy.wsdd"; private static final String CLIENT_WSDD = "client.wsdd"; private static final String AXIS_DEPLOY_SERVICE = "AdminService"; public Object lookupClient(JMXServiceURL address, Map environment) throws IOException { String endpoint = getEndpoint(address, environment); InputStream wsdd = getClass().getResourceAsStream(CLIENT_WSDD); if (wsdd == null) throw new IOException("Could not find AXIS deployment descriptor"); Service service = new Service(new FileProvider(wsdd)); service.setMaintainSession(true); return new SOAPClientInvoker(endpoint, service); } protected String getServletClassName() { return AxisServlet.class.getName(); } protected void deploy(JMXServiceURL address, Map environment) throws IOException { String path = address.getURLPath(); if (!path.endsWith("/")) path += "/"; String deployPath = path + AXIS_DEPLOY_SERVICE; JMXServiceURL temp = new JMXServiceURL(address.getProtocol(), address.getHost(), address.getPort(), deployPath); String deployEndpoint = getEndpoint(temp, environment); try { AdminClient deployer = new AdminClient(); Options options = new Options(null); options.setDefaultURL(deployEndpoint); InputStream wsdd = getClass().getResourceAsStream(SERVER_DEPLOY_WSDD); if (wsdd == null) throw new IOException("Could not find AXIS deployment descriptor"); deployer.process(options, wsdd); } catch (RuntimeException x) { throw x; } catch (Exception x) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.INFO)) logger.info("Exception while deploying AXIS service", x); throw new IOException("Could not deploy connector server to AXIS " + x.toString()); } } protected void undeploy(JMXServiceURL address, Map environment) throws IOException { String path = address.getURLPath(); if (!path.endsWith("/")) path += "/"; String undeployPath = path + AXIS_DEPLOY_SERVICE; JMXServiceURL temp = new JMXServiceURL(address.getProtocol(), address.getHost(), address.getPort(), undeployPath); String undeployEndpoint = getEndpoint(temp, environment); try { AdminClient deployer = new AdminClient(); Options options = new Options(null); options.setDefaultURL(undeployEndpoint); InputStream wsdd = getClass().getResourceAsStream(SERVER_UNDEPLOY_WSDD); if (wsdd == null) throw new IOException("Could not find AXIS deployment descriptor " + SERVER_UNDEPLOY_WSDD); deployer.process(options, wsdd); } catch (Exception x) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.INFO)) logger.info("Exception while undeploying AXIS service", x); throw new IOException("Could not undeploy connector server " + x.toString()); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/client.wsdd100644 0 0 26717 10513545721 21775 0ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/server-deploy.wsdd100644 0 0 27652 10513545721 23316 0ustar 0 0 http://mx4j.sourceforge.net/remote/soap/1.0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/server-undeploy.wsdd100644 0 0 152 10513545721 23603 0ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/Resolver.java100644 0 0 1001 10513545721 23034 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.resolver.soap.ssl; import java.util.Map; /** * @version $Revision: 1.1 $ */ public class Resolver extends mx4j.tools.remote.resolver.soap.Resolver { protected String getEndpointProtocol(Map environment) { return "https"; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/client.wsdd100644 0 0 27100 10513545721 22561 0ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/server-deploy.wsdd100644 0 0 27655 10513545721 24122 0ustar 0 0 http://mx4j.sourceforge.net/remote/soap/1.0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/server-undeploy.wsdd100644 0 0 152 10513545721 24404 0ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/rmi/SSLRMIClientSocketFactory.java100644 0 0 1653 10513545721 23304 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.rmi; import java.io.IOException; import java.io.Serializable; import java.net.Socket; import java.rmi.server.RMIClientSocketFactory; import javax.net.ssl.SSLSocketFactory; /** * @version $Revision: 1.3 $ */ public class SSLRMIClientSocketFactory implements RMIClientSocketFactory, Serializable { public Socket createSocket(String host, int port) throws IOException { return SSLSocketFactory.getDefault().createSocket(host, port); } public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; return getClass() == obj.getClass(); } public int hashCode() { return 13; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/rmi/SSLRMIServerSocketFactory.java100644 0 0 2120 10513545721 23322 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.rmi; import java.io.IOException; import java.net.ServerSocket; import java.rmi.server.RMIServerSocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; /** * @version $Revision: 1.4 $ */ public class SSLRMIServerSocketFactory implements RMIServerSocketFactory { private final SSLContext sslContext; private final int backlog; public SSLRMIServerSocketFactory(SSLContext sslContext) { this(sslContext, 50); } public SSLRMIServerSocketFactory(SSLContext sslContext, int backlog) { this.sslContext = sslContext; this.backlog = backlog; } public ServerSocket createServerSocket(int port) throws IOException { SSLServerSocketFactory factory = sslContext.getServerSocketFactory(); return factory.createServerSocket(port, backlog); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/ClientExceptionCatcher.java100644 0 0 12004 10513545721 23205 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.management.MBeanException; import javax.management.RuntimeMBeanException; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.tools.remote.http.HTTPConnection; import org.apache.axis.AxisFault; /** * Handles exceptions thrown on server-side by rethrowing them on client side. * Axis, as of version 1.1, is not able to do this transparently, so we have to * manually do it here, by parsing the class name and message that are encoded * by Axis in the response. * * @version $Revision: 1.5 $ */ class ClientExceptionCatcher implements InvocationHandler { public static HTTPConnection newInstance(HTTPConnection target) { ClientExceptionCatcher handler = new ClientExceptionCatcher(target); return (HTTPConnection)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[]{HTTPConnection.class}, handler); } private final HTTPConnection target; private ClientExceptionCatcher(HTTPConnection target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { try { return method.invoke(target, args); } catch (InvocationTargetException x) { throw x.getTargetException(); } } catch (Throwable x) { throw handleException(x, method.getExceptionTypes()); } } private Throwable handleException(Throwable x, Class[] declared) { if (x instanceof Error) return x; if (x instanceof AxisFault) x = extractThrowable((AxisFault)x); if (isDeclaredOrRuntime(x, declared)) return x; return new IOException(x.toString()); } private Throwable extractThrowable(AxisFault fault) { String name = fault.getFaultString(); if (name == null) return fault; // FaultStrings in Axis 1.1 are obtained with Throwable.toString(), // which is : . // Here we parse the string to re-create the exception int colon = name.indexOf(':'); String className = colon < 0 ? name : name.substring(0, colon).trim(); String message = colon < 0 ? null : name.substring(colon + 1).trim(); Class cls = null; try { // Try to load the class: mostly these are JMX exceptions or java.* exceptions // so we can use this class' classloader cls = getClass().getClassLoader().loadClass(className); } catch (ClassNotFoundException x) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot load Throwable class " + className, x); } if (cls == null) return fault; Object exception = null; if (message != null) { try { // Try to find the suitable constructor Constructor ctor = cls.getConstructor(new Class[]{String.class}); exception = ctor.newInstance(new Object[]{message}); } catch (Throwable x) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot find constructor " + className + "(String message)", x); } } if (exception == null) { try { exception = cls.newInstance(); } catch (Throwable x) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot find constructor " + className + "()", x); } } // Handle JMX exceptions with special case constructors if (MBeanException.class.getName().equals(className)) { exception = new MBeanException(null, message); } else if (RuntimeMBeanException.class.getName().equals(className)) { exception = new RuntimeMBeanException(null, message); } if (!(exception instanceof Throwable)) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Could not recreate exception thrown on server side: " + className); return fault; } return (Throwable)exception; } private boolean isDeclaredOrRuntime(Throwable x, Class[] declared) { if (x instanceof RuntimeException) return true; for (int i = 0; i < declared.length; ++i) { Class exception = declared[i]; if (exception.isInstance(x)) return true; } return false; } private Logger getLogger() { return Log.getLogger(getClass().getName()); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/ConnectionIDRequestHandler.java100644 0 0 3122 10513545721 23762 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; /** * This class is used in the Axis deployment descriptor, and parses the SOAP header * (on server-side) that contains the connection ID sent by the client. * * @version $Revision: 1.5 $ */ public class ConnectionIDRequestHandler extends BasicHandler { public void invoke(MessageContext context) throws AxisFault { Message message = context.getRequestMessage(); SOAPEnvelope envelope = message.getSOAPEnvelope(); SOAPHeaderElement header = envelope.getHeaderByName(SOAPConstants.NAMESPACE_URI, SOAPConstants.CONNECTION_ID_HEADER_NAME); if (header == null) throw new AxisFault("Could not find mandatory header " + SOAPConstants.CONNECTION_ID_HEADER_NAME); try { String id = (String)header.getValueAsType(XMLType.XSD_STRING); if (id != null && id.length() > 0) context.setProperty(SOAPConstants.CONNECTION_ID_HEADER_NAME, id); } catch (Exception x) { throw AxisFault.makeFault(x); } finally { header.setProcessed(true); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/SOAPClientInvoker.java100644 0 0 44511 10513545721 22065 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; import java.io.IOException; import java.util.Set; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.NotificationResult; import javax.security.auth.Subject; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; import javax.xml.rpc.ServiceException; import mx4j.tools.remote.http.HTTPConnection; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.message.SOAPHeaderElement; /** * @version $Revision: 1.3 $ */ public class SOAPClientInvoker implements HTTPConnection { private static final QName qObjectName = new QName(SOAPConstants.NAMESPACE_URI, "ObjectName"); private static final QName qObjectInstance = new QName(SOAPConstants.NAMESPACE_URI, "ObjectInstance"); private static final QName qSubject = new QName(SOAPConstants.NAMESPACE_URI, "Subject"); private final String endpoint; private final Service service; private String connectionId; public SOAPClientInvoker(String endpoint, Service service) { this.endpoint = endpoint; this.service = service; } public String connect(Object credentials) throws IOException, SecurityException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "connect")); call.addParameter("credentials", XMLType.XSD_ANY, ParameterMode.IN); call.setReturnType(XMLType.XSD_STRING); // call.addFault(new QName(SOAPConstants.NAMESPACE_URI, "SecurityException"), SecurityException.class, XMLType.XSD_ANY, true); connectionId = (String)call.invoke(new Object[]{credentials}); return connectionId; } public void close() throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "close")); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[0]); } public String getConnectionId() throws IOException { return connectionId; } public Integer addNotificationListener(ObjectName name, Object filter, Subject delegate) throws InstanceNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "addNotificationListener")); call.addParameter("observed", qObjectName, ParameterMode.IN); call.addParameter("filter", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_INT); return (Integer)call.invoke(new Object[]{name, filter, delegate}); } public void removeNotificationListeners(ObjectName observed, Integer[] ids, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "removeNotificationListeners")); call.addParameter("observed", qObjectName, ParameterMode.IN); call.addParameter("ids", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{observed, ids, delegate}); } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "fetchNotifications")); call.addParameter("sequence", XMLType.XSD_LONG, ParameterMode.IN); call.addParameter("maxNumber", XMLType.XSD_INT, ParameterMode.IN); call.addParameter("timeout", XMLType.XSD_LONG, ParameterMode.IN); call.setReturnType(new QName(SOAPConstants.NAMESPACE_URI, "NotificationResult")); NotificationResult result = (NotificationResult)call.invoke(new Object[]{new Long(clientSequenceNumber), new Integer(maxNotifications), new Long(timeout)}); return result; } public void addNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "addNotificationListener")); call.addParameter("observed", qObjectName, ParameterMode.IN); call.addParameter("listener", qObjectName, ParameterMode.IN); call.addParameter("filter", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("handback", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{name, listener, filter, handback, delegate}); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "removeNotificationListener")); call.addParameter("observed", qObjectName, ParameterMode.IN); call.addParameter("listener", qObjectName, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{name, listener, delegate}); } public void removeNotificationListener(ObjectName name, ObjectName listener, Object filter, Object handback, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "removeNotificationListener")); call.addParameter("observed", qObjectName, ParameterMode.IN); call.addParameter("listener", qObjectName, ParameterMode.IN); call.addParameter("filter", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("handback", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{name, listener, filter, handback, delegate}); } public MBeanInfo getMBeanInfo(ObjectName objectName, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getMBeanInfo")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(new QName(SOAPConstants.NAMESPACE_URI, "MBeanInfo")); MBeanInfo info = (MBeanInfo)call.invoke(new Object[]{objectName, delegate}); return info; } public boolean isInstanceOf(ObjectName objectName, String className, Subject delegate) throws InstanceNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "isInstanceOf")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("className", XMLType.XSD_STRING, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_BOOLEAN); Boolean isinstanceof = (Boolean)call.invoke(new Object[]{objectName, className, delegate}); return isinstanceof.booleanValue(); } public String[] getDomains(Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getDomains")); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.SOAP_ARRAY); String[] domains = (String[])call.invoke(new Object[]{delegate}); return domains; } public String getDefaultDomain(Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getDefaultDomain")); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_STRING); String domain = (String)call.invoke(new Object[]{delegate}); return domain; } public ObjectInstance createMBean(String className, ObjectName objectName, Object args, String[] parameters, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "createMBean")); call.addParameter("className", XMLType.XSD_STRING, ParameterMode.IN); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("arguments", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("signature", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(qObjectInstance); ObjectInstance instance = (ObjectInstance)call.invoke(new Object[]{className, objectName, args, parameters, delegate}); return instance; } public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object args, String[] parameters, Subject delegate) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "createMBean")); call.addParameter("className", XMLType.XSD_STRING, ParameterMode.IN); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("loaderName", qObjectName, ParameterMode.IN); call.addParameter("arguments", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("signature", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(qObjectInstance); ObjectInstance instance = (ObjectInstance)call.invoke(new Object[]{className, objectName, loaderName, args, parameters, delegate}); return instance; } public void unregisterMBean(ObjectName objectName, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "unregisterMBean")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{objectName, delegate}); } public Object getAttribute(ObjectName objectName, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getAttribute")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("attributeName", XMLType.XSD_STRING, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_ANY); Object result = call.invoke(new Object[]{objectName, attribute, delegate}); return result; } public void setAttribute(ObjectName objectName, Object attribute, Subject delegate) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "setAttribute")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("attribute", new QName(SOAPConstants.NAMESPACE_URI, "Attribute"), ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.AXIS_VOID); call.invoke(new Object[]{objectName, attribute, delegate}); } public AttributeList getAttributes(ObjectName objectName, String[] attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getAttributes")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("attributeNames", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(new QName(SOAPConstants.NAMESPACE_URI, "AttributeList")); AttributeList list = (AttributeList)call.invoke(new Object[]{objectName, attributes, delegate}); return list; } public AttributeList setAttributes(ObjectName objectName, Object attributes, Subject delegate) throws InstanceNotFoundException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "setAttributes")); QName qAttributeList = new QName(SOAPConstants.NAMESPACE_URI, "AttributeList"); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("attributeList", qAttributeList, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(qAttributeList); AttributeList list = (AttributeList)call.invoke(new Object[]{objectName, attributes, delegate}); return list; } public Object invoke(ObjectName objectName, String methodName, Object args, String[] parameters, Subject delegate) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "invoke")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("operationName", XMLType.XSD_STRING, ParameterMode.IN); call.addParameter("arguments", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("signature", XMLType.SOAP_ARRAY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_ANY); Object object = call.invoke(new Object[]{objectName, methodName, args, parameters, delegate}); return object; } public Integer getMBeanCount(Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getMBeanCount")); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_INT); Integer count = (Integer)call.invoke(new Object[]{delegate}); return count; } public boolean isRegistered(ObjectName objectName, Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "isRegistered")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(XMLType.XSD_BOOLEAN); Boolean registered = (Boolean)call.invoke(new Object[]{objectName, delegate}); return registered.booleanValue(); } public ObjectInstance getObjectInstance(ObjectName objectName, Subject delegate) throws InstanceNotFoundException, IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "getObjectInstance")); call.addParameter("objectName", qObjectName, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(qObjectInstance); ObjectInstance instance = (ObjectInstance)call.invoke(new Object[]{objectName, delegate}); return instance; } public Set queryMBeans(ObjectName patternName, Object filter, Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "queryMBeans")); call.addParameter("pattern", qObjectName, ParameterMode.IN); call.addParameter("query", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(new QName(SOAPConstants.NAMESPACE_URI, "Set")); Set set = (Set)call.invoke(new Object[]{patternName, filter, delegate}); return set; } public Set queryNames(ObjectName patternName, Object filter, Subject delegate) throws IOException { Call call = createCall(); call.setOperationName(new QName(SOAPConstants.NAMESPACE_URI, "queryNames")); call.addParameter("pattern", qObjectName, ParameterMode.IN); call.addParameter("query", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("delegate", qSubject, ParameterMode.IN); call.setReturnType(new QName(SOAPConstants.NAMESPACE_URI, "Set")); Set set = (Set)call.invoke(new Object[]{patternName, filter, delegate}); return set; } private Call createCall() throws IOException { try { Call call = (Call)service.createCall(); call.setTargetEndpointAddress(endpoint); SOAPHeaderElement connectionIDHeader = new SOAPHeaderElement(SOAPConstants.NAMESPACE_URI, SOAPConstants.CONNECTION_ID_HEADER_NAME, connectionId); connectionIDHeader.setMustUnderstand(true); call.addHeader(connectionIDHeader); return call; } catch (ServiceException x) { throw new IOException(x.toString()); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/SOAPConnector.java100644 0 0 2160 10513545721 21215 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; import java.io.IOException; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.remote.JMXServiceURL; import javax.security.auth.Subject; import mx4j.tools.remote.http.HTTPConnection; import mx4j.tools.remote.http.HTTPConnectionMBeanServerConnection; import mx4j.tools.remote.http.HTTPConnector; /** * @version $Revision: 1.20 $ */ public class SOAPConnector extends HTTPConnector { public SOAPConnector(JMXServiceURL url, Map environment) throws IOException { super(url, environment); } protected MBeanServerConnection doGetMBeanServerConnection(Subject delegate) throws IOException { HTTPConnection catcher = ClientExceptionCatcher.newInstance(getHTTPConnection()); return new HTTPConnectionMBeanServerConnection(catcher, delegate, getRemoteNotificationClientHandler()); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/SOAPConstants.java100644 0 0 1021 10513545721 21232 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; /** * @version $Revision: 1.5 $ */ class SOAPConstants { static final String NAMESPACE_URI = "http://mx4j.sourceforge.net/remote/soap/1.0"; static final String CONNECTION_ID_HEADER_NAME = "connectionId"; private SOAPConstants() { } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/SOAPService.java100644 0 0 2204 10513545721 20662 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; import mx4j.tools.remote.http.HTTPService; import org.apache.axis.MessageContext; /** * The server-side service (the WebService actually) where remote calls end up * after being parsed by Axis. * This is, in Axis jargon, the 'pivot' of the invocation chain. * It is used in the Axis deployment descriptor, and as such must be a public class. * * @version $Revision: 1.3 $ */ public class SOAPService extends HTTPService { protected String findRequestURL() { MessageContext context = MessageContext.getCurrentContext(); return (String)context.getProperty(MessageContext.TRANS_URL); } protected String getProtocol() { return "soap"; } protected String findConnectionId() { MessageContext context = MessageContext.getCurrentContext(); return (String)context.getProperty(SOAPConstants.CONNECTION_ID_HEADER_NAME); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/SSLSOAPService.java100644 0 0 1015 10513545721 21243 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap; /** * This 'pivot' is the one to be used when the invocation is uses the * https protocol * * @version $Revision: 1.1 $ */ public class SSLSOAPService extends SOAPService { protected String getProtocol() { return "soap+ssl"; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeDeser.java100644 0 0 1575 10513545721 23274 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.Attribute; import org.xml.sax.SAXException; /** * @version $Revision: 1.7 $ */ public class AttributeDeser extends AxisDeserializer { private String attributeName; private Object attributeValue; public void onSetChildValue(Object value, Object hint) throws SAXException { if (AttributeSer.NAME.equals(hint)) attributeName = (String)value; else if (AttributeSer.VALUE.equals(hint)) attributeValue = value; } protected Object createObject() throws SAXException { return new Attribute(attributeName, attributeValue); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeDeserFactory.java100644 0 0 1151 10513545721 24612 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.7 $ */ public class AttributeDeserFactory extends BaseDeserializerFactory { public AttributeDeserFactory(Class javaType, QName xmlType) { super(AttributeDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeListDeser.java100644 0 0 1465 10513545721 24126 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.AttributeList; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class AttributeListDeser extends AxisDeserializer { private AttributeList attributes = new AttributeList(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) attributes.add(value); } protected Object createObject() throws SAXException { return attributes; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeListDeserFactory.java100644 0 0 1157 10513545721 25454 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class AttributeListDeserFactory extends BaseDeserializerFactory { public AttributeListDeserFactory(Class javaType, QName xmlType) { super(AttributeListDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeListSer.java100644 0 0 3650 10513545721 23613 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.Attribute; import javax.management.AttributeList; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.6 $ */ public class AttributeListSer extends AxisSerializer { static final String TYPE = "AttributeList"; public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { AttributeList list = (AttributeList)value; context.startElement(name, attributes); for (Iterator i = list.iterator(); i.hasNext();) { Attribute item = (Attribute)i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, item); } context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element sequence = types.createElement(SCHEMA_SEQUENCE); complexType.appendChild(sequence); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", AttributeSer.TYPE); sequence.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeListSerFactory.java100644 0 0 1153 10513545721 25137 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.5 $ */ public class AttributeListSerFactory extends BaseSerializerFactory { public AttributeListSerFactory(Class javaType, QName xmlType) { super(AttributeListSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeSer.java100644 0 0 4070 10513545721 22754 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.Attribute; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.8 $ */ public class AttributeSer extends AxisSerializer { static final String TYPE = "Attribute"; static final String NAME = "name"; static final String VALUE = "value"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName VALUE_QNAME = new QName("", VALUE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Attribute attribute = (Attribute)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, attribute.getName()); context.serialize(VALUE_QNAME, null, attribute.getValue()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element valueElement = types.createElement(SCHEMA_ELEMENT); valueElement.setAttribute("name", VALUE); valueElement.setAttribute("type", XMLType.XSD_ANYTYPE.getLocalPart()); allElement.appendChild(valueElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AttributeSerFactory.java100644 0 0 1137 10513545721 24305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class AttributeSerFactory extends BaseSerializerFactory { public AttributeSerFactory(Class javaType, QName xmlType) { super(AttributeSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AxisDeserializer.java100644 0 0 6476 10513545721 23622 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import mx4j.log.Log; import mx4j.log.Logger; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.DeserializerTarget; import org.apache.axis.message.SOAPHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public abstract class AxisDeserializer extends DeserializerImpl { protected Logger getLogger() { return Log.getLogger(getClass().getName()); } public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("Enter: " + getClass().getName() + ".onStartElement()"); logger.trace("namespace: " + namespace); logger.trace("localName: " + localName); logger.trace("prefix: " + prefix); } } public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("Enter: " + getClass().getName() + ".onStartChild()"); logger.trace("namespace: " + namespace); logger.trace("localName: " + localName); logger.trace("prefix: " + prefix); } /* if (context.isNil(attributes)) { setChildValue(null, localName); return null; } */ QName itemType = context.getTypeFromAttributes(namespace, localName, attributes); Deserializer deserializer = null; if (itemType != null) deserializer = context.getDeserializerForType(itemType); if (deserializer == null) deserializer = new DeserializerImpl(); deserializer.registerValueTarget(new DeserializerTarget(this, localName)); addChildDeserializer(deserializer); return (SOAPHandler)deserializer; } public void setChildValue(Object value, Object hint) throws SAXException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("Enter: " + getClass().getName() + ".setChildValue()"); logger.trace("value: " + value); logger.trace("hint: " + hint); } onSetChildValue(value, hint); } protected abstract void onSetChildValue(Object value, Object hint) throws SAXException; public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("Enter: " + getClass().getName() + ".onEndElement()"); logger.trace("namespace: " + namespace); logger.trace("localName: " + localName); } setValue(createObject()); } protected abstract Object createObject() throws SAXException; } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/AxisSerializer.java100644 0 0 1711 10513545721 23274 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import org.apache.axis.Constants; import org.apache.axis.encoding.Serializer; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; /** * @version $Revision: 1.4 $ */ public abstract class AxisSerializer implements Serializer { protected static final String SCHEMA_COMPLEX_TYPE = "complexType"; protected static final String SCHEMA_ALL = "all"; protected static final String SCHEMA_ELEMENT = "element"; protected static final String SCHEMA_SEQUENCE = "sequence"; public Element writeSchema(Class javaType, Types types) throws Exception { return null; } public String getMechanismType() { return Constants.AXIS_SAX; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanAttributeInfoDeser.java100644 0 0 2740 10513545721 25006 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanAttributeInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanAttributeInfoDeser extends AxisDeserializer { private String name; private String className; private String description; private boolean isReadable; private boolean isWritable; private boolean isIs; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanAttributeInfoSer.NAME.equals(hint)) name = (String)value; else if (MBeanAttributeInfoSer.CLASS_NAME.equals(hint)) className = (String)value; else if (MBeanAttributeInfoSer.DESCRIPTION.equals(hint)) description = (String)value; else if (MBeanAttributeInfoSer.IS_READABLE.equals(hint)) isReadable = ((Boolean)value).booleanValue(); else if (MBeanAttributeInfoSer.IS_WRITABLE.equals(hint)) isWritable = ((Boolean)value).booleanValue(); else if (MBeanAttributeInfoSer.IS_IS.equals(hint)) isIs = ((Boolean)value).booleanValue(); } protected Object createObject() throws SAXException { return new MBeanAttributeInfo(name, className, description, isReadable, isWritable, isIs); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanAttributeInfoDeserFactory.java100644 0 0 1204 10513545721 26330 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanAttributeInfoDeserFactory extends BaseDeserializerFactory { public MBeanAttributeInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanAttributeInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanAttributeInfoSer.java100644 0 0 7577 10513545721 24512 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanAttributeInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanAttributeInfoSer extends AxisSerializer { static final String TYPE = "MBeanAttributeInfo"; static final String NAME = "name"; static final String CLASS_NAME = "type"; static final String DESCRIPTION = "description"; static final String IS_READABLE = "isReadable"; static final String IS_WRITABLE = "isWritable"; static final String IS_IS = "isIs"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName TYPE_QNAME = new QName("", CLASS_NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName IS_READABLE_QNAME = new QName("", IS_READABLE); private static final QName IS_WRITABLE_QNAME = new QName("", IS_WRITABLE); private static final QName IS_IS_QNAME = new QName("", IS_IS); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanAttributeInfo info = (MBeanAttributeInfo)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, info.getName()); context.serialize(TYPE_QNAME, null, info.getType()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.serialize(IS_READABLE_QNAME, null, info.isReadable() ? Boolean.TRUE : Boolean.FALSE); context.serialize(IS_WRITABLE_QNAME, null, info.isWritable() ? Boolean.TRUE : Boolean.FALSE); context.serialize(IS_IS_QNAME, null, info.isIs() ? Boolean.TRUE : Boolean.FALSE); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", CLASS_NAME); typeElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(typeElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); Element readableElement = types.createElement(SCHEMA_ELEMENT); readableElement.setAttribute("name", IS_READABLE); readableElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(readableElement); Element writableElement = types.createElement(SCHEMA_ELEMENT); writableElement.setAttribute("name", IS_WRITABLE); writableElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(writableElement); Element isElement = types.createElement(SCHEMA_ELEMENT); isElement.setAttribute("name", IS_IS); isElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(isElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanAttributeInfoSerFactory.java100644 0 0 1172 10513545721 26023 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanAttributeInfoSerFactory extends BaseSerializerFactory { public MBeanAttributeInfoSerFactory(Class javaType, QName xmlType) { super(MBeanAttributeInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanConstructorInfoDeser.java100644 0 0 2150 10513545721 25363 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanConstructorInfo; import javax.management.MBeanParameterInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanConstructorInfoDeser extends AxisDeserializer { private String name; private String description; private MBeanParameterInfo[] signature; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanConstructorInfoSer.NAME.equals(hint)) name = (String)value; else if (MBeanConstructorInfoSer.DESCRIPTION.equals(hint)) description = (String)value; else if (MBeanConstructorInfoSer.SIGNATURE.equals(hint)) signature = (MBeanParameterInfo[])value; } protected Object createObject() throws SAXException { return new MBeanConstructorInfo(name, description, signature); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanConstructorInfoDeserFactory.java100644 0 0 1212 10513545721 26711 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanConstructorInfoDeserFactory extends BaseDeserializerFactory { public MBeanConstructorInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanConstructorInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanConstructorInfoSer.java100644 0 0 5111 10513545721 25052 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanConstructorInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanConstructorInfoSer extends AxisSerializer { static final String TYPE = "MBeanConstructorInfo"; static final String NAME = "name"; static final String DESCRIPTION = "description"; static final String SIGNATURE = "signature"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName SIGNATURE_QNAME = new QName("", SIGNATURE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanConstructorInfo info = (MBeanConstructorInfo)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, info.getName()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.serialize(SIGNATURE_QNAME, null, info.getSignature()); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); Element signatureElement = types.createElement(SCHEMA_ELEMENT); signatureElement.setAttribute("name", SIGNATURE); signatureElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(signatureElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanConstructorInfoSerFactory.java100644 0 0 1200 10513545721 26375 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanConstructorInfoSerFactory extends BaseSerializerFactory { public MBeanConstructorInfoSerFactory(Class javaType, QName xmlType) { super(MBeanConstructorInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanInfoDeser.java100644 0 0 3306 10513545721 23121 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanInfoDeser extends AxisDeserializer { private String className; private String description; private MBeanAttributeInfo[] attributes; private MBeanConstructorInfo[] constructors; private MBeanOperationInfo[] operations; private MBeanNotificationInfo[] notifications; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanInfoSer.CLASS_NAME.equals(hint)) className = (String)value; else if (MBeanInfoSer.DESCRIPTION.equals(hint)) description = (String)value; else if (MBeanInfoSer.ATTRIBUTES.equals(hint)) attributes = (MBeanAttributeInfo[])value; else if (MBeanInfoSer.CONSTRUCTORS.equals(hint)) constructors = (MBeanConstructorInfo[])value; else if (MBeanInfoSer.OPERATIONS.equals(hint)) operations = (MBeanOperationInfo[])value; else if (MBeanInfoSer.NOTIFICATIONS.equals(hint)) notifications = (MBeanNotificationInfo[])value; } protected Object createObject() throws SAXException { return new MBeanInfo(className, description, attributes, constructors, operations, notifications); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanInfoDeserFactory.java100644 0 0 1151 10513545721 24445 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanInfoDeserFactory extends BaseDeserializerFactory { public MBeanInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanInfoSer.java100644 0 0 7727 10513545721 22623 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanInfoSer extends AxisSerializer { static final String TYPE = "MBeanInfo"; static final String CLASS_NAME = "className"; static final String DESCRIPTION = "description"; static final String ATTRIBUTES = "attributes"; static final String CONSTRUCTORS = "constructors"; static final String OPERATIONS = "operations"; static final String NOTIFICATIONS = "notifications"; private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName ATTRIBUTES_QNAME = new QName("", ATTRIBUTES); private static final QName CONSTRUCTORS_QNAME = new QName("", CONSTRUCTORS); private static final QName OPERATIONS_QNAME = new QName("", OPERATIONS); private static final QName NOTIFICATIONS_QNAME = new QName("", NOTIFICATIONS); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanInfo info = (MBeanInfo)value; context.startElement(name, attributes); context.serialize(CLASS_NAME_QNAME, null, info.getClassName()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.serialize(ATTRIBUTES_QNAME, null, info.getAttributes()); context.serialize(CONSTRUCTORS_QNAME, null, info.getConstructors()); context.serialize(OPERATIONS_QNAME, null, info.getOperations()); context.serialize(NOTIFICATIONS_QNAME, null, info.getNotifications()); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", CLASS_NAME); typeElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(typeElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); Element attributesElement = types.createElement(SCHEMA_ELEMENT); attributesElement.setAttribute("name", ATTRIBUTES); attributesElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(attributesElement); Element constructorsElement = types.createElement(SCHEMA_ELEMENT); constructorsElement.setAttribute("name", CONSTRUCTORS); constructorsElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(constructorsElement); Element operationsElement = types.createElement(SCHEMA_ELEMENT); operationsElement.setAttribute("name", OPERATIONS); operationsElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(operationsElement); Element notificationsElement = types.createElement(SCHEMA_ELEMENT); notificationsElement.setAttribute("name", NOTIFICATIONS); notificationsElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(notificationsElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanInfoSerFactory.java100644 0 0 1137 10513545721 24140 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanInfoSerFactory extends BaseSerializerFactory { public MBeanInfoSerFactory(Class javaType, QName xmlType) { super(MBeanInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanNotificationInfoDeser.java100644 0 0 2113 10513545721 25463 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanNotificationInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanNotificationInfoDeser extends AxisDeserializer { private String name; private String description; private String[] notificationTypes; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanNotificationInfoSer.NAME.equals(hint)) name = (String)value; else if (MBeanNotificationInfoSer.DESCRIPTION.equals(hint)) description = (String)value; else if (MBeanNotificationInfoSer.NOTIFICATION_TYPES.equals(hint)) notificationTypes = (String[])value; } protected Object createObject() throws SAXException { return new MBeanNotificationInfo(notificationTypes, name, description); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanNotificationInfoDeserFactory.java100644 0 0 1215 10513545721 27015 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanNotificationInfoDeserFactory extends BaseDeserializerFactory { public MBeanNotificationInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanNotificationInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanNotificationInfoSer.java100644 0 0 5164 10513545721 25163 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanNotificationInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanNotificationInfoSer extends AxisSerializer { static final String TYPE = "MBeanNotificationInfo"; static final String NAME = "name"; static final String DESCRIPTION = "description"; static final String NOTIFICATION_TYPES = "notificationTypes"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName NOTIFICATION_TYPES_QNAME = new QName("", NOTIFICATION_TYPES); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanNotificationInfo info = (MBeanNotificationInfo)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, info.getName()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.serialize(NOTIFICATION_TYPES_QNAME, null, info.getNotifTypes()); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); Element typesElement = types.createElement(SCHEMA_ELEMENT); typesElement.setAttribute("name", NOTIFICATION_TYPES); typesElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(typesElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanNotificationInfoSerFactory.java100644 0 0 1203 10513545721 26501 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanNotificationInfoSerFactory extends BaseSerializerFactory { public MBeanNotificationInfoSerFactory(Class javaType, QName xmlType) { super(MBeanNotificationInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanOperationInfoDeser.java100644 0 0 2556 10513545721 25010 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanOperationInfoDeser extends AxisDeserializer { private String name; private String description; private MBeanParameterInfo[] signature; private String className; private int impact; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanOperationInfoSer.NAME.equals(hint)) name = (String)value; else if (MBeanOperationInfoSer.DESCRIPTION.equals(hint)) description = (String)value; else if (MBeanOperationInfoSer.SIGNATURE.equals(hint)) signature = (MBeanParameterInfo[])value; else if (MBeanOperationInfoSer.CLASS_NAME.equals(hint)) className = (String)value; else if (MBeanOperationInfoSer.IMPACT.equals(hint)) impact = ((Integer)value).intValue(); } protected Object createObject() throws SAXException { return new MBeanOperationInfo(name, description, signature, className, impact); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanOperationInfoDeserFactory.java100644 0 0 1204 10513545721 26325 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanOperationInfoDeserFactory extends BaseDeserializerFactory { public MBeanOperationInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanOperationInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanOperationInfoSer.java100644 0 0 6621 10513545721 24474 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanOperationInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanOperationInfoSer extends AxisSerializer { static final String TYPE = "MBeanOperationInfo"; static final String NAME = "name"; static final String CLASS_NAME = "type"; static final String DESCRIPTION = "description"; static final String SIGNATURE = "signature"; static final String IMPACT = "impact"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName SIGNATURE_QNAME = new QName("", SIGNATURE); private static final QName IMPACT_QNAME = new QName("", IMPACT); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanOperationInfo info = (MBeanOperationInfo)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, info.getName()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.serialize(SIGNATURE_QNAME, null, info.getSignature()); context.serialize(CLASS_NAME_QNAME, null, info.getReturnType()); context.serialize(IMPACT_QNAME, null, new Integer(info.getImpact())); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); Element signatureElement = types.createElement(SCHEMA_ELEMENT); signatureElement.setAttribute("name", SIGNATURE); signatureElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(signatureElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", CLASS_NAME); typeElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(typeElement); Element impactElement = types.createElement(SCHEMA_ELEMENT); impactElement.setAttribute("name", IMPACT); impactElement.setAttribute("type", XMLType.XSD_INT.getLocalPart()); allElement.appendChild(impactElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanOperationInfoSerFactory.java100644 0 0 1172 10513545721 26020 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanOperationInfoSerFactory extends BaseSerializerFactory { public MBeanOperationInfoSerFactory(Class javaType, QName xmlType) { super(MBeanOperationInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanParameterInfoDeser.java100644 0 0 2025 10513545721 24757 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanParameterInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class MBeanParameterInfoDeser extends AxisDeserializer { private String name; private String className; private String description; public void onSetChildValue(Object value, Object hint) throws SAXException { if (MBeanParameterInfoSer.NAME.equals(hint)) name = (String)value; else if (MBeanParameterInfoSer.CLASS_NAME.equals(hint)) className = (String)value; else if (MBeanParameterInfoSer.DESCRIPTION.equals(hint)) description = (String)value; } protected Object createObject() throws SAXException { return new MBeanParameterInfo(name, className, description); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanParameterInfoDeserFactory.java100644 0 0 1204 10513545721 26305 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanParameterInfoDeserFactory extends BaseDeserializerFactory { public MBeanParameterInfoDeserFactory(Class javaType, QName xmlType) { super(MBeanParameterInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanParameterInfoSer.java100644 0 0 5044 10513545721 24452 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanParameterInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class MBeanParameterInfoSer extends AxisSerializer { static final String TYPE = "MBeanParameterInfo"; static final String NAME = "name"; static final String CLASS_NAME = "type"; static final String DESCRIPTION = "description"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { MBeanParameterInfo info = (MBeanParameterInfo)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, info.getName()); context.serialize(CLASS_NAME_QNAME, null, info.getType()); context.serialize(DESCRIPTION_QNAME, null, info.getDescription()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", CLASS_NAME); typeElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(typeElement); Element descrElement = types.createElement(SCHEMA_ELEMENT); descrElement.setAttribute("name", DESCRIPTION); descrElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descrElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanParameterInfoSerFactory.java100644 0 0 1172 10513545721 26000 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class MBeanParameterInfoSerFactory extends BaseSerializerFactory { public MBeanParameterInfoSerFactory(Class javaType, QName xmlType) { super(MBeanParameterInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationDeser.java100644 0 0 2102 10513545721 26034 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MBeanServerNotification; import javax.management.ObjectName; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationDeser extends NotificationDeser { private ObjectName mbeanName; public void onSetChildValue(Object value, Object hint) throws SAXException { super.onSetChildValue(value, hint); if (MBeanServerNotificationSer.MBEAN_NAME.equals(hint)) mbeanName = (ObjectName)value; } protected Object createObject() throws SAXException { MBeanServerNotification notification = new MBeanServerNotification(getType(), getSource(), getSequenceNumber(), mbeanName); notification.setTimeStamp(getTimeStamp()); notification.setUserData(getUserData()); return notification; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationDeserFactory.java100644 0 0 1223 10513545721 27367 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationDeserFactory extends BaseDeserializerFactory { public MBeanServerNotificationDeserFactory(Class javaType, QName xmlType) { super(MBeanServerNotificationDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationFilterDeser.java100644 0 0 2705 10513545721 27213 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.ObjectName; import javax.management.relation.MBeanServerNotificationFilter; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationFilterDeser extends AxisDeserializer { private MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter(); protected void onSetChildValue(Object value, Object hint) throws SAXException { if (NotificationFilterSupportSer.NOTIFICATION_TYPE.equals(hint)) filter.enableType((String)value); else if (MBeanServerNotificationFilterSer.ALL_DISABLED.equals(hint) && ((Boolean)value).booleanValue()) filter.disableAllObjectNames(); else if (MBeanServerNotificationFilterSer.ALL_ENABLED.equals(hint) && ((Boolean)value).booleanValue()) filter.enableAllObjectNames(); else if (MBeanServerNotificationFilterSer.ENABLED_OBJECT_NAME.equals(hint)) filter.enableObjectName((ObjectName)value); else if (MBeanServerNotificationFilterSer.DISABLED_OBJECT_NAME.equals(hint)) filter.disableObjectName((ObjectName)value); } protected Object createObject() throws SAXException { return filter; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationFilterDeserFactory.java100644 0 0 1245 10513545721 30541 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationFilterDeserFactory extends BaseDeserializerFactory { public MBeanServerNotificationFilterDeserFactory(Class javaType, QName xmlType) { super(MBeanServerNotificationFilterDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationFilterSer.java100644 0 0 6140 10513545721 26677 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import java.util.Vector; import javax.management.NotificationFilterSupport; import javax.management.ObjectName; import javax.management.relation.MBeanServerNotificationFilter; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationFilterSer extends NotificationFilterSupportSer { static final String ENABLED_OBJECT_NAME = "enabledObjectName"; static final String DISABLED_OBJECT_NAME = "disabledObjectName"; static final String ALL_DISABLED = "allDisabled"; static final String ALL_ENABLED = "allEnabled"; private static final QName ENABLED_OBJECT_NAME_QNAME = new QName("", ENABLED_OBJECT_NAME); private static final QName DISABLED_OBJECT_NAME_QNAME = new QName("", DISABLED_OBJECT_NAME); private static final QName ALL_DISABLED_QNAME = new QName("", ALL_DISABLED); private static final QName ALL_ENABLED_QNAME = new QName("", ALL_ENABLED); protected void onSerialize(SerializationContext context, NotificationFilterSupport filter) throws IOException { super.onSerialize(context, filter); MBeanServerNotificationFilter serverFilter = (MBeanServerNotificationFilter)filter; Vector enabledNames = serverFilter.getEnabledObjectNames(); Vector disabledNames = serverFilter.getDisabledObjectNames(); // A special logic should be implemented: an empty vector has a different meaning than a null vector // See JMX specification (javadocs) for further details if (enabledNames != null) { if (enabledNames.size() == 0) { context.serialize(ALL_DISABLED_QNAME, null, Boolean.TRUE); } else { context.serialize(ALL_DISABLED_QNAME, null, Boolean.FALSE); } for (Iterator i = enabledNames.iterator(); i.hasNext();) { ObjectName enabled = (ObjectName)i.next(); context.serialize(ENABLED_OBJECT_NAME_QNAME, null, enabled); } } if (disabledNames != null) { if (disabledNames.size() == 0) { context.serialize(ALL_ENABLED_QNAME, null, Boolean.TRUE); } else { context.serialize(ALL_ENABLED_QNAME, null, Boolean.FALSE); } for (Iterator i = disabledNames.iterator(); i.hasNext();) { ObjectName disabled = (ObjectName)i.next(); context.serialize(DISABLED_OBJECT_NAME_QNAME, null, disabled); } } } public Element writeSchema(Class javaType, Types types) throws Exception { // TODO: Use XML Schema syntax to specify that this is a subclass of NotificationFilterSupport return null; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationFilterSerFactory.java100644 0 0 1233 10513545721 30225 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationFilterSerFactory extends BaseSerializerFactory { public MBeanServerNotificationFilterSerFactory(Class javaType, QName xmlType) { super(MBeanServerNotificationFilterSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationSer.java100644 0 0 2507 10513545721 25534 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.MBeanServerNotification; import javax.management.Notification; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationSer extends NotificationSer { static final String MBEAN_NAME = "mbeanName"; private static final QName MBEAN_NAME_QNAME = new QName("", MBEAN_NAME); protected void onSerialize(SerializationContext context, Notification notification) throws IOException { super.onSerialize(context, notification); MBeanServerNotification serverNotification = (MBeanServerNotification)notification; context.serialize(MBEAN_NAME_QNAME, null, serverNotification.getMBeanName()); } public Element writeSchema(Class aClass, Types types) throws Exception { // TODO: Use XML Schema syntax to specify that this is a subclass of Notification return super.writeSchema(aClass, types); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MBeanServerNotificationSerFactory.java100644 0 0 1211 10513545721 27053 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class MBeanServerNotificationSerFactory extends BaseSerializerFactory { public MBeanServerNotificationSerFactory(Class javaType, QName xmlType) { super(MBeanServerNotificationSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MonitorNotificationDeser.java100644 0 0 4730 10513545721 25323 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javax.management.ObjectName; import javax.management.monitor.MonitorNotification; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public class MonitorNotificationDeser extends NotificationDeser { private ObjectName monitoredName; private String monitoredAttribute; private Object gaugeValue; private Object triggerValue; public void onSetChildValue(Object value, Object hint) throws SAXException { super.onSetChildValue(value, hint); if (MonitorNotificationSer.DERIVED_GAUGE.equals(hint)) gaugeValue = value; else if (MonitorNotificationSer.OBSERVED_ATTRIBUTE.equals(hint)) monitoredAttribute = (String)value; else if (MonitorNotificationSer.OBSERVED_OBJECT.equals(hint)) monitoredName = (ObjectName)value; else if (MonitorNotificationSer.TRIGGER.equals(hint)) triggerValue = value; } protected Object createObject() throws SAXException { // MonitorNotification's constructor is package private: // MonitorNotification(String type, Object source, long sequenceNumber, long timeStamp, String message, ObjectName monitoredName, String attribute, Object gauge, Object trigger) try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Constructor ctor = MonitorNotification.class.getDeclaredConstructor(new Class[]{String.class, Object.class, long.class, long.class, String.class, ObjectName.class, String.class, Object.class, Object.class}); // Necessary to invoke package-level constructor ctor.setAccessible(true); return ctor.newInstance(new Object[]{getType(), getSource(), new Long(getSequenceNumber()), new Long(getTimeStamp()), getMessage(), monitoredName, monitoredAttribute, gaugeValue, triggerValue}); } }); } catch (PrivilegedActionException x) { throw new SAXException(x.getException()); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MonitorNotificationDeserFactory.java100644 0 0 1207 10513545721 26647 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class MonitorNotificationDeserFactory extends BaseDeserializerFactory { public MonitorNotificationDeserFactory(Class javaType, QName xmlType) { super(MonitorNotificationDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MonitorNotificationSer.java100644 0 0 6032 10513545721 25007 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.Notification; import javax.management.monitor.MonitorNotification; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; /** * @version $Revision: 1.4 $ */ public class MonitorNotificationSer extends NotificationSer { static final String TYPE = "MonitorNotification"; static final String DERIVED_GAUGE = "derivedGauge"; static final String OBSERVED_ATTRIBUTE = "observedAttribute"; static final String OBSERVED_OBJECT = "observedObject"; static final String TRIGGER = "trigger"; private static final QName DERIVED_GAUGE_QNAME = new QName("", DERIVED_GAUGE); private static final QName OBSERVED_ATTRIBUTE_QNAME = new QName("", OBSERVED_ATTRIBUTE); private static final QName OBSERVED_OBJECT_QNAME = new QName("", OBSERVED_OBJECT); private static final QName TRIGGER_QNAME = new QName("", TRIGGER); protected void onSerialize(SerializationContext context, Notification notification) throws IOException { super.onSerialize(context, notification); MonitorNotification monNot = (MonitorNotification)notification; context.serialize(DERIVED_GAUGE_QNAME, null, monNot.getDerivedGauge()); context.serialize(OBSERVED_ATTRIBUTE_QNAME, null, monNot.getObservedAttribute()); context.serialize(OBSERVED_OBJECT_QNAME, null, monNot.getObservedObject()); context.serialize(TRIGGER_QNAME, null, monNot.getTrigger()); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = super.writeSchema(aClass, types); Element derivedGaugeElement = types.createElement(SCHEMA_ELEMENT); derivedGaugeElement.setAttribute("name", DERIVED_GAUGE); derivedGaugeElement.setAttribute("type", XMLType.XSD_ANYTYPE.getLocalPart()); complexType.appendChild(derivedGaugeElement); Element observedAttElement = types.createElement(SCHEMA_ELEMENT); observedAttElement.setAttribute("name", OBSERVED_ATTRIBUTE); observedAttElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); complexType.appendChild(observedAttElement); Element observedObjectElement = types.createElement(SCHEMA_ELEMENT); observedObjectElement.setAttribute("name", OBSERVED_OBJECT); observedObjectElement.setAttribute("type", ObjectNameSer.TYPE); complexType.appendChild(observedObjectElement); Element triggerElement = types.createElement(SCHEMA_ELEMENT); triggerElement.setAttribute("name", TRIGGER); triggerElement.setAttribute("type", XMLType.XSD_ANYTYPE.getLocalPart()); complexType.appendChild(triggerElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/MonitorNotificationSerFactory.java100644 0 0 1175 10513545721 26342 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class MonitorNotificationSerFactory extends BaseSerializerFactory { public MonitorNotificationSerFactory(Class javaType, QName xmlType) { super(MonitorNotificationSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationDeser.java100644 0 0 3573 10513545721 23757 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.Notification; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public class NotificationDeser extends AxisDeserializer { private String type; private Object source; private long sequenceNumber; private long timeStamp; private String message; private Object userData; public void onSetChildValue(Object value, Object hint) throws SAXException { if (NotificationSer.CLASS_NAME.equals(hint)) type = (String)value; else if (NotificationSer.SOURCE.equals(hint)) source = value; else if (NotificationSer.SEQUENCE_NUMBER.equals(hint)) sequenceNumber = ((Long)value).longValue(); else if (NotificationSer.TIMESTAMP.equals(hint)) timeStamp = ((Long)value).longValue(); else if (NotificationSer.MESSAGE.equals(hint)) message = (String)value; else if (NotificationSer.USER_DATA.equals(hint)) userData = value; } protected Object createObject() throws SAXException { Notification notification = new Notification(getType(), getSource(), getSequenceNumber(), getTimeStamp(), getMessage()); notification.setUserData(getUserData()); return notification; } protected String getType() { return type; } protected Object getSource() { return source; } protected long getSequenceNumber() { return sequenceNumber; } protected long getTimeStamp() { return timeStamp; } protected String getMessage() { return message; } protected Object getUserData() { return userData; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationDeserFactory.java100644 0 0 1162 10513545721 25277 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.4 $ */ public class NotificationDeserFactory extends BaseDeserializerFactory { public NotificationDeserFactory(Class javaType, QName xmlType) { super(NotificationDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationFilterSupportDeser.java100644 0 0 1514 10513545721 26513 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.NotificationFilterSupport; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class NotificationFilterSupportDeser extends AxisDeserializer { private NotificationFilterSupport filter = new NotificationFilterSupport(); protected void onSetChildValue(Object value, Object hint) throws SAXException { if (NotificationFilterSupportSer.NOTIFICATION_TYPE.equals(hint)) filter.enableType((String)value); } protected Object createObject() throws SAXException { return filter; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationFilterSupportDeserFactory.java100644 0 0 1231 10513545721 30037 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class NotificationFilterSupportDeserFactory extends BaseDeserializerFactory { public NotificationFilterSupportDeserFactory(Class javaType, QName xmlType) { super(NotificationFilterSupportDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationFilterSupportSer.java100644 0 0 4465 10513545721 26212 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import java.util.Vector; import javax.management.NotificationFilterSupport; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class NotificationFilterSupportSer extends AxisSerializer { static final String TYPE = "NotificationFilterSupport"; static final String NOTIFICATION_TYPE = "notificationType"; private static final QName NOTIFICATION_TYPE_QNAME = new QName("", NOTIFICATION_TYPE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { NotificationFilterSupport filter = (NotificationFilterSupport)value; context.startElement(name, attributes); onSerialize(context, filter); context.endElement(); } protected void onSerialize(SerializationContext context, NotificationFilterSupport filter) throws IOException { Vector types = filter.getEnabledTypes(); for (Iterator i = types.iterator(); i.hasNext();) { String type = (String)i.next(); context.serialize(NOTIFICATION_TYPE_QNAME, null, type); } } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", NOTIFICATION_TYPE); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", Constants.XSD_STRING.getLocalPart()); allElement.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationFilterSupportSerFactory.java100644 0 0 1217 10513545721 27532 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class NotificationFilterSupportSerFactory extends BaseSerializerFactory { public NotificationFilterSupportSerFactory(Class javaType, QName xmlType) { super(NotificationFilterSupportSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationResultDeser.java100644 0 0 2402 10513545721 25144 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.remote.NotificationResult; import javax.management.remote.TargetedNotification; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public class NotificationResultDeser extends AxisDeserializer { private long earliestSequenceNumber; private long nextSequenceNumber; private TargetedNotification[] targetedNotifications; public void onSetChildValue(Object value, Object hint) throws SAXException { if (NotificationResultSer.EARLIEST_NUMBER.equals(hint)) earliestSequenceNumber = ((Long)value).longValue(); else if (NotificationResultSer.NEXT_NUMBER.equals(hint)) nextSequenceNumber = ((Long)value).longValue(); else if (NotificationResultSer.NOTIFICATIONS.equals(hint)) targetedNotifications = (TargetedNotification[])value; } protected Object createObject() throws SAXException { return new NotificationResult(earliestSequenceNumber, nextSequenceNumber, targetedNotifications); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationResultDeserFactory.java100644 0 0 1204 10513545721 26473 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.4 $ */ public class NotificationResultDeserFactory extends BaseDeserializerFactory { public NotificationResultDeserFactory(Class javaType, QName xmlType) { super(NotificationResultDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationResultSer.java100644 0 0 5471 10513545721 24644 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.remote.NotificationResult; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.4 $ */ public class NotificationResultSer extends AxisSerializer { static final String TYPE = "NotificationResult"; static final String EARLIEST_NUMBER = "earliestSequenceNumber"; static final String NEXT_NUMBER = "nextSequenceNumber"; static final String NOTIFICATIONS = "targetedNotifications"; private static final QName EARLIEST_NUMBER_QNAME = new QName("", EARLIEST_NUMBER); private static final QName NEXT_NUMBER_QNAME = new QName("", NEXT_NUMBER); private static final QName NOTIFICATIONS_QNAME = new QName("", NOTIFICATIONS); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { NotificationResult notificationResult = (NotificationResult)value; context.startElement(name, attributes); context.serialize(EARLIEST_NUMBER_QNAME, null, new Long(notificationResult.getEarliestSequenceNumber())); context.serialize(NEXT_NUMBER_QNAME, null, new Long(notificationResult.getNextSequenceNumber())); context.serialize(NOTIFICATIONS_QNAME, null, notificationResult.getTargetedNotifications()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", EARLIEST_NUMBER); typeElement.setAttribute("type", XMLType.XSD_LONG.getLocalPart()); allElement.appendChild(typeElement); Element sourceElement = types.createElement(SCHEMA_ELEMENT); sourceElement.setAttribute("name", NEXT_NUMBER); sourceElement.setAttribute("type", XMLType.XSD_LONG.getLocalPart()); allElement.appendChild(sourceElement); Element sequenceNumberElement = types.createElement(SCHEMA_ELEMENT); sequenceNumberElement.setAttribute("name", NOTIFICATIONS); sequenceNumberElement.setAttribute("type", XMLType.SOAP_ARRAY.getLocalPart()); allElement.appendChild(sequenceNumberElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationResultSerFactory.java100644 0 0 1172 10513545721 26166 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.4 $ */ public class NotificationResultSerFactory extends BaseSerializerFactory { public NotificationResultSerFactory(Class javaType, QName xmlType) { super(NotificationResultSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationSer.java100644 0 0 10141 10513545721 23453 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.Notification; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.4 $ */ public class NotificationSer extends AxisSerializer { static final String TYPE = "Notification"; static final String CLASS_NAME = "type"; static final String SOURCE = "source"; static final String SEQUENCE_NUMBER = "sequenceNumber"; static final String TIMESTAMP = "timeStamp"; static final String MESSAGE = "message"; static final String USER_DATA = "userData"; private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); private static final QName SOURCE_QNAME = new QName("", SOURCE); private static final QName SEQUENCE_NUMBER_QNAME = new QName("", SEQUENCE_NUMBER); private static final QName TIMESTAMP_QNAME = new QName("", TIMESTAMP); private static final QName MESSAGE_QNAME = new QName("", MESSAGE); private static final QName USER_DATA_QNAME = new QName("", USER_DATA); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Notification notification = (Notification)value; context.startElement(name, attributes); onSerialize(context, notification); context.endElement(); } protected void onSerialize(SerializationContext context, Notification notification) throws IOException { context.serialize(CLASS_NAME_QNAME, null, notification.getType()); context.serialize(SOURCE_QNAME, null, notification.getSource()); context.serialize(SEQUENCE_NUMBER_QNAME, null, new Long(notification.getSequenceNumber())); context.serialize(TIMESTAMP_QNAME, null, new Long(notification.getTimeStamp())); context.serialize(MESSAGE_QNAME, null, notification.getMessage()); context.serialize(USER_DATA_QNAME, null, notification.getUserData()); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", CLASS_NAME); typeElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(typeElement); Element sourceElement = types.createElement(SCHEMA_ELEMENT); sourceElement.setAttribute("name", SOURCE); sourceElement.setAttribute("type", XMLType.XSD_ANYTYPE.getLocalPart()); allElement.appendChild(sourceElement); Element sequenceNumberElement = types.createElement(SCHEMA_ELEMENT); sequenceNumberElement.setAttribute("name", SEQUENCE_NUMBER); sequenceNumberElement.setAttribute("type", XMLType.XSD_LONG.getLocalPart()); allElement.appendChild(sequenceNumberElement); Element timeStampElement = types.createElement(SCHEMA_ELEMENT); timeStampElement.setAttribute("name", TIMESTAMP); timeStampElement.setAttribute("type", XMLType.XSD_LONG.getLocalPart()); allElement.appendChild(timeStampElement); Element messageElement = types.createElement(SCHEMA_ELEMENT); messageElement.setAttribute("name", MESSAGE); messageElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(messageElement); Element userDataElement = types.createElement(SCHEMA_ELEMENT); userDataElement.setAttribute("name", USER_DATA); userDataElement.setAttribute("type", XMLType.XSD_ANYTYPE.getLocalPart()); allElement.appendChild(userDataElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/NotificationSerFactory.java100644 0 0 1150 10513545721 24763 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.4 $ */ public class NotificationSerFactory extends BaseSerializerFactory { public NotificationSerFactory(Class javaType, QName xmlType) { super(NotificationSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectInstanceDeser.java100644 0 0 1670 10513545721 24220 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.xml.sax.SAXException; /** * @version $Revision: 1.6 $ */ public class ObjectInstanceDeser extends AxisDeserializer { private ObjectName objectName; private String className; protected void onSetChildValue(Object value, Object hint) throws SAXException { if (ObjectInstanceSer.CLASS_NAME.equals(hint)) className = (String)value; else if (ObjectInstanceSer.OBJECT_NAME.equals(hint)) objectName = (ObjectName)value; } protected Object createObject() throws SAXException { return new ObjectInstance(objectName, className); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectInstanceDeserFactory.java100644 0 0 1170 10513545721 25543 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class ObjectInstanceDeserFactory extends BaseDeserializerFactory { public ObjectInstanceDeserFactory(Class javaType, QName xmlType) { super(ObjectInstanceDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectInstanceSer.java100644 0 0 4264 10513545721 23711 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.ObjectInstance; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class ObjectInstanceSer extends AxisSerializer { static final String TYPE = "ObjectInstance"; static final String OBJECT_NAME = "objectName"; static final String CLASS_NAME = "className"; private static final QName OBJECTNAME_QNAME = new QName("", OBJECT_NAME); private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { ObjectInstance instance = (ObjectInstance)value; context.startElement(name, attributes); context.serialize(OBJECTNAME_QNAME, null, instance.getObjectName()); context.serialize(CLASS_NAME_QNAME, null, instance.getClassName()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element objectNameElement = types.createElement(SCHEMA_ELEMENT); objectNameElement.setAttribute("name", OBJECT_NAME); objectNameElement.setAttribute("type", ObjectNameSer.TYPE); allElement.appendChild(objectNameElement); Element classNameElement = types.createElement(SCHEMA_ELEMENT); classNameElement.setAttribute("name", CLASS_NAME); classNameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(classNameElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectInstanceSerFactory.java100644 0 0 1156 10513545721 25236 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class ObjectInstanceSerFactory extends BaseSerializerFactory { public ObjectInstanceSerFactory(Class javaType, QName xmlType) { super(ObjectInstanceSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectNameDeser.java100644 0 0 1651 10513545721 23333 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.xml.sax.SAXException; /** * @version $Revision: 1.5 $ */ public class ObjectNameDeser extends AxisDeserializer { private String canonicalName; public void onSetChildValue(Object value, Object hint) throws SAXException { if (ObjectNameSer.NAME.equals(hint)) canonicalName = (String)value; } protected Object createObject() throws SAXException { try { return new ObjectName(canonicalName); } catch (MalformedObjectNameException x) { throw new SAXException(x); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectNameDeserFactory.java100644 0 0 1154 10513545721 24661 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.6 $ */ public class ObjectNameDeserFactory extends BaseDeserializerFactory { public ObjectNameDeserFactory(Class javaType, QName xmlType) { super(ObjectNameDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectNameSer.java100644 0 0 3251 10513545721 23020 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.ObjectName; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class ObjectNameSer extends AxisSerializer { static final String TYPE = "ObjectName"; static final String NAME = "canonicalName"; private static final QName NAME_QNAME = new QName("", NAME); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { ObjectName objectName = (ObjectName)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, objectName.getCanonicalName()); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", NAME); element.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ObjectNameSerFactory.java100644 0 0 1142 10513545721 24345 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.6 $ */ public class ObjectNameSerFactory extends BaseSerializerFactory { public ObjectNameSerFactory(Class javaType, QName xmlType) { super(ObjectNameSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/PrincipalDeser.java100644 0 0 2206 10513545721 23242 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.lang.reflect.Constructor; import org.xml.sax.SAXException; /** * @version $Revision: 1.5 $ */ public class PrincipalDeser extends AxisDeserializer { private String className; private String name; public void onSetChildValue(Object value, Object hint) throws SAXException { if (PrincipalSer.CLASS_NAME.equals(hint)) className = (String)value; else if (PrincipalSer.NAME.equals(hint)) name = (String)value; } protected Object createObject() throws SAXException { try { Class principalClass = Thread.currentThread().getContextClassLoader().loadClass(className); Constructor ctor = principalClass.getConstructor(new Class[]{String.class}); return ctor.newInstance(new Object[]{name}); } catch (Exception x) { throw new SAXException(x); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/PrincipalDeserFactory.java100644 0 0 1151 10513545721 24570 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.5 $ */ public class PrincipalDeserFactory extends BaseDeserializerFactory { public PrincipalDeserFactory(Class javaType, QName xmlType) { super(PrincipalDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/PrincipalSer.java100644 0 0 4152 10513545721 22733 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.security.Principal; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.4 $ */ public class PrincipalSer extends AxisSerializer { static final String TYPE = "Principal"; static final String CLASS_NAME = "className"; static final String NAME = "name"; private static final QName CLASS_NAME_QNAME = new QName("", CLASS_NAME); private static final QName NAME_QNAME = new QName("", NAME); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Principal principal = (Principal)value; context.startElement(name, attributes); context.serialize(CLASS_NAME_QNAME, null, principal.getClass().getName()); context.serialize(NAME_QNAME, null, principal.getName()); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element classNameElement = types.createElement(SCHEMA_ELEMENT); classNameElement.setAttribute("name", CLASS_NAME); classNameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(classNameElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/PrincipalSerFactory.java100644 0 0 1137 10513545721 24263 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.5 $ */ public class PrincipalSerFactory extends BaseSerializerFactory { public PrincipalSerFactory(Class javaType, QName xmlType) { super(PrincipalSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RelationTypeSupportDeser.java100644 0 0 2353 10513545721 25340 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.util.ArrayList; import java.util.List; import javax.management.relation.RelationTypeSupport; import javax.management.relation.RoleInfo; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RelationTypeSupportDeser extends AxisDeserializer { String relationName; List roleInfos = new ArrayList(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (RelationTypeSupportSer.NAME.equals(hint)) relationName = (String)value; if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) roleInfos.add(value); } protected Object createObject() throws SAXException { try { RoleInfo[] infAry = new RoleInfo[roleInfos.size()]; roleInfos.toArray(infAry); return new RelationTypeSupport(relationName, infAry); } catch (Exception e) { throw new SAXException(e); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RelationTypeSupportDeserFactory.java100644 0 0 1210 10513545721 26657 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RelationTypeSupportDeserFactory extends BaseDeserializerFactory { public RelationTypeSupportDeserFactory(Class javaType, QName xmlType) { super(RelationTypeSupportDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RelationTypeSupportSer.java100644 0 0 5107 10513545721 25027 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.relation.RelationTypeSupport; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RelationTypeSupportSer extends AxisSerializer { static final String TYPE = "RelationTypeSupport"; static final String NAME = "name"; static final String ROLE_INFOS = "roleInfos"; private static final QName NAME_QNAME = new QName("", NAME); private static final QName ROLE_INFOS_QNAME = new QName("", ROLE_INFOS); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RelationTypeSupport relTypeSup = (RelationTypeSupport)value; context.startElement(name, attributes); context.serialize(NAME_QNAME, null, relTypeSup.getRelationTypeName()); for (Iterator i = relTypeSup.getRoleInfos().iterator(); i.hasNext();) { context.serialize(Constants.QNAME_LITERAL_ITEM, null, i.next()); } context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element sequence = types.createElement(SCHEMA_SEQUENCE); complexType.appendChild(sequence); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", RoleInfoSer.TYPE); sequence.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RelationTypeSupportSerFactory.java100644 0 0 1175 10513545721 26360 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RelationTypeSupportSerFactory extends BaseSerializerFactory { public RelationTypeSupportSerFactory(Class javaType, QName xmlType) { super(RelationTypeSupportSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleDeser.java100644 0 0 1663 10513545721 22230 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.util.ArrayList; import java.util.List; import javax.management.relation.Role; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleDeser extends AxisDeserializer { String roleName; List roleValue = new ArrayList(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (RoleSer.ROLE_NAME.equals(hint)) roleName = (String)value; if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) roleValue.add(value); } protected Object createObject() throws SAXException { return new Role(roleName, roleValue); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleDeserFactory.java100644 0 0 1133 10513545721 23550 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleDeserFactory extends BaseDeserializerFactory { public RoleDeserFactory(Class javaType, QName xmlType) { super(RoleDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleInfoDeser.java100644 0 0 3212 10513545721 23034 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.relation.RoleInfo; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleInfoDeser extends AxisDeserializer { private String name; private String description; private String refMBeanClassName; private boolean readable; private boolean writeable; private int minDegree; private int maxDegree; public void onSetChildValue(Object value, Object hint) throws SAXException { if (RoleInfoSer.NAME.equals(hint)) name = (String)value; if (RoleInfoSer.DESCRIPTION.equals(hint)) description = (String)value; if (RoleInfoSer.REF_MBEAN_CLASS_NAME.equals(hint)) refMBeanClassName = (String)value; if (RoleInfoSer.READABLE.equals(hint)) readable = ((Boolean)value).booleanValue(); if (RoleInfoSer.WRITEABLE.equals(hint)) writeable = ((Boolean)value).booleanValue(); if (RoleInfoSer.MIN_DEGREE.equals(hint)) minDegree = ((Integer)value).intValue(); if (RoleInfoSer.MAX_DEGREE.equals(hint)) maxDegree = ((Integer)value).intValue(); } protected Object createObject() throws SAXException { try { RoleInfo roleInfo = new RoleInfo(name, refMBeanClassName, readable, writeable, minDegree, maxDegree, description); return roleInfo; } catch (Exception e) { throw new SAXException(e); } } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleInfoDeserFactory.java100644 0 0 1146 10513545721 24370 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleInfoDeserFactory extends BaseDeserializerFactory { public RoleInfoDeserFactory(Class javaType, QName xmlType) { super(RoleInfoDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleInfoSer.java100644 0 0 10775 10513545721 22557 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.relation.RoleInfo; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleInfoSer extends AxisSerializer { static final String TYPE = "RoleInfo"; static final String MAX_DEGREE = "maxDegree"; static final String MIN_DEGREE = "minDegree"; static final String NAME = "name"; static final String DESCRIPTION = "description"; static final String REF_MBEAN_CLASS_NAME = "refMBeanClassName"; static final String READABLE = "readable"; static final String WRITEABLE = "writeable"; private static final QName MAX_DEGREE_QNAME = new QName("", MAX_DEGREE); private static final QName MIN_DEGREE_QNAME = new QName("", MIN_DEGREE); private static final QName NAME_QNAME = new QName("", NAME); private static final QName DESCRIPTION_QNAME = new QName("", DESCRIPTION); private static final QName REF_MBEAN_CLASS_NAME_QNAME = new QName("", REF_MBEAN_CLASS_NAME); private static final QName READABLE_QNAME = new QName("", READABLE); private static final QName WRITABLE_QNAME = new QName("", WRITEABLE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RoleInfo roleInfo = (RoleInfo)value; context.startElement(name, attributes); context.serialize(MAX_DEGREE_QNAME, null, new Integer(roleInfo.getMaxDegree())); context.serialize(MIN_DEGREE_QNAME, null, new Integer(roleInfo.getMaxDegree())); context.serialize(NAME_QNAME, null, roleInfo.getName()); context.serialize(DESCRIPTION_QNAME, null, roleInfo.getDescription()); context.serialize(REF_MBEAN_CLASS_NAME_QNAME, null, roleInfo.getRefMBeanClassName()); context.serialize(READABLE_QNAME, null, roleInfo.isReadable() ? Boolean.TRUE : Boolean.FALSE); context.serialize(WRITABLE_QNAME, null, roleInfo.isWritable() ? Boolean.TRUE : Boolean.FALSE); context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element maxDegreeElement = types.createElement(SCHEMA_ELEMENT); maxDegreeElement.setAttribute("name", MAX_DEGREE); maxDegreeElement.setAttribute("type", XMLType.XSD_INT.getLocalPart()); allElement.appendChild(maxDegreeElement); Element minDegreeElement = types.createElement(SCHEMA_ELEMENT); minDegreeElement.setAttribute("name", MIN_DEGREE); minDegreeElement.setAttribute("type", XMLType.XSD_INT.getLocalPart()); allElement.appendChild(minDegreeElement); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(nameElement); Element descriptionElement = types.createElement(SCHEMA_ELEMENT); descriptionElement.setAttribute("name", DESCRIPTION); descriptionElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(descriptionElement); Element refMBeanClassNameElement = types.createElement(SCHEMA_ELEMENT); refMBeanClassNameElement.setAttribute("name", REF_MBEAN_CLASS_NAME); refMBeanClassNameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); allElement.appendChild(refMBeanClassNameElement); Element readableElement = types.createElement(SCHEMA_ELEMENT); readableElement.setAttribute("name", READABLE); readableElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(readableElement); Element writeableElement = types.createElement(SCHEMA_ELEMENT); writeableElement.setAttribute("name", WRITEABLE); writeableElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(writeableElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleInfoSerFactory.java100644 0 0 1134 10513545721 24054 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleInfoSerFactory extends BaseSerializerFactory { public RoleInfoSerFactory(Class javaType, QName xmlType) { super(RoleInfoSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleListDeser.java100644 0 0 1434 10513545721 23060 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.relation.RoleList; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleListDeser extends AxisDeserializer { private RoleList roles = new RoleList(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) roles.add(value); } protected Object createObject() throws SAXException { return roles; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleListDeserFactory.java100644 0 0 1146 10513545721 24410 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleListDeserFactory extends BaseDeserializerFactory { public RoleListDeserFactory(Class javaType, QName xmlType) { super(RoleListDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleListSer.java100644 0 0 3616 10513545721 22553 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.relation.Role; import javax.management.relation.RoleList; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleListSer extends AxisSerializer { static final String TYPE = "RoleList"; public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RoleList list = (RoleList)value; context.startElement(name, attributes); for (Iterator i = list.iterator(); i.hasNext();) { Role item = (Role)i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, item); } context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element sequence = types.createElement(SCHEMA_SEQUENCE); complexType.appendChild(sequence); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", RoleSer.TYPE); sequence.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleListSerFactory.java100644 0 0 1134 10513545721 24074 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleListSerFactory extends BaseSerializerFactory { public RoleListSerFactory(Class javaType, QName xmlType) { super(RoleListSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleResultDeser.java100644 0 0 2037 10513545721 23423 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.relation.RoleList; import javax.management.relation.RoleResult; import javax.management.relation.RoleUnresolvedList; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleResultDeser extends AxisDeserializer { private RoleList roleList; private RoleUnresolvedList roleUnresolvedList; protected void onSetChildValue(Object value, Object hint) throws SAXException { if (RoleResultSer.ROLE_LIST.equals(hint)) roleList = (RoleList)value; if (RoleResultSer.ROLE_UNRESOLVED_LIST.equals(hint)) roleUnresolvedList = (RoleUnresolvedList)value; } protected Object createObject() throws SAXException { return new RoleResult(roleList, roleUnresolvedList); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleResultDeserFactory.java100644 0 0 1155 10513545721 24753 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleResultDeserFactory extends BaseDeserializerFactory { public RoleResultDeserFactory(Class javaType, QName xmlType) { super(RoleResultDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleResultSer.java100644 0 0 4162 10513545721 23113 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.relation.RoleResult; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleResultSer extends AxisSerializer { static final String TYPE = "RoleResult"; static final String ROLE_LIST = "roleList"; static final String ROLE_UNRESOLVED_LIST = "roleUnresolvedList"; protected static final QName ROLE_LIST_QNAME = new QName("", ROLE_LIST); protected static final QName ROLE_UNRESOLVED_LIST_QNAME = new QName("", ROLE_UNRESOLVED_LIST); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RoleResult role = (RoleResult)value; context.startElement(name, attributes); context.serialize(ROLE_LIST_QNAME, null, role.getRoles()); context.serialize(ROLE_UNRESOLVED_LIST_QNAME, null, role.getRolesUnresolved()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element roleListElement = types.createElement(SCHEMA_ELEMENT); roleListElement.setAttribute("name", ROLE_LIST); roleListElement.setAttribute("type", RoleListSer.TYPE); complexType.appendChild(roleListElement); Element roleUnresolvedListElement = types.createElement(SCHEMA_ELEMENT); roleUnresolvedListElement.setAttribute("name", ROLE_LIST); roleUnresolvedListElement.setAttribute("type", RoleUnresolvedListSer.TYPE); complexType.appendChild(roleUnresolvedListElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleResultSerFactory.java100644 0 0 1142 10513545721 24436 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleResultSerFactory extends BaseSerializerFactory { public RoleResultSerFactory(Class javaType, QName xmlType) { super(RoleResultSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleSer.java100644 0 0 5014 10513545721 21711 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.ObjectName; import javax.management.relation.Role; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleSer extends AxisSerializer { static final String TYPE = "Role"; static final String ROLE_NAME = "roleName"; static final String ROLE_VALUE = "roleValue"; protected static final QName ROLE_NAME_QNAME = new QName("", ROLE_NAME); protected static final QName ROLE_VALUE_QNAME = new QName("", ROLE_VALUE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Role role = (Role)value; context.startElement(name, attributes); context.serialize(ROLE_NAME_QNAME, null, role.getRoleName()); for (Iterator i = role.getRoleValue().iterator(); i.hasNext();) { ObjectName on = (ObjectName)i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, on); } context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element nameElement = types.createElement(SCHEMA_ELEMENT); nameElement.setAttribute("name", ROLE_NAME); nameElement.setAttribute("type", XMLType.XSD_STRING.getLocalPart()); complexType.appendChild(nameElement); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element sequence = types.createElement(SCHEMA_SEQUENCE); complexType.appendChild(sequence); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", AttributeSer.TYPE); sequence.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleSerFactory.java100644 0 0 1120 10513545721 23233 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleSerFactory extends BaseSerializerFactory { public RoleSerFactory(Class javaType, QName xmlType) { super(RoleSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedDeser.java100644 0 0 1524 10513545721 24273 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.relation.RoleUnresolved; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedDeser extends RoleDeser { private int problemType; public void onSetChildValue(Object value, Object hint) throws SAXException { super.onSetChildValue(value, hint); if (RoleUnresolvedSer.PROBLEM_TYPE.equals(hint)) problemType = ((Integer)value).intValue(); } protected Object createObject() throws SAXException { return new RoleUnresolved(roleName, roleValue, problemType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedDeserFactory.java100644 0 0 1170 10513545721 25620 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedDeserFactory extends BaseDeserializerFactory { public RoleUnresolvedDeserFactory(Class javaType, QName xmlType) { super(RoleUnresolvedDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedListDeser.java100644 0 0 1504 10513545721 25125 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.relation.RoleUnresolvedList; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedListDeser extends AxisDeserializer { private RoleUnresolvedList roles = new RoleUnresolvedList(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) roles.add(value); } protected Object createObject() throws SAXException { return roles; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedListDeserFactory.java100644 0 0 1204 10513545721 26452 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedListDeserFactory extends BaseDeserializerFactory { public RoleUnresolvedListDeserFactory(Class javaType, QName xmlType) { super(RoleUnresolvedListDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedListSer.java100644 0 0 3750 10513545721 24621 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.relation.RoleUnresolved; import javax.management.relation.RoleUnresolvedList; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedListSer extends AxisSerializer { static final String TYPE = "RoleUnresolvedList"; public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RoleUnresolvedList list = (RoleUnresolvedList)value; context.startElement(name, attributes); for (Iterator i = list.iterator(); i.hasNext();) { RoleUnresolved item = (RoleUnresolved)i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, item); } context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element sequence = types.createElement(SCHEMA_SEQUENCE); complexType.appendChild(sequence); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", RoleUnresolvedSer.TYPE); sequence.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedListSerFactory.java100644 0 0 1172 10513545721 26145 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedListSerFactory extends BaseSerializerFactory { public RoleUnresolvedListSerFactory(Class javaType, QName xmlType) { super(RoleUnresolvedListSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedSer.java100644 0 0 3746 10513545721 23772 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import javax.management.ObjectName; import javax.management.relation.RoleUnresolved; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedSer extends RoleSer { static final String TYPE = "RoleUnresolved"; static final String PROBLEM_TYPE = "problemType"; private static final QName PROBLEM_TYPE_QNAME = new QName("", PROBLEM_TYPE); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { RoleUnresolved role = (RoleUnresolved)value; context.startElement(name, attributes); context.serialize(ROLE_NAME_QNAME, null, role.getRoleName()); for (Iterator i = role.getRoleValue().iterator(); i.hasNext();) { ObjectName on = (ObjectName)i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, on); } context.serialize(PROBLEM_TYPE_QNAME, null, new Integer(role.getProblemType())); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = super.writeSchema(aClass, types); Element problemType = types.createElement(SCHEMA_ELEMENT); problemType.setAttribute("name", PROBLEM_TYPE); problemType.setAttribute("type", XMLType.XSD_INT.getLocalPart()); complexType.appendChild(problemType); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/RoleUnresolvedSerFactory.java100644 0 0 1156 10513545721 25313 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class RoleUnresolvedSerFactory extends BaseSerializerFactory { public RoleUnresolvedSerFactory(Class javaType, QName xmlType) { super(RoleUnresolvedSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SetDeser.java100644 0 0 1417 10513545721 22057 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.util.HashSet; import java.util.Set; import org.apache.axis.Constants; import org.xml.sax.SAXException; /** * @version $Revision: 1.5 $ */ public class SetDeser extends AxisDeserializer { private Set set = new HashSet(); public void onSetChildValue(Object value, Object hint) throws SAXException { if (Constants.QNAME_LITERAL_ITEM.getLocalPart().equals(hint)) set.add(value); } protected Object createObject() throws SAXException { return set; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SetDeserFactory.java100644 0 0 1127 10513545721 23405 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.4 $ */ public class SetDeserFactory extends BaseDeserializerFactory { public SetDeserFactory(Class javaType, QName xmlType) { super(SetDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SetSer.java100644 0 0 3522 10513545721 21545 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import java.util.Iterator; import java.util.Set; import javax.xml.namespace.QName; import org.apache.axis.Constants; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.5 $ */ public class SetSer extends AxisSerializer { static final String TYPE = "Set"; public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Set set = (Set)value; context.startElement(name, attributes); for (Iterator i = set.iterator(); i.hasNext();) { Object item = i.next(); context.serialize(Constants.QNAME_LITERAL_ITEM, null, item); } context.endElement(); } public Element writeSchema(Class javaType, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); types.writeSchemaElement(Constants.SOAP_VECTOR, complexType); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element element = types.createElement(SCHEMA_ELEMENT); element.setAttribute("name", Constants.QNAME_LITERAL_ITEM.getLocalPart()); element.setAttribute("minOccurs", "0"); element.setAttribute("maxOccurs", "unbounded"); element.setAttribute("type", Constants.XSD_ANYTYPE.getLocalPart()); allElement.appendChild(element); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SetSerFactory.java100644 0 0 1115 10513545721 23071 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.4 $ */ public class SetSerFactory extends BaseSerializerFactory { public SetSerFactory(Class javaType, QName xmlType) { super(SetSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SubjectDeser.java100644 0 0 2275 10513545721 22726 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.util.Set; import javax.security.auth.Subject; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public class SubjectDeser extends AxisDeserializer { private boolean readOnly; private Set principals; private Set publicCredentials; private Set privateCredentials; public void onSetChildValue(Object value, Object hint) throws SAXException { if (SubjectSer.READ_ONLY.equals(hint)) readOnly = ((Boolean)value).booleanValue(); else if (SubjectSer.PRINCIPALS.equals(hint)) principals = (Set)value; else if (SubjectSer.PUBLIC_CREDENTIALS.equals(hint)) publicCredentials = (Set)value; else if (SubjectSer.PRIVATE_CREDENTIALS.equals(hint)) privateCredentials = (Set)value; } protected Object createObject() throws SAXException { return new Subject(readOnly, principals, publicCredentials, privateCredentials); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SubjectDeserFactory.java100644 0 0 1143 10513545721 24247 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.4 $ */ public class SubjectDeserFactory extends BaseDeserializerFactory { public SubjectDeserFactory(Class javaType, QName xmlType) { super(SubjectDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SubjectSer.java100644 0 0 6244 10513545721 22415 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.security.auth.Subject; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.4 $ */ public class SubjectSer extends AxisSerializer { static final String TYPE = "Subject"; static final String READ_ONLY = "readOnly"; static final String PRINCIPALS = "principals"; static final String PUBLIC_CREDENTIALS = "publicCredentials"; static final String PRIVATE_CREDENTIALS = "privateCredentials"; private static final QName READ_ONLY_QNAME = new QName("", READ_ONLY); private static final QName PRINCIPALS_QNAME = new QName("", PRINCIPALS); private static final QName PUBLIC_CREDENTIALS_QNAME = new QName("", PUBLIC_CREDENTIALS); private static final QName PRIVATE_CREDENTIALS_QNAME = new QName("", PRIVATE_CREDENTIALS); public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { Subject subject = (Subject)value; context.startElement(name, attributes); context.serialize(READ_ONLY_QNAME, null, new Boolean(subject.isReadOnly())); context.serialize(PRINCIPALS_QNAME, null, subject.getPrincipals()); context.serialize(PUBLIC_CREDENTIALS_QNAME, null, subject.getPublicCredentials()); context.serialize(PRIVATE_CREDENTIALS_QNAME, null, subject.getPrivateCredentials()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element readOnlyElement = types.createElement(SCHEMA_ELEMENT); readOnlyElement.setAttribute("name", READ_ONLY); readOnlyElement.setAttribute("type", XMLType.XSD_BOOLEAN.getLocalPart()); allElement.appendChild(readOnlyElement); Element principalsElement = types.createElement(SCHEMA_ELEMENT); principalsElement.setAttribute("name", PRINCIPALS); principalsElement.setAttribute("type", SetSer.TYPE); allElement.appendChild(principalsElement); Element publicCredentialsElement = types.createElement(SCHEMA_ELEMENT); publicCredentialsElement.setAttribute("name", PUBLIC_CREDENTIALS); publicCredentialsElement.setAttribute("type", SetSer.TYPE); allElement.appendChild(publicCredentialsElement); Element privateCredentialsElement = types.createElement(SCHEMA_ELEMENT); privateCredentialsElement.setAttribute("name", PRIVATE_CREDENTIALS); privateCredentialsElement.setAttribute("type", SetSer.TYPE); allElement.appendChild(privateCredentialsElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/SubjectSerFactory.java100644 0 0 1131 10513545721 23733 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.4 $ */ public class SubjectSerFactory extends BaseSerializerFactory { public SubjectSerFactory(Class javaType, QName xmlType) { super(SubjectSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TargetedNotificationDeser.java100644 0 0 1755 10513545721 25437 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.Notification; import javax.management.remote.TargetedNotification; import org.xml.sax.SAXException; /** * @version $Revision: 1.4 $ */ public class TargetedNotificationDeser extends AxisDeserializer { private Notification notification; private Integer listenerID; public void onSetChildValue(Object value, Object hint) throws SAXException { if (TargetedNotificationSer.NOTIFICATION.equals(hint)) notification = (Notification)value; else if (TargetedNotificationSer.LISTENER_ID.equals(hint)) listenerID = (Integer)value; } protected Object createObject() throws SAXException { return new TargetedNotification(notification, listenerID); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TargetedNotificationDeserFactory.java100644 0 0 1212 10513545721 26753 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.4 $ */ public class TargetedNotificationDeserFactory extends BaseDeserializerFactory { public TargetedNotificationDeserFactory(Class javaType, QName xmlType) { super(TargetedNotificationDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TargetedNotificationSer.java100644 0 0 4352 10513545721 25122 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.remote.TargetedNotification; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; import org.xml.sax.Attributes; /** * @version $Revision: 1.4 $ */ public class TargetedNotificationSer extends AxisSerializer { static final String NOTIFICATION = "notification"; static final String LISTENER_ID = "listenerID"; private static final QName NOTIFICATION_QNAME = new QName("", NOTIFICATION); private static final QName LISTENER_ID_QNAME = new QName("", LISTENER_ID); static final String TYPE = "TargetedNotification"; public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { TargetedNotification targetedNotification = (TargetedNotification)value; context.startElement(name, attributes); context.serialize(NOTIFICATION_QNAME, null, targetedNotification.getNotification()); context.serialize(LISTENER_ID_QNAME, null, targetedNotification.getListenerID()); context.endElement(); } public Element writeSchema(Class aClass, Types types) throws Exception { Element complexType = types.createElement(SCHEMA_COMPLEX_TYPE); complexType.setAttribute("name", TYPE); Element allElement = types.createElement(SCHEMA_ALL); complexType.appendChild(allElement); Element typeElement = types.createElement(SCHEMA_ELEMENT); typeElement.setAttribute("name", NOTIFICATION); typeElement.setAttribute("type", NotificationSer.TYPE); allElement.appendChild(typeElement); Element sourceElement = types.createElement(SCHEMA_ELEMENT); sourceElement.setAttribute("name", LISTENER_ID); sourceElement.setAttribute("type", XMLType.XSD_INT.getLocalPart()); allElement.appendChild(sourceElement); return complexType; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TargetedNotificationSerFactory.java100644 0 0 1200 10513545721 26437 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.4 $ */ public class TargetedNotificationSerFactory extends BaseSerializerFactory { public TargetedNotificationSerFactory(Class javaType, QName xmlType) { super(TargetedNotificationSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TimerNotificationDeser.java100644 0 0 1723 10513545721 24753 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.management.timer.TimerNotification; import org.xml.sax.SAXException; /** * @version $Revision: 1.3 $ */ public class TimerNotificationDeser extends NotificationDeser { private Integer notificationID; public void onSetChildValue(Object value, Object hint) throws SAXException { super.onSetChildValue(value, hint); if (TimerNotificationSer.NOTIFICATION_ID.equals(hint)) notificationID = (Integer)value; } protected Object createObject() throws SAXException { TimerNotification notification = new TimerNotification(getType(), getSource(), getSequenceNumber(), getTimeStamp(), getMessage(), notificationID); return notification; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TimerNotificationDeserFactory.java100644 0 0 1202 10513545721 26273 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseDeserializerFactory; /** * @version $Revision: 1.3 $ */ public class TimerNotificationDeserFactory extends BaseDeserializerFactory { public TimerNotificationDeserFactory(Class javaType, QName xmlType) { super(TimerNotificationDeser.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TimerNotificationSer.java100644 0 0 3021 10513545721 24433 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import java.io.IOException; import javax.management.Notification; import javax.management.timer.TimerNotification; import javax.xml.namespace.QName; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.XMLType; import org.apache.axis.wsdl.fromJava.Types; import org.w3c.dom.Element; /** * @version $Revision: 1.3 $ */ public class TimerNotificationSer extends NotificationSer { static final String NOTIFICATION_ID = "notificationID"; private static final QName NOTIFICATION_ID_QNAME = new QName("", NOTIFICATION_ID); protected void onSerialize(SerializationContext context, Notification notification) throws IOException { super.onSerialize(context, notification); TimerNotification serverNotification = (TimerNotification)notification; context.serialize(NOTIFICATION_ID_QNAME, null, serverNotification.getNotificationID()); } public Element writeSchema(Class aClass, Types types) throws Exception { Element elem = super.writeSchema(aClass, types); Element notID = types.createElement(SCHEMA_ELEMENT); notID.setAttribute("name", NOTIFICATION_ID); notID.setAttribute("type", XMLType.XSD_INT.getLocalPart()); elem.appendChild(notID); return elem; } } mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/TimerNotificationSerFactory.java100644 0 0 1170 10513545721 25766 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.remote.soap.axis.ser; import javax.xml.namespace.QName; import org.apache.axis.encoding.ser.BaseSerializerFactory; /** * @version $Revision: 1.3 $ */ public class TimerNotificationSerFactory extends BaseSerializerFactory { public TimerNotificationSerFactory(Class javaType, QName xmlType) { super(TimerNotificationSer.class, xmlType, javaType); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/AbstractStatisticsRecorder.java100644 0 0 12233 10513545721 23027 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; import java.util.SortedMap; import java.util.TreeMap; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Logger; /** * Class AbstractStatisticsRecorder. Abstract Parent of the Stats collector * classes. It implements some basic services * * @version $Revision: 1.6 $ * @see StatisticsRecorderMBean */ public abstract class AbstractStatisticsRecorder implements StatisticsRecorderMBean, MBeanRegistration { /* Indicates whether the Monitor is active */ protected boolean isActive = false; /* MBeanServer reference */ protected MBeanServer server; /* Maximum amount of entries */ protected int maxEntries = 256; /* Holds the entries */ protected SortedMap entries = new TreeMap(); /* Initial recording date */ protected Date recordingStart; /* Indicates if the type of the recorded value is double */ protected boolean isDouble = false; /* Statistical values */ protected double minimumValue, maximumValue, averageValue; /* Count of recorded values */ protected long count = 0; protected Logger getLogger() { return Log.getLogger(getClass().getName()); } public void start() { Logger logger = getLogger(); if (!isActive) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Starting statistics recorder " + this); this.isActive = true; recordingStart = new Date(); entries.clear(); minimumValue = maximumValue = averageValue = 0; count = 0; isDouble = false; try { doStart(); } catch (Exception e) { logger.error("Exception while starting recorder " + this, e); } } } public void stop() { Logger logger = getLogger(); if (isActive) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Starting statistics recorder " + this); this.isActive = false; try { doStop(); } catch (Exception e) { logger.error("Exception starting recorder " + this, e); } } } public Number getAverage() { return createValue(averageValue); } public Number getMin() { return createValue(minimumValue); } public Number getMax() { return createValue(maximumValue); } public synchronized boolean isActive() { return isActive; } public int getMaxEntries() { return maxEntries; } public void setMaxEntries(int maxEntries) { if (maxEntries <= 0) { throw new IllegalArgumentException("Max entries has to be bigger than 0"); } this.maxEntries = maxEntries; } public SortedMap getEntries() { return (SortedMap)((TreeMap)entries).clone(); } public Date getRecordingStart() { return recordingStart; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { this.server = server; return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { this.stop(); } public void postDeregister() { } /** * Subclasses may override this to offer a custom startup procedure */ protected void doStart() throws Exception { } /** * Subclasses may override this to offer a custom stop procedure */ protected void doStop() throws Exception { } /** * Adds an entry to the collection. It also reduces the size if too big * and updates the statics */ protected synchronized void addEntry(Date key, Number value) { if (isActive) { entries.put(new PointTime(key, count++), value); if (entries.size() > maxEntries) { while (entries.size() > maxEntries) { entries.remove(entries.firstKey()); } } calculateStats(value); } } /** * Updates the statistics */ private void calculateStats(Number value) { if (!isDouble && (value instanceof Double || value instanceof Float)) { isDouble = true; } double newValue = value.doubleValue(); if (count == 1) { maximumValue = minimumValue = averageValue = newValue; return; } if (newValue > maximumValue) { maximumValue = newValue; } if (newValue < minimumValue) { minimumValue = newValue; } averageValue = (1 - 1 / (double)count) * averageValue + 1 / (double)count * newValue; } private Number createValue(double targetValue) { if (isDouble) { return new Double(targetValue); } else { return new Long((long)targetValue); } } } mx4j-3.0.2/src/tools/mx4j/tools/stats/NotificationStatisticsRecorder.java100644 0 0 3164 10513545721 23675 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; import javax.management.AttributeChangeNotification; import javax.management.AttributeChangeNotificationFilter; import javax.management.Notification; import javax.management.NotificationListener; /** * NotificationStatisticsRecorder records statistics of an attribute * based on notifications emitted when it changes. The observed MBean has to * emit notifications when the value change * * @version $Revision: 1.4 $ */ public class NotificationStatisticsRecorder extends ObserverStatisticsRecorder implements NotificationListener { protected boolean registered = false; protected void startObserving() throws Exception { AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(observedAttribute); server.addNotificationListener(observedName, this, filter, null); registered = true; } protected void stopObserving() throws Exception { if (registered) { server.removeNotificationListener(observedName, this); } } public void handleNotification(Notification notification, Object object) { AttributeChangeNotification anot = (AttributeChangeNotification)notification; addEntry(new Date(), (Number)anot.getNewValue()); } public String toString() { return "NotificationStatisticsRecorder"; } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ObserverStatisticsRecorder.java100644 0 0 6257 10513545721 23044 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.ObjectName; /** * @version $Revision: 1.4 $ */ public abstract class ObserverStatisticsRecorder extends AbstractStatisticsRecorder implements ObserverStatisticsRecorderMBean { protected ObjectName observedName = null; protected String observedAttribute = null; public void setObservedObject(ObjectName object) { this.observedName = object; } public ObjectName getObservedObject() { return observedName; } public String getObservedAttribute() { return observedAttribute; } public void setObservedAttribute(String attribute) { this.observedAttribute = attribute; } protected void doStart() throws Exception { if (observedName == null || observedAttribute == null) { getLogger().warn(new StringBuffer(this.toString()).append(" cannot start with objectName ").append(observedName).append(" and attribute ").append(observedAttribute).toString()); stop(); return; } if (!server.isRegistered(observedName)) { getLogger().warn(new StringBuffer(this.toString()).append(" cannot start since objectName is not registered").toString()); stop(); return; } MBeanInfo info = server.getMBeanInfo(observedName); MBeanAttributeInfo[] attributes = info.getAttributes(); MBeanAttributeInfo theAttribute = null; boolean found = false; for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(observedAttribute)) { theAttribute = attributes[i]; found = true; break; } } if (!found) { getLogger().warn(new StringBuffer(this.toString()).append(" cannot start with objectName ").append(observedName).append(" since attribute ").append(observedAttribute).append(" does not belong to the MBean interface").toString()); stop(); return; } if (!theAttribute.isReadable()) { getLogger().warn(new StringBuffer(this.toString()).append(" cannot start with objectName ").append(observedName).append(" since attribute ").append(observedAttribute).append(" is not readable").toString()); stop(); return; } Object value = server.getAttribute(observedName, observedAttribute); if (!(value instanceof Number)) { getLogger().warn(new StringBuffer(this.toString()).append(" cannot start with objectName ").append(observedName).append(" since attribute ").append(observedAttribute).append(" is not a number").toString()); stop(); return; } startObserving(); } protected abstract void startObserving() throws Exception; protected abstract void stopObserving() throws Exception; protected void doStop() throws Exception { stopObserving(); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ObserverStatisticsRecorderMBean.java100644 0 0 1605 10513545721 23737 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import javax.management.ObjectName; /** * Management interface for ObserverStatisticsRecorder MBeans. * * @version $Revision: 1.3 $ */ public interface ObserverStatisticsRecorderMBean extends StatisticsRecorderMBean { /** * Sets the ObjectName to be observed */ public void setObservedObject(ObjectName object); /** * Returns the observed ObjectName */ public ObjectName getObservedObject(); /** * Returns the observed Attribute */ public String getObservedAttribute(); /** * Sets the Attribute to be observed */ public void setObservedAttribute(String attribute); } mx4j-3.0.2/src/tools/mx4j/tools/stats/ObserverStatisticsRecorderMBeanDescription.java100644 0 0 1511 10513545721 26137 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface descriptions for the ObserverStatisticsRecorder MBean. * * @version $Revision: 1.3 $ */ public class ObserverStatisticsRecorderMBeanDescription extends StatisticsRecorderMBeanDescription { public String getAttributeDescription(String attribute) { if (attribute.equals("ObservedAttribute")) { return "The Attribute to be observed"; } if (attribute.equals("ObservedObject")) { return "The ObjectName to be observed"; } return super.getAttributeDescription(attribute); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/PointTime.java100644 0 0 2675 10513545721 17424 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; /** * Class PointTime encapsulates the time and order of a value. We want to * index the recorded time but in the event of a repeated time, it will * have another index which should be unique. The class is Comparable * and the order is given first by the date and if those are equals by * the index * * @version $Revision: 1.3 $ */ public class PointTime implements Comparable { private Date date; private long index; public PointTime(Date date, long index) { this.date = date; this.index = index; } public Date getDate() { return date; } public long getIndex() { return index; } public int compareTo(Object o) { PointTime p = (PointTime)o; if (date.equals(p.date)) { return (int)(index - p.index); } else { return date.compareTo(p.date); } } public boolean equals(Object o) { if (o == null) { throw new NullPointerException(); } if (!(o instanceof PointTime)) { return false; } PointTime p = (PointTime)o; return p.date.equals(date) && (p.index == index); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/StatisticsRecorderMBean.java100644 0 0 3302 10513545721 22223 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; import java.util.SortedMap; /** * Management interface to be implemented by recorder MBeans. * RecorderMBeans store a value and also keep statistics about the given value. * Different implementations can determine how to acquire and calculate the value. *

* The MBean doesn't starts automatically. It has to wait for a {@link #start} call * * @version $Revision: 1.4 $ * @see PointTime */ public interface StatisticsRecorderMBean { /** * Returns the Maximum Value */ public Number getMax(); /** * Returns the Average Value */ public Number getAverage(); /** * Returns the Minimum Value */ public Number getMin(); /** * Returns how many entries may be recorded. When the maximum amount is * reached the default behaviour is to forget the oldest one */ public int getMaxEntries(); /** * Sets the maximum entries stored in this recorder */ public void setMaxEntries(int maxEntries); /** * Returns the date when it started recording */ public Date getRecordingStart(); /** * Returs a sorted map of the recorded values indexed by PointTime */ public SortedMap getEntries(); /** * Indicates whether the MBean is recording values */ public boolean isActive(); /** * Starts recording a variable */ public void start(); /** * Stops recording a variable */ public void stop(); } mx4j-3.0.2/src/tools/mx4j/tools/stats/StatisticsRecorderMBeanDescription.java100644 0 0 3325 10513545721 24434 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.lang.reflect.Method; import mx4j.MBeanDescriptionAdapter; /** * Descriptions of the {@link StatisticsRecorderMBean} interface * * @version $Revision: 1.4 $ * @see PointTime */ public class StatisticsRecorderMBeanDescription extends MBeanDescriptionAdapter { public String getAttributeDescription(String attribute) { if (attribute.equals("Max")) { return "Maximum observed value"; } if (attribute.equals("Min")) { return "Minimum observed value"; } if (attribute.equals("Average")) { return "Average of the observed values"; } if (attribute.equals("MaxEntries")) { return "Amount of values stored in memory"; } if (attribute.equals("RecordingStart")) { return "Date when the recording was inited"; } if (attribute.equals("Entries")) { return "SortedMap of the recorded values indexed by PointTime values"; } if (attribute.equals("Active")) { return "Indicates whether the MBean is recording"; } return super.getAttributeDescription(attribute); } public String getOperationDescription(Method operation) { if (operation.equals("start")) { return "Starts the recording"; } if (operation.equals("stop")) { return "Stops the recording"; } return super.getOperationDescription(operation); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/TimedStatisticsRecorder.java100644 0 0 3435 10513545721 22312 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * TimedStatisticsRecorder records statistics of an attribute * with a timer polling the value every certain interval * * @version $Revision: 1.4 $ */ public class TimedStatisticsRecorder extends ObserverStatisticsRecorder implements TimedStatisticsRecorderMBean { protected boolean registered = false; protected static Timer timer = new Timer(); protected CollectTask task = new CollectTask(); protected long granularity = 1000L; public TimedStatisticsRecorder() { } public void setGranularity(long granularity) { this.granularity = granularity; } public long getGranularity() { return granularity; } public String toString() { return "TimedStatisticsRecorder"; } protected synchronized void startObserving() throws Exception { task = new CollectTask(); timer.schedule(task, 0, granularity); } protected synchronized void stopObserving() throws Exception { task.cancel(); } private class CollectTask extends TimerTask { public void run() { try { Number value = (Number)server.getAttribute(observedName, observedAttribute); addEntry(new Date(), value); } catch (Exception e) { getLogger().error(new StringBuffer(" Exception reading attribute ").append(observedAttribute).append(" of MBean ").append(observedName).toString(), e); } } } } mx4j-3.0.2/src/tools/mx4j/tools/stats/TimedStatisticsRecorderMBean.java100644 0 0 1266 10513545721 23215 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface for TimedStatisticsRecorder MBeans. * * @version $Revision: 1.3 $ */ public interface TimedStatisticsRecorderMBean extends ObserverStatisticsRecorderMBean { /** * Sets how often the MBean will poll the variable value */ public void setGranularity(long granularity); /** * Returns how often the MBean will poll the variable value */ public long getGranularity(); } mx4j-3.0.2/src/tools/mx4j/tools/stats/TimedStatisticsRecorderMBeanDescription.java100644 0 0 1345 10513545721 25417 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface description for TimedStatisticsRecorder MBeans. * * @version $Revision: 1.3 $ */ public class TimedStatisticsRecorderMBeanDescription extends ObserverStatisticsRecorderMBeanDescription { public String getAttributeDescription(String attribute) { if ("Granularity".equals(attribute)) { return "How often the MBean will poll the variable value"; } return super.getAttributeDescription(attribute); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ValueStatisticsRecorder.java100644 0 0 2345 10513545721 22323 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; /** * ValueStatisticsRecorder records statistics of an attribute * based on changes on the variable value. If you want to use you have to explictly * set the variable value. *

* Example usage: *

 * ObjectName name = new ObjectName("Domain:name=value");
 * server.createMBean("mx4j.tools.stats.ValueStatisticsRecorder", name, null);
 * server.invoke(name, "start", null, null);
 * // Every time the value is set the statistics are updated
 * server.setAttribute(name, "Attribute", new Double(10));
 * 
* * @version $Revision: 1.5 $ */ public class ValueStatisticsRecorder extends AbstractStatisticsRecorder implements ValueStatisticsRecorderMBean { protected Number value = null; public void setValue(Number value) { this.value = value; addEntry(new Date(), value); } public Number getValue() { return value; } public String toString() { return "ValueStatisticsRecorder"; } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ValueStatisticsRecorderMBean.java100644 0 0 1155 10513545721 23224 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface for the ValueStatisticsRecorder MBean. * * @version $Revision: 1.3 $ */ public interface ValueStatisticsRecorderMBean extends StatisticsRecorderMBean { /** * Sets the value to be recorded */ public void setValue(Number value); /** * Returns the recorded value */ public Number getValue(); } mx4j-3.0.2/src/tools/mx4j/tools/stats/ValueStatisticsRecorderMBeanDescription.java100644 0 0 1245 10513545721 25430 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * MBean description. * @see StatisticsMBean * * @version $Revision: 1.3 $ */ public class ValueStatisticsRecorderMBeanDescription extends StatisticsRecorderMBeanDescription { public String getAttributeDescription(String attribute) { if ("Value".equals(attribute)) { return "The value to be recorded"; } return super.getAttributeDescription(attribute); } } class TimedStatisticsRecorder extends ObserverStatisticsRecorder implements TimedStatisticsRecorderMBean { protected boolean registered = false; protected static Timer timer = new Timer(); protected CollectTask task = new CollectTask(); protected long granularity = 1000L; public TimedStatisticsRecorder() { } public void setGranularity(long granularity) { this.granularity = granularity; } public long getGranularity() { return granularity; } public String toString() { return "TimedStatisticsRecorder"; } protected synchronized void startObserving() throws Exception { task = new CollectTask(); timer.schedule(task, 0, granularity); } protected synchronized void stopObserving() throws Exception { task.cancel(); } private class CollectTask extends TimerTask { public void run() { try { Number value = (Number)server.getAttribute(observedName, observedAttribute); addEntry(new Date(), value); } catch (Exception e) { getLogger().error(new StringBuffer(" Exception reading attribute ").append(observedAttribute).append(" of MBean ").append(observedName).toString(), e); } } } } mx4j-3.0.2/src/tools/mx4j/tools/stats/TimedStatisticsRecorderMBean.java100644 0 0 1266 10513545721 23215 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface for TimedStatisticsRecorder MBeans. * * @version $Revision: 1.3 $ */ public interface TimedStatisticsRecorderMBean extends ObserverStatisticsRecorderMBean { /** * Sets how often the MBean will poll the variable value */ public void setGranularity(long granularity); /** * Returns how often the MBean will poll the variable value */ public long getGranularity(); } mx4j-3.0.2/src/tools/mx4j/tools/stats/TimedStatisticsRecorderMBeanDescription.java100644 0 0 1345 10513545721 25417 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; /** * Management interface description for TimedStatisticsRecorder MBeans. * * @version $Revision: 1.3 $ */ public class TimedStatisticsRecorderMBeanDescription extends ObserverStatisticsRecorderMBeanDescription { public String getAttributeDescription(String attribute) { if ("Granularity".equals(attribute)) { return "How often the MBean will poll the variable value"; } return super.getAttributeDescription(attribute); } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ValueStatisticsRecorder.java100644 0 0 2345 10513545721 22323 0ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.tools.stats; import java.util.Date; /** * ValueStatisticsRecorder records statistics of an attribute * based on changes on the variable value. If you want to use you have to explictly * set the variable value. *

* Example usage: *

 * ObjectName name = new ObjectName("Domain:name=value");
 * server.createMBean("mx4j.tools.stats.ValueStatisticsRecorder", name, null);
 * server.invoke(name, "start", null, null);
 * // Every time the value is set the statistics are updated
 * server.setAttribute(name, "Attribute", new Double(10));
 * 
* * @version $Revision: 1.5 $ */ public class ValueStatisticsRecorder extends AbstractStatisticsRecorder implements ValueStatisticsRecorderMBean { protected Number value = null; public void setValue(Number value) { this.value = value; addEntry(new Date(), value); } public Number getValue() { return value; } public String toString() { return "ValueStatisticsRecorder"; } } mx4j-3.0.2/src/tools/mx4j/tools/stats/ValueStatisticsRecorderMBean.java100644 0 0 1155 10513545721 23224 0ustar 0 0