mx4j-3.0.2/build/ 40755 0 0 0 10513545721 10532 5 ustar 0 0 mx4j-3.0.2/lib/ 40755 0 0 0 10513545721 10201 5 ustar 0 0 mx4j-3.0.2/src/ 40755 0 0 0 10513545721 10222 5 ustar 0 0 mx4j-3.0.2/src/core/ 40755 0 0 0 10513545721 11152 5 ustar 0 0 mx4j-3.0.2/src/core/javax/ 40755 0 0 0 10513545721 12263 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/ 40755 0 0 0 10513545721 14377 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/loading/ 40755 0 0 0 10513545721 16014 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/modelmbean/ 40755 0 0 0 10513545721 16502 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/monitor/ 40755 0 0 0 10513545721 16066 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/openmbean/ 40755 0 0 0 10513545721 16343 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/relation/ 40755 0 0 0 10513545721 16214 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/remote/ 40755 0 0 0 10513545721 15672 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/remote/rmi/ 40755 0 0 0 10513545721 16461 5 ustar 0 0 mx4j-3.0.2/src/core/javax/management/timer/ 40755 0 0 0 10513545721 15517 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/ 40755 0 0 0 10513545721 12034 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/loading/ 40755 0 0 0 10513545721 13451 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/log/ 40755 0 0 0 10513545721 12615 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/monitor/ 40755 0 0 0 10513545721 13523 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/persist/ 40755 0 0 0 10513545721 13525 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/ 40755 0 0 0 10513545721 13327 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/ 40755 0 0 0 10513545721 15161 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/iiop/ 40755 0 0 0 10513545721 16121 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/provider/rmi/ 40755 0 0 0 10513545721 15750 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/ 40755 0 0 0 10513545721 15170 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/iiop/ 40755 0 0 0 10513545721 16130 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/resolver/rmi/ 40755 0 0 0 10513545721 15757 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/remote/rmi/ 40755 0 0 0 10513545721 14116 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/server/ 40755 0 0 0 10513545721 13342 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/server/interceptor/ 40755 0 0 0 10513545721 15700 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/timer/ 40755 0 0 0 10513545721 13154 5 ustar 0 0 mx4j-3.0.2/src/core/mx4j/util/ 40755 0 0 0 10513545721 13011 5 ustar 0 0 mx4j-3.0.2/src/docs/ 40755 0 0 0 10513545721 11152 5 ustar 0 0 mx4j-3.0.2/src/docs/english/ 40755 0 0 0 10513545721 12603 5 ustar 0 0 mx4j-3.0.2/src/docs/images/ 40755 0 0 0 10513545721 12417 5 ustar 0 0 mx4j-3.0.2/src/docs/xsl/ 40755 0 0 0 10513545721 11760 5 ustar 0 0 mx4j-3.0.2/src/etc/ 40755 0 0 0 10513545721 10775 5 ustar 0 0 mx4j-3.0.2/src/examples/ 40755 0 0 0 10513545721 12040 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/ 40755 0 0 0 10513545721 12722 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/ 40755 0 0 0 10513545721 14540 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/ 40755 0 0 0 10513545721 16005 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/dynamic/ 40755 0 0 0 10513545721 17431 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/helloworld/ 40755 0 0 0 10513545721 20160 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/iiop/ 40755 0 0 0 10513545721 16745 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/legacy/ 40755 0 0 0 10513545721 17251 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/mbeans/rmi/ 40755 0 0 0 10513545721 16574 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/ 40755 0 0 0 10513545721 16033 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/interception/ 40755 0 0 0 10513545721 20536 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/notification/ 40755 0 0 0 10513545721 20521 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ 40755 0 0 0 10513545721 16622 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/iiop/ 40755 0 0 0 10513545721 17562 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/rmi/ssl/ 40755 0 0 0 10513545721 17423 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/security/ 40755 0 0 0 10513545721 17702 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/remote/simple/ 40755 0 0 0 10513545721 17324 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/ 40755 0 0 0 10513545721 16363 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/loading/ 40755 0 0 0 10513545721 20000 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/services/relation/ 40755 0 0 0 10513545721 20200 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/ 40755 0 0 0 10513545721 15700 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/ 40755 0 0 0 10513545721 17332 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/adaptor/http/ 40755 0 0 0 10513545721 20311 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/config/ 40755 0 0 0 10513545721 17145 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/jython/ 40755 0 0 0 10513545721 17213 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/mail/ 40755 0 0 0 10513545721 16622 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/persister/ 40755 0 0 0 10513545721 17720 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/ 40755 0 0 0 10513545721 17173 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ 40755 0 0 0 10513545721 20625 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/hessian/ssl/ 40755 0 0 0 10513545721 21426 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/remote/soap/ 40755 0 0 0 10513545721 20135 5 ustar 0 0 mx4j-3.0.2/src/examples/mx4j/examples/tools/xdoclet/ 40755 0 0 0 10513545721 17342 5 ustar 0 0 mx4j-3.0.2/src/test/ 40755 0 0 0 10513545721 11201 5 ustar 0 0 mx4j-3.0.2/src/test/test/ 40755 0 0 0 10513545721 12160 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/ 40755 0 0 0 10513545721 13271 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/ 40755 0 0 0 10513545721 15405 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/ 40755 0 0 0 10513545721 17517 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/ 40755 0 0 0 10513545721 22374 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/ 40755 0 0 0 10513545721 24110 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/ 40755 0 0 0 10513545721 21520 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/ 40755 0 0 0 10513545721 23234 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/loading/ 40755 0 0 0 10513545721 17022 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/modelmbean/ 40755 0 0 0 10513545721 17510 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/modelmbean/support/ 40755 0 0 0 10513545721 21224 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/monitor/ 40755 0 0 0 10513545721 17074 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/openmbean/ 40755 0 0 0 10513545721 17351 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/relation/ 40755 0 0 0 10513545721 17222 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/ 40755 0 0 0 10513545721 16700 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/ 40755 0 0 0 10513545721 21012 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/ 40755 0 0 0 10513545721 23667 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/ 40755 0 0 0 10513545721 25403 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/ 40755 0 0 0 10513545721 23013 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/rmi/ 40755 0 0 0 10513545721 17467 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/support/ 40755 0 0 0 10513545721 20414 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/support/ 40755 0 0 0 10513545721 17121 5 ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/timer/ 40755 0 0 0 10513545721 16525 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/ 40755 0 0 0 10513545721 13042 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/log/ 40755 0 0 0 10513545721 13623 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/remote/ 40755 0 0 0 10513545721 14335 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/server/ 40755 0 0 0 10513545721 14350 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/timer/ 40755 0 0 0 10513545721 14162 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/ 40755 0 0 0 10513545721 14202 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/ 40755 0 0 0 10513545721 15634 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/adaptor/http/ 40755 0 0 0 10513545721 16613 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/config/ 40755 0 0 0 10513545721 15447 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/ 40755 0 0 0 10513545721 14761 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/jython/ 40755 0 0 0 10513545721 15515 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/ 40755 0 0 0 10513545721 15475 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/burlap/ 40755 0 0 0 10513545721 16762 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/hessian/ 40755 0 0 0 10513545721 17127 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/local/ 40755 0 0 0 10513545721 16567 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/proxy/ 40755 0 0 0 10513545721 16656 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/remote/soap/ 40755 0 0 0 10513545721 16437 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/stats/ 40755 0 0 0 10513545721 15340 5 ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/util/ 40755 0 0 0 10513545721 14017 5 ustar 0 0 mx4j-3.0.2/src/tools/ 40755 0 0 0 10513545721 11362 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/ 40755 0 0 0 10513545721 12244 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/ 40755 0 0 0 10513545721 13404 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ 40755 0 0 0 10513545721 15036 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/ 40755 0 0 0 10513545721 16015 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/ 40755 0 0 0 10513545721 16623 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/ 40755 0 0 0 10513545721 15637 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/config/ 40755 0 0 0 10513545721 14651 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/i18n/ 40755 0 0 0 10513545721 14163 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/jython/ 40755 0 0 0 10513545721 14717 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/mail/ 40755 0 0 0 10513545721 14326 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/naming/ 40755 0 0 0 10513545721 14655 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/ 40755 0 0 0 10513545721 14677 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/ 40755 0 0 0 10513545721 16141 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/burlap/ 40755 0 0 0 10513545721 17426 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/hessian/ 40755 0 0 0 10513545721 17573 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/caucho/serialization/ 40755 0 0 0 10513545721 21016 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/http/ 40755 0 0 0 10513545721 15656 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/http/jetty/ 40755 0 0 0 10513545721 17015 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/local/ 40755 0 0 0 10513545721 15771 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/ 40755 0 0 0 10513545721 16531 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ 40755 0 0 0 10513545721 20016 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/burlap/ssl/ 40755 0 0 0 10513545721 20617 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ 40755 0 0 0 10513545721 20163 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/hessian/ssl/ 40755 0 0 0 10513545721 20764 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/local/ 40755 0 0 0 10513545721 17623 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ 40755 0 0 0 10513545721 17473 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/provider/soap/ssl/ 40755 0 0 0 10513545721 20274 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/proxy/ 40755 0 0 0 10513545721 16060 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/ 40755 0 0 0 10513545721 16540 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/ 40755 0 0 0 10513545721 20025 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/burlap/ssl/ 40755 0 0 0 10513545721 20626 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/ 40755 0 0 0 10513545721 20172 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/hessian/ssl/ 40755 0 0 0 10513545721 20773 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/local/ 40755 0 0 0 10513545721 17632 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ 40755 0 0 0 10513545721 17502 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/ 40755 0 0 0 10513545721 20303 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/rmi/ 40755 0 0 0 10513545721 15466 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/ 40755 0 0 0 10513545721 15641 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ 40755 0 0 0 10513545721 16605 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/remote/soap/axis/ser/ 40755 0 0 0 10513545721 17376 5 ustar 0 0 mx4j-3.0.2/src/tools/mx4j/tools/stats/ 40755 0 0 0 10513545721 14542 5 ustar 0 0 mx4j-3.0.2/Apache-LICENSE.txt 100644 0 0 5156 10513545712 12541 0 ustar 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
* This class is used by the {@link javax.management.MBeanServerFactory} to delegate the
* creation of new instances of {@link javax.management.MBeanServerDelegate} and
* {@link javax.management.MBeanServer}.
* This implementation further delegates the work to {@link mx4j.server.MX4JMBeanServerBuilder}
* to return implementations in the The {@link javax.management.MBeanServerFactory} creates the delegate before
* creating the MBeanServer itself and providing a reference to the created delegate.
* Note that the delegate passed to the MBeanServer might not be the instance returned
* by this builder; for example, it could be a wrapper around it.
* Only MBeans whose codesource has this permission can be registered in the MBeanServer.
* This permission is composed by a target name, whose only valid value are
*
* Wildcard matching routine by Karl Heuer. Public Domain.
*/
private boolean wildcardMatch(String s, String p)
{
if (s == null && p == null) return true;
if (s == null) return false;
if (p == null) return true;
char c;
int si = 0, pi = 0;
int slen = s.length();
int plen = p.length();
while (pi < plen) // While still string
{
c = p.charAt(pi++);
if (c == '?')
{
if (++si > slen) return false;
}
else if (c == '[') // Start of choice
{
boolean wantit = true;
boolean seenit = false;
if (p.charAt(pi) == '!')
{
wantit = false;
++pi;
}
while (++pi < plen && (c = p.charAt(pi)) != ']')
{
if (p.charAt(pi) == '-' && pi + 1 < plen)
{
if (s.charAt(si) >= c && s.charAt(si) <= p.charAt(pi + 1))
{
seenit = true;
}
pi += 1;
}
else
{
if (c == s.charAt(si))
{
seenit = true;
}
}
}
if ((pi >= plen) || (wantit != seenit)) return false;
++pi;
++si;
}
else if (c == '*') // Wildcard
{
if (pi >= plen) return true;
do
{
if (wildcardMatch(s.substring(si), p.substring(pi))) return true;
}
while (++si < slen);
return false;
}
else if (c == '\\')
{
if (pi >= plen || p.charAt(pi++) != s.charAt(si++)) return false;
}
else
{
if (si >= slen || c != s.charAt(si++)) return false;
}
}
return (si == slen);
}
}
mx4j-3.0.2/src/core/javax/management/NotCompliantMBeanException.java 100644 0 0 1241 10513545721 22526 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Thrown when trying to register an MBean object that is not a compliant JMX MBean.
*
* @version $Revision: 1.7 $
*/
public class NotCompliantMBeanException extends OperationsException
{
private static final long serialVersionUID = 5175579583207963577L;
public NotCompliantMBeanException()
{
}
public NotCompliantMBeanException(String message)
{
super(message);
}
}
mx4j-3.0.2/src/core/javax/management/NotQueryExp.java 100644 0 0 2011 10513545721 17574 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The QueryExp for the 'not' operation
*
* @version $Revision: 1.6 $
* @serial include
*/
class NotQueryExp extends QueryEval implements QueryExp
{
private static final long serialVersionUID = 5269643775896723397L;
/**
* @serial The expression to negate
*/
private QueryExp exp;
NotQueryExp(QueryExp exp)
{
this.exp = exp;
}
public void setMBeanServer(MBeanServer server)
{
super.setMBeanServer(server);
if (exp != null) exp.setMBeanServer(server);
}
public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
if (exp != null) return !exp.apply(name);
return false;
}
}
mx4j-3.0.2/src/core/javax/management/Notification.java 100644 0 0 12521 10513545721 20006 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.EventObject;
/**
* Notifications are events emitted by {@link NotificationEmitter}s
*
* @version $Revision: 1.8 $
*/
public class Notification extends EventObject
{
private static final long serialVersionUID = -7516092053498031989L;
/**
* @serial The notification type
*/
private String type;
/**
* @serial The notification sequence number
*/
private long sequenceNumber;
/**
* @serial The notification timestamp
*/
private long timeStamp;
/**
* @serial The notification message
*/
private String message;
/**
* @serial The notification user data
*/
private Object userData;
/**
* A duplicate for the existing data member in EventObject: this one is not transient and should hold only
* ObjectNames (so they are Serializable and can be sent along the wire for remote notifications), and it's
* protected and not private for a mistake in JMX 1.0, but for binary compatibility we leave it protected.
*
* @serial The ObjectName of the emitter MBean
*/
protected Object source;
/**
* Convenience constructor for Parameters:< Throws:
* The MBeanPermission contains a target name and a comma separated list of target actions.
* The target name is composed by:
*
*
* When used in the target name, the wildcard '*' may be used to specify packages, classes or methods as a whole.
* When used in the actions, the wildcard '*' indicates all actions.
* An example of policy file is the following:
*
* grant codebase my-jmx-application.jar
* {
* permission javax.management.MBeanPermission "mx4j.tools.naming.NamingService", "instantiate, registerMBean, unregisterMBean";
* permission javax.management.MBeanPermission "mx4j.tools.naming.NamingService#start", "invoke";
* permission javax.management.MBeanPermission "mx4j.tools.naming.NamingService#stop", "invoke";
* }
*
*
* @version $Revision: 1.11 $
*/
public class MBeanPermission extends Permission
{
private static final long serialVersionUID = 0xde755825e2a117abL;
private static final String WILDCARD = "*";
private static final String NILCARD = "-";
/**
* @serial The permission actions
*/
private String actions;
private transient int hash;
private transient String className;
private transient String memberName;
private transient ObjectName objectName;
private transient ArrayList actionsList;
/**
* Creates a new MBeanPermission
*
* @param name The target name
* @param actions The comma separated list of actions
*/
public MBeanPermission(String name, String actions)
{
super(name);
this.actions = actions;
parse(name, actions);
}
/**
* Creates a new MBeanPermission. If the parts composing the target name are all specified as null,
* the wildcard target name '*' is assumed.
*
* @param className The className part of the target name, may be null
* @param memberName The memberName part of the target name, may be null
* @param objectName The ObjectName part of the target name, may be null
* @param actions The comma separated list of actions
*/
public MBeanPermission(String className, String memberName, ObjectName objectName, String actions)
{
this(createTargetName(className, memberName, objectName), actions);
}
private static String createTargetName(String className, String memberName, ObjectName objectName)
{
StringBuffer target = new StringBuffer();
target.append(className == null ? "-" : className);
target.append('#');
target.append(memberName == null ? "-" : memberName);
target.append('[');
target.append(objectName == null ? "-" : objectName.getCanonicalName());
target.append(']');
return target.toString();
}
private void parse(String name, String actions)
{
className = parseClassName(name);
memberName = parseMemberName(name);
objectName = parseObjectName(name);
actionsList = parseActions(actions);
}
public int hashCode()
{
if (hash == 0) hash = computeHash();
return hash;
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
if (getClass() != obj.getClass()) return false;
// Must have the same target name, and the same action list, after parsing
MBeanPermission other = (MBeanPermission)obj;
// The parsed members can be null (means they're the nilcard)
if (!areEqual(getClassName(), other.getClassName())) return false;
if (!areEqual(getMemberName(), other.getMemberName())) return false;
if (!areEqual(getObjectName(), other.getObjectName())) return false;
return getActionsList().equals(other.getActionsList());
}
private boolean areEqual(Object obj1, Object obj2)
{
if (obj1 == null) return obj2 == null;
return obj1.equals(obj2);
}
public String getActions()
{
return actions;
}
private String getClassName()
{
return className;
}
private String getMemberName()
{
return memberName;
}
private ObjectName getObjectName()
{
return objectName;
}
private ArrayList getActionsList()
{
return actionsList;
}
public boolean implies(Permission p)
{
if (p == null) return false;
if (getClass() != p.getClass()) return false;
MBeanPermission permission = (MBeanPermission)p;
if (!impliesClassName(permission)) return false;
if (!impliesMemberName(permission)) return false;
if (!impliesObjectName(permission)) return false;
if (!impliesActions(permission)) return false;
return true;
}
private boolean impliesClassName(MBeanPermission p)
{
return impliesTarget(getClassName(), p.getClassName());
}
private boolean impliesMemberName(MBeanPermission p)
{
return impliesTarget(getMemberName(), p.getMemberName());
}
private boolean impliesTarget(String thisTarget, String otherTarget)
{
// Handle nilcards
if (thisTarget == null) return otherTarget == null;
if (otherTarget == null) return true;
// Easy and fast check
if (thisTarget.equals(otherTarget)) return true;
// Now see the wildcard. While thisTarget can be wildcarded in several ways,
// otherTarget is created only with the full wildcard, or with no wildcard
boolean otherWildcard = otherTarget.indexOf(WILDCARD) >= 0;
boolean thisWildcard = thisTarget.indexOf(WILDCARD) >= 0;
if (thisWildcard)
{
if (otherWildcard)
{
// otherTarget can only be '*'
return thisTarget.equals(WILDCARD);
}
else
{
// We support all types of wildcarding with '*'
return Utils.wildcardMatch(thisTarget, otherTarget);
}
}
else
{
if (otherWildcard)
{
return false;
}
else
{
return thisTarget.equals(otherTarget);
}
}
}
private boolean impliesObjectName(MBeanPermission p)
{
ObjectName name1 = getObjectName();
ObjectName name2 = p.getObjectName();
// Handle nilcards
if (name1 == null) return name2 == null;
if (name2 == null) return true;
return name1.implies(name2);
}
private boolean impliesActions(MBeanPermission p)
{
ArrayList thisActions = getActionsList();
boolean thisWild = thisActions.contains(WILDCARD);
ArrayList otherActions = p.getActionsList();
boolean otherWild = otherActions.contains(WILDCARD);
// Access is granted for all actions
if (thisWild) return true;
// Access was not granted for all actions, but is requested for all actions
if (otherWild) return false;
if (thisActions.containsAll(otherActions)) return true;
// Special check: queryMBeans implies queryNames
if (otherActions.contains("queryNames") && thisActions.contains("queryMBeans"))
{
// Umpf, this is ugly, but not immediate: must care multithreading
for (int i = 0; i < otherActions.size(); ++i)
{
Object perm = otherActions.get(i);
if ("queryNames".equals(perm)) continue;
if (!thisActions.contains(perm)) return false;
}
return true;
}
return false;
}
private String parseClassName(String name)
{
if (name == null) throw new IllegalArgumentException("Target name cannot be null");
String target = name.trim();
if (target.length() == 0) throw new IllegalArgumentException("Target name cannot be empty");
// Try to find the ObjectName beginning
int square = target.indexOf('[');
if (square >= 0)
{
// There is an ObjectName, take only the classname and member
target = target.substring(0, square).trim();
}
// There is only the ObjectName, means classname == wildcard
if (target.length() == 0) return WILDCARD;
// Try to find the member beginning
int pound = target.indexOf('#');
if (pound >= 0)
{
// There is a member, take only the classname
target = target.substring(0, pound).trim();
}
// There is only the member, means classname == wildcard
if (target.length() == 0) return WILDCARD;
// Check for the nilcard
if (target.equals(NILCARD)) return null;
return target;
}
private String parseMemberName(String name)
{
// Checks already done in parseClassName
String target = name.trim();
// Try to find the ObjectName beginning
int square = target.indexOf('[');
if (square >= 0)
{
// There is an ObjectName, take only the classname and member
target = target.substring(0, square).trim();
}
// There is only the ObjectName, means member == wildcard
if (target.length() == 0) return WILDCARD;
// Try to find the member beginning
int pound = target.indexOf('#');
if (pound >= 0)
{
// There is a member, take only it
target = target.substring(pound + 1).trim();
}
else
{
// No member, means member == wildcard
target = WILDCARD;
}
// Check for the nilcard
if (target.equals(NILCARD)) return null;
return target;
}
private ObjectName parseObjectName(String name)
{
// Checks already done in parseClassName
String target = name.trim();
String inside = "*:*";
// Find beginning of ObjectName
int open = target.indexOf('[');
if (open >= 0)
{
int close = target.indexOf(']');
if (close < 0) throw new IllegalArgumentException("Missing closing ObjectName bracket");
// Find the ObjectName string inside the brackets
inside = target.substring(open + 1, close).trim();
if (inside.length() == 0)
{
inside = "*:*";
}
else if (inside.equals(NILCARD))
{
return null;
}
}
// Create the ObjectName
try
{
ObjectName objectName = new ObjectName(inside);
return objectName;
}
catch (MalformedObjectNameException x)
{
throw new IllegalArgumentException("Invalid ObjectName: " + inside);
}
}
private ArrayList parseActions(String actions)
{
if (actions == null) throw new IllegalArgumentException("Actions list cannot be null");
actions = actions.trim();
if (actions.length() == 0) throw new IllegalArgumentException("Actions list cannot be empty");
// Split the comma separated list of actions
ArrayList list = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(actions, ",");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken().trim();
if (token.length() == 0) continue;
if (token.equals(WILDCARD))
{
list.clear();
list.add(WILDCARD);
return list;
}
else
{
list.add(token);
}
}
if (list.size() < 1) throw new IllegalArgumentException("No actions specified");
// It is very important for hashCode() and equals() that the list is sorted
Collections.sort(list);
return list;
}
private int computeHash()
{
String cls = getClassName();
int hash = cls == null ? NILCARD.hashCode() : cls.hashCode();
String member = getMemberName();
hash ^= member == null ? NILCARD.hashCode() : member.hashCode();
ObjectName name = getObjectName();
hash ^= name == null ? NILCARD.hashCode() : name.hashCode();
hash ^= getActionsList().hashCode();
return hash;
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
parse(getName(), getActions());
}
}
mx4j-3.0.2/src/core/javax/management/MBeanRegistration.java 100644 0 0 4241 10513545721 20715 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Defines a series of callbacks that allow the MBean to interact with the process of MBean
* registration and unregistration performed by the MBeanServer.
* Implementing this interface is an easy way for an MBean to get the reference to the
* MBeanServer that manages it.
*
* @version $Revision: 1.6 $
*/
public interface MBeanRegistration
{
/**
* Callback called just before MBean registration in the MBeanServer.
* Any exception thrown by this method will cause the MBean registration to abort.
*
* @param server The MBeanServer on which the MBean will be registered.
* @param name The ObjectName
of the MBean.
* @return The ObjectName
of the registered MBean, must not be null
* @throws Exception Any possible exception generated by this method will be caught
* by the MBeanServer
and re-thrown as an MBeanRegistrationException
* to the client.
*/
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception;
/**
* Callback called just after the MBean has been registered (successfully or not).
*
* @param registrationDone True if the registration was successful, false otherwise.
*/
public void postRegister(Boolean registrationDone);
/**
* Callback called just before MBean unregistration from the MBeanServer.
* Any exception thrown by this method will cause the MBean unregistration to abort.
*
* @throws Exception Any possible exception generated by this method will be caught
* by the MBeanServer
and re-thrown as an MBeanRegistrationException
* to the client.
*/
public void preDeregister() throws Exception;
/**
* Callback called just after the MBean has been successfully unregistered.
*/
public void postDeregister();
}
mx4j-3.0.2/src/core/javax/management/MBeanRegistrationException.java 100644 0 0 1211 10513545721 22566 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* @version $Revision: 1.8 $
* @see MBeanRegistration
*/
public class MBeanRegistrationException extends MBeanException
{
private static final long serialVersionUID = 4482382455277067805L;
public MBeanRegistrationException(Exception x)
{
super(x);
}
public MBeanRegistrationException(Exception x, String message)
{
super(x, message);
}
}
mx4j-3.0.2/src/core/javax/management/MBeanServer.java 100644 0 0 25362 10513545721 17540 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.ObjectInputStream;
import java.util.Set;
import javax.management.loading.ClassLoaderRepository;
/**
* A local client can create, register, unregister and access registered MBeans by means of this interface, that is
* the core component of JMX.
* An implementation of this interface can only be obtained from {@link MBeanServerFactory}.
* Almost all methods require an {@link MBeanPermission} to be invoked under SecurityManager.
*
* @version $Revision: 1.8 $
*/
public interface MBeanServer extends MBeanServerConnection
{
public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException;
public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException;
public void removeNotificationListener(ObjectName observed, ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException;
public void removeNotificationListener(ObjectName observed, NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException;
public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException;
public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException;
public MBeanInfo getMBeanInfo(ObjectName objectName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException;
public boolean isInstanceOf(ObjectName objectName, String className)
throws InstanceNotFoundException;
public String[] getDomains();
public String getDefaultDomain();
public ObjectInstance createMBean(String className, ObjectName objectName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException;
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException;
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException;
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException;
public void unregisterMBean(ObjectName objectName)
throws InstanceNotFoundException, MBeanRegistrationException;
public Object getAttribute(ObjectName objectName, String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;
public void setAttribute(ObjectName objectName, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException;
public AttributeList getAttributes(ObjectName objectName, String[] attributes)
throws InstanceNotFoundException, ReflectionException;
public AttributeList setAttributes(ObjectName objectName, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException;
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException;
public Integer getMBeanCount();
public boolean isRegistered(ObjectName objectname);
public ObjectInstance getObjectInstance(ObjectName objectName)
throws InstanceNotFoundException;
public Set queryMBeans(ObjectName patternName, QueryExp filter);
public Set queryNames(ObjectName patternName, QueryExp filter);
/**
* Instantiates an object of the given class using the MBeanServer's {@link ClassLoaderRepository}.
* The given class should have a public parameterless constructor.
*
* @param className The class name of the object to be instantiated.
* @return The newly instantiated object.
* @throws ReflectionException Wraps a Java reflection exception thrown while trying to create the instance
* @throws MBeanException Thrown if the constructor of the object throws an exception
*/
public Object instantiate(String className)
throws ReflectionException, MBeanException;
/**
* Instantiates an object of the given class using the specified ClassLoader MBean.
* If loaderName
is null, the classloader of the MBeanServer will be used.
* The given class should have a public parameterless constructor.
*
* @param className The class name of the MBean to be instantiated.
* @param loaderName The object name of the class loader to be used.
* @return The newly instantiated object.
* @throws ReflectionException Wraps a Java reflection exception thrown while trying to create the instance
* @throws MBeanException Thrown if the constructor of the object throws an exception
* @throws InstanceNotFoundException The specified classloader MBean is not registered in the MBeanServer.
*/
public Object instantiate(String className, ObjectName loaderName)
throws ReflectionException, MBeanException, InstanceNotFoundException;
/**
* Instantiates an object of the given class using the MBeanServer's {@link ClassLoaderRepository}.
* The given class should have a public constructor matching the given signature, and will be called
* passing the given arguments.
*
* @param className The class name of the object to be instantiated.
* @param args The arguments passed to the constructor.
* @param parameters The signature of the constructor.
* @return The newly instantiated object.
* @throws ReflectionException Wraps a Java reflection exception thrown while trying to create the instance
* @throws MBeanException Thrown if the constructor of the object throws an exception
*/
public Object instantiate(String className, Object[] args, String[] parameters)
throws ReflectionException, MBeanException;
/**
* Instantiates an object of the given class using the specified ClassLoader MBean.
* If loaderName
is null, the classloader of the MBeanServer will be used.
* The given class should have a public constructor matching the given signature, and will be called
* passing the given arguments.
*
* @param className The class name of the MBean to be instantiated.
* @param loaderName The object name of the class loader to be used.
* @param args The arguments passed to the constructor.
* @param parameters The signature of the constructor.
* @return The newly instantiated object.
* @throws ReflectionException Wraps a Java reflection exception thrown while trying to create the instance
* @throws MBeanException Thrown if the constructor of the object throws an exception
* @throws InstanceNotFoundException The specified classloader MBean is not registered in the MBeanServer.
*/
public Object instantiate(String className, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, MBeanException, InstanceNotFoundException;
/**
* Registers the given MBean with the given ObjectName.
* The ObjectName may be null, but the MBean should then implement {@link MBeanRegistration}.
*
* @param mbean The MBean to be registered.
* @param objectName The ObjectName of the MBean, may be null.
* @return An ObjectInstance, containing the ObjectName and the Java class name of the newly registered MBean.
* @throws InstanceAlreadyExistsException An MBean with the same ObjectName is already registered in the MBeanServer.
* @throws MBeanRegistrationException Thrown if a problem is encountered during registration.
* @throws NotCompliantMBeanException The given MBean is not a JMX compliant MBean
*/
public ObjectInstance registerMBean(Object mbean, ObjectName objectName)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException;
/**
* @deprecated Use {@link #getClassLoader} to obtain the classloader for deserialization.
*/
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] bytes)
throws InstanceNotFoundException, OperationsException, ReflectionException;
/**
* @deprecated Use {@link #getClassLoaderRepository} to obtain the ClassLoaderRepository for deserialization.
*/
public ObjectInputStream deserialize(String className, byte[] bytes)
throws OperationsException, ReflectionException;
/**
* @deprecated Use {@link #getClassLoaderFor} to obtain the classloader for deserialization.
*/
public ObjectInputStream deserialize(ObjectName objectName, byte[] bytes)
throws InstanceNotFoundException, OperationsException;
/**
* Returns the ClassLoader that was used for loading the named MBean.
*
* @param mbeanName The ObjectName of the MBean.
* @return The ClassLoader used to load the names MBean.
* @throws InstanceNotFoundException If the named MBean is not found.
* @since JMX 1.2
*/
public ClassLoader getClassLoaderFor(ObjectName mbeanName)
throws InstanceNotFoundException;
/**
* Returns the named classloader MBean. If the given loaderName
is null, the classloader
* of the MBeanServer will be used.
*
* @param loaderName The ObjectName of the classloader MBean, or null.
* @return The named classloader MBean.
* @throws InstanceNotFoundException If the named classloader MBean is not found.
* @since JMX 1.2
*/
public ClassLoader getClassLoader(ObjectName loaderName)
throws InstanceNotFoundException;
/**
* Returns the ClassLoaderRepository for this MBeanServer.
*
* @since JMX 1.2
*/
public ClassLoaderRepository getClassLoaderRepository();
}
mx4j-3.0.2/src/core/javax/management/MBeanServerBuilder.java 100644 0 0 4146 10513545721 21024 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import mx4j.server.MX4JMBeanServerBuilder;
/**
* mx4j.server
package.createMBean(className, objectName, null, null)
.
*
* @see #createMBean(String, ObjectName, Object[], String[])
*/
public ObjectInstance createMBean(String className, ObjectName objectName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException;
/**
* Instantiates and registers an MBean of the specified class with the given ObjectName in the MBeanServer.
* The MBeanServer will use its ClassLoaderRepository to load the class of the MBean and the specified
* constructor's parameter classes, and creates the instance passing the specified arguments.
* The ObjectName may be null if the MBean implements {@link MBeanRegistration}
*
* @param className The class name of the MBean to be instantiated.
* @param objectName The ObjectName of the MBean, may be null.
* @param args An array containing the arguments to pass to the constructor.
* @param parameters An array containing the signature of the constructor.
* @return An ObjectInstance, containing the ObjectName and the Java class name of the newly instantiated MBean.
* @throws ReflectionException If a reflection exception is thrown.
* @throws InstanceAlreadyExistsException If another MBean with the same ObjectName is already registered in the MBeanServer.
* @throws MBeanRegistrationException If an exception is thrown during MBean's registration.
* @throws MBeanException If the constructor of the MBean has thrown an exception
* @throws NotCompliantMBeanException If the MBean is not a JMX compliant MBean
* @throws IOException If a communication problem occurred.
*/
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException;
/**
* A facility method for createMBean(className, objectName, loaderName, null, null)
.
*
* @see #createMBean(String, ObjectName, ObjectName, Object[], String[])
*/
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException;
/**
* Instantiates and registers an MBean of the specified class with the given ObjectName in the MBeanServer.
* The MBeanServer will use the specified classloader MBean to load the class of the MBean and the specified
* constructor's parameter classes, and creates the instance passing the specified arguments, or the classloader
* of the MBeanServer if the classloader ObjectName is null.
* The ObjectName may be null if the MBean implements {@link MBeanRegistration}
*
* @param className The class name of the MBean to be instantiated.
* @param objectName The ObjectName of the MBean, may be null.
* @param loaderName The ObjectName of the classloader MBean to be used.
* @param args An array containing the arguments to pass to the constructor.
* @param parameters An array containing the signature of the constructor.
* @return An ObjectInstance, containing the ObjectName and the Java class name of the newly instantiated MBean.
* @throws ReflectionException If a reflection exception is thrown.
* @throws InstanceAlreadyExistsException If another MBean with the same ObjectName is already registered in the MBeanServer.
* @throws MBeanRegistrationException If an exception is thrown during MBean's registration.
* @throws MBeanException If the constructor of the MBean has thrown an exception
* @throws NotCompliantMBeanException If the MBean is not a JMX compliant MBean
* @throws InstanceNotFoundException If the specified classloader MBean is not registered in the MBeanServer.
* @throws IOException If a communication problem occurred.
*/
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException;
/**
* Unregisters the MBean with the specified ObjectName from this MBeanServer.
*
* @param objectName The ObjectName of the MBean to be unregistered.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws MBeanRegistrationException If an exception is thrown during MBean's unregistration.
* @throws IOException If a communication problem occurred.
*/
public void unregisterMBean(ObjectName objectName)
throws InstanceNotFoundException, MBeanRegistrationException, IOException;
/**
* Gets the value of the specified attribute of the named MBean.
*
* @param objectName The ObjectName of the MBean from which the attribute is to be retrieved.
* @param attribute The attribute name.
* @return The value of the specified attribute.
* @throws AttributeNotFoundException If the specified attribute does not belong to the management interface of the MBean.
* @throws MBeanException If the MBean's getter method throws an exception.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws ReflectionException If a reflection exception is thrown.
* @throws IOException If a communication problem occurred.
* @see #setAttribute
*/
public Object getAttribute(ObjectName objectName, String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException;
/**
* Sets the value of the specified attribute of the named MBean.
*
* @param objectName The name of the MBean within which the attribute is to be set.
* @param attribute The Attribute to be set.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws AttributeNotFoundException If the specified attribute does not belong to the management interface of the MBean.
* @throws InvalidAttributeValueException If the value specified for the attribute does not match the attribute's type
* @throws MBeanException If the MBean's setter method throws an exception.
* @throws ReflectionException If a reflection exception is thrown.
* @throws IOException If a communication problem occurred.
* @see #getAttribute
*/
public void setAttribute(ObjectName objectName, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException;
/**
* Gets the values of several attributes of the named MBean.
*
* @param objectName The ObjectName of the MBean from which the attributes are to be retrieved.
* @param attributes The attribute names.
* @return An AttributeList containing the values of the attributes that it has been possible to retrieve.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws ReflectionException If a reflection exception is thrown.
* @throws IOException If a communication problem occurred.
* @see #setAttributes
*/
public AttributeList getAttributes(ObjectName objectName, String[] attributes)
throws InstanceNotFoundException, ReflectionException, IOException;
/**
* Sets the values of several attributes of the named MBean.
*
* @param objectName The name of the MBean within which the attribute is to be set.
* @param attributes The AttributeList containing the Attributes to be set.
* @return The AttributeList containing the attributes that it has been possible to set.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws ReflectionException If a reflection exception is thrown.
* @throws IOException If a communication problem occurred.
* @see #getAttributes
*/
public AttributeList setAttributes(ObjectName objectName, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException, IOException;
/**
* Invokes the specified operation on the named MBean.
*
* @param objectName The ObjectName of the MBean on which the method is to be invoked.
* @param methodName The name of the operation to be invoked.
* @param args An array containing the arguments to pass to the operation.
* @param parameters An array containing the signature of the operation.
* @return The return value of the operation, or null if the operation returns void.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws MBeanException If the MBean's operation method throws an exception.
* @throws ReflectionException If a reflection exception is thrown.
* @throws IOException If a communication problem occurred.
*/
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException, IOException;
/**
* Returns the number of MBeans registered in this MBeanServer.
*
* @throws IOException If a communication problem occurred.
*/
public Integer getMBeanCount()
throws IOException;
/**
* Checks whether the given ObjectName identifies an MBean registered in this MBeanServer.
*
* @param objectName The ObjectName to be checked.
* @return True if an MBean with the specified ObjectName is already registered in the MBeanServer.
* @throws IOException If a communication problem occurred.
*/
public boolean isRegistered(ObjectName objectName)
throws IOException;
/**
* Gets the ObjectInstance for the named MBean registered with the MBeanServer.
*
* @param objectName The ObjectName of the MBean.
* @return The ObjectInstance associated with the named MBean.
* @throws InstanceNotFoundException If the specified MBean is not registered in the MBeanServer.
* @throws IOException If a communication problem occurred.
*/
public ObjectInstance getObjectInstance(ObjectName objectName)
throws InstanceNotFoundException, IOException;
/**
* Gets a subset of the ObjectInstances belonging to MBeans registered in this MBeanServer.
* It is possible to filter the set of MBeans by specifying a pattern for MBean's ObjectNames, and a query expression
* to be evaluated to further filter the set of MBeans.
* The set can be further restricted if any exception is thrown during retrieval of MBean (for example for
* security reasons): the failing MBean will not be included.
*
* @param patternName The ObjectName pattern identifying the MBeans to be retrieved, or null to retrieve all MBeans.
* @param filter The query expression to be evaluated for selecting MBeans, or null.
* @return A set containing the ObjectInstance objects for the selected MBeans.
* @throws IOException If a communication problem occurred.
*/
public Set queryMBeans(ObjectName patternName, QueryExp filter)
throws IOException;
/**
* Gets a subset of the ObjectNames belonging to MBeans registered in this MBeanServer.
* It is possible to filter the set of MBeans by specifying a pattern for MBean's ObjectNames, and a query expression
* to be evaluated to further filter the set of MBeans.
* The set can be further restricted if any exception is thrown during retrieval of MBean (for example for
* security reasons): the failing MBean will not be included.
*
* @param patternName The ObjectName pattern identifying the MBeans to be retrieved, or null to retrieve all MBeans.
* @param filter The query expression to be evaluated for selecting MBeans, or null.
* @return A set containing the ObjectNames for the selected MBeans.
* @throws IOException If a communication problem occurred.
*/
public Set queryNames(ObjectName patternName, QueryExp filter)
throws IOException;
}
mx4j-3.0.2/src/core/javax/management/MBeanServerDelegate.java 100644 0 0 7372 10513545721 21154 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.server.UID;
/**
* The MBean that broadcasts notifications about registration and unregistration of other MBeans.
* It is registered with ObjectName JMImplementation:type=MBeanServerDelegate
.
* It also gives information about the JMX version and implementation.
*
* @version $Revision: 1.24 $
*/
public class MBeanServerDelegate implements MBeanServerDelegateMBean, NotificationEmitter
{
private static long mbeanServerCount;
// Only notifications of type MBeanServerNotification are emitted by this class, so the array must have length 1
private static final MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[]{new MBeanNotificationInfo
(new String[]{MBeanServerNotification.REGISTRATION_NOTIFICATION, MBeanServerNotification.UNREGISTRATION_NOTIFICATION},
MBeanServerNotification.class.getName(), // as required by the spec
"Notifications emitted by the MBeanServerDelegate MBean upon registration or unregistration of MBeans")};
private String mbeanServerID;
private NotificationBroadcasterSupport broadcaster = new NotificationBroadcasterSupport();
/**
* Creates a new instance of the MBeanServerDelegate
*/
public MBeanServerDelegate()
{
}
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException
{
broadcaster.addNotificationListener(listener, filter, handback);
}
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException
{
broadcaster.removeNotificationListener(listener);
}
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException
{
broadcaster.removeNotificationListener(listener, filter, handback);
}
public MBeanNotificationInfo[] getNotificationInfo()
{
return notifications;
}
/**
* @see NotificationBroadcasterSupport#sendNotification
*/
public void sendNotification(Notification notification)
{
broadcaster.sendNotification(notification);
}
public String getMBeanServerId()
{
// Evaluate lazily, since it may be an expensive operation
synchronized (this)
{
if (mbeanServerID == null) mbeanServerID = generateMBeanServerID();
}
return mbeanServerID;
}
public String getImplementationName()
{
return "MX4J";
}
public String getImplementationVendor()
{
return "The MX4J Team";
}
public String getImplementationVersion()
{
return "3.0.2";
}
public String getSpecificationName()
{
return "Java Management Extensions";
}
public String getSpecificationVendor()
{
return "Sun Microsystems";
}
public String getSpecificationVersion()
{
return "1.2 Maintenance Release";
}
private String getLocalHost()
{
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException ignored)
{
return "localhost";
}
}
private String generateMBeanServerID()
{
long count = 0;
synchronized (MBeanServerDelegate.class)
{
++mbeanServerCount;
count = mbeanServerCount;
}
UID uid = new UID();
return uid.toString() + ":" + getLocalHost() + ":" + count;
}
}
mx4j-3.0.2/src/core/javax/management/MBeanServerDelegateMBean.java 100644 0 0 2470 10513545721 22051 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Defines the management interface for the MBeanServerDelegate.
*
* @version $Revision: 1.6 $
*/
public interface MBeanServerDelegateMBean
{
/**
* Returns the implementation name, for example 'MX4J'.
*/
public String getImplementationName();
/**
* Returns the implementation vendor, for example 'The MX4J Team'.
*/
public String getImplementationVendor();
/**
* Returns the implementation version, for example '1.1'.
*/
public String getImplementationVersion();
/**
* Returns the MBeanServer ID.
*
* @see javax.management.MBeanServerFactory#findMBeanServer
*/
public String getMBeanServerId();
/**
* Returns the JMX specification name, the string 'Java Management Extensions'.
*/
public String getSpecificationName();
/**
* Returns the JMX specification vendor, the string 'Sun Microsystems'.
*/
public String getSpecificationVendor();
/**
* Returns the JMX specification version, for example '1.2'.
*/
public String getSpecificationVersion();
}
mx4j-3.0.2/src/core/javax/management/MBeanServerFactory.java 100644 0 0 20622 10513545721 21062 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import javax.management.loading.ClassLoaderRepository;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* @version $Revision: 1.25 $
*/
public class MBeanServerFactory
{
private static ArrayList servers = new ArrayList();
private MBeanServerFactory()
{
}
private static Logger getLogger()
{
return Log.getLogger(MBeanServerFactory.class.getName());
}
public static MBeanServer createMBeanServer()
{
return createMBeanServer(null);
}
public static MBeanServer createMBeanServer(String defaultDomain)
{
MBeanServer server = createMBeanServerImpl(defaultDomain, "createMBeanServer");
synchronized (servers)
{
servers.add(server);
}
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer " + server + " registered successfully");
return server;
}
public static MBeanServer newMBeanServer()
{
return newMBeanServer(null);
}
public static MBeanServer newMBeanServer(String defaultDomain)
{
return createMBeanServerImpl(defaultDomain, "newMBeanServer");
}
public static void releaseMBeanServer(MBeanServer server)
{
Logger logger = getLogger();
try
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Releasing MBeanServer " + server);
if (server != null)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new MBeanServerPermission("releaseMBeanServer"));
boolean removed = false;
synchronized (servers)
{
removed = servers.remove(server);
}
if (removed)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer " + server + " released successfully");
}
else
{
if (logger.isEnabledFor(Logger.INFO)) logger.info("MBeanServer " + server + " not released, cannot find it");
}
}
else
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot release a null MBeanServer");
}
}
catch (SecurityException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Security Exception caught while releasing MBeanServer " + server, x);
throw x;
}
}
public static ArrayList findMBeanServer(String id)
{
Logger logger = getLogger();
ArrayList list = null;
try
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Finding MBeanServer with ID: " + id);
SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new MBeanServerPermission("findMBeanServer"));
if (id == null)
{
list = (ArrayList)servers.clone();
}
else
{
list = new ArrayList();
synchronized (servers)
{
for (int i = 0; i < servers.size(); ++i)
{
MBeanServer server = (MBeanServer)servers.get(i);
String serverId = getMBeanServerId(server);
if (id.equals(serverId))
{
list.add(server);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Found matching MBeanServer: " + server);
}
}
}
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer(s) found: " + list);
return list;
}
catch (SecurityException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Security Exception caught while finding MBeanServer with ID: " + id, x);
throw x;
}
}
private static String getMBeanServerId(final MBeanServer server)
{
try
{
return (String)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception
{
return server.getAttribute(ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"), "MBeanServerId");
}
});
}
catch (SecurityException x)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("No permission to get MBeanServerID", x);
}
catch (PrivilegedActionException x)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Could not get MBeanServerID", x.getException());
}
catch (Throwable x)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Could not get MBeanServerID", x);
}
return null;
}
public static ClassLoaderRepository getClassLoaderRepository(MBeanServer server)
{
// Yes, throw NPE is server is null (spec compliant)
return server.getClassLoaderRepository();
}
private static MBeanServer createMBeanServerImpl(String domain, String permission)
{
Logger logger = getLogger();
boolean trace = logger.isEnabledFor(Logger.TRACE);
try
{
SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(new MBeanServerPermission(permission));
// get MBeanServerBuilder
if (trace) logger.trace("Obtaining MBeanServerBuilder");
final MBeanServerBuilder builder = createMBeanServerBuilder();
if (trace) logger.trace("Using MBeanServerBuilder " + builder.getClass());
// create delegate
if (trace) logger.trace("Creating MBeanServerDelegate...");
final MBeanServerDelegate delegate = builder.newMBeanServerDelegate();
if (trace) logger.trace("MBeanServerDelegate " + delegate.getClass() + " created successfully");
// create MBean server
if (trace) logger.trace("Creating MBeanServer...");
MBeanServer mbs = builder.newMBeanServer(domain, null, delegate);
if (trace) logger.trace("MBeanServer " + mbs + " created successfully");
if (logger.isEnabledFor(Logger.INFO))
{
String mbeanServerId = getMBeanServerId(mbs);
if (mbeanServerId != null)
logger.info("Created MBeanServer with ID: " + mbeanServerId);
else
logger.info("Created MBeanServer");
}
return mbs;
}
catch (SecurityException x)
{
if (trace) logger.trace("Security Exception caught while creating an MBeanServer", x);
throw x;
}
}
private static MBeanServerBuilder createMBeanServerBuilder()
{
final Class builderClass = loadMBeanServerBuilderClass();
try
{
return (MBeanServerBuilder)builderClass.newInstance();
}
catch (ClassCastException e)
{
throw new JMRuntimeException("Specified MBeanServerBuilder must be a subclass of MBeanServerBuilder: " + builderClass);
}
catch (IllegalAccessException e)
{
throw new JMRuntimeException("Can't instantiate MBeanServerBuilder " + builderClass + ": " + e);
}
catch (InstantiationException e)
{
throw new JMRuntimeException("Can't instantiate MBeanServerBuilder " + builderClass + ": " + e);
}
}
private static Class loadMBeanServerBuilderClass()
{
String builderClassName = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty("javax.management.builder.initial");
}
});
if (builderClassName == null || builderClassName.length() == 0)
{
return MBeanServerBuilder.class;
}
try
{
return Thread.currentThread().getContextClassLoader().loadClass(builderClassName);
}
catch (ClassNotFoundException e)
{
throw new JMRuntimeException("MBeanServerBuilder class not found: " + builderClassName);
}
}
}
mx4j-3.0.2/src/core/javax/management/MBeanServerInvocationHandler.java 100644 0 0 20212 10513545721 23055 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import mx4j.util.Utils;
/**
*/
public class MBeanServerInvocationHandler implements InvocationHandler
{
private final MBeanServerConnection connection;
private final ObjectName objectName;
public MBeanServerInvocationHandler(MBeanServerConnection connection, ObjectName objectName)
{
this.connection = connection;
this.objectName = objectName;
}
public static Object newProxyInstance(MBeanServerConnection connection, ObjectName name, Class mbeanInterface, boolean notificationBroadcaster)
{
if (mbeanInterface == null) throw new IllegalArgumentException("MBean interface cannot be null");
if (!mbeanInterface.isInterface()) throw new IllegalArgumentException("Class parameter must be an interface");
if (name == null) throw new IllegalArgumentException("MBean ObjectName cannot be null");
if (connection == null) throw new IllegalArgumentException("MBeanServerConnection cannot be null");
Class[] interfaces = null;
if (notificationBroadcaster && !(mbeanInterface.equals(NotificationEmitter.class)))
{
if ((mbeanInterface.equals(NotificationBroadcaster.class)))
{
interfaces = new Class[]{NotificationEmitter.class};
}
else
{
interfaces = new Class[]{mbeanInterface, NotificationEmitter.class};
}
}
else
{
interfaces = new Class[]{mbeanInterface};
}
// The client must be able to cast the returned object to the mbeanInterface it passes,
// so the classloader must be the same
ClassLoader loader = mbeanInterface.getClassLoader();
return Proxy.newProxyInstance(loader, interfaces, new MBeanServerInvocationHandler(connection, name));
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Class[] declared = method.getExceptionTypes();
Class declaringClass = method.getDeclaringClass();
if (declaringClass.equals(NotificationBroadcaster.class) || declaringClass.equals(NotificationEmitter.class))
{
return invokeNotificationMethod(proxy, method, args, declared);
}
// No need to check for consistency between the signature and the args parameter,
// since the invocation it is not done by reflection, but statically
if (Utils.isAttributeSetter(method))
{
String name = method.getName().substring(3);
Attribute attribute = new Attribute(name, args[0]);
try
{
connection.setAttribute(objectName, attribute);
return null;
}
catch (Throwable x)
{
unwrapThrowable(x, declared);
}
}
else if (Utils.isAttributeGetter(method))
{
String n = method.getName();
String name = null;
if (n.startsWith("is"))
name = n.substring(2);
else
name = n.substring(3);
try
{
return connection.getAttribute(objectName, name);
}
catch (Throwable x)
{
unwrapThrowable(x, declared);
}
}
else
{
Class[] parameters = method.getParameterTypes();
String[] params = new String[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
params[i] = parameters[i].getName();
}
try
{
return connection.invoke(objectName, method.getName(), args, params);
}
catch (Throwable x)
{
unwrapThrowable(x, declared);
}
}
return null;
}
/**
* Convenience method that invokes Notification-related methods.
*
* @param proxy Proxy object created by the newProxyInstance method
* @param method The java.lang.Method
to be invoked
* @param args The method's arguments
* @param declared The method's declared exceptions
*/
private Object invokeNotificationMethod(Object proxy, Method method, Object[] args, Class[] declared)
throws Throwable
{
String methodName = method.getName();
int numArgs = (args == null) ? 0 : args.length;
if (methodName.equals("addNotificationListener"))
{
try
{
connection.addNotificationListener(objectName, (NotificationListener)args[0], (NotificationFilter)args[1], args[2]);
}
catch (Throwable t)
{
unwrapThrowable(t, declared);
}
return null;
}
else if (methodName.equals("removeNotificationListener"))
{
switch (numArgs)
{
case 1:
try
{
connection.removeNotificationListener(objectName, (NotificationListener)args[0]);
}
catch (Throwable t)
{
unwrapThrowable(t, declared);
}
return null;
case 3:
try
{
connection.removeNotificationListener(objectName, (NotificationListener)args[0], (NotificationFilter)args[1], args[2]);
}
catch (Throwable t)
{
unwrapThrowable(t, declared);
}
return null;
default :
throw new IllegalArgumentException("Method removeNotificationListener must have 1 or 3 arguments");
}
}
else if (methodName.equals("getNotificationInfo"))
{
try
{
MBeanInfo info = connection.getMBeanInfo(objectName);
return info.getNotifications();
}
catch (Throwable t)
{
unwrapThrowable(t, declared);
}
return null;
}
else
{
throw new IllegalArgumentException("Method " + methodName + " not known to MBean: " + objectName);
}
}
/**
* Rethrows 'as is' the given throwable. If it is an instance of one of the given declared
classes,
* this method tries to (recursively) unwrap it and rethrow it.
*
* @param x The java.lang.Throwable
to unwrap
* @param declared An array of java.lang.Class
objects representing the declared exceptions
* of the invoked method.
* @throws java.lang.Throwable
*/
private void unwrapThrowable(Throwable x, Class[] declared) throws Throwable
{
if (declared != null)
{
// See if the exception is declared by the method
// If so, just rethrow it.
for (int i = 0; i < declared.length; ++i)
{
Class exception = declared[i];
if (exception.isInstance(x))
throw x;
}
}
// The exception is not declared, try to unwrap it
if (x instanceof MBeanException)
{
unwrapThrowable(((MBeanException)x).getTargetException(), declared);
}
else if (x instanceof ReflectionException)
{
unwrapThrowable(((ReflectionException)x).getTargetException(), declared);
}
else if (x instanceof RuntimeOperationsException)
{
unwrapThrowable(((RuntimeOperationsException)x).getTargetException(), declared);
}
else if (x instanceof RuntimeMBeanException)
{
unwrapThrowable(((RuntimeMBeanException)x).getTargetException(), declared);
}
else if (x instanceof RuntimeErrorException)
{
unwrapThrowable(((RuntimeErrorException)x).getTargetError(), declared);
}
else
{
// Rethrow as is. Since this exception is not declared by the methods of the interface,
// if it is checked it will be thrown as an UndeclaredThrowableException, if it is unchecked
// it will be rethrown as is.
throw x;
}
}
}
mx4j-3.0.2/src/core/javax/management/MBeanServerNotification.java 100644 0 0 4177 10513545721 22070 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The notification emitted by the {@link MBeanServerDelegate delegate MBean}
* when an MBean is registered or unregistered.
*
* @version $Revision: 1.9 $
*/
public class MBeanServerNotification extends Notification
{
private static final long serialVersionUID = 2876477500475969677L;
/**
* The type of the notification when an MBean is registered
*/
public static final String REGISTRATION_NOTIFICATION = "JMX.mbean.registered";
/**
* The type of the notification when an MBean is unregistered
*/
public static final String UNREGISTRATION_NOTIFICATION = "JMX.mbean.unregistered";
/**
* @serial The ObjectName of the MBean that is registered or unregistered
*/
private ObjectName objectName;
/**
* Creates a new MBeanServerNotification.
*
* @param type Either REGISTRATION_NOTIFICATION or UNREGISTRATION_NOTIFICATION
* @param source The MBeanServerDelegate's ObjectName
* @param sequenceNumber A sequence number
* @param objectName The ObjectName of the MBean registered or unregistered
*/
public MBeanServerNotification(String type, Object source, long sequenceNumber, ObjectName objectName)
{
super(type, source, sequenceNumber, "");
if (!type.equals(REGISTRATION_NOTIFICATION) && !type.equals(UNREGISTRATION_NOTIFICATION))
{
throw new RuntimeOperationsException(new IllegalArgumentException("Bad notification type for MBeanServerNotification"));
}
this.objectName = objectName;
}
/**
* Returns the ObjectName of the MBean that was registered or unregistered
*/
public ObjectName getMBeanName()
{
return objectName;
}
public String toString()
{
StringBuffer b = new StringBuffer(super.toString());
b.append("[");
b.append(getMBeanName());
b.append("]");
return b.toString();
}
}
mx4j-3.0.2/src/core/javax/management/MBeanServerPermission.java 100644 0 0 11775 10513545721 21614 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.BasicPermission;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
/**
* The permission that guards access to MBeanServerFactory methods.
* It has no actions, only target names can be provided.
* The wildcard "*" means all names, and "createMBeanServer" implies "newMBeanServer", and the names
* can be specified as a comma separated list.
* The list of target names is the following:
*
*
*
* @version $Revision: 1.14 $
*/
public class MBeanServerPermission extends BasicPermission
{
private static final long serialVersionUID = 0xb16c9a6bd5fae3d2L;
private transient ArrayList targets;
private transient boolean wildcard;
/**
* Creates a new MBeanServerPermission with the specified name and no actions
*
* @param name The comma separated list of target names
*/
public MBeanServerPermission(String name)
{
this(name, null);
}
/**
* Creates a new MBeanServerPermission with the specified name and actions, but the actions will be ignored
*
* @param name The comma separated list of target names
* @param actions Ignored
*/
public MBeanServerPermission(String name, String actions)
{
super(name);
parseName(name);
if (actions != null && actions.length() != 0) throw new IllegalArgumentException("Actions must be null or an empty string");
}
/**
* Returns null, as this permission does not have actions
*/
public String getActions()
{
return null;
}
public int hashCode()
{
return targets.hashCode();
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
try
{
MBeanServerPermission other = (MBeanServerPermission)obj;
// We don't check wildcard: if targets is empty, means we have a wildcard (see parseName)
return targets.equals(other.targets);
}
catch (ClassCastException x)
{
}
return false;
}
public boolean implies(Permission p)
{
if (p == null) return false;
if (getClass() != p.getClass()) return false;
MBeanServerPermission other = (MBeanServerPermission)p;
if (wildcard) return true;
if (other.wildcard) return false;
if (targets.containsAll(other.targets)) return true;
// We have to manage the case where this contains createMBeanServer and other contains newMBeanServer
if (other.targets.contains("newMBeanServer") && targets.contains("createMBeanServer"))
{
// Beware the case where we have MBeanServerPermission "createMBeanServer" and
// MBeanServerPermission "newMBeanServer, findMBeanServer": the first should not imply the second.
for (int i = 0; i < other.targets.size(); ++i)
{
Object perm = other.targets.get(i);
if ("newMBeanServer".equals(perm)) continue;
if (!targets.contains(perm)) return false;
}
return true;
}
return false;
}
private void parseName(String name)
{
if (name == null) throw new IllegalArgumentException("Permission name cannot be null");
name = name.trim();
if (name.length() == 0) throw new IllegalArgumentException("Permission name cannot be empty");
targets = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(name, ",");
while (tokenizer.hasMoreTokens())
{
String target = tokenizer.nextToken().trim();
if (target.length() == 0) continue;
if ("*".equals(target))
{
targets.clear();
wildcard = true;
return;
}
else if ("newMBeanServer".equals(target) || "createMBeanServer".equals(target) || "findMBeanServer".equals(target) || "releaseMBeanServer".equals(target))
{
targets.add(target);
}
else
{
throw new IllegalArgumentException("Invalid permission name: " + target);
}
}
if (targets.size() < 1) throw new IllegalArgumentException("Permission name does not contain targets");
// Important to provide same hashcode and equals to permission with names in different order
Collections.sort(targets);
}
public PermissionCollection newPermissionCollection()
{
return null;
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
parseName(getName());
}
}
mx4j-3.0.2/src/core/javax/management/MBeanTrustPermission.java 100644 0 0 2740 10513545721 21437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.security.BasicPermission;
/**
* Permission that MBean class must have in order to be trusted. register
and the wildcard *
.
* The actions are ignored.
*
* @version $Revision: 1.5 $
*/
public class MBeanTrustPermission extends BasicPermission
{
private static final long serialVersionUID = 0xd707c1ae24fd55e4L;
/**
* Creates a new MBeanTrustPermission with the specified target name and no actions
*
* @param name Can only be "register" or "*"
*/
public MBeanTrustPermission(String name)
{
this(name, null);
}
/**
* Creates a new MBeanTrustPermission with the specified target name and actions, but the actions will be ignored
*
* @param name Can only be "register" or "*"
* @param actions Ignored
*/
public MBeanTrustPermission(String name, String actions)
{
super(name, actions);
if (!"register".equals(name) && !"*".equals(name)) throw new IllegalArgumentException("Target name must be 'register' or '*' not '" + name + "'");
}
}
mx4j-3.0.2/src/core/javax/management/MalformedObjectNameException.java 100644 0 0 1117 10513545721 23054 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* @version $Revision: 1.8 $
*/
public class MalformedObjectNameException extends OperationsException
{
private static final long serialVersionUID = -572689714442915824L;
public MalformedObjectNameException()
{
}
public MalformedObjectNameException(String message)
{
super(message);
}
}
mx4j-3.0.2/src/core/javax/management/MatchQueryExp.java 100644 0 0 6735 10513545721 20111 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* @version $Revision: 1.7 $
* @serial include
*/
class MatchQueryExp extends QueryEval implements QueryExp
{
private static final long serialVersionUID = -7156603696948215014L;
/**
* @serial The value to match
*/
private final AttributeValueExp exp;
/**
* @serial The matching pattern
*/
private final String pattern;
MatchQueryExp(AttributeValueExp exp, StringValueExp pattern)
{
this.exp = exp;
this.pattern = pattern == null ? null : pattern.getValue();
}
public void setMBeanServer(MBeanServer server)
{
super.setMBeanServer(server);
if (exp != null) exp.setMBeanServer(server);
}
public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
ValueExp value = exp.apply(name);
if (value instanceof StringValueExp)
{
return wildcardMatch(((StringValueExp)value).getValue(), pattern);
}
return false;
}
/**
* Tests whether string s is matched by pattern p.
* Supports "?", "*", "[", each of which may be escaped with "\";
* Character classes may use "!" for negation and "-" for range.
* Not yet supported: internationalization; "\" inside brackets.Notification(type, source, sequenceNumber, System.currentTimeMillis(), null)
*
* @see #Notification(String, Object, long, long, String)
*/
public Notification(String type, Object source, long sequenceNumber)
{
this(type, source, sequenceNumber, System.currentTimeMillis(), null);
}
/**
* Convenience constructor for Notification(type, source, sequenceNumber, timestamp, null)
*
* @see #Notification(String, Object, long, long, String)
*/
public Notification(String type, Object source, long sequenceNumber, long timeStamp)
{
this(type, source, sequenceNumber, timeStamp, null);
}
/**
* Convenience constructor for Notification(type, source, sequenceNumber, System.currentTimeMillis(), message)
*
* @see #Notification(String, Object, long, long, String)
*/
public Notification(String type, Object source, long sequenceNumber, String message)
{
this(type, source, sequenceNumber, System.currentTimeMillis(), message);
}
/**
* Creates a new Notification
*
* @param type The notification type
* @param source The ObjectName of the emitter MBean
* @param sequenceNumber The Notification sequence number
* @param timeStamp The notification timestamp
* @param message The Notification message
*/
public Notification(String type, Object source, long sequenceNumber, long timeStamp, String message)
{
// Data member source of EventObject is transient
super(source);
this.source = source;
this.type = type;
this.sequenceNumber = sequenceNumber;
this.timeStamp = timeStamp;
this.message = message;
}
/**
* Returns the notification message
*/
public String getMessage()
{
return message;
}
/**
* Returns the notification type
*/
public String getType()
{
return type;
}
/**
* Returns the notification source
*
* @see #setSource
*/
public Object getSource()
{
return this.source;
}
/**
* Sets the notification source
*
* @see #getSource
*/
public void setSource(Object source)
{
this.source = source;
}
/**
* Returns the notification sequence number
*
* @see #setSequenceNumber
*/
public long getSequenceNumber()
{
return sequenceNumber;
}
/**
* Sets the notification sequence number
*
* @see #getSequenceNumber
*/
public void setSequenceNumber(long sequenceNumber)
{
this.sequenceNumber = sequenceNumber;
}
/**
* Returns the notification timestamp
*
* @see #setTimeStamp
*/
public long getTimeStamp()
{
return timeStamp;
}
/**
* Sets the notification timestamp
*
* @see #getTimeStamp
*/
public void setTimeStamp(long timeStamp)
{
this.timeStamp = timeStamp;
}
/**
* Returns the notification user data
*
* @see #setUserData
*/
public Object getUserData()
{
return userData;
}
/**
* Sets the notification user data
*
* @see #getUserData
*/
public void setUserData(Object userData)
{
this.userData = userData;
}
public String toString()
{
StringBuffer b = new StringBuffer("[");
b.append("source=").append(getSource()).append(", ");
b.append("message=").append(getMessage()).append(", ");
b.append("sequence=").append(getSequenceNumber()).append(", ");
b.append("type=").append(getType()).append(", ");
b.append("time=").append(getTimeStamp()).append(", ");
b.append("data=").append(getUserData());
b.append("]");
return b.toString();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
// EventObject data member is transient
super.source = source;
}
}
mx4j-3.0.2/src/core/javax/management/NotificationBroadcaster.java 100644 0 0 3475 10513545721 22150 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Although not deprecated, this interface should not be used since JMX 1.2; use
* {@link NotificationEmitter} instead.
*
* @version $Revision: 1.8 $
* @see Notification
*/
public interface NotificationBroadcaster
{
/**
* Returns the metadata information associated with this emitter.
*/
public MBeanNotificationInfo[] getNotificationInfo();
/**
* Adds a notification listener to this emitter.
*
* @param listener The notification listener which will handle the notifications emitted.
* @param filter Filters notifications that the listener should receive; may be null, if no filtering is required.
* @param handback An opaque object to be sent back to the listener when a notification is emitted.
* @see #removeNotificationListener(NotificationListener)
*/
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException;
/**
* Removes a notification listener from this emitter.
* If the listener has been registered with different handback objects or notification filters,
* all entries corresponding to the listener will be removed.
*
* @param listener The notification listener that was previously added to this emitter.
* @throws ListenerNotFoundException If the listener is not registered with the emitter.
* @see #addNotificationListener(NotificationListener, NotificationFilter, Object)
*/
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException;
}
mx4j-3.0.2/src/core/javax/management/NotificationBroadcasterSupport.java 100644 0 0 32466 10513545721 23567 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* Provides an implementation of NotificationEmitter interface.
* This can be used as the super class of an MBean that sends notifications.
* It is not specified whether the notification dispatch model is synchronous or asynchronous.
* That is, when a thread calls sendNotification, the NotificationListener.handleNotification
* method of each listener may be called within that thread (a synchronous model)
* or within some other thread (an asynchronous model).
* Applications should not depend on notification dispatch being synchronous or being asynchronous. Thus:
*
*
*
* @version $Revision: 1.19 $
*/
public class NotificationBroadcasterSupport implements NotificationEmitter
{
private static final NotificationFilter NULL_FILTER = new NotificationFilter()
{
public boolean isNotificationEnabled(Notification notification)
{
return true;
}
public String toString()
{
return "null filter";
}
};
private static final Object NULL_HANDBACK = new Object()
{
public String toString()
{
return "null handback";
}
};
private HashMap m_listeners = new HashMap();
public NotificationBroadcasterSupport()
{
}
private Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Adding notification listener: " + listener + ", filter: " + filter + ", handback: " + handback + " to " + this);
if (listener == null) throw new IllegalArgumentException("Notification listener cannot be null");
// Normalize the arguments
if (filter == null) filter = NULL_FILTER;
if (handback == null) handback = NULL_HANDBACK;
FilterHandbackPair pair = new FilterHandbackPair(filter, handback);
synchronized (this)
{
ArrayList pairs = (ArrayList)m_listeners.get(listener);
if (pairs == null)
{
// A new listener, register it
pairs = new ArrayList();
pairs.add(pair);
m_listeners.put(listener, pairs);
}
else
{
// Check that the same triple (listener, filter, handback) is not already registered
for (int i = 0; i < pairs.size(); ++i)
{
FilterHandbackPair other = (FilterHandbackPair)pairs.get(i);
if (pair.filter.equals(other.filter) && pair.handback.equals(other.handback))
{
// Same filter and same handback for the same listener, it's already registered
throw new RuntimeOperationsException(new IllegalArgumentException("Notification listener is already registered"));
}
}
// Not yet registered, register.
// Do not merge this call with the one in the if branch: like this is easier to debug
// (I know the if-else branch from where I'm coming)
pairs.add(pair);
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Filters - Handbacks for this listener: " + pairs);
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Notification listener added successfully to " + this);
}
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Removing notification listener: " + listener);
int removed = removeNotificationListenerImpl(listener, null, null);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace(removed + " notification listener(s) removed successfully from " + this);
}
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Removing notification listener: " + listener + ", filter: " + filter + ", handback: " + handback);
// Normalize the arguments if necessary
if (filter == null) filter = NULL_FILTER;
if (handback == null) handback = NULL_HANDBACK;
int removed = removeNotificationListenerImpl(listener, filter, handback);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace(removed + " notification listener(s) removed successfully from " + this);
}
private int removeNotificationListenerImpl(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
Logger logger = getLogger();
synchronized (this)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Listeners for " + this + " are: " + m_listeners);
ArrayList pairs = (ArrayList)m_listeners.get(listener);
if (pairs == null) throw new ListenerNotFoundException("NotificationListener " + listener + " not found");
if (filter == null)
{
if (handback == null)
{
// Means I want to remove all triplets for this listener
ArrayList removed = (ArrayList)m_listeners.remove(listener);
return removed.size();
}
else
{
// Means I want to remove all triplets with the given handback for this listener
int count = 0;
for (int i = 0; i < pairs.size(); ++i)
{
Object hand = ((FilterHandbackPair)pairs.get(i)).handback;
if (handback.equals(hand))
{
pairs.remove(i);
++count;
}
}
if (count == 0) throw new ListenerNotFoundException("NotificationListener " + listener + " with handback " + handback + " not found");
// Check if it was the last listener
if (pairs.isEmpty()) m_listeners.remove(listener);
return count;
}
}
else
{
if (handback == null)
{
// Means I want to remove all triplets with the given filter for this listener
int count = 0;
for (int i = 0; i < pairs.size(); ++i)
{
Object filt = ((FilterHandbackPair)pairs.get(i)).filter;
if (filter.equals(filt))
{
pairs.remove(i);
++count;
}
}
if (count == 0) throw new ListenerNotFoundException("NotificationListener " + listener + " with filter " + filter + " not found");
// Check if it was the last listener
if (pairs.isEmpty()) m_listeners.remove(listener);
return count;
}
else
{
// Means I want to remove all triplets with the given filter and handback for this listener
int count = 0;
for (int i = 0; i < pairs.size(); ++i)
{
FilterHandbackPair pair = (FilterHandbackPair)pairs.get(i);
if (filter.equals(pair.filter) && handback.equals(pair.handback))
{
pairs.remove(i);
++count;
}
}
if (count == 0) throw new ListenerNotFoundException("NotificationListener " + listener + " with filter " + filter + " and handback " + handback + " not found");
// Check if it was the last listener
if (pairs.isEmpty()) m_listeners.remove(listener);
return count;
}
}
}
}
public MBeanNotificationInfo[] getNotificationInfo()
{
// Subclasses should override returning more informations
return new MBeanNotificationInfo[0];
}
/**
* Sends the given notification to all registered listeners
*
* @param notification The notification to send
*/
public void sendNotification(Notification notification)
{
Logger logger = getLogger();
boolean trace = logger.isEnabledFor(Logger.TRACE);
boolean info = logger.isEnabledFor(Logger.INFO);
HashMap listeners = null;
synchronized (this)
{
// Clone the listeners, so we can notify without holding any lock
// It is a shallow copy, below we will clone the pairs as well
// I don't care if in the middle someone else adds or remove other pairs
listeners = (HashMap)m_listeners.clone();
}
// Loop over all listeners
Iterator i = listeners.keySet().iterator();
if (i.hasNext() && trace) logger.trace("Sending notifications from " + this);
while (i.hasNext())
{
NotificationListener listener = (NotificationListener)i.next();
if (trace) logger.trace("\tListener is: " + listener);
// Clone again the pairs for this listener.
// I freezed the listeners with the first clone, if someone removes a pair
// in the middle of notifications I don't care: here I clone the actual pairs
ArrayList pairs = null;
synchronized (this)
{
pairs = (ArrayList)listeners.get(listener);
pairs = (ArrayList)pairs.clone();
}
if (trace) logger.trace("\tFilters - Handback for this listener: " + pairs);
// Loop over the same listener that registered many times with different filter / handbacks
for (int j = 0; j < pairs.size(); ++j)
{
FilterHandbackPair pair = (FilterHandbackPair)pairs.get(j);
NotificationFilter filter = pair.filter;
Object handback = pair.handback;
// Denormalize filter and handback if necessary
if (filter == NULL_FILTER) filter = null;
if (handback == NULL_HANDBACK) handback = null;
boolean enabled = false;
try
{
enabled = filter == null || filter.isNotificationEnabled(notification);
}
catch (Throwable x)
{
if (info) logger.info("Throwable caught from isNotificationEnabled", x);
// And go on
}
if (trace) logger.trace("\t\tFilter is: " + filter + ", enabled: " + enabled);
if (enabled)
{
if (trace)
{
logger.debug("\t\tHandback is: " + handback);
logger.debug("\t\tSending notification " + notification);
}
try
{
handleNotification(listener, notification, handback);
}
catch (Throwable x)
{
if (info) logger.info("Throwable caught from handleNotification", x);
// And go on with next listener
}
}
}
}
}
/**
* This method is called by {@link #sendNotification} for each listener in order to send the notification to that listener.
* It can be overridden in subclasses to change the behaviour of notification delivery,
* for instance to deliver the notification in a separate thread.
* It is not guaranteed that this method is called by the same thread as the one that called sendNotification.
* The default implementation of this method is equivalent to
* listener.handleNotification(notif, handback);
*
* @param listener - the listener to which the notification is being delivered.
* @param notification - the notification being delivered to the listener.
* @param handback - the handback object that was supplied when the listener was added.
* @since JMX 1.2
*/
protected void handleNotification(NotificationListener listener, Notification notification, Object handback)
{
listener.handleNotification(notification, handback);
}
private static class FilterHandbackPair
{
private NotificationFilter filter;
private Object handback;
private FilterHandbackPair(NotificationFilter filter, Object handback)
{
this.filter = filter;
this.handback = handback;
}
}
}
mx4j-3.0.2/src/core/javax/management/NotificationEmitter.java 100644 0 0 2260 10513545721 21317 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Interface implemented by an MBean that emits Notifications.
*
* @version $Revision: 1.4 $
* @see Notification
* @since JMX 1.2
*/
public interface NotificationEmitter extends NotificationBroadcaster
{
/**
* Removes a notification listener from this MBean.
* The MBean must have a registered listener that exactly matches the given listener, filter, and handback parameters.
*
* @param listener The listener that was previously added to this MBean.
* @param filter The filter that was specified when the listener was added.
* @param handback The handback that was specified when the listener was added.
* @throws ListenerNotFoundException If the triple listener, filter, handback is not registered with the emitter
*/
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException;
}
mx4j-3.0.2/src/core/javax/management/NotificationFilter.java 100644 0 0 1337 10513545721 21137 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.Serializable;
/**
* Implemented by a class that wants to filter {@link Notification}s sent to a
* {@link NotificationListener}.
*
* @version $Revision: 1.6 $
*/
public interface NotificationFilter extends Serializable
{
/**
* Invoked before sending the Notification to the listener.
*
* @return True if the Notification should be sent, false otherwise
*/
public boolean isNotificationEnabled(Notification notification);
}
mx4j-3.0.2/src/core/javax/management/NotificationFilterSupport.java 100644 0 0 10221 10513545721 22544 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
/**
* Default implementation of a NotificationListener that filters out Notifications that
* does not match the types enabled in this filter.
*
* @version $Revision: 1.11 $
*/
// Change not needed, workaround to a TCK bug only to achieve TCK compliance
// public class NotificationFilterSupport implements NotificationFilter
public class NotificationFilterSupport implements NotificationFilter, Serializable
{
private static final long serialVersionUID = 6579080007561786969L;
private static final String serialName = "enabledTypes";
/**
* @serialField enabledTypes List The list of notification types that this filter will not filter out
*/
private static final ObjectStreamField[] serialPersistentFields =
{
new ObjectStreamField(serialName, List.class)
};
private HashSet types = new HashSet();
public boolean equals(Object o)
{
if (this == o) return true;
if (!(o instanceof NotificationFilterSupport)) return false;
final NotificationFilterSupport support = (NotificationFilterSupport)o;
if (!types.equals(support.types)) return false;
return true;
}
public int hashCode()
{
return types.hashCode();
}
/**
* Allows the given notification type to be received by listeners
*
* @param type The notification type to enable
* @throws IllegalArgumentException If the notification type is null
*/
public void enableType(String type) throws IllegalArgumentException
{
if (type == null) throw new IllegalArgumentException("Null notification type");
synchronized (types)
{
types.add(type);
}
}
/**
* Forbids all notification types to be received by listeners
*/
public void disableAllTypes()
{
synchronized (types)
{
types.clear();
}
}
/**
* Forbids the gven notification type to be received by listeners
*
* @param type The notification type to disable
*/
public void disableType(String type)
{
synchronized (types)
{
types.remove(type);
}
}
/**
* Returns the notification type that are not filtered out by this filter
*/
public Vector getEnabledTypes()
{
Vector v = new Vector();
synchronized (types)
{
v.addAll(types);
}
return v;
}
/**
* Filters out notifications whose type is not enabled in this filter.
*
* @param notification The notification to filter
* @return True if the notification should be delivered to the listener, false otherwise
*/
public boolean isNotificationEnabled(Notification notification)
{
String type = notification.getType();
if (type != null)
{
for (Iterator i = getEnabledTypes().iterator(); i.hasNext();)
{
String t = (String)i.next();
if (type.startsWith(t)) return true;
}
}
return false;
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = in.readFields();
Vector vector = (Vector)fields.get(serialName, null);
if (fields.defaulted(serialName))
{
throw new IOException("Serialized stream corrupted: expecting a non-null Vector");
}
if (types == null) types = new HashSet();
types.clear();
types.addAll(vector);
}
private void writeObject(ObjectOutputStream out) throws IOException
{
ObjectOutputStream.PutField fields = out.putFields();
Vector vector = getEnabledTypes();
fields.put(serialName, vector);
out.writeFields();
}
}
mx4j-3.0.2/src/core/javax/management/NotificationListener.java 100644 0 0 1350 10513545721 21472 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.util.EventListener;
/**
* Implemented by an object that want to receive notifications.
*
* @version $Revision: 1.7 $
*/
public interface NotificationListener extends EventListener
{
/**
* Called when a notification occurs.
*
* @param notification The notification object
* @param handback Helps in associating information regarding the listener.
*/
public void handleNotification(Notification notification, Object handback);
}
mx4j-3.0.2/src/core/javax/management/NumericValueExp.java 100644 0 0 2033 10513545721 20411 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The ValueExp that represents a number.
*
* @version $Revision: 1.6 $
* @serial include
*/
class NumericValueExp extends QueryEval implements ValueExp
{
private static final long serialVersionUID = -4679739485102359104L;
/**
* @serial The number
*/
private Number val;
NumericValueExp(Number val)
{
this.val = val;
}
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
return this;
}
boolean isDouble()
{
return val instanceof Float || val instanceof Double;
}
double doubleValue()
{
return val.doubleValue();
}
long longValue()
{
return val.longValue();
}
}
mx4j-3.0.2/src/core/javax/management/ObjectInstance.java 100644 0 0 5073 10513545721 20237 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.Serializable;
/**
* Identifies an MBean registered in the MBeanServer. An ObjectInstance carries the information
* about MBean's ObjectName and class name.
*
* @version $Revision: 1.7 $
*/
public class ObjectInstance implements Serializable
{
private static final long serialVersionUID = -4099952623687795850L;
/**
* @serial The MBean class name
*/
private String className;
/**
* @serial The MBean ObjectName
*/
private ObjectName name;
/**
* Creates a new ObjectInstance
*
* @param objectName The ObjectName of the MBean
* @param className The class name of the MBean
* @throws MalformedObjectNameException If the ObjectName string does not represent a valid ObjectName
*/
public ObjectInstance(String objectName, String className) throws MalformedObjectNameException
{
this(new ObjectName(objectName), className);
}
/**
* Creates a new ObjectInstance
*
* @param objectName The ObjectName of the MBean
* @param className The class name of the MBean
*/
public ObjectInstance(ObjectName objectName, String className)
{
if (objectName == null || objectName.isPattern()) throw new RuntimeOperationsException(new IllegalArgumentException("Invalid object name"));
if (className == null || className.trim().length() == 0) throw new RuntimeOperationsException(new IllegalArgumentException("Class name cannot be null or empty"));
this.name = objectName;
this.className = className;
}
public boolean equals(Object object)
{
if (object == null) return false;
if (object == this) return true;
try
{
ObjectInstance other = (ObjectInstance)object;
return name.equals(other.name) && className.equals(other.className);
}
catch (ClassCastException ignored)
{
}
return false;
}
public int hashCode()
{
return name.hashCode() ^ className.hashCode();
}
/**
* Returns the ObjectName of the MBean
*/
public ObjectName getObjectName()
{
return name;
}
/**
* Returns the class name of the MBean
*
* @return
*/
public String getClassName()
{
return className;
}
public String toString()
{
return getClassName() + "@" + getObjectName();
}
}
mx4j-3.0.2/src/core/javax/management/ObjectName.java 100644 0 0 65600 10513545721 17375 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import mx4j.MX4JSystemKeys;
import mx4j.util.Utils;
/**
* @version $Revision: 1.26 $
*/
public class ObjectName implements QueryExp, Serializable
{
private static final long serialVersionUID = 1081892073854801359L;
private static final boolean cacheEnabled;
private static final WeakObjectNameCache cache;
static
{
String enableCache = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_OBJECTNAME_CACHING);
}
});
if (enableCache != null)
{
cacheEnabled = Boolean.valueOf(enableCache).booleanValue();
}
else
{
// Cache is on by default
cacheEnabled = true;
}
if (cacheEnabled)
{
cache = new WeakObjectNameCache();
}
else
{
cache = null;
}
}
private transient String propertiesString;
private transient boolean isPropertyPattern;
private transient boolean isDomainPattern;
private transient String canonicalName;
public ObjectName(String name) throws NullPointerException, MalformedObjectNameException
{
if (name == null) throw new NullPointerException("ObjectName 'name' parameter can't be null");
if (name.length() == 0) name = "*:*";
parse(name);
}
public ObjectName(String domain, Hashtable table) throws NullPointerException, MalformedObjectNameException
{
if (domain == null) throw new NullPointerException("ObjectName 'domain' parameter can't be null");
if (table == null) throw new NullPointerException("ObjectName 'table' parameter can't be null");
if (!isDomainValid(domain)) throw new MalformedObjectNameException("Invalid domain: " + domain);
if (table.isEmpty()) throw new MalformedObjectNameException("Properties table cannot be empty");
for (Iterator i = table.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
String key = entry.getKey().toString();
if (!isKeyValid(key)) throw new MalformedObjectNameException("Invalid key: " + key);
Object value = entry.getValue();
if (!(value instanceof String)) throw new MalformedObjectNameException("Property values must be Strings");
String strvalue = value.toString();
if (!isValueValid(strvalue)) throw new MalformedObjectNameException("Invalid value: " + strvalue);
}
init(domain, convertPropertiesToString(new TreeMap(table)), table);
}
public ObjectName(String domain, String key, String value) throws NullPointerException, MalformedObjectNameException
{
if (domain == null) throw new NullPointerException("ObjectName 'domain' parameter can't be null");
if (key == null) throw new NullPointerException("ObjectName 'key' parameter can't be null");
if (value == null) throw new NullPointerException("ObjectName 'value' parameter can't be null");
if (!isDomainValid(domain)) throw new MalformedObjectNameException("Invalid domain: " + domain);
if (!isKeyValid(key)) throw new MalformedObjectNameException("Invalid key: " + key);
if (!isValueValid(value)) throw new MalformedObjectNameException("Invalid value: " + value);
Map table = new HashMap();
table.put(key, value);
init(domain, convertPropertiesToString(table), table);
}
public boolean apply(ObjectName name) throws NullPointerException
{
boolean result = false;
if (name.isPattern())
result = false;
else if (isPattern())
result = domainsMatch(this, name) && propertiesMatch(this, name);
else
result = equals(name);
return result;
}
boolean implies(ObjectName name)
{
return domainsMatch(this, name) && propertiesMatch(this, name);
}
private boolean domainsMatch(ObjectName name1, ObjectName name2)
{
String thisDomain = name1.getDomain();
boolean thisPattern = name1.isDomainPattern();
String otherDomain = name2.getDomain();
boolean otherPattern = name2.isDomainPattern();
if (!thisPattern && otherPattern) return false;
if (!thisPattern && !otherPattern && !thisDomain.equals(otherDomain)) return false;
return Utils.wildcardMatch(thisDomain, otherDomain);
}
private boolean propertiesMatch(ObjectName name1, ObjectName name2)
{
Map thisProperties = name1.getPropertiesMap();
boolean thisPattern = name1.isPropertyPattern();
Map otherProperties = name2.getPropertiesMap();
boolean otherPattern = name2.isPropertyPattern();
if (!thisPattern && otherPattern) return false;
if (!thisPattern && !otherPattern && !thisProperties.equals(otherProperties)) return false;
if (thisPattern && !otherProperties.entrySet().containsAll(thisProperties.entrySet())) return false;
return true;
}
public void setMBeanServer(MBeanServer server)
{
}
public String getCanonicalKeyPropertyListString()
{
String canonical = getCanonicalName();
int index = canonical.indexOf(':');
String list = canonical.substring(index + 1);
if (isPropertyPattern())
{
if (getKeyPropertyListString().length() == 0)
return list.substring(0, list.length() - "*".length());
else
return list.substring(0, list.length() - ",*".length());
}
return list;
}
public String getCanonicalName()
{
return canonicalName;
}
public String getDomain()
{
String canonical = getCanonicalName();
int index = canonical.indexOf(':');
return canonical.substring(0, index);
}
public String getKeyProperty(String key) throws NullPointerException
{
Map props = getPropertiesMap();
return (String)props.get(key);
}
public Hashtable getKeyPropertyList()
{
return new Hashtable(getPropertiesMap());
}
private Map getPropertiesMap()
{
// TODO: Consider to cache this Map
try
{
return convertStringToProperties(getKeyPropertyListString(), null);
}
catch (MalformedObjectNameException x)
{
return null;
}
}
public String getKeyPropertyListString()
{
return propertiesString;
}
public boolean isPattern()
{
return isDomainPattern() || isPropertyPattern();
}
public boolean isPropertyPattern()
{
return isPropertyPattern;
}
public boolean isDomainPattern()
{
return isDomainPattern;
}
public static ObjectName getInstance(ObjectName name) throws NullPointerException
{
if (name.getClass() == ObjectName.class) return name;
try
{
return getInstance(name.getCanonicalName());
}
catch (MalformedObjectNameException x)
{
throw new IllegalArgumentException(x.toString());
}
}
public static ObjectName getInstance(String name) throws NullPointerException, MalformedObjectNameException
{
if (cacheEnabled)
{
ObjectName cached = null;
synchronized (cache)
{
cached = cache.get(name);
}
if (cached != null) return cached;
}
// Keep ObjectName creation, that takes time for parsing, outside the synchronized block.
return new ObjectName(name);
}
public static ObjectName getInstance(String domain, Hashtable table) throws NullPointerException, MalformedObjectNameException
{
return new ObjectName(domain, table);
}
public static ObjectName getInstance(String domain, String key, String value) throws NullPointerException, MalformedObjectNameException
{
return new ObjectName(domain, key, value);
}
public static String quote(String value) throws NullPointerException
{
StringBuffer buffer = new StringBuffer("\"");
for (int i = 0; i < value.length(); ++i)
{
char ch = value.charAt(i);
switch (ch)
{
case '\n':
buffer.append("\\n");
break;
case '\"':
buffer.append("\\\"");
break;
case '\\':
buffer.append("\\\\");
break;
case '*':
buffer.append("\\*");
break;
case '?':
buffer.append("\\?");
break;
default:
buffer.append(ch);
break;
}
}
buffer.append("\"");
return buffer.toString();
}
public static String unquote(String value) throws IllegalArgumentException, NullPointerException
{
int lastIndex = value.length() - 1;
if (lastIndex < 1 || value.charAt(0) != '\"' || value.charAt(lastIndex) != '\"') throw new IllegalArgumentException("The given string is not quoted");
StringBuffer buffer = new StringBuffer();
for (int i = 1; i < lastIndex; ++i)
{
char ch = value.charAt(i);
if (ch == '\\')
{
// Found a backslash, let's see if it marks an escape sequence
++i;
if (i == lastIndex) throw new IllegalArgumentException("Invalid escape sequence at the end of quoted string");
ch = value.charAt(i);
switch (ch)
{
case 'n':
buffer.append("\n");
break;
case '\"':
buffer.append("\"");
break;
case '\\':
buffer.append("\\");
break;
case '*':
buffer.append("*");
break;
case '?':
buffer.append("?");
break;
default:
throw new IllegalArgumentException("Invalid escape sequence: \\" + ch);
}
}
else
{
switch (ch)
{
case '\n':
case '\"':
case '*':
case '?':
throw new IllegalArgumentException("Invalid unescaped character: " + ch);
default:
buffer.append(ch);
}
}
}
return buffer.toString();
}
private void parse(String name) throws MalformedObjectNameException
{
boolean isSubclass = getClass() != ObjectName.class;
// It is important from the security point of view to not cache subclasses.
// An EvilObjectName may return an allowed domain when security checks are made, and
// a prohibited domain when performing operations. Here we make sure that subclasses
// are not cached.
if (cacheEnabled && !isSubclass)
{
ObjectName cached = null;
synchronized (cache)
{
cached = cache.get(name);
}
if (cached != null)
{
// This ObjectName is already created, just copy it to avoid string parsing
propertiesString = cached.getKeyPropertyListString();
isDomainPattern = cached.isDomainPattern();
isPropertyPattern = cached.isPropertyPattern();
canonicalName = cached.getCanonicalName();
return;
}
}
String domain = parseDomain(name);
if (!isDomainValid(domain)) throw new MalformedObjectNameException("Invalid domain: " + domain);
// Properties must be handled carefully.
// The main problem is to create the keyPropertiesListString for non trivial cases such as
// 1. no properties
// 2. presence of the '*' wildcard in the middle of the list
// 3. quoted values that contain the '*' wildcard
// while maintaining the properties' order
String properties = parseProperties(name);
// Preliminar, easy checks
if (properties.trim().length() < 1) throw new MalformedObjectNameException("Missing properties");
if (properties.trim().endsWith(",")) throw new MalformedObjectNameException("Missing property after trailing comma");
StringBuffer propsString = new StringBuffer();
Map table = convertStringToProperties(properties, propsString);
init(domain, propsString.toString(), table);
if (cacheEnabled && !isSubclass)
{
// Cache this ObjectName
synchronized (cache)
{
// Overwrite if 2 threads computed the same ObjectName: we have been unlucky
cache.put(name, this);
}
}
}
private String parseDomain(String objectName) throws MalformedObjectNameException
{
int colon = objectName.indexOf(':');
if (colon < 0) throw new MalformedObjectNameException("Missing ':' character in ObjectName");
String domain = objectName.substring(0, colon);
return domain;
}
private boolean isDomainValid(String domain)
{
if (domain == null) return false;
if (domain.indexOf('\n') >= 0) return false;
if (domain.indexOf(":") >= 0) return false;
return true;
}
private String parseProperties(String objectName) throws MalformedObjectNameException
{
int colon = objectName.indexOf(':');
if (colon < 0) throw new MalformedObjectNameException("Missing ':' character in ObjectName");
String list = objectName.substring(colon + 1);
return list;
}
/**
* Returns a Map containing the pairs (key,value) parsed from the given string.
* If the given string contains the wildcard '*', then the returned Hashtable will contains the pair (*,*).
* If the given StringBuffer is not null, it will be filled with the
* {@link #getKeyPropertyListString keyPropertiesListString}.
*
* @see #initProperties
*/
private Map convertStringToProperties(String properties, StringBuffer buffer) throws MalformedObjectNameException
{
if (buffer != null) buffer.setLength(0);
Map table = new HashMap();
StringBuffer toBeParsed = new StringBuffer(properties);
while (toBeParsed.length() > 0)
{
String key = parsePropertyKey(toBeParsed);
String value = null;
if ("*".equals(key))
value = "*";
else
value = parsePropertyValue(toBeParsed);
Object duplicate = table.put(key, value);
if (duplicate != null) throw new MalformedObjectNameException("Duplicate key not allowed: " + key);
if (buffer != null && !"*".equals(key))
{
if (buffer.length() > 0) buffer.append(',');
buffer.append(key).append('=').append(value);
}
}
return table;
}
private String parsePropertyKey(StringBuffer buffer) throws MalformedObjectNameException
{
String toBeParsed = buffer.toString();
int equal = toBeParsed.indexOf('=');
int comma = toBeParsed.indexOf(',');
if (equal < 0 && comma < 0)
{
// Then it can only be the asterisk
String key = toBeParsed.trim();
if (!"*".equals(key)) throw new MalformedObjectNameException("Invalid key: '" + key + "'");
buffer.setLength(0);
return key;
}
if (comma >= 0 && comma < equal)
{
// Then it can only be the asterisk
String key = toBeParsed.substring(0, comma).trim();
if (!"*".equals(key)) throw new MalformedObjectNameException("Invalid key: '" + key + "'");
buffer.delete(0, comma + 1);
return key;
}
// Normal key
String key = toBeParsed.substring(0, equal);
if (!isKeyValid(key)) throw new MalformedObjectNameException("Invalid key: '" + key + "'");
buffer.delete(0, equal + 1);
return key;
}
private boolean isKeyValid(String key)
{
if (key == null) return false;
if (key.trim().length() < 1) return false;
if (key.indexOf('\n') >= 0) return false;
if (key.indexOf(',') >= 0) return false;
if (key.indexOf('=') >= 0) return false;
if (key.indexOf('*') >= 0) return false;
if (key.indexOf('?') >= 0) return false;
if (key.indexOf(':') >= 0) return false;
return true;
}
private String parsePropertyValue(StringBuffer buffer) throws MalformedObjectNameException
{
String toBeParsed = buffer.toString();
if (toBeParsed.trim().startsWith("\""))
{
// It's quoted, delimiter is the closing quote
int start = toBeParsed.indexOf('"') + 1;
int endQuote = -1;
while ((endQuote = toBeParsed.indexOf('"', start)) >= 0)
{
int bslashes = countBackslashesBackwards(toBeParsed, endQuote);
if (bslashes % 2 != 0)
{
start = endQuote + 1;
continue;
}
// Found closing quote
String value = toBeParsed.substring(0, endQuote + 1).trim();
if (!isValueValid(value)) throw new MalformedObjectNameException("Invalid value: '" + value + "'");
buffer.delete(0, endQuote + 1);
// Remove also a possible trailing comma
toBeParsed = buffer.toString();
if (toBeParsed.trim().startsWith(","))
{
int comma = toBeParsed.indexOf(',');
buffer.delete(0, comma + 1);
return value;
}
else if (toBeParsed.trim().length() == 0)
{
buffer.setLength(0);
return value;
}
else
{
throw new MalformedObjectNameException("Garbage after quoted value: " + toBeParsed);
}
}
throw new MalformedObjectNameException("Missing closing quote: " + toBeParsed);
}
else
{
// Non quoted, delimiter is comma
int comma = toBeParsed.indexOf(',');
if (comma >= 0)
{
String value = toBeParsed.substring(0, comma);
if (!isValueValid(value)) throw new MalformedObjectNameException("Invalid value: '" + value + "'");
buffer.delete(0, comma + 1);
return value;
}
else
{
String value = toBeParsed;
if (!isValueValid(value)) throw new MalformedObjectNameException("Invalid value: '" + value + "'");
buffer.setLength(0);
return value;
}
}
}
private int indexOfLastConsecutiveBackslash(String value, int from)
{
int index = value.indexOf('\\', from);
if (index < 0) return index;
if (index == value.length() - 1) return index;
// Probe next char
int next = indexOfLastConsecutiveBackslash(value, from + 1);
if (next < 0)
return index;
else
return next;
}
private boolean isValueValid(String value)
{
if (value == null) return false;
if (value.length() == 0) return false;
if (value.indexOf('\n') >= 0) return false;
if (value.trim().startsWith("\""))
{
// strip leading and trailing spaces
value = value.trim();
// check value has quotes at start and end
if (value.length() < 2) return false;
if (value.charAt(value.length()-1) != '"') return false;
// check final quote is not escaped
if (countBackslashesBackwards(value, value.length()-1) % 2 == 1) return false;
// Unquote the value
value = value.substring(1, value.length() - 1);
// Be sure escaped values are interpreted correctly
int start = 0;
int index = -1;
do
{
index = indexOfLastConsecutiveBackslash(value, start);
if (index >= 0)
{
// Found a backslash sequence, see if it's an escape or a backslash
int count = countBackslashesBackwards(value, index + 1);
if (count % 2 != 0)
{
// Odd number of backslashes, probe next character, should be either '\', 'n', '"', '?', '*'
if (index == value.length() - 1) return false;
char next = value.charAt(index + 1);
if (next != '\\' && next != 'n' && next != '"' && next != '?' && next != '*') return false;
}
start = index + 1;
}
}
while (index >= 0);
start = 0;
index = -1;
do
{
index = value.indexOf('"', start);
if (index < 0) index = value.indexOf('*', start);
if (index < 0) index = value.indexOf('?', start);
if (index >= 0)
{
int bslashCount = countBackslashesBackwards(value, index);
// There is a special character not preceded by an odd number of backslashes
if (bslashCount % 2 == 0) return false;
start = index + 1;
}
}
while (index >= 0);
}
else
{
if (value.indexOf(',') >= 0) return false;
if (value.indexOf('=') >= 0) return false;
if (value.indexOf(':') >= 0) return false;
if (value.indexOf('"') >= 0) return false;
if (value.indexOf('*') >= 0) return false;
if (value.indexOf('?') >= 0) return false;
}
return true;
}
private int countBackslashesBackwards(String string, int from)
{
int bslashCount = 0;
while (--from >= 0)
{
if (string.charAt(from) == '\\')
++bslashCount;
else
break;
}
return bslashCount;
}
/**
* Initializes this ObjectName with the given domain, propertiesString and properties.
*
* @see #convertStringToProperties
*/
private void init(String domain, String propertiesString, Map properties)
{
initDomain(domain);
initProperties(properties);
this.propertiesString = propertiesString;
StringBuffer buffer = new StringBuffer(domain).append(':').append(convertPropertiesToString(new TreeMap(properties)));
if (isPropertyPattern())
{
if (getKeyPropertyListString().length() == 0)
buffer.append('*');
else
buffer.append(",*");
}
canonicalName = buffer.toString();
}
/**
* If the given domain contains the '*' or the '?' characters, sets this ObjectName as a domain pattern.
*/
private void initDomain(String domain)
{
// Domain may contain '*' and '?' characters if it's a pattern
if (domain.indexOf('*') >= 0 || domain.indexOf('?') >= 0)
{
isDomainPattern = true;
}
}
/**
* If present, it removes the pair (*,*) from the given Hashtable, and sets this ObjectName as a property pattern.
*
* @see #convertStringToProperties
*/
private void initProperties(Map properties)
{
if (properties.containsKey("*"))
{
// The Hashtable will never contain the '*'
properties.remove("*");
isPropertyPattern = true;
}
}
/**
* Converts the pairs present in the given Map into a comma separated list of tokens
* with the form 'key=value'
*/
private String convertPropertiesToString(Map properties)
{
StringBuffer b = new StringBuffer();
boolean firstTime = true;
for (Iterator i = properties.entrySet().iterator(); i.hasNext();)
{
if (!firstTime)
b.append(",");
else
firstTime = false;
Map.Entry entry = (Map.Entry)i.next();
b.append(entry.getKey());
b.append("=");
b.append(entry.getValue());
}
return b.toString();
}
public int hashCode()
{
return getCanonicalName().hashCode();
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
try
{
ObjectName other = (ObjectName)obj;
return getCanonicalName().equals(other.getCanonicalName());
}
catch (ClassCastException ignored)
{
}
return false;
}
public String toString()
{
return getName(false);
}
private String getName(boolean canonical)
{
// TODO: Remove the boolean argument, not used anymore
StringBuffer buffer = new StringBuffer(getDomain()).append(':');
String properties = canonical ? getCanonicalKeyPropertyListString() : getKeyPropertyListString();
buffer.append(properties);
if (isPropertyPattern())
{
if (properties.length() == 0)
buffer.append("*");
else
buffer.append(",*");
}
return buffer.toString();
}
private void writeObject(ObjectOutputStream out) throws IOException
{
out.defaultWriteObject();
String name = getName(false);
out.writeObject(name);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
String objectName = (String)in.readObject();
try
{
parse(objectName);
}
catch (MalformedObjectNameException x)
{
throw new InvalidObjectException("String representing the ObjectName is not a valid ObjectName: " + x.toString());
}
}
private static class WeakObjectNameCache
{
private ReferenceQueue queue = new ReferenceQueue();
private HashMap map = new HashMap();
public void put(String key, ObjectName value)
{
cleanup();
map.put(key, WeakValue.create(key, value, queue));
}
public ObjectName get(String key)
{
cleanup();
WeakValue value = (WeakValue)map.get(key);
if (value == null)
return null;
else
return (ObjectName)value.get();
}
private void cleanup()
{
WeakValue ref = null;
while ((ref = (WeakValue)queue.poll()) != null)
{
map.remove(ref.getKey());
}
}
private static final class WeakValue extends WeakReference
{
private Object key;
/**
* Creates a new WeakValue
*
* @return null if the given value is null.
*/
public static WeakValue create(Object key, Object value, ReferenceQueue queue)
{
if (value == null) return null;
return new WeakValue(key, value, queue);
}
private WeakValue(Object key, Object value, ReferenceQueue queue)
{
super(value, queue);
this.key = key;
}
public Object getKey()
{
return key;
}
}
}
}
mx4j-3.0.2/src/core/javax/management/OperationsException.java 100644 0 0 1215 10513545721 21340 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Thrown when an Exception is thrown by the MBeanServer when executing MBeanServer methods.
*
* @version $Revision: 1.8 $
*/
public class OperationsException extends JMException
{
private static final long serialVersionUID = -4967597595580536216L;
public OperationsException()
{
}
public OperationsException(String message)
{
super(message);
}
}
mx4j-3.0.2/src/core/javax/management/OrQueryExp.java 100644 0 0 2246 10513545721 17426 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The QueryExp for an 'or' operation
*
* @version $Revision: 1.6 $
* @serial include
*/
class OrQueryExp extends QueryEval implements QueryExp
{
private static final long serialVersionUID = 2962973084421716523L;
/**
* @serial The left-side expression
*/
private QueryExp exp1;
/**
* @serial The right-side expression
*/
private QueryExp exp2;
OrQueryExp(QueryExp exp1, QueryExp exp2)
{
this.exp1 = exp1;
this.exp2 = exp2;
}
public void setMBeanServer(MBeanServer server)
{
super.setMBeanServer(server);
if (exp1 != null) exp1.setMBeanServer(server);
if (exp2 != null) exp2.setMBeanServer(server);
}
public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
return exp1.apply(name) || exp2.apply(name);
}
}
mx4j-3.0.2/src/core/javax/management/PersistentMBean.java 100644 0 0 2276 10513545721 20411 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* This interface is implemented by MBeans that are able to make themselves persistent.
*
* @version $Revision: 1.6 $
*/
public interface PersistentMBean
{
/**
* Loads a previously saved MBean state into the MBean itself.
*
* @throws MBeanException If an exception occurred during loading or if loading is not supported.
* @throws InstanceNotFoundException If some MBean needed for loading is not found.
* @see #store
*/
public void load() throws MBeanException, InstanceNotFoundException, RuntimeOperationsException;
/**
* Stores the MBean state into a persistent media.
*
* @throws MBeanException If an exception occurred during storing or if storing is not supported.
* @throws InstanceNotFoundException If some MBean needed for storing is not found.
*/
public void store() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException;
}
mx4j-3.0.2/src/core/javax/management/QualifiedAttributeValueExp.java 100644 0 0 3046 10513545721 22603 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The ValueExp that represent the value of an attribute of a specific MBean.
*
* @version $Revision: 1.6 $
* @serial include
*/
class QualifiedAttributeValueExp extends AttributeValueExp
{
private static final long serialVersionUID = 8832517277410933254L;
/**
* The MBean class name
*/
private String className;
private transient MBeanServer server;
QualifiedAttributeValueExp(String className, String attr)
{
super(attr);
this.className = className;
}
public void setMBeanServer(MBeanServer server)
{
super.setMBeanServer(server);
this.server = server;
}
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
try
{
// getObjectInstance is called for compatibility with the RI;
// in fact, when used under security manager, calling this method requires
// the proper permission to call getObjectInstance.
String cls = server.getObjectInstance(name).getClassName();
if (cls.equals(className)) return super.apply(name);
}
catch (InstanceNotFoundException ignored)
{
}
throw new InvalidApplicationException(className);
}
}
mx4j-3.0.2/src/core/javax/management/Query.java 100644 0 0 15723 10513545721 16474 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Factory class for constructing query expressions.
*
* @version $Revision: 1.9 $
*/
public class Query
{
public static final int GT = 0;
public static final int LT = 1;
public static final int GE = 2;
public static final int LE = 3;
public static final int EQ = 4;
public static final int PLUS = 0;
public static final int MINUS = 1;
public static final int TIMES = 2;
public static final int DIV = 3;
/**
* Returns a query expression for the result of the NOT operation on the given expression.
*/
public static QueryExp not(QueryExp queryExp)
{
return new NotQueryExp(queryExp);
}
/**
* Returns a query expression for the result of the AND operation on the two given expressions.
*/
public static QueryExp and(QueryExp q1, QueryExp q2)
{
return new AndQueryExp(q1, q2);
}
/**
* Returns a query expression for the result of the OR operation on the two given expressions.
*/
public static QueryExp or(QueryExp q1, QueryExp q2)
{
return new OrQueryExp(q1, q2);
}
/**
* Returns a query expression for the result of v1
GREATER-THAN v2
.
*/
public static QueryExp gt(ValueExp v1, ValueExp v2)
{
return new BinaryRelQueryExp(GT, v1, v2);
}
/**
* Returns a query expression for the result of v1
GREATER-THAN-OR-EQUAL v2
.
*/
public static QueryExp geq(ValueExp v1, ValueExp v2)
{
return new BinaryRelQueryExp(GE, v1, v2);
}
/**
* Returns a query expression for the result of v1
LESS-THAN-OR-EQUAL v2
.
*/
public static QueryExp leq(ValueExp v1, ValueExp v2)
{
return new BinaryRelQueryExp(LE, v1, v2);
}
/**
* Returns a query expression for the result of v1
LESS-THAN v2
.
*/
public static QueryExp lt(ValueExp v1, ValueExp v2)
{
return new BinaryRelQueryExp(LT, v1, v2);
}
/**
* Returns a query expression for the result of v1
EQUAL v2
.
*/
public static QueryExp eq(ValueExp v1, ValueExp v2)
{
return new BinaryRelQueryExp(EQ, v1, v2);
}
/**
* Returns a query expression for the result of v1
LESS-THAN-OR-EQUAL v2
LESS-THAN-OR-EQUAL v3
*/
public static QueryExp between(ValueExp v1, ValueExp v2, ValueExp v3)
{
return new BetweenQueryExp(v1, v2, v3);
}
/**
* Returns a query expression for the result of val
being present as one element of the given array.
*/
public static QueryExp in(ValueExp val, ValueExp valueList[])
{
return new InQueryExp(val, valueList);
}
/**
* Returns the expression value that represent the value of an attribute of a generic MBean.
*/
public static AttributeValueExp attr(String name)
{
return new AttributeValueExp(name);
}
/**
* Returns the expression value that represent the value of an attribute of an MBean of the specified class.
*/
public static AttributeValueExp attr(String className, String name)
{
return new QualifiedAttributeValueExp(className, name);
}
/**
* Returns the expression value that represent the class name of an MBean.
*/
public static AttributeValueExp classattr()
{
return new ClassAttributeValueExp();
}
/**
* Returns the expression value that represent the given string.
*/
public static StringValueExp value(String val)
{
return new StringValueExp(val);
}
/**
* Returns the expression value that represent the given number.
*/
public static ValueExp value(Number val)
{
return new NumericValueExp(val);
}
/**
* Returns the expression value that represent the given number.
*/
public static ValueExp value(int val)
{
return value(new Integer(val));
}
/**
* Returns the expression value that represent the given number.
*/
public static ValueExp value(long val)
{
return value(new Long(val));
}
/**
* Returns the expression value that represent the given number.
*/
public static ValueExp value(float val)
{
return value(new Float(val));
}
/**
* Returns the expression value that represent the given number.
*/
public static ValueExp value(double val)
{
return value(new Double(val));
}
/**
* Returns the expression value that represent the given boolean.
*/
public static ValueExp value(boolean val)
{
return new BooleanValueExp(val);
}
/**
* Returns a expression value for the result of value1
PLUS value2
*/
public static ValueExp plus(ValueExp value1, ValueExp value2)
{
return new BinaryOpValueExp(PLUS, value1, value2);
}
/**
* Returns a expression value for the result of value1
MINUS value2
*/
public static ValueExp minus(ValueExp value1, ValueExp value2)
{
return new BinaryOpValueExp(MINUS, value1, value2);
}
/**
* Returns a expression value for the result of value1
TIMES value2
*/
public static ValueExp times(ValueExp value1, ValueExp value2)
{
return new BinaryOpValueExp(TIMES, value1, value2);
}
/**
* Returns a expression value for the result of value1
DIVIDED value2
*/
public static ValueExp div(ValueExp value1, ValueExp value2)
{
return new BinaryOpValueExp(DIV, value1, value2);
}
/**
* Returns a query expression for the result of the wildcard match between the given attribute value and the string pattern.
*/
public static QueryExp match(AttributeValueExp a, StringValueExp s)
{
return new MatchQueryExp(a, s);
}
/**
* Returns a query expression for the result of the match, as initial string, between the given attribute value and the string pattern.
*/
public static QueryExp initialSubString(AttributeValueExp a, StringValueExp s)
{
return new MatchQueryExp(a, new StringValueExp(s.getValue() + "*"));
}
/**
* Returns a query expression for the result of the match, as contained string, between the given attribute value and the string pattern.
*/
public static QueryExp anySubString(AttributeValueExp a, StringValueExp s)
{
return new MatchQueryExp(a, new StringValueExp("*" + s.getValue() + "*"));
}
/**
* Returns a query expression for the result of the match, as final string, between the given attribute value and the string pattern.
*/
public static QueryExp finalSubString(AttributeValueExp a, StringValueExp s)
{
return new MatchQueryExp(a, new StringValueExp("*" + s.getValue()));
}
}
mx4j-3.0.2/src/core/javax/management/QueryEval.java 100644 0 0 2265 10513545721 17261 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.Serializable;
/**
* The base class for QueryExp implementations.
*
* @version $Revision: 1.7 $
*/
public abstract class QueryEval implements Serializable
{
private static final long serialVersionUID = 2675899265640874796L;
private transient MBeanServer server;
private static ThreadLocal serverPerThread = new ThreadLocal();
/**
* Sets the MBeanServer used by the QueryExp implementation to evaluate the expression.
*/
public void setMBeanServer(MBeanServer server)
{
this.server = server;
serverPerThread.set(server);
}
/**
* Returns the MBeanServer used by the QueryExp implementation to evaluate the expression.
* This method is static for a mistake in the JMX spec, should not be needed, but it's implemented
* for sake of compatibility.
*/
public static MBeanServer getMBeanServer()
{
return (MBeanServer)serverPerThread.get();
}
}
mx4j-3.0.2/src/core/javax/management/QueryExp.java 100644 0 0 2210 10513545721 17114 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.Serializable;
/**
* Represents a query expression. Query expressions are created with the {@link Query} class.
*
* @version $Revision: 1.7 $
*/
public interface QueryExp extends Serializable
{
/**
* Applies this expression on the specified MBean.
*
* @param name The ObjectName
of the MBean
on which the expression is applied.
* @return True if the query was successfully applied, false otherwise.
*/
public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException;
/**
* Sets the MBeanServer
used (possibly) to apply the query expression, for example to retrieve
* the value of an attribute for the MBean specified in {@link #apply}
*/
public void setMBeanServer(MBeanServer server);
}
mx4j-3.0.2/src/core/javax/management/ReflectionException.java 100644 0 0 4577 10513545721 21325 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Thrown when an MBeanServer operation encounter a Java reflection exception such as ClassNotFoundException,
* NoSuchMethodException, etc; it wraps the actual exception thrown
*
* @version $Revision: 1.8 $
*/
public class ReflectionException extends JMException
{
private static final long serialVersionUID = 9170809325636915553L;
/**
* @serial The nested reflection exception
*/
private Exception exception;
/**
* Creates a new ReflectionException
*
* @param x The nested Exception
*/
public ReflectionException(Exception x)
{
this.exception = x;
}
/**
* Creates a new ReflectionException
*
* @param x The nested Exception
* @param message The message
*/
public ReflectionException(Exception x, String message)
{
super(message);
this.exception = x;
}
public String getMessage()
{
return super.getMessage() + " nested exception is " + exception;
}
/**
* Returns the nested reflection Exception
*/
public Exception getTargetException()
{
return exception;
}
/**
* Returns the nested reflection Exception
*/
public Throwable getCause()
{
return getTargetException();
}
public void printStackTrace()
{
if (exception == null)
{
super.printStackTrace();
}
else
{
synchronized (System.err)
{
System.err.println(this);
exception.printStackTrace();
}
}
}
public void printStackTrace(PrintStream s)
{
if (exception == null)
{
super.printStackTrace(s);
}
else
{
synchronized (s)
{
s.println(this);
exception.printStackTrace(s);
}
}
}
public void printStackTrace(PrintWriter w)
{
if (exception == null)
{
super.printStackTrace(w);
}
else
{
synchronized (w)
{
w.println(this);
exception.printStackTrace(w);
}
}
}
}
mx4j-3.0.2/src/core/javax/management/RuntimeErrorException.java 100644 0 0 4314 10513545721 21655 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Thrown when an Error is thrown by the MBeanServer; it wraps the actual error thrown.
*
* @version $Revision: 1.7 $
*/
public class RuntimeErrorException extends JMRuntimeException
{
private static final long serialVersionUID = 704338937753949796L;
/**
* @serial The nested error
*/
private Error error;
/**
* Creates a new RuntimeErrorException
*
* @param error The nested Error
*/
public RuntimeErrorException(Error error)
{
this.error = error;
}
/**
* Creates a new RuntimeErrorException
*
* @param error The nested Error
* @param message The message
*/
public RuntimeErrorException(Error error, String message)
{
super(message);
this.error = error;
}
public String getMessage()
{
return super.getMessage() + " nested error is " + error;
}
/**
* Returns the nested Error
*/
public Error getTargetError()
{
return error;
}
/**
* Returns the nested Error
*/
public Throwable getCause()
{
return getTargetError();
}
public void printStackTrace()
{
if (error == null)
{
super.printStackTrace();
}
else
{
synchronized (System.err)
{
System.err.println(this);
error.printStackTrace();
}
}
}
public void printStackTrace(PrintStream s)
{
if (error == null)
{
super.printStackTrace(s);
}
else
{
synchronized (s)
{
s.println(this);
error.printStackTrace(s);
}
}
}
public void printStackTrace(PrintWriter w)
{
if (error == null)
{
super.printStackTrace(w);
}
else
{
synchronized (w)
{
w.println(this);
error.printStackTrace(w);
}
}
}
}
mx4j-3.0.2/src/core/javax/management/RuntimeMBeanException.java 100644 0 0 4733 10513545721 21553 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Thrown when a MBean method invoked by the MBeanServer throws any non-reflection RuntimeException.
*
* @version $Revision: 1.8 $
*/
public class RuntimeMBeanException extends JMRuntimeException
{
private static final long serialVersionUID = 5274912751982730171L;
/**
* @serial The nested exception
*/
private RuntimeException runtimeException;
/**
* Creates a new RuntimeMBeanException
*
* @param exception The nested RuntimeException
*/
public RuntimeMBeanException(RuntimeException exception)
{
this.runtimeException = exception;
}
/**
* Creates a new RuntimeMBeanException
*
* @param exception The nested RuntimeException
* @param message The message
*/
public RuntimeMBeanException(RuntimeException exception, String message)
{
super(message);
this.runtimeException = exception;
}
/**
* Returns the nested RuntimeException
*/
public RuntimeException getTargetException()
{
return runtimeException;
}
/**
* Returns the nested RuntimeException
*/
public Throwable getCause()
{
return getTargetException();
}
public String getMessage()
{
return super.getMessage() + " nested runtime exception is " + runtimeException;
}
public void printStackTrace()
{
if (runtimeException == null)
{
super.printStackTrace();
}
else
{
synchronized (System.err)
{
System.err.println(this);
runtimeException.printStackTrace();
}
}
}
public void printStackTrace(PrintStream s)
{
if (runtimeException == null)
{
super.printStackTrace(s);
}
else
{
synchronized (s)
{
s.println(this);
runtimeException.printStackTrace(s);
}
}
}
public void printStackTrace(PrintWriter w)
{
if (runtimeException == null)
{
super.printStackTrace(w);
}
else
{
synchronized (w)
{
w.println(this);
runtimeException.printStackTrace(w);
}
}
}
}
mx4j-3.0.2/src/core/javax/management/RuntimeOperationsException.java 100644 0 0 4716 10513545721 22715 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Thrown when a RuntimeException is thrown by the MBeanServer when executing MBeanServer methods.
*
* @version $Revision: 1.9 $
*/
public class RuntimeOperationsException extends JMRuntimeException
{
private static final long serialVersionUID = -8408923047489133588L;
/**
* @serial The nested RuntimeException
*/
private RuntimeException runtimeException;
/**
* Creates a new RuntimeOperationsException
*
* @param x The nested RuntimeException
*/
public RuntimeOperationsException(RuntimeException x)
{
this.runtimeException = x;
}
/**
* Creates a new RuntimeOperationsException
*
* @param x The nested RuntimeException
* @param message The message
*/
public RuntimeOperationsException(RuntimeException x, String message)
{
super(message);
this.runtimeException = x;
}
/**
* Returns the nested RuntimeException
*/
public RuntimeException getTargetException()
{
return runtimeException;
}
/**
* Returns the nested RuntimeException
*/
public Throwable getCause()
{
return getTargetException();
}
public String getMessage()
{
return super.getMessage() + " nested runtime exception is " + runtimeException;
}
public void printStackTrace()
{
if (runtimeException == null)
{
super.printStackTrace();
}
else
{
synchronized (System.err)
{
System.err.println(this);
runtimeException.printStackTrace();
}
}
}
public void printStackTrace(PrintStream s)
{
if (runtimeException == null)
{
super.printStackTrace(s);
}
else
{
synchronized (s)
{
s.println(this);
runtimeException.printStackTrace(s);
}
}
}
public void printStackTrace(PrintWriter w)
{
if (runtimeException == null)
{
super.printStackTrace(w);
}
else
{
synchronized (w)
{
w.println(this);
runtimeException.printStackTrace(w);
}
}
}
}
mx4j-3.0.2/src/core/javax/management/ServiceNotFoundException.java 100644 0 0 1171 10513545721 22273 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* Thrown when the requested service is not found
*
* @version $Revision: 1.7 $
*/
public class ServiceNotFoundException extends OperationsException
{
private static final long serialVersionUID = -3990675661956646827L;
public ServiceNotFoundException()
{
}
public ServiceNotFoundException(String message)
{
super(message);
}
}
mx4j-3.0.2/src/core/javax/management/StandardMBean.java 100644 0 0 41771 10513545721 20034 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import mx4j.AbstractDynamicMBean;
import mx4j.server.MBeanIntrospector;
import mx4j.server.MBeanMetaData;
/**
* StandardMBean eases the development of MBeans that have a management interface described
* by a java interface, like plain standard MBeans have; differently from a plain standard
* MBean, StandardMBean is not tied to the JMX lexical patterns and allows more control on the
* customization of the MBeanInfo that describes the MBean (for example it allows to describe
* metadata descriptions).
* Usage of StandardMBean with a management interface that does not follow the JMX lexical patterns:
*
* public interface Management
* {
* ...
* }
*
* public class Service implements Management
* {
* ...
* }
*
* Service service = new Service();
* StandardMBean mbean = new StandardMBean(service, Management.class);
* MBeanServer server = ...;
* ObjectName name = ...;
* server.registerMBean(mbean, name);
*
* Usage of a subclass of StandardMBean:
*
* public interface Management
* {
* ...
* }
*
* public class Service extends StandardMBean implements Management
* {
* public Service()
* {
* super(Manegement.class);
* }
* ...
* }
*
* Service mbean = new Service();
* MBeanServer server = ...;
* ObjectName name = ...;
* server.registerMBean(mbean, name);
*
* Usage of StandardMBean with a management interface that follows the JMX lexical patterns
* (this is similar to plain standard MBeans):
*
* public interface ServiceMBean
* {
* ...
* }
*
* public class Service implements ServiceMBean
* {
* ...
* }
*
* Service service = new Service();
* StandardMBean mbean = new StandardMBean(service, null);
* MBeanServer server = ...;
* ObjectName name = ...;
* server.registerMBean(mbean, name);
*
*
* @version $Revision: 1.5 $
* @since JMX 1.2
*/
public class StandardMBean implements DynamicMBean
{
private MBeanMetaData metadata;
private MBeanInfo info;
private DynamicMBean support;
/**
* Creates a new StandardMBean.
*
* @param implementation The MBean implementation for this StandardMBean
* @param management The management interface; if null, the JMX lexical patterns will be used
* @throws IllegalArgumentException If implementation
is null
* @throws NotCompliantMBeanException If implementation
does not implement managementInterface
,
* or if the management interface is not a valid JMX Management Interface
* @see #setImplementation
*/
public StandardMBean(Object implementation, Class management) throws NotCompliantMBeanException
{
this(implementation, management, false);
}
/**
* Creates a new StandardMBean using 'this' as implementation.
*
* @see #StandardMBean(Object,Class)
*/
protected StandardMBean(Class managementInterface) throws NotCompliantMBeanException
{
this(null, managementInterface, true);
}
private StandardMBean(Object implementation, Class management, boolean useThis) throws NotCompliantMBeanException
{
if (useThis) implementation = this;
if (implementation == null) throw new IllegalArgumentException("Implementation cannot be null");
if (management != null && !management.isInterface()) throw new NotCompliantMBeanException("Class " + management + " is not an interface");
metadata = introspectMBean(implementation, management);
if (metadata == null) throw new NotCompliantMBeanException("StandardMBean is not compliant");
support = new StandardMBeanSupport();
}
/**
* Sets the MBean implementation for this StandardMBean.
*
* @param implementation The MBean implementation for this StandardMBean
* @throws IllegalArgumentException If implementation
is null
* @throws NotCompliantMBeanException If implementation
does not implement the management interface
* returned by {@link #getMBeanInterface}
* @see #StandardMBean(Object,Class)
*/
public void setImplementation(Object implementation) throws NotCompliantMBeanException
{
if (implementation == null) throw new IllegalArgumentException("Implementation cannot be null");
Class management = getMBeanInterface();
if (!management.isInstance(implementation)) throw new NotCompliantMBeanException("Implementation " + implementation + " does not implement interface " + management);
metadata.setMBean(implementation);
}
/**
* Returns the implementation supplied to this StandardMBean, or this object if no implementation was supplied
*
* @see #StandardMBean(Object,Class)
* @see #setImplementation
*/
public Object getImplementation()
{
return metadata.getMBean();
}
/**
* Returns the management interface for this MBean. This interface is set at creation time and cannot be changed
* even if the implementation object can be changed (but it must implement the same interface).
*
* @see #StandardMBean(Object,Class)}
* @see #setImplementation
*/
public final Class getMBeanInterface()
{
return metadata.getMBeanInterface();
}
/**
* Returns the class of the MBean implementation for this StandardMBean, or 'this' (sub)class if no
* implementation was supplied.
*
* @see #StandardMBean(Object,Class)}
*/
public Class getImplementationClass()
{
return metadata.getMBean().getClass();
}
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException
{
return support.getAttribute(attribute);
}
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
support.setAttribute(attribute);
}
public AttributeList getAttributes(String[] attributes)
{
return support.getAttributes(attributes);
}
public AttributeList setAttributes(AttributeList attributes)
{
return support.setAttributes(attributes);
}
public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException
{
return support.invoke(method, arguments, params);
}
/**
* See {@link DynamicMBean#getMBeanInfo}.
* By default, the metadata is cached the first time is created; if the caching has been disabled,
* the metadata is created from scratch each time.
*
* @see #getCachedMBeanInfo
* @see #cacheMBeanInfo
*/
public MBeanInfo getMBeanInfo()
{
MBeanInfo info = getCachedMBeanInfo();
if (info == null)
{
info = setupMBeanInfo(metadata.getMBeanInfo());
cacheMBeanInfo(info);
}
return info;
}
/**
* Returns the class name of this MBean.
* By default returns {@link MBeanInfo#getClassName info.getClassName()}
*/
protected String getClassName(MBeanInfo info)
{
return info == null ? null : info.getClassName();
}
/**
* Returns the description for this MBean.
* By default returns {@link MBeanInfo#getDescription info.getDescription()}
*/
protected String getDescription(MBeanInfo info)
{
return info == null ? null : info.getDescription();
}
/**
* Returns the description for the given feature.
* By default returns {@link MBeanFeatureInfo#getDescription info.getDescription()}
*
* @see #getDescription(MBeanAttributeInfo)
* @see #getDescription(MBeanConstructorInfo)
* @see #getDescription(MBeanOperationInfo)
*/
protected String getDescription(MBeanFeatureInfo info)
{
return info == null ? null : info.getDescription();
}
/**
* Returns the description for the given attribute.
* By default calls {@link #getDescription(MBeanFeatureInfo)}
*/
protected String getDescription(MBeanAttributeInfo info)
{
return getDescription((MBeanFeatureInfo)info);
}
/**
* Returns the description for the given constructor.
* By default calls {@link #getDescription(MBeanFeatureInfo)}
*/
protected String getDescription(MBeanConstructorInfo info)
{
return getDescription((MBeanFeatureInfo)info);
}
/**
* Returns the description for the given operation.
* By default calls {@link #getDescription(MBeanFeatureInfo)}
*/
protected String getDescription(MBeanOperationInfo info)
{
return getDescription((MBeanFeatureInfo)info);
}
/**
* Returns the description of the (sequence + 1)th parameter (that is: if sequence is 0 returns the description of the first
* parameter, if sequence is 1 returns the description of the second parameter, and so on) for the given constructor.
* By default returns {@link MBeanParameterInfo#getDescription param.getDescription()}.
*/
protected String getDescription(MBeanConstructorInfo constructor, MBeanParameterInfo param, int sequence)
{
return param == null ? null : param.getDescription();
}
/**
* Returns the description of the (sequence + 1)th parameter (that is: if sequence is 0 returns the description of the first
* parameter, if sequence is 1 returns the description of the second parameter, and so on) for the given operation.
* By default returns {@link MBeanParameterInfo#getDescription param.getDescription()}.
*/
protected String getDescription(MBeanOperationInfo operation, MBeanParameterInfo param, int sequence)
{
return param == null ? null : param.getDescription();
}
/**
* Returns the name of the (sequence + 1)th parameter (that is: if sequence is 0 returns the name of the first
* parameter, if sequence is 1 returns the name of the second parameter, and so on) for the given constructor.
* By default returns {@link MBeanParameterInfo#getName param.getName()}.
*/
protected String getParameterName(MBeanConstructorInfo constructor, MBeanParameterInfo param, int sequence)
{
return param == null ? null : param.getName();
}
/**
* Returns the name of the (sequence + 1)th parameter (that is: if sequence is 0 returns the name of the first
* parameter, if sequence is 1 returns the name of the second parameter, and so on) for the given operation.
* By default returns {@link MBeanParameterInfo#getName param.getName()}.
*/
protected String getParameterName(MBeanOperationInfo operation, MBeanParameterInfo param, int sequence)
{
return param == null ? null : param.getName();
}
/**
* Returns the impact flag for the given MBeanOperationInfo.
* By default returns {@link MBeanOperationInfo#getImpact info.getImpact()}
*/
protected int getImpact(MBeanOperationInfo info)
{
return info == null ? MBeanOperationInfo.UNKNOWN : info.getImpact();
}
/**
* Returns, by default, the given constructors
if implementation
* is 'this' object or null, otherwise returns null.
* Since the MBean that is registered in an MBeanServer is always an instance of StandardMBean,
* there is no meaning in providing MBeanConstructorInfo if the implementation passed to
* {@link #StandardMBean(Object,Class)} is not 'this' object.
*/
protected MBeanConstructorInfo[] getConstructors(MBeanConstructorInfo[] constructors, Object implementation)
{
if (implementation == this || implementation == null) return constructors;
return null;
}
/**
* Returns the cached MBeanInfo, or null if the MBeanInfo is not cached.
*
* @see #cacheMBeanInfo
* @see #getMBeanInfo
*/
protected MBeanInfo getCachedMBeanInfo()
{
return info;
}
/**
* Caches the given MBeanInfo after it has been created, by introspection, with the information
* provided to constructors.
* Override to disable caching, or to install different caching policies.
*
* @param info The MBeanInfo to cache; if it is null, the cache is cleared.
* @see #getCachedMBeanInfo
* @see #getMBeanInfo
*/
protected void cacheMBeanInfo(MBeanInfo info)
{
this.info = info;
}
/**
* This method calls the callbacks provided by this class that allow the user to customize the MBeanInfo
*
* @param info The MBeanInfo as it was introspected
*/
private MBeanInfo setupMBeanInfo(MBeanInfo info)
{
String clsName = getClassName(info);
String description = getDescription(info);
MBeanConstructorInfo[] ctors = setupConstructors(info.getConstructors());
MBeanAttributeInfo[] attrs = setupAttributes(info.getAttributes());
MBeanOperationInfo[] opers = setupOperations(info.getOperations());
MBeanNotificationInfo[] notifs = setupNotifications(info.getNotifications());
return new MBeanInfo(clsName, description, attrs, ctors, opers, notifs);
}
private MBeanConstructorInfo[] setupConstructors(MBeanConstructorInfo[] originalCtors)
{
MBeanConstructorInfo[] ctors = getConstructors(originalCtors, getImplementation());
if (ctors == null) return null;
MBeanConstructorInfo[] newCtors = new MBeanConstructorInfo[ctors.length];
for (int i = 0; i < ctors.length; ++i)
{
MBeanConstructorInfo ctor = ctors[i];
if (ctor == null) continue;
MBeanParameterInfo[] newParams = null;
MBeanParameterInfo[] params = ctor.getSignature();
if (params != null)
{
newParams = new MBeanParameterInfo[params.length];
for (int j = 0; j < params.length; ++j)
{
MBeanParameterInfo param = params[j];
if (param == null) continue;
String paramName = getParameterName(ctor, param, j);
String paramDescr = getDescription(ctor, param, j);
newParams[j] = new MBeanParameterInfo(paramName, param.getType(), paramDescr);
}
}
String ctorDescr = getDescription(ctor);
newCtors[i] = new MBeanConstructorInfo(ctor.getName(), ctorDescr, newParams);
}
return newCtors;
}
private MBeanAttributeInfo[] setupAttributes(MBeanAttributeInfo[] attrs)
{
if (attrs == null) return null;
MBeanAttributeInfo[] newAttrs = new MBeanAttributeInfo[attrs.length];
for (int i = 0; i < attrs.length; ++i)
{
MBeanAttributeInfo attr = attrs[i];
if (attr == null) continue;
String attrDescr = getDescription(attr);
newAttrs[i] = new MBeanAttributeInfo(attr.getName(), attr.getType(), attrDescr, attr.isReadable(), attr.isWritable(), attr.isIs());
}
return newAttrs;
}
private MBeanOperationInfo[] setupOperations(MBeanOperationInfo[] opers)
{
if (opers == null) return null;
MBeanOperationInfo[] newOpers = new MBeanOperationInfo[opers.length];
for (int i = 0; i < opers.length; ++i)
{
MBeanOperationInfo oper = opers[i];
if (oper == null) continue;
MBeanParameterInfo[] newParams = null;
MBeanParameterInfo[] params = oper.getSignature();
if (params != null)
{
newParams = new MBeanParameterInfo[params.length];
for (int j = 0; j < params.length; ++j)
{
MBeanParameterInfo param = params[j];
if (param == null) continue;
String paramName = getParameterName(oper, param, j);
String paramDescr = getDescription(oper, param, j);
newParams[j] = new MBeanParameterInfo(paramName, param.getType(), paramDescr);
}
}
String operDescr = getDescription(oper);
int operImpact = getImpact(oper);
newOpers[i] = new MBeanOperationInfo(oper.getName(), operDescr, newParams, oper.getReturnType(), operImpact);
}
return newOpers;
}
private MBeanNotificationInfo[] setupNotifications(MBeanNotificationInfo[] notifs)
{
return notifs == null ? null : notifs;
}
private MBeanMetaData introspectMBean(Object implementation, Class management)
{
MBeanMetaData metadata = MBeanMetaData.Factory.create();
metadata.setMBean(implementation);
metadata.setClassLoader(implementation.getClass().getClassLoader());
metadata.setMBeanStandard(true);
metadata.setMBeanInterface(management);
MBeanIntrospector introspector = new MBeanIntrospector();
introspector.introspect(metadata);
if (!introspector.isMBeanCompliant(metadata)) return null;
return metadata;
}
private class StandardMBeanSupport extends AbstractDynamicMBean
{
public synchronized MBeanInfo getMBeanInfo()
{
return StandardMBean.this.getMBeanInfo();
}
protected Object getResource()
{
return StandardMBean.this.getImplementation();
}
}
}
mx4j-3.0.2/src/core/javax/management/StringValueExp.java 100644 0 0 2363 10513545721 20263 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
/**
* The ValueExp that represents a string.
*
* @version $Revision: 1.6 $
*/
public class StringValueExp implements ValueExp
{
private static final long serialVersionUID = -3256390509806284044L;
/**
* @serial The string
*/
private String val;
/**
* Creates a new StringValueExp with a null string
*/
public StringValueExp()
{
this(null);
}
/**
* Creates a new StringValueExp with the given string
*/
public StringValueExp(String value)
{
this.val = value;
}
/**
* Returns the string represented by this instance
*/
public String getValue()
{
return val;
}
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
{
return this;
}
public void setMBeanServer(MBeanServer server)
{
// Not needed
}
public String toString()
{
return val;
}
}
mx4j-3.0.2/src/core/javax/management/ValueExp.java 100644 0 0 2105 10513545721 17066 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management;
import java.io.Serializable;
/**
* Represents values that can be passed to relational expressions such as strings, numbers, booleans and MBean attribute values.
*
* @version $Revision: 1.7 $
*/
public interface ValueExp extends Serializable
{
/**
* Applies this expression on the specified MBean.
*
* @param name The ObjectName
of the MBean
on which the expression is applied.
* @return The value expression that has been applied to the MBean
*/
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException;
/**
* Sets the MBeanServer
used (possibly) to apply the value expression
*/
public void setMBeanServer(MBeanServer server);
}
mx4j-3.0.2/src/core/javax/management/loading/ClassLoaderRepository.java 100644 0 0 5047 10513545721 23256 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
/**
* A repository for ClassLoader MBeans.
* A ClassLoaderRepository contains the ClassLoader that loaded the MBeanServer and
* registered MBeans that are ClassLoader subclasses and that does not implement the
* {@link PrivateClassLoader} interface.
* The order of registration for ClassLoader MBeans is important, as it will define
* the behavior of MLets, see {@link MLet#findClass}; the MBeanServer's ClassLoader is
* always the first ClassLoader.
*
* @version $Revision: 1.6 $
* @see MLet
* @see javax.management.MBeanServer#getClassLoaderRepository
*/
public interface ClassLoaderRepository
{
/**
* Loads the given class iterating through the list of classloaders contained in this repository,
* from the first to the last.
* The method returns as soon as the class is found, or throws a ClassNotFoundException
*
* @param className The name of the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class is not found
* @see #loadClassBefore
*/
public Class loadClass(String className) throws ClassNotFoundException;
/**
* Loads the given class iterating through the list of classloaders contained in this repository,
* from the first to the last, excluded the specified ClassLoader.
* The method returns as soon as the class is found, or throws a ClassNotFoundException
*
* @param loader The ClassLoader that should not be asked to load the class
* @param className The name of the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class is not found
* @see #loadClassBefore
*/
public Class loadClassWithout(ClassLoader loader, String className) throws ClassNotFoundException;
/**
* Loads the given class iterating through the list of classloaders contained in this repository,
* from the first to the specified ClassLoader (that is not asked to load the class).
*
* @param loader The ClassLoader that should not be asked to load the class and where the search must stop
* @param className The name of the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class is not found
*/
public Class loadClassBefore(ClassLoader loader, String className) throws ClassNotFoundException;
} mx4j-3.0.2/src/core/javax/management/loading/DefaultLoaderRepository.java 100644 0 0 2641 10513545721 23572 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
import java.util.ArrayList;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
/**
* @version $Revision: 1.7 $
* @deprecated No replacement. Just throw away all code that referenced this class, and use
* {@link javax.management.MBeanServer#getClassLoaderRepository} instead.
*/
public class DefaultLoaderRepository
{
public DefaultLoaderRepository()
{
}
public static Class loadClass(String className) throws ClassNotFoundException
{
return loadClassWithout(null, className);
}
public static Class loadClassWithout(ClassLoader loader, String className) throws ClassNotFoundException
{
ArrayList servers = MBeanServerFactory.findMBeanServer(null);
for (int i = 0; i < servers.size(); ++i)
{
MBeanServer server = (MBeanServer)servers.get(i);
ClassLoaderRepository repository = server.getClassLoaderRepository();
try
{
return repository.loadClassWithout(loader, className);
}
catch (ClassNotFoundException ignored)
{
}
}
throw new ClassNotFoundException(className);
}
}
mx4j-3.0.2/src/core/javax/management/loading/MLet.java 100644 0 0 45640 10513545721 17646 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ServiceNotFoundException;
import mx4j.loading.ClassLoaderObjectInputStream;
import mx4j.loading.MLetParseException;
import mx4j.loading.MLetParser;
import mx4j.loading.MLetTag;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* @version $Revision: 1.28 $
*/
public class MLet extends URLClassLoader implements MLetMBean, MBeanRegistration, Externalizable
{
private MBeanServer server;
private ObjectName objectName;
private boolean delegateToCLR;
private ThreadLocal loadingOnlyLocally = new ThreadLocal();
private ThreadLocal loadingWithRepository = new ThreadLocal();
private String libraryDir;
public MLet()
{
this(new URL[0]);
}
public MLet(URL[] urls)
{
this(urls, true);
}
public MLet(URL[] urls, boolean delegateToCLR)
{
super(urls);
setDelegateToCLR(delegateToCLR);
loadingWithRepository.set(Boolean.FALSE);
loadingOnlyLocally.set(Boolean.FALSE);
}
public MLet(URL[] urls, ClassLoader parent)
{
this(urls, parent, true);
}
public MLet(URL[] urls, ClassLoader parent, boolean delegateToCLR)
{
super(urls, parent);
setDelegateToCLR(delegateToCLR);
loadingWithRepository.set(Boolean.FALSE);
loadingOnlyLocally.set(Boolean.FALSE);
}
public MLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)
{
this(urls, parent, factory, true);
}
public MLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory, boolean delegateToCLR)
{
super(urls, parent, factory);
this.setDelegateToCLR(delegateToCLR);
loadingWithRepository.set(Boolean.FALSE);
loadingOnlyLocally.set(Boolean.FALSE);
}
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception
{
this.server = server;
objectName = name == null ? new ObjectName(this.server.getDefaultDomain(), "type", "MLet") : name;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet service " + objectName + " preRegistered successfully");
return objectName;
}
public void postRegister(Boolean registrationDone)
{
Logger logger = getLogger();
if (!registrationDone.booleanValue())
{
server = null;
if (logger.isEnabledFor(Logger.INFO)) logger.info("MLet service " + objectName + " was not registered");
}
else
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet service " + objectName + " postRegistered successfully");
}
}
public void preDeregister() throws Exception
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet service " + objectName + " preDeregistered successfully");
}
public void postDeregister()
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet service " + objectName + " postDeregistered successfully");
}
public void addURL(String url) throws ServiceNotFoundException
{
addURL(createURL(url));
}
public void addURL(URL url)
{
Logger logger = getLogger();
if (!Arrays.asList(getURLs()).contains(url))
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Adding URL to this MLet (" + objectName + ") classpath: " + url);
super.addURL(url);
}
else
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("URL already present in this MLet (" + objectName + ") classpath: " + url);
}
}
public Class loadClass(String name, ClassLoaderRepository repository) throws ClassNotFoundException
{
if (repository == null)
{
Class cls = loadClassLocally(name);
return cls;
}
else
{
try
{
Class cls = loadClassLocally(name);
return cls;
}
catch (ClassNotFoundException x)
{
// Not found locally, try the given repository
Class cls = loadClassFromRepository(name, repository);
return cls;
}
}
}
/**
* Loads the given class from this MLet only (with the usual parent delegation mechanism); the
* ClassLoaderRepository is not asked to load the class.
*
* @param name The name of the class to load.
* @return The loaded class
* @throws ClassNotFoundException
*/
private Class loadClassLocally(String name) throws ClassNotFoundException
{
// Here I must call super.loadClass(name) but not delegate to the CLR when I arrive to MLet.findClass
// I cannot call findClassLocally directly because otherwise the mechanism of parent delegation
// implemented in loadClass() is skipped and the parent loaders do not have the chance to
// load the given class
try
{
loadingOnlyLocally.set(Boolean.TRUE);
return loadClass(name);
}
finally
{
loadingOnlyLocally.set(Boolean.FALSE);
}
}
/**
* Loads the given class from the given non-null ClassLoaderRepository using
* {@link ClassLoaderRepository#loadClassBefore}
*/
private Class loadClassFromRepository(String name, ClassLoaderRepository repository) throws ClassNotFoundException
{
return repository.loadClassBefore(this, name);
}
protected Class findClass(String name) throws ClassNotFoundException
{
Logger logger = getLogger();
boolean trace = logger.isEnabledFor(Logger.TRACE);
// It may be possible that loading started with this MLet, then delegated to the CLR
// and came again to query this MLet which, if not stopped, will delegate to the CLR
// again in an endless loop. This is possible if this MLet is the parent of a child
// MLet registered before its parent.
if (loadingWithRepository.get() == Boolean.TRUE)
{
if (trace) logger.trace("MLet " + this + " is recursively calling itself to load class " + name + ": skipping further searches");
throw new ClassNotFoundException(name);
}
if (trace) logger.trace("Finding class " + name + "...");
try
{
Class cls = findClassLocally(name);
if (trace) logger.trace("Class " + name + " found in this MLet's classpath " + this);
return cls;
}
catch (ClassNotFoundException x)
{
if (!isDelegateToCLR())
{
if (trace) logger.trace("MLet " + this + " does not delegate to the ClassLoaderRepository");
throw x;
}
if (loadingOnlyLocally.get() == Boolean.TRUE) throw x;
if (server == null) throw x;
if (trace) logger.trace("Class " + name + " not found in this MLet's classpath " + this + ", trying the ClassLoaderRepository...", x);
try
{
loadingWithRepository.set(Boolean.TRUE);
ClassLoaderRepository repository = server.getClassLoaderRepository();
Class cls = loadClassFromRepository(name, repository);
if (trace) logger.trace("Class " + name + " found with ClassLoaderRepository " + repository);
return cls;
}
catch (ClassNotFoundException xx)
{
if (trace) logger.trace("Class " + name + " not found in ClassLoaderRepository, giving up", xx);
throw new ClassNotFoundException(name);
}
finally
{
loadingWithRepository.set(Boolean.FALSE);
}
}
}
private Class findClassLocally(String name) throws ClassNotFoundException
{
return super.findClass(name);
}
public Set getMBeansFromURL(String url) throws ServiceNotFoundException
{
return getMBeansFromURL(createURL(url));
}
public Set getMBeansFromURL(URL url) throws ServiceNotFoundException
{
if (url == null) throw new ServiceNotFoundException("Cannot load MBeans from null URL");
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet " + this + ", reading MLET file from " + url);
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream(baos);
try
{
is = url.openStream();
readFromAndWriteTo(is, os);
}
catch (IOException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot read input stream from URL " + url, x);
throw new ServiceNotFoundException(x.toString());
}
finally
{
try
{
if (is != null) is.close();
os.close();
}
catch (IOException ignored)
{
}
}
String mletFileContent = null;
try
{
mletFileContent = new String(baos.toByteArray(), "UTF-8");
}
catch (UnsupportedEncodingException x)
{
mletFileContent = baos.toString();
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet File content is:\n" + mletFileContent);
return parseMLetFile(mletFileContent, url);
}
private Set parseMLetFile(String content, URL mletFileURL) throws ServiceNotFoundException
{
Logger logger = getLogger();
try
{
HashSet mbeans = new HashSet();
MLetParser parser = new MLetParser(this);
List tags = parser.parse(content);
for (int i = 0; i < tags.size(); ++i)
{
MLetTag tag = (MLetTag)tags.get(i);
// Add the MBean's codebase to the MLet classloader
String[] jars = tag.parseArchive();
for (int j = 0; j < jars.length; ++j)
{
String jar = jars[j];
URL codebase = handleCheck(tag, jar, mletFileURL, mbeans);
URL archiveURL = tag.createArchiveURL(codebase, jar);
addURL(archiveURL);
}
// Create and register the MBean
Object obj = createMBean(tag);
mbeans.add(obj);
}
return mbeans;
}
catch (MLetParseException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot parse MLet file", x);
throw new ServiceNotFoundException(x.toString());
}
}
/**
* This method handle the call to {@link #check}, a method that it's a big mistake in JMX 1.2
*/
private URL handleCheck(MLetTag tag, String archive, URL mletFileURL, Set mbeans)
{
HashMap map = new HashMap();
map.put("codebaseURL", tag.normalizeCodeBase(mletFileURL));
map.put("codebase", tag.getCodeBase());
map.put("archive", tag.getArchive());
map.put("code", tag.getCode());
map.put("object", tag.getObject());
map.put("name", tag.getObjectName());
map.put("version", tag.getVersion());
MLetContent mletContent = new MLetContent(mletFileURL, map);
try
{
// JMX 1.2 FAAAAANTASTIC check method
return check(mletContent.getVersion(), mletContent.getCodeBase(), archive, mletContent);
}
catch (Throwable x)
{
mbeans.add(x);
return null;
}
}
/**
* This method is called when an MLet file has been parsed and before its information is used by this MLet.
* By overriding this method subclasses have the possibility to perform caching and versioning of jars,
* but unfortunately it contains as parameter a package private class, that thus forbids overriding: a big
* mistake in the JMX 1.2 specification.
*
* @since JMX 1.2
*/
protected URL check(String version, URL codebase, String archive, MLetContent content) throws Exception
{
return codebase;
}
private Object createMBean(MLetTag tag) throws ServiceNotFoundException
{
if (server == null) throw new ServiceNotFoundException("MLet not registered on the MBeanServer");
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MLet " + this + ", creating MBean from\n" + tag);
try
{
Object mbean = null;
if (tag.getObject() != null)
{
// Read the file from the codebase URLs of this classloader
String name = tag.getObject();
InputStream is = getResourceAsStream(name);
if (is == null) throw new ServiceNotFoundException("Cannot find serialized MBean " + name + " in MLet " + this);
InputStream bis = new BufferedInputStream(is);
// Deserialize using the MLet classloader
ObjectInputStream ois = new ClassLoaderObjectInputStream(bis, this);
mbean = ois.readObject();
}
else
{
// Instantiate using the MLet classloader
String clsName = tag.getCode();
Object[] args = tag.getArguments();
String[] params = tag.getSignature();
mbean = server.instantiate(clsName, objectName, args, params);
}
ObjectName objectName = tag.getObjectName();
ObjectInstance instance = server.registerMBean(mbean, objectName);
return instance;
}
catch (Throwable t)
{
return t;
}
}
protected String findLibrary(String libraryName)
{
// When asked to load a library, I should convert the library name to the system specific name
// For example if libraryName == "stat", on Solaris the conversion yields libstat.so, on Windows yields stat.dll
final String sysLibraryName = System.mapLibraryName(libraryName);
// Try to load the native libaray from jar only using the library name
String path = copyLibrary(sysLibraryName);
if (path != null) return path;
// Library not found so try to load the library using the os specific architecture
String osPath = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
StringBuffer buffer = new StringBuffer();
buffer.append(System.getProperty("os.name")).append(File.separator);
buffer.append(System.getProperty("os.arch")).append(File.separator);
buffer.append(System.getProperty("os.version")).append(File.separator);
buffer.append("lib").append(File.separator).append(sysLibraryName);
return buffer.toString();
}
});
osPath = removeSpaces(osPath);
return copyLibrary(osPath);
}
private String copyLibrary(String library)
{
Logger logger = getLogger();
library = library.replace('\\', '/');
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Loading library " + library);
URL libraryURL = getResource(library);
InputStream is = null;
OutputStream os = null;
try
{
try
{
is = getResourceAsStream(library);
if (is == null) return null;
if (!(is instanceof BufferedInputStream)) is = new BufferedInputStream(is);
File localLibrary = new File(getLibraryDirectory(), library);
URL localLibraryURL = localLibrary.toURL();
// The library is local and its directory is in the classpath of this MLet
if (localLibraryURL.equals(libraryURL)) return localLibrary.getCanonicalPath();
// Copy the library (that can be remote) locally, overwriting old versions
try
{
os = new BufferedOutputStream(new FileOutputStream(localLibrary));
readFromAndWriteTo(is, os);
return localLibrary.getCanonicalPath();
}
finally
{
if (os != null) os.close();
}
}
finally
{
if (is != null) is.close();
}
}
catch (IOException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot copy the library to the library directory " + getLibraryDirectory(), x);
return null;
}
}
private void readFromAndWriteTo(InputStream is, OutputStream os) throws IOException
{
byte[] buffer = new byte[64];
int read = -1;
while ((read = is.read(buffer)) >= 0) os.write(buffer, 0, read);
}
private String removeSpaces(String string)
{
int space = -1;
StringBuffer buffer = new StringBuffer();
while ((space = string.indexOf(' ')) >= 0)
{
buffer.append(string.substring(0, space));
string = string.substring(space + 1);
}
buffer.append(string);
return buffer.toString();
}
public String getLibraryDirectory()
{
return libraryDir;
}
public void setLibraryDirectory(String libdir)
{
libraryDir = libdir;
}
private boolean isDelegateToCLR()
{
return delegateToCLR;
}
private void setDelegateToCLR(boolean delegateToCLR)
{
this.delegateToCLR = delegateToCLR;
}
private URL createURL(String urlString) throws ServiceNotFoundException
{
try
{
URL url = new URL(urlString);
return url;
}
catch (MalformedURLException x)
{
throw new ServiceNotFoundException(x.toString());
}
}
private Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
/**
* Restores this MLet content from the given ObjectInput. Implementation of this method is optional,
* and if not implemented throws an UnsupportedOperationException.
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException, UnsupportedOperationException
{
throw new UnsupportedOperationException("MLet.readExternal");
}
/**
* Stores this MLet content in the given ObjectOutput. Implementation of this method is optional,
* and if not implemented throws an UnsupportedOperationException.
*/
public void writeExternal(ObjectOutput out) throws IOException, UnsupportedOperationException
{
throw new UnsupportedOperationException("MLet.writeExternal");
}
}
mx4j-3.0.2/src/core/javax/management/loading/MLetContent.java 100644 0 0 3415 10513545721 21153 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
import java.net.URL;
import java.util.Map;
/**
* This class is supposed to represent an MLET tag in a MLet file; a big
* mistake in JMX 1.2 specification introduced this class in a poorly designed
* {@link MLet#check} method, but left this class package private, so that it is totally
* useless. Furthermore, this class is so implementation dependent that should have never
* seen the light in the public API. But must be present for spec compliance.
*
* @version $Revision: 1.3 $
*/
class MLetContent
{
private Map attributes;
private URL mletFileURL;
private URL codebaseURL;
public MLetContent(URL mletFileURL, Map attributes)
{
this.mletFileURL = mletFileURL;
this.attributes = attributes;
codebaseURL = (URL)attributes.remove("codebaseURL");
}
public Map getAttributes()
{
return attributes;
}
public URL getDocumentBase()
{
return mletFileURL;
}
public URL getCodeBase()
{
return codebaseURL;
}
public String getJarFiles()
{
return (String)getParameter("archive");
}
public String getCode()
{
return (String)getParameter("code");
}
public String getSerializedObject()
{
return (String)getParameter("object");
}
public String getName()
{
return (String)getParameter("name");
}
public String getVersion()
{
return (String)getParameter("version");
}
public Object getParameter(String s)
{
return attributes.get(s.toLowerCase());
}
}
mx4j-3.0.2/src/core/javax/management/loading/MLetMBean.java 100644 0 0 4366 10513545721 20531 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
import javax.management.ServiceNotFoundException;
/**
* Management interface for MLets
*
* @version $Revision: 1.6 $
*/
public interface MLetMBean
{
/**
* @throws ServiceNotFoundException If the specified string URL is malformed
* @see #addURL(URL)
*/
public void addURL(String url) throws ServiceNotFoundException;
/**
* @see java.net.URLClassLoader#addURL
*/
public void addURL(URL url);
/**
* @see java.net.URLClassLoader#getURLs
*/
public URL[] getURLs();
/**
* @see java.net.URLClassLoader#getResource
*/
public URL getResource(String name);
/**
* @see java.net.URLClassLoader#getResourceAsStream
*/
public InputStream getResourceAsStream(String name);
/**
* @see java.net.URLClassLoader#getResources
*/
public Enumeration getResources(String name) throws IOException;
/**
* Shortcut for {@link #getMBeansFromURL(URL)}
*/
public Set getMBeansFromURL(String url) throws ServiceNotFoundException;
/**
* Registers, in the MBeanServer where this MLet is registered, the MBeans specified in the MLet
* file pointed by the given URL.
*
* @param url The URL of the MLet file to load
* @return A Set containing the ObjectInstances of the successfully registered MBeans,
* or Throwables that specifies why the MBean could not be registered.
* @throws ServiceNotFoundException If the given URL is invalid, or does not point to a valid MLet file
*/
public Set getMBeansFromURL(URL url) throws ServiceNotFoundException;
/**
* Returns the directory used to store native libraries
*
* @see #setLibraryDirectory
*/
public String getLibraryDirectory();
/**
* Sets the directory used to store native libraries
*
* @see #getLibraryDirectory
*/
public void setLibraryDirectory(String libdir);
}
mx4j-3.0.2/src/core/javax/management/loading/PrivateClassLoader.java 100644 0 0 1027 10513545721 22503 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
/**
* Tag interface that identifies classloader MBeans that should not be added to the
* MBeanServer's ClassLoaderRepository when registered in the MBeanServer.
*
* @version $Revision: 1.3 $
* @since JMX 1.2
*/
public interface PrivateClassLoader
{
}
mx4j-3.0.2/src/core/javax/management/loading/PrivateMLet.java 100644 0 0 4236 10513545721 21155 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.loading;
import java.net.URL;
import java.net.URLStreamHandlerFactory;
/**
* An MLet that is not registered in the MBeanServer's ClassLoaderRepository (since it implements
* the tag interface PrivateClassLoader).
*
* @version $Revision: 1.3 $
* @since JMX 1.2
*/
public class PrivateMLet extends MLet implements PrivateClassLoader
{
/**
* Creates a new PrivateMLet
*
* @param urls The URLs from where loading classes and resources
* @param delegateToCLR True if the MLet should delegate to the MBeanServer's ClassLoaderRepository
* in case the class or resource cannot be found by this MLet, false otherwise
*/
public PrivateMLet(URL[] urls, boolean delegateToCLR)
{
super(urls, delegateToCLR);
}
/**
* Creates a new PrivateMLet
*
* @param urls The URLs from where loading classes and resources
* @param parent The parent classloader
* @param delegateToCLR True if the MLet should delegate to the MBeanServer's ClassLoaderRepository
* in case the class or resource cannot be found by this MLet, false otherwise
*/
public PrivateMLet(URL[] urls, ClassLoader parent, boolean delegateToCLR)
{
super(urls, parent, delegateToCLR);
}
/**
* Creates a new PrivateMLet
*
* @param urls The URLs from where loading classes and resources
* @param parent The parent classloader
* @param factory The URL stream handler factory to handle custom URL schemes
* @param delegateToCLR True if the MLet should delegate to the MBeanServer's ClassLoaderRepository
* in case the class or resource cannot be found by this MLet, false otherwise
*/
public PrivateMLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory, boolean delegateToCLR)
{
super(urls, parent, factory, delegateToCLR);
}
}
mx4j-3.0.2/src/core/javax/management/modelmbean/DescriptorSupport.java 100644 0 0 42756 10513545721 23213 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.modelmbean;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.management.Descriptor;
import javax.management.MBeanException;
import javax.management.RuntimeOperationsException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
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;
/**
* @version $Revision: 1.31 $
*/
public class DescriptorSupport implements Descriptor
{
private static final long serialVersionUID = -6292969195866300415L;
private HashMap descriptor;
private transient HashMap fields = new HashMap(20);
public DescriptorSupport()
{
}
public DescriptorSupport(int initNumFields) throws MBeanException, RuntimeOperationsException
{
if (initNumFields <= 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Number of Fields cannot be <= 0"));
}
fields = new HashMap(initNumFields);
}
public DescriptorSupport(DescriptorSupport inDescr)
{
if (inDescr != null)
{
setFields(inDescr.getFieldNames(), inDescr.getFieldValues(inDescr.getFieldNames()));
}
}
public DescriptorSupport(String xml) throws MBeanException, RuntimeOperationsException, XMLParseException
{
if (xml == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Descriptor XML string is null"));
}
NodeList fields = documentFromXML(xml).getElementsByTagName("field");
for (int i = 0; i < fields.getLength(); i++)
{
addFieldFromXML(fields.item(i));
}
}
public DescriptorSupport(String[] pairs)
{
if (pairs != null && pairs.length != 0)
{
for (int i = 0; i < pairs.length; ++i)
{
String pair = pairs[i];
// null or empty strings are to be ignored
if (pair == null || pair.length() == 0) continue;
int equal = pair.indexOf('=');
if (equal < 1)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Illegal pair: " + pair));
}
else
{
String name = pair.substring(0, equal);
Object value = null;
if (equal < pair.length() - 1)
{
value = pair.substring(equal + 1);
}
setField(name, value);
}
}
}
}
public DescriptorSupport(String[] names, Object[] values) throws RuntimeOperationsException
{
setFields(names, values);
}
public Object clone() throws RuntimeOperationsException
{
return new DescriptorSupport(this);
}
public Object getFieldValue(String name) throws RuntimeOperationsException
{
if (name == null || name.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid field name"));
}
// Field names are case insensitive, retrieve the value from the case-insensitive map
ValueHolder holder = (ValueHolder)fields.get(name.toLowerCase());
return holder == null ? null : holder.fieldValue;
}
public void setField(String name, Object value) throws RuntimeOperationsException
{
checkField(name, value);
// update field but keep the original name if an entry already exists
String lcase = name.toLowerCase();
ValueHolder holder = (ValueHolder) fields.get(lcase);
ValueHolder newHolder = new ValueHolder(holder == null ? name : holder.fieldName, value);
fields.put(lcase, newHolder);
}
public void removeField(String name)
{
if (name != null)
{
fields.remove(name.toLowerCase());
}
}
public String[] getFieldNames()
{
// Preserve the case of field names so use the ones from the values
String[] names = new String[fields.size()];
int x = 0;
for (Iterator i = fields.values().iterator(); i.hasNext();)
{
ValueHolder holder = (ValueHolder) i.next();
names[x++] = holder.fieldName;
}
return names;
}
public Object[] getFieldValues(String[] names)
{
// quick check for empty descriptor (which overrides all)
if (fields.isEmpty()) return new Object[0];
if (names == null)
{
// All values must be returned
Object[] list = new Object[fields.size()];
int x = 0;
for (Iterator i = fields.values().iterator(); i.hasNext();)
{
ValueHolder holder = (ValueHolder) i.next();
list[x++] = holder.fieldValue;
}
return list;
}
Object[] list = new Object[names.length];
for (int i = 0; i < names.length; ++i)
{
try
{
list[i] = getFieldValue(names[i]);
}
catch (RuntimeOperationsException x)
{
list[i] = null;
}
}
return list;
}
public String[] getFields()
{
String[] values = new String[fields.size()];
StringBuffer buffer = new StringBuffer();
// Preserve the case of field names
int x = 0;
for (Iterator i = fields.values().iterator(); i.hasNext();)
{
ValueHolder holder = (ValueHolder) i.next();
String key = holder.fieldName;
Object value = holder.fieldValue;
buffer.setLength(0);
buffer.append(key);
buffer.append("=");
if (value != null)
{
if (value instanceof String)
{
buffer.append(value.toString());
}
else
{
buffer.append("(");
buffer.append(value.toString());
buffer.append(")");
}
}
values[x++] = buffer.toString();
}
return values;
}
public void setFields(String[] names, Object[] values) throws RuntimeOperationsException
{
if (names == null || values == null || names.length != values.length)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid arguments"));
}
for (int i = 0; i < names.length; ++i)
{
setField(names[i], values[i]);
}
}
public boolean isValid() throws RuntimeOperationsException
{
if (getFieldValue("name") == null || getFieldValue("descriptorType") == null) return false;
try
{
for (Iterator i = fields.values().iterator(); i.hasNext();)
{
ValueHolder holder = (ValueHolder) i.next();
checkField(holder.fieldName, holder.fieldValue);
}
return true;
}
catch (RuntimeOperationsException x)
{
return false;
}
}
public String toXMLString()
{
StringBuffer buf = new StringBuffer(32);
buf.append("OpenType
instance
*/
public OpenType getElementOpenType()
{
return elementType;
}
/**
* Test whether object is a value for this ArrayType
instance.
*
* @return boolean True if object is a value
*/
public boolean isValue(Object object)
{
if (object == null || !object.getClass().isArray())
{
return false;
}
if (elementType instanceof SimpleType)
{
return getClassName().equals(object.getClass().getName());
}
if (elementType instanceof TabularType || elementType instanceof CompositeType)
{
try
{
Class elementClass = Thread.currentThread().getContextClassLoader().loadClass(getClassName());
if (elementClass.isAssignableFrom(object.getClass()))
{
return checkElements((Object[]) object, dimension);
}
}
catch (ClassNotFoundException x)
{
return false;
}
}
return false;
}
/**
* Check if object is equal with this ArrayType
*
* @return true If Equal
*/
public boolean equals(Object object)
{
if (object == null)
return false;
if (object == this) return true;
if (object != null)
{
if (object instanceof ArrayType)
{
ArrayType checkedType = (ArrayType)object;
if (checkedType.dimension != dimension)
return false;
if (getElementOpenType().equals(checkedType.getElementOpenType()))
return true;
}
}
return false;
}
/**
* Compute the hashCode of this ArrayType
*
* @return int The computed hashCode
*/
public int hashCode()
{
if (hashCode == 0)
{
computeHashCode();
}
return hashCode;
}
/**
* Format this ArrayType is a String
*
* @return String The readable format
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(elementType.getClassName());
sb.append("(typename=");
sb.append(getTypeName());
sb.append(",dimension=");
sb.append("" + dimension);
sb.append(",elementType=");
sb.append(elementType.toString());
sb.append(")");
return sb.toString();
}
/**
* Returns a Description
*/
private static String createDescription(OpenType type, int size)
{
StringBuffer sb = new StringBuffer("" + size);
sb.append("-dimension array of ");
sb.append(type.getClassName());
return sb.toString();
}
private static String createArrayName(OpenType type, int size)
{
if (size <= 0) throw new IllegalArgumentException("int type dimension must be greater than or equal to 1");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++)
sb.append("[");
sb.append("L");
sb.append(type.getClassName());
sb.append(";");
return sb.toString();
}
private void computeHashCode()
{
hashCode = (dimension + elementType.hashCode());
}
private boolean checkElements(Object[] array, int dim) {
if (dim == 1)
{
OpenType arrayType = getElementOpenType();
for (int i = 0; i < array.length; i++)
{
Object o = array[i];
if (o != null && !arrayType.isValue(o))
{
return false;
}
}
return true;
} else {
for (int i = 0; i < array.length; i++)
{
Object o = array[i];
if (o != null && !checkElements((Object[])o, dim-1))
{
return false;
}
}
return true;
}
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/CompositeData.java 100644 0 0 1330 10513545721 22034 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.util.Collection;
/**
* @version $Revision: 1.6 $
*/
public interface CompositeData
{
public boolean containsKey(String key);
public boolean containsValue(Object value);
public boolean equals(Object object);
public Object get(String key);
public Object[] getAll(String[] keys);
public CompositeType getCompositeType();
public int hashCode();
public String toString();
public Collection values();
}
mx4j-3.0.2/src/core/javax/management/openmbean/CompositeDataSupport.java 100644 0 0 32712 10513545721 23461 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class CompositeDataSupport implements CompositeData, Serializable
{
private static final long serialVersionUID = 8003518976613702244L;
private SortedMap contents = new TreeMap();
private CompositeType compositeType;
private transient int m_hashcode = 0;
/**
* Constructs a CompositeDataSupport instance with the specified compositeType, whose item values are specified by itemValues[], in the same order as in itemNames[].
* As a CompositeType does not specify any order on its items, the itemNames[] parameter is used to specify the order in which the values are given in itemValues[].
* The items contained in this CompositeDataSupport instance are internally stored in a TreeMap, thus sorted in ascending lexicographic order of their names,
* for faster retrieval of individual item values.
* The constructor checks that all the constrainsts listed below for each parameter are satisfied, and throws the appropriate exception if they are not
*
* @param compositeType - the composite type of this composite data instance; must not be null.
* @param itemNames - itemNames must list, in any order, all the item names defined in compositeType;
* the order in which the names are listed, is used to match values in itemValues[]; must not be null or empty.
* @param itemValues - the values of the items, listed in the same order as their respective names in itemNames; each item value can be null,
* but if it is non-null it must be a valid value for the open type defined in compositeType for the corresponding item;
* must be of the same size as itemNames; must not be null or empty.
* @throws IllegalArgumentException if compositeType is null, or itemNames[] or itemValues[] is null or empty, or one of the elements in itemNames[] is a null or empty string,
* or itemNames[] and itemValues[] are not of the same size.
* @throws OpenDataException if itemNames[] or itemValues[]'s size differs from the number of items defined in compositeType, or one of the elements in itemNames[] does not exist
* as an item name defined in compositeType, or one of the elements in itemValues[] is not a valid value for the corresponding item as defined in compositeType
*/
public CompositeDataSupport(CompositeType compositeType, String[] itemNames, Object[] itemValues) throws OpenDataException
{
init(compositeType, itemNames, itemValues);
}
/**
* Constructs a CompositeDataSupport instance with the specified compositeType, whose items names and corresponding values are given by the mappings in the map items.
* This constructor converts the keys to a string array and the values to an object array and calls
* CompositeDataSupport(javax.management.openmbean.CompositeType, java.lang.String[], java.lang.Object[]).
*
* @param compositeType - the composite type of this composite data instance; must not be null.
* @param items - the mappings of all the item names to their values; items must contain all the item names defined in compositeType; must not be null or empty
* @throws IllegalArgumentException - if compositeType is null, or items is null or empty, or one of the keys in items is a null or empty string, or one of the values in items is null
* @throws OpenDataException - if items' size differs from the number of items defined in compositeType, or one of the keys in items does not exist as an item name defined in compositeType,
* or one of the values in items is not a valid value for the corresponding item as defined in compositeType.
* @throws ArrayStoreException - if any of the keys in items cannot be cast to a String
*/
public CompositeDataSupport(CompositeType compositeType, Map items) throws OpenDataException
{
init(compositeType, items != null ? (String[])items.keySet().toArray(new String[items.size()]) : null, items != null ? items.values().toArray() : null);
}
/**
* do all the work of the constructor so radObject can validate all invariants by calling the method
*/
private void init(CompositeType compositeType, String[] itemNames, Object[] itemValues) throws OpenDataException
{
if (compositeType == null) throw new IllegalArgumentException("Null CompositeType is not an acceptable value");
if (itemNames == null || itemNames.length == 0) throw new IllegalArgumentException("ItemNames cannot be null or empty (zero length)");
if (itemValues == null || itemValues.length == 0) throw new IllegalArgumentException("ItemValues cannot be null or empty (zero length)");
if (itemNames.length != itemValues.length) throw new IllegalArgumentException("Both the itemNames and itemValues arrays must be of equals length");
// now validate the the contents itemNames must be of the same length and contain all items present in the compositeType keys
validateTypes(compositeType, itemNames);
// check itemValues are valid values for openTypes
validateContents(compositeType, itemNames, itemValues);
// valid now assign compositeType
this.compositeType = compositeType;
// add the validated values and keys to the sortedMap
createMapData(itemNames, itemValues);
}
private void validateContents(CompositeType compositeType,
String[] itemNames,
Object[] itemValues)
throws OpenDataException
{
for (int i = 0; i < itemValues.length; i++)
{
if (itemValues[i] != null)
{
OpenType openType = compositeType.getType(itemNames[i]);
if (!(openType.isValue(itemValues[i])))
throw new OpenDataException("itemValue at index "
+ i
+ " is not a valid value for itemName "
+ itemNames[i]
+ " and itemType "
+ openType);
}
}
}
/**
* validates that the itemNames are present (in full) in the keySet of the compositeType
*/
private void validateTypes(CompositeType compositeType, String[] itemNames) throws OpenDataException
{
for (int i = 0; i < itemNames.length; i++)
{
if (itemNames[i] == null || itemNames[i].trim().equals("")) throw new IllegalArgumentException("Value of itemName at [" + i + "] is null or empty, unacceptable values");
}
Set keyTypes = compositeType.keySet();
if (itemNames.length != keyTypes.size()) throw new OpenDataException("The size of array arguments itemNames[] and itemValues[] should be equal to the number of items defined in argument compositeType");
if (!(Arrays.asList(itemNames).containsAll(keyTypes))) throw new OpenDataException("itemNames[] does not contain all names defined in the compositeType of this instance.");
}
/**
* fill the SortedMap with it's keys and values keys are the String[] itemNames and the values are the Object[] itemValues consisting of openTypes
*/
private void createMapData(String[] itemNames, Object[] itemValues)
{
for (int i = 0; i < itemNames.length; i++)
{
contents.put(itemNames[i], itemValues[i]);
}
}
/**
* @return the composite type of this composite data instance
*/
public CompositeType getCompositeType()
{
return compositeType;
}
/**
* @param key - the key for which to return the value
* @return - the value of the item whose name is key
* @throws IllegalArgumentException if key is null or an empty String
* @throws InvalidKeyException if key is not an existing item name for this CompositeData instance
*/
public Object get(String key)
{
if (key == null || key.trim().equals("")) throw new IllegalArgumentException("Null or empty key");
if (!(contents.containsKey(key.trim()))) throw new InvalidKeyException("Key with value " + key + " is not a current stored key in this instance");
return contents.get(key.trim());
}
/**
* Returns an array of the values of the items whose names are specified by keys, in the same order as keys this method simple calls get for each key
*
* @param the array of keys for which to return the corresponding values in the same order as specified in the keys
* @return the resulting array of values found
* @throws IllegalArgumentException if an element in keys is null or an empty String
* @throws InvalidKeyException if a key is not currently stored in this instances map
*/
public Object[] getAll(String[] keys)
{
/** should this throw an exception or under following conditions merely return an empty object[0] ?? */
if (keys == null || keys.length == 0) return new Object[0];
Object[] dataMapValues = new Object[keys.length];
for (int i = 0; i < keys.length; i++)
{
dataMapValues[i] = get(keys[i]);
}
return dataMapValues;
}
/**
* Returns true if and only if this CompositeData instance contains an item whose name is key. If key is a null or empty String, this method simply returns false
*
* @param key the key for which to find a value
* @return true if value found false otherwise
*/
public boolean containsKey(String key)
{
if (key == null || key.trim().equals("")) return false;
return contents.containsKey(key);
}
/**
* Returns true if and only if this CompositeData instance contains an item whose value is value
*
* @param value - the value to determine if present
* @return true if found false otherwise
*/
public boolean containsValue(Object value)
{
return contents.containsValue(value);
}
/**
* Returns an unmodifiable Collection view of the item values contained in this CompositeData instance. The returned collection's iterator will return the values in the
* ascending lexicographic order of the corresponding item names.
*
* @return unmodifiable collection of current values
*/
public Collection values()
{
return Collections.unmodifiableCollection(contents.values());
}
/**
* tests that the Object obj is equal to this compositeData instance
*
* @param obj - the Object to test if is equals
* @return true if and only if
*
*
*/
public boolean equals(Object obj)
{
if (!(obj instanceof CompositeData))
return false;
CompositeData compositeData = (CompositeData)obj;
boolean result =
getCompositeType().equals(compositeData.getCompositeType());
if (result)
{
Iterator i = contents.entrySet().iterator();
while (i.hasNext() && result)
{
Map.Entry entry = (Map.Entry)i.next();
String key = (String)entry.getKey();
Object entryvalue = entry.getValue();
Object cdvalue = compositeData.get(key);
if (entryvalue == null)
{
result = (cdvalue == null);
}
else
{
result = entryvalue.equals(cdvalue);
}
}
}
return result;
}
/**
* Using the same information as in equals test to create the hashcode
* i.e) The hash code of a CompositeDataSupport instance is the sum of the hash codes of all elements of information used in equals comparisons (ie: its composite type and all the item values).
*
* @return the calculated HashCode for this Object
*/
public int hashCode()
{
if (m_hashcode == 0)
{
int result = getCompositeType().hashCode();
for (Iterator i = contents.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
if (entry.getValue() != null) result += entry.getValue().hashCode();
}
m_hashcode = result;
}
return m_hashcode;
}
/**
* The string representation consists of the name of this class (ie javax.management.openmbean.CompositeDataSupport),
* the string representation of the composite type of this instance, and the string representation of the contents (ie list the itemName=itemValue mappings).
*
* @return a string representation of this CompositeDataSupport instance.
*/
public String toString()
{
StringBuffer buffer = new StringBuffer(getClass().getName());
buffer.append("\tCompositeType = ");
buffer.append(compositeType.toString());
buffer.append("\tcontents are: ");
buffer.append(contents.toString());
return buffer.toString();
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/CompositeType.java 100644 0 0 25272 10513545721 22137 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* @version $Revision: 1.11 $
*/
public class CompositeType extends OpenType implements Serializable
{
private static final long serialVersionUID = -5366242454346948798L;
private TreeMap nameToDescription;
private TreeMap nameToType;
private transient String m_classStringValue = null;
private transient int m_hashcode = 0;
/**
* The CompositeType class is the open type class whose instances describe the types of CompositeData values
* The Java class name of composite data values this composite type represents (ie the class name returned by
* the getClassName method) is set to the string value returned by CompositeData.class.getName().
* OpenMBeanAttributeInfo
represents an attribute of
* an OpenMBean
*
* @version $Revision: 1.4 $
* @see OpenMBeanAttributeInfoSupport
*/
public interface OpenMBeanAttributeInfo extends OpenMBeanParameterInfo
{
/**
* Returns true if the attribute is readable, false in not.
*
* @return boolean true of readable
*/
public boolean isReadable();
/**
* Returns true if the attribute is writable, false in not.
*
* @return boolean true of writable
*/
public boolean isWritable();
/**
* Returns true if the attribute described is accessed through a isXXX
* getter
*
*
* Note: applies only to boolean and Boolean values
*
Object
for equality with this instance.
*
*
* The operation returns true if and only if the following statements
* are all true:
* OpenMBeanAttributeInfo
*
* @return int The hashCode value
*/
public int hashCode();
/**
* Returns a string representation of this OpenMBeanAttributeInfo
instance.
*
* @return String The representation as string
*/
public String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java 100644 0 0 21315 10513545721 25226 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.management.MBeanAttributeInfo;
/**
* @version $Revision: 1.14 $
*/
public class OpenMBeanAttributeInfoSupport extends MBeanAttributeInfo implements OpenMBeanAttributeInfo, Serializable
{
private static final long serialVersionUID = -4867215622149721849L;
private OpenType openType;
private Object defaultValue = null;
private Set legalValues = null;
private Comparable minValue = null;
private Comparable maxValue = null;
private transient int hashCode = 0;
private transient String toStringName = null;
public OpenMBeanAttributeInfoSupport(String name, String description, OpenType openType, boolean isReadable, boolean isWritable, boolean isIs)
{
super(name, openType == null ? "" : openType.getClassName(), description, isReadable, isWritable, isIs);
if (openType == null)
throw new IllegalArgumentException("OpenType can't be null");
if (name == null || name.length() == 0 || name.trim().length() == 0)
throw new IllegalArgumentException("name can't be null or empty");
if (description == null || description.length() == 0 || description.trim().length() == 0)
throw new IllegalArgumentException("description can't be null or empty");
this.openType = openType;
}
public OpenMBeanAttributeInfoSupport(String name, String description, OpenType openType, boolean isReadable, boolean isWritable, boolean isIs, Object defaultValue) throws OpenDataException
{
this(name, description, openType, isReadable, isWritable, isIs);
if (openType instanceof ArrayType || openType instanceof TabularType)
{
if (defaultValue != null)
throw new OpenDataException("defaultValue is not supported for ArrayType and TabularType. Should be null");
}
if (defaultValue != null && !openType.isValue(defaultValue))
throw new OpenDataException("defaultValue is not a valid value for the given OpenType");
this.defaultValue = defaultValue;
}
public OpenMBeanAttributeInfoSupport(String name, String description, OpenType openType, boolean isReadable, boolean isWritable, boolean isIs, Object defaultValue, Object[] legalValues) throws OpenDataException
{
this(name, description, openType, isReadable, isWritable, isIs, defaultValue);
if (openType instanceof ArrayType || openType instanceof TabularType)
{
if (legalValues != null && legalValues.length > 0)
throw new OpenDataException("legalValues isn't allowed for ArrayType and TabularType. Should be null or empty array");
}
else if (legalValues != null && legalValues.length > 0)
{
Set tmpSet = new HashSet(legalValues.length);
for (int i = 0; i < legalValues.length; i++)
{
Object lv = legalValues[i];
if (openType.isValue(lv))
{
tmpSet.add(lv);
}
else
{
throw new OpenDataException("An Entry in the set of legalValues is not a valid value for the given opentype");
}
}
if (defaultValue != null && !tmpSet.contains(defaultValue))
{
throw new OpenDataException("The legal value set must include the default value");
}
this.legalValues = Collections.unmodifiableSet(tmpSet);
}
}
public OpenMBeanAttributeInfoSupport(String name, String description, OpenType openType, boolean isReadable, boolean isWritable, boolean isIs, Object defaultValue, Comparable minValue, Comparable maxValue) throws OpenDataException
{
this(name, description, openType, isReadable, isWritable, isIs, defaultValue);
if (minValue != null)
if (!openType.isValue(minValue))
throw new OpenDataException("minValue is not a valid value for the specified openType");
if (maxValue != null)
if (!openType.isValue(maxValue))
throw new OpenDataException("maxValue is not a valid value for the specified openType");
if (minValue != null && maxValue != null)
if (minValue.compareTo(maxValue) > 0)
throw new OpenDataException("minValue and/or maxValue is " +
"invalid: minValue is greater than maxValue");
if (defaultValue != null && minValue != null)
if (minValue.compareTo(defaultValue) > 0)
throw new OpenDataException("defaultvalue and/or minValue is invalid: minValue is greater than defaultValue");
if (defaultValue != null && maxValue != null)
if (((Comparable)defaultValue).compareTo(maxValue) > 0)
throw new OpenDataException("defaultvalue and/or maxValue is invalid: defaultValue is greater than maxValue");
this.minValue = minValue;
this.maxValue = maxValue;
}
public OpenType getOpenType()
{
return openType;
}
public Object getDefaultValue()
{
return defaultValue;
}
public Set getLegalValues()
{
return legalValues;
}
public Comparable getMinValue()
{
return minValue;
}
public Comparable getMaxValue()
{
return maxValue;
}
public boolean hasDefaultValue()
{
return defaultValue != null;
}
public boolean hasLegalValues()
{
return legalValues != null;
}
public boolean hasMinValue()
{
return minValue != null;
}
public boolean hasMaxValue()
{
return maxValue != null;
}
public boolean isValue(Object obj)
{
if (defaultValue != null)
{
if (openType.isValue(obj)) return true;
}
else
{
if (obj == null) return true;
}
return false;
}
public boolean equals(Object obj)
{
if (obj == this) return true;
// obj should not be null
if (obj == null) return false;
// obj should implement OpenMBeanAttributeInfo
if (!(obj instanceof OpenMBeanAttributeInfo)) return false;
OpenMBeanAttributeInfo other = (OpenMBeanAttributeInfo)obj;
if (!getName().equals(other.getName())) return false;
if (!getOpenType().equals(other.getOpenType())) return false;
if (isReadable() != other.isReadable()) return false;
if (isWritable() != other.isWritable()) return false;
if (isIs() != other.isIs()) return false;
if (hasDefaultValue())
{
if (!getDefaultValue().equals(other.getDefaultValue())) return false;
}
else
{
if (other.hasDefaultValue()) return false;
}
if (hasMinValue())
{
if (!getMinValue().equals(other.getMinValue())) return false;
}
else
{
if (other.hasMinValue()) return false;
}
if (hasMaxValue())
{
if (!getMaxValue().equals(other.getMaxValue())) return false;
}
else
{
if (other.hasMaxValue()) return false;
}
if (hasLegalValues())
{
if (!getLegalValues().equals(other.getLegalValues())) return false;
}
else
{
if (other.hasLegalValues()) return false;
}
return true;
}
public int hashCode()
{
if (hashCode == 0)
{
int result = getName().hashCode();
result += getOpenType().hashCode();
result += (hasDefaultValue() == false) ? 0 : getDefaultValue().hashCode();
result += (hasLegalValues() == false) ? 0 : getLegalValues().hashCode();
result += (hasMinValue() == false) ? 0 : getMinValue().hashCode();
result += (hasMaxValue() == false) ? 0 : getMaxValue().hashCode();
hashCode = result;
}
return hashCode;
}
public String toString()
{
if (toStringName == null)
{
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("(name=");
sb.append(getName());
sb.append(", opentype=");
sb.append(openType.toString());
sb.append(", defaultValue=");
sb.append(hasDefaultValue() ? getDefaultValue().toString() : "null");
sb.append(", minValue=");
sb.append(hasMinValue() ? getMinValue().toString() : "null");
sb.append(", maxValue=");
sb.append(hasMaxValue() ? getMaxValue().toString() : "null");
sb.append(", legalValues=");
sb.append(hasLegalValues() ? getLegalValues().toString() : "null");
sb.append(")");
toStringName = sb.toString();
}
return toStringName;
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanConstructorInfo.java 100644 0 0 1151 10513545721 24167 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import javax.management.MBeanParameterInfo;
/**
* @version $Revision: 1.3 $
*/
public interface OpenMBeanConstructorInfo
{
public String getDescription();
public String getName();
public MBeanParameterInfo[] getSignature();
public boolean equals(Object obj);
public int hashCode();
public String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanConstructorInfoSupport.java 100644 0 0 3746 10513545721 25600 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Arrays;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanParameterInfo;
/**
* @version $Revision: 1.6 $
*/
public class OpenMBeanConstructorInfoSupport extends MBeanConstructorInfo implements OpenMBeanConstructorInfo, Serializable
{
private static final long serialVersionUID = -4400441579007477003L;
// No non-transient fields allowed
private transient int m_hashcode = 0;
public OpenMBeanConstructorInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature)
{
super(name, description, signature == null ? null : (MBeanParameterInfo[])Arrays.asList(signature).toArray(new MBeanParameterInfo[0]));
if (name == null || name.trim().length() == 0) throw new IllegalArgumentException("name parameter cannot be null or an empty string");
if (description == null || description.trim().length() == 0) throw new IllegalArgumentException("description parameter cannot be null or an empty string");
}
public boolean equals(Object obj)
{
if (!(obj instanceof OpenMBeanConstructorInfo)) return false;
OpenMBeanConstructorInfo toCompare = (OpenMBeanConstructorInfo)obj;
return (getName().equals(toCompare.getName()) && Arrays.equals(getSignature(), toCompare.getSignature()));
}
public int hashCode()
{
if (m_hashcode == 0)
{
int result = getName().hashCode();
result += Arrays.asList(getSignature()).hashCode();
m_hashcode = result;
}
return m_hashcode;
}
public String toString()
{
return (getClass().getName() + " ( name = " + getName() + " signature = " + Arrays.asList(getSignature()).toString() + " )");
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanInfo.java 100644 0 0 4534 10513545721 21731 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
/**
* The OpenMBeanInfo
describes an OpenMBean.
*
* @version $Revision: 1.4 $
* @see javax.management.MBeanInfo
*/
public interface OpenMBeanInfo
{
/**
* Return the fully qualified classname that this OpenMBeanInfo describes
*
* @return String The fully qualified classname
*/
public String getClassName();
/**
* Returns a human readable description
*
* @return String The human readable description
*/
public String getDescription();
/**
* Returns an instance of MBeanAttributeInfo ( OpenMBeanAttributeInfo )
*
* @return MBeanAttributeInfo the OpenMBeanAttributeInfo array
* @see OpenMBeanAttributeInfo
* @see javax.management.MBeanAttributeInfo
*/
public MBeanAttributeInfo[] getAttributes();
/**
* Returns an instance of MBeanOperationInfo ( OpenMBeanOperationInfo )
*
* @return MBeanOperationInfo the OpenMBeanOperationInfo array
*/
public MBeanOperationInfo[] getOperations();
/**
* Returns an array of MBeanConstructorInfo ( OpenMBeanConstructorInfo )
*
* @return MBeanConstructorInfo the OpenMBeanConstructorInfo array
*/
public MBeanConstructorInfo[] getConstructors();
/**
* Returns an array of MBeanNotificationInfo which describes notifications
* by this OpenMBeanInfo
*
* @return MBeanNotificationInfo An array of notifications
*/
public MBeanNotificationInfo[] getNotifications();
/**
* Checks if the given Object is equal with this OpenMBeanInfo
*
* @return boolean If equal
*/
public boolean equals(Object obj);
/**
* Returns the hashCode of this OpenMBean info
*
* @return int the hashcode
*/
public int hashCode();
/**
* Returns a String representation
*
* @return String The String representation of this OpenMBeanInfo
*/
public String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanInfoSupport.java 100644 0 0 10554 10513545721 23345 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
/**
* @version $Revision: 1.11 $
*/
public class OpenMBeanInfoSupport extends MBeanInfo implements OpenMBeanInfo, Serializable
{
private static final long serialVersionUID = 4349395935420511492L;
// No non-transient data members allowed
private transient int hashCode = 0;
public OpenMBeanInfoSupport(String className, String description, OpenMBeanAttributeInfo[] openAttributes, OpenMBeanConstructorInfo[] openConstructors, OpenMBeanOperationInfo[] openOperations, MBeanNotificationInfo[] notifications)
{
// We cant pass this directly because OpenMBean*Info
// and friends isn't a direct subclass of their MBean*Info
// counterpart but the *Support. We need to do an arraycopy
// for this to work and the implementation should be a
// subclass of thir MBean*Support counterpart
super(className, description, createMBeanAttributes(openAttributes), createMBeanConstructors(openConstructors), createMBeanOperations(openOperations), notifications);
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof OpenMBeanInfo)) return false;
OpenMBeanInfo other = (OpenMBeanInfo)obj;
String thisClassName = getClassName();
String otherClassName = other.getClassName();
if (thisClassName != null ? !thisClassName.equals(otherClassName) : otherClassName != null) return false;
if (!compare(getConstructors(), other.getConstructors())) return false;
if (!compare(getAttributes(), other.getAttributes())) return false;
if (!compare(getOperations(), other.getOperations())) return false;
if (!compare(getNotifications(), other.getNotifications())) return false;
return true;
}
private boolean compare(Object[] o1, Object[] o2) {
return new HashSet(Arrays.asList(o1)).equals(new HashSet(Arrays.asList(o2)));
}
public int hashCode()
{
if (hashCode == 0)
{
int hash = getClassName() == null ? 0 : getClassName().hashCode();
if (getConstructors() != null) hash += new HashSet(Arrays.asList(getConstructors())).hashCode();
if (getAttributes() != null) hash += new HashSet(Arrays.asList(getAttributes())).hashCode();
if (getOperations() != null) hash += new HashSet(Arrays.asList(getOperations())).hashCode();
if (getNotifications() != null) hash += new HashSet(Arrays.asList(getNotifications())).hashCode();
hashCode = hash;
}
return hashCode;
}
/**
* Helper Method for OpenMBeanAttributeInfo[] to MBeanAttributeInfo[]
*/
private static MBeanAttributeInfo[] createMBeanAttributes(OpenMBeanAttributeInfo[] attributes) throws ArrayStoreException
{
if (attributes == null) return null;
MBeanAttributeInfo[] attrInfo = new MBeanAttributeInfo[attributes.length];
System.arraycopy(attributes, 0, attrInfo, 0, attrInfo.length);
return attrInfo;
}
/**
* Helper Method for OpenMBeanConstructorInfo[] to MBeanConstructorInfo[]
*/
private static MBeanConstructorInfo[] createMBeanConstructors(OpenMBeanConstructorInfo[] constructors) throws ArrayStoreException
{
if (constructors == null) return null;
MBeanConstructorInfo[] constInfo = new MBeanConstructorInfo[constructors.length];
System.arraycopy(constructors, 0, constInfo, 0, constInfo.length);
return constInfo;
}
/**
* Helper Method for OpenMBeanOperationsInfo[] to MBeanOperationsInfo[]
*/
private static MBeanOperationInfo[] createMBeanOperations(OpenMBeanOperationInfo[] operations) throws ArrayStoreException
{
if (operations == null) return null;
MBeanOperationInfo[] operInfo = new MBeanOperationInfo[operations.length];
System.arraycopy(operations, 0, operInfo, 0, operInfo.length);
return operInfo;
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanOperationInfo.java 100644 0 0 5734 10513545721 23615 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import javax.management.MBeanParameterInfo;
/**
* Describes operation of an OpenMBean
*
* @version $Revision: 1.6 $
*/
public interface OpenMBeanOperationInfo
{
/**
* Returs a human readable description about this operation.
*
* @return String The human readable operation description
*/
public String getDescription();
/**
* Returns the name of the operation being described by this
* OpenMBeanOperationInfo
*
* @return String the Operation name
*/
public String getName();
/**
* Returns an array of MBeanParameterInfo
for the operation
*
* @param MBeanParameterInfo An array of Parameterinfo
*/
public MBeanParameterInfo[] getSignature();
/**
* Returns a constant which qualifies the impact of the operation
* being described by the OpenMBeanOperationInfo
.
*
*
* The return constant is one of the ff:
*
*
* OpenMBeanOperationInfo
*
* @return OpenType The OpenType object
*/
public OpenType getReturnOpenType(); // open MBean specific method
/**
* Test the specified object for equality.
*
*
* This method will return true if and only if the following
* conditions are true:
*
*
* OpenMBeanOperationInfo
*
* @return int The hashcode
*/
public int hashCode();
/**
* Return a String representation
*/
public String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanOperationInfoSupport.java 100644 0 0 7577 10513545721 25221 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Arrays;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
/**
* @version $Revision: 1.11 $
*/
public class OpenMBeanOperationInfoSupport extends MBeanOperationInfo implements OpenMBeanOperationInfo, Serializable
{
private static final long serialVersionUID = 4996859732565369366L;
private OpenType returnOpenType;
private transient int hashCode = 0;
private transient String toStringName = null;
public OpenMBeanOperationInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature, OpenType returntype, int impact)
{
super(name, description, (signature == null) ? (MBeanParameterInfo[])Arrays.asList(new OpenMBeanParameterInfo[0]).toArray(new MBeanParameterInfo[0]) : (MBeanParameterInfo[])Arrays.asList(signature).toArray(new MBeanParameterInfo[0]), returntype == null ? "" : returntype.getClassName(), impact);
// Superclass constructors don't do the necessary validation
if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty");
if (description == null || description.length() == 0) throw new IllegalArgumentException("descripiton cannot be null or empty");
if (returntype == null) throw new IllegalArgumentException("return open type cannont be null");
if (impact != MBeanOperationInfo.ACTION
&& impact != MBeanOperationInfo.ACTION_INFO
&& impact != MBeanOperationInfo.INFO
&& impact != MBeanOperationInfo.UNKNOWN)
{
throw new IllegalArgumentException("invalid impact");
}
if (signature != null && signature.getClass().isInstance(MBeanParameterInfo[].class))
{
throw new ArrayStoreException("signature elements can't be assigned to MBeanParameterInfo");
}
this.returnOpenType = returntype;
}
public OpenType getReturnOpenType()
{
return returnOpenType;
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof OpenMBeanOperationInfo)) return false;
OpenMBeanOperationInfo other = (OpenMBeanOperationInfo)obj;
String thisName = getName();
String otherName = other.getName();
if (thisName != null ? !thisName.equals(otherName) : otherName != null) return false;
if (other.getImpact() != getImpact()) return false;
OpenType thisReturn = getReturnOpenType();
OpenType otherReturn = other.getReturnOpenType();
if (thisReturn != null ? !thisReturn.equals(otherReturn) : otherReturn != null) return false;
if (!Arrays.equals(getSignature(), other.getSignature())) return false;
return true;
}
public int hashCode()
{
if (hashCode == 0)
{
int result = getName().hashCode();
result += getReturnOpenType().hashCode();
result += getImpact();
result += java.util.Arrays.asList(getSignature()).hashCode();
hashCode = result;
}
return hashCode;
}
public String toString()
{
if (toStringName == null)
{
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName());
sb.append("(name=");
sb.append(getName());
sb.append(",signature=");
sb.append(java.util.Arrays.asList(getSignature()).toString());
sb.append(",returnOpenType=");
sb.append(returnOpenType.toString());
sb.append(",impact=");
sb.append(getImpact());
sb.append(")");
toStringName = sb.toString();
}
return toStringName;
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanParameterInfo.java 100644 0 0 1613 10513545721 23565 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.util.Set;
/**
* @version $Revision: 1.3 $
*/
public interface OpenMBeanParameterInfo
{
public String getDescription();
public String getName();
public OpenType getOpenType();
public Object getDefaultValue();
public Set getLegalValues();
public Comparable getMinValue();
public Comparable getMaxValue();
public boolean hasDefaultValue();
public boolean hasLegalValues();
public boolean hasMinValue();
public boolean hasMaxValue();
public boolean isValue(Object obj);
public boolean equals(Object obj);
public int hashCode();
public String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenMBeanParameterInfoSupport.java 100644 0 0 20463 10513545721 25206 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.management.MBeanParameterInfo;
/**
* @version $Revision: 1.9 $
*/
public class OpenMBeanParameterInfoSupport extends MBeanParameterInfo implements OpenMBeanParameterInfo, Serializable
{
private static final long serialVersionUID = -7235016873758443122L;
private OpenType openType = null;
private Object defaultValue = null;
private Set legalValues = null;
private Comparable minValue = null;
private Comparable maxValue = null;
private transient int m_hashcode = 0;
public OpenMBeanParameterInfoSupport(String name, String description, OpenType openType)
{
super(name, openType == null ? "" : openType.getClassName(), description);
if (name == null || name.trim().length() == 0) throw new IllegalArgumentException("name parameter cannot be null or an empty string.");
if (description == null || description.trim().length() == 0) throw new IllegalArgumentException("description parameter cannot be null or an empty string.");
if (openType == null) throw new IllegalArgumentException("OpenType parameter cannot be null.");
this.openType = openType;
}
public OpenMBeanParameterInfoSupport(String name, String description, OpenType openType, Object defaultValue) throws OpenDataException
{
this(name, description, openType);
if (defaultValue != null)
{
if (openType.isArray() || openType instanceof TabularType) throw new OpenDataException("openType should not be an ArrayType or a TabularType when a default value is required.");
if (!(openType.isValue(defaultValue))) throw new OpenDataException("defaultValue class name " + defaultValue.getClass().getName() + " does not match the one defined in openType.");
this.defaultValue = defaultValue;
}
}
public OpenMBeanParameterInfoSupport(String name, String description, OpenType openType, Object defaultValue, Object[] legalValues) throws OpenDataException
{
this(name, description, openType, defaultValue);
if (legalValues != null && legalValues.length > 0)
{
if (openType.isArray() || openType instanceof TabularType) throw new OpenDataException("legalValues not supported if openType is an ArrayType or an instanceof TabularType");
for (int i = 0; i < legalValues.length; i++)
{
if (!(openType.isValue(legalValues[i]))) throw new OpenDataException("The element at index " + i + " of type " + legalValues[i] + " is not an value specified in openType.");
}
// all checked assign Object[] legalValues to set legalValues
assignLegalValues(legalValues);
if (hasDefaultValue() && hasLegalValues() && !(this.legalValues.contains(defaultValue))) throw new OpenDataException("LegalValues must contain the defaultValue");
}
}
public OpenMBeanParameterInfoSupport(String name, String description, OpenType openType, Object defaultValue, Comparable minValue, Comparable maxValue) throws OpenDataException
{
this(name, description, openType, defaultValue);
if (minValue != null)
{
/** test is a valid value for the specified openType */
if (!(openType.isValue(minValue))) throw new OpenDataException("Comparable value of " + minValue.getClass().getName() + " does not match the openType value of " + openType.getClassName());
this.minValue = minValue;
}
if (maxValue != null)
{
if (!(openType.isValue(maxValue))) throw new OpenDataException("Comparable value of " + maxValue.getClass().getName() + " does not match the openType value of " + openType.getClassName());
this.maxValue = maxValue;
}
if (hasMinValue() && hasMaxValue() && minValue.compareTo(maxValue) > 0) throw new OpenDataException("minValue cannot be greater than maxValue.");
if (hasDefaultValue() && hasMinValue() && minValue.compareTo(defaultValue) > 0) throw new OpenDataException("minValue cannot be greater than defaultValue.");
if (hasDefaultValue() && hasMaxValue() && ((Comparable)defaultValue).compareTo(maxValue) > 0) throw new OpenDataException("defaultValue cannot be greater than maxValue.");
}
/**
* Assigns the validated Object[] into the set legal values as the constructor states
* this is unmodifiable will create an unmodifiable set
*/
private void assignLegalValues(Object[] legalValues)
{
HashSet modifiableSet = new HashSet();
for (int i = 0; i < legalValues.length; i++)
{
modifiableSet.add(legalValues[i]);
}
this.legalValues = Collections.unmodifiableSet(modifiableSet);
}
public OpenType getOpenType()
{
return openType;
}
public Object getDefaultValue()
{
return defaultValue;
}
public Set getLegalValues()
{
return legalValues;
}
public Comparable getMinValue()
{
return minValue;
}
public Comparable getMaxValue()
{
return maxValue;
}
public boolean hasDefaultValue()
{
return defaultValue != null;
}
public boolean hasLegalValues()
{
return legalValues != null;
}
public boolean hasMinValue()
{
return minValue != null;
}
public boolean hasMaxValue()
{
return maxValue != null;
}
public boolean isValue(Object obj)
{
// if any object is null and they have a defaultValue then isValue is true for anything else null obj returns false (must be first test) as the rest will return false for the null object
if (hasDefaultValue() && obj == null) return true;
if (!(openType.isValue(obj))) return false;
if (hasLegalValues() && (!(legalValues.contains(obj)))) return false;
if (hasMinValue() && minValue.compareTo(obj) > 0) return false;
if (hasMaxValue() && maxValue.compareTo(obj) < 0) return false;
return true;
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (obj == null) return false;
if (!(obj instanceof OpenMBeanParameterInfo)) return false;
OpenMBeanParameterInfo paramObj = (OpenMBeanParameterInfo)obj;
if (!getName().equals(paramObj.getName())) return false;
if (!getOpenType().equals(paramObj.getOpenType())) return false;
if (hasDefaultValue() && (!getDefaultValue().equals(paramObj.getDefaultValue()))) return false;
if (!hasDefaultValue() && paramObj.hasDefaultValue()) return false;
if (hasMinValue() && !(getMinValue().equals(paramObj.getMinValue()))) return false;
if (!hasMinValue() && paramObj.hasMinValue()) return false;
if (hasMaxValue() && !(getMaxValue().equals(paramObj.getMaxValue()))) return false;
if (!hasMaxValue() && paramObj.hasMaxValue()) return false;
if (hasLegalValues() && !(getLegalValues().equals(paramObj.getLegalValues()))) return false;
if (!hasLegalValues() && paramObj.hasLegalValues()) return false;
return true;
}
public int hashCode()
{
if (m_hashcode == 0)
{
int result = getName().hashCode();
result += getOpenType().hashCode();
result += (hasDefaultValue() == false) ? 0 : getDefaultValue().hashCode();
result += (hasLegalValues() == false) ? 0 : getLegalValues().hashCode();
result += (hasMinValue() == false) ? 0 : getMinValue().hashCode();
result += (hasMaxValue() == false) ? 0 : getMaxValue().hashCode();
m_hashcode = result;
}
return m_hashcode;
}
public String toString()
{
StringBuffer buf = new StringBuffer(getClass().getName());
buf.append("\t(name = ");
buf.append(getName());
buf.append("\topenType = ");
buf.append(openType.toString());
buf.append("\tdefault value = ");
buf.append(String.valueOf(defaultValue));
buf.append("\tmin value = ");
buf.append(String.valueOf(minValue));
buf.append("\tmax value = ");
buf.append(String.valueOf(maxValue));
buf.append("\tlegal values = ");
buf.append(String.valueOf(legalValues));
buf.append(")");
return buf.toString();
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/OpenType.java 100644 0 0 11102 10513545721 21061 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import mx4j.util.Utils;
/**
* @version $Revision: 1.12 $
*/
public abstract class OpenType implements Serializable
{
private static final long serialVersionUID = -9195195325186646468L;
public static final String[] ALLOWED_CLASSNAMES =
{
"java.lang.Void",
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Character",
"java.lang.Short",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Float",
"java.lang.Double",
"java.lang.String",
"java.math.BigDecimal",
"java.math.BigInteger",
"java.util.Date",
"javax.management.ObjectName",
CompositeData.class.getName(),
TabularData.class.getName()
};
private String className = null;
private String typeName = null;
private String description = null;
protected OpenType(String className, String typeName, String description) throws OpenDataException
{
initialize(className, typeName, description);
}
/**
* private convenience method for the readObject method to call so that code is not being duplicated in the constructor and the readObject methods
*/
private void initialize(String className, String typeName, String description) throws OpenDataException
{
if (className == null) throw new IllegalArgumentException("null className is invalid");
if (typeName == null) throw new IllegalArgumentException("null typeName is invalid");
if (description == null) throw new IllegalArgumentException("null description is invalid");
if (!(validateClass(className))) throw new OpenDataException("Class does not represent one of the allowed className types");
this.className = className;
this.typeName = typeName;
this.description = description;
}
/**
* private validate method just to do some type checking with regards to that the entered className matches the array of allowed types
*/
private boolean validateClass(String className)
{
/** test we do not have an array if it is it is allowed but it is not listed in the allowed types (be too long) so remove the array
* indicator [[[[[L etc and the ; at the end to test if the array type is of the correct class listed above.
*/
if (className.startsWith("[")) className = className.substring(className.indexOf("L") + 1, (className.length() - 1));
for (int i = 0; i < ALLOWED_CLASSNAMES.length; i++)
{
if (className.equals(ALLOWED_CLASSNAMES[i])) return true;
}
return false;
}
/**
* Retrieve the className
*
* @return the name of the class
*/
public String getClassName()
{
return className;
}
/**
* Retrieve the description
*
* @return description
*/
public String getDescription()
{
return description;
}
/**
* Retrieve the typeName
*
* @return typeName
*/
public String getTypeName()
{
return typeName;
}
/**
* check if this instance represents an array or not
*
* @return true if the class represents an array, false otherwise
*/
public boolean isArray()
{
Class c = null;
try
{
c = Utils.loadClass(Thread.currentThread().getContextClassLoader(), className);
}
catch (ClassNotFoundException e)
{
return false;
}
return c.isArray();
}
/**
* read out object, validate it using the same methods the constructor uses to validate its' invariants
*/
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
try
{
initialize(className, typeName, description);
}
catch (OpenDataException e)
{
throw new StreamCorruptedException("The object read from the ObjectInputStream during deserialization is not valid");
}
}
public abstract boolean isValue(Object object);
public abstract boolean equals(Object object);
public abstract int hashCode();
public abstract String toString();
}
mx4j-3.0.2/src/core/javax/management/openmbean/SimpleType.java 100644 0 0 16450 10513545721 21424 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* The SimpleType class is the open type class whose instances describe all open data values which are neither arrays, * nor {@link CompositeData} values, nor {@link TabularData} values. It predefines all its possible instances as static fields, * and has no public constructor.
* *Given a SimpleType instance describing values whose Java class name is className, the internal fields corresponding to the * TypeName and description of this SimpleType instance are also set to className. In other words, its methods getClassName, getTypeName * and getDescription all return the same string value className.
* * @version $Revision: 1.13 $ */ public final class SimpleType extends OpenType implements Serializable { private static final long serialVersionUID = 2215577471957694503L; // No non-transient fields allowed public final static SimpleType BIGDECIMAL; public final static SimpleType BIGINTEGER; public final static SimpleType BOOLEAN; public final static SimpleType BYTE; public final static SimpleType CHARACTER; public final static SimpleType DOUBLE; public final static SimpleType FLOAT; public final static SimpleType INTEGER; public final static SimpleType LONG; public final static SimpleType OBJECTNAME; public final static SimpleType SHORT; public final static SimpleType STRING; public final static SimpleType DATE; public final static SimpleType VOID; static { /* * We need to assign them to temp one by one, or the compiler * will complain. We need to assign temp=null even though * the exception will not happen. */ SimpleType temp = null; try { temp = new SimpleType("java.math.BigDecimal"); } catch (OpenDataException ignored) { } BIGDECIMAL = temp; temp = null; // BIGINTEGER try { temp = new SimpleType("java.math.BigInteger"); } catch (OpenDataException ignored) { } BIGINTEGER = temp; temp = null; //BOOLEAN try { temp = new SimpleType("java.lang.Boolean"); } catch (OpenDataException ignored) { } BOOLEAN = temp; temp = null; //BYTE try { temp = new SimpleType("java.lang.Byte"); } catch (OpenDataException ignored) { } BYTE = temp; temp = null; //CHARACTER try { temp = new SimpleType("java.lang.Character"); } catch (OpenDataException ignored) { } CHARACTER = temp; temp = null; //DOUBLE try { temp = new SimpleType("java.lang.Double"); } catch (OpenDataException ignored) { } DOUBLE = temp; temp = null; //FLOAT try { temp = new SimpleType("java.lang.Float"); } catch (OpenDataException ignored) { } FLOAT = temp; temp = null; //INTEGER try { temp = new SimpleType("java.lang.Integer"); } catch (OpenDataException ignored) { } INTEGER = temp; temp = null; //LONG try { temp = new SimpleType("java.lang.Long"); } catch (OpenDataException ignored) { } LONG = temp; temp = null; //OBJECTNAME try { temp = new SimpleType("javax.management.ObjectName"); } catch (OpenDataException ignored) { } OBJECTNAME = temp; temp = null; //SHORT try { temp = new SimpleType("java.lang.Short"); } catch (OpenDataException ignored) { } SHORT = temp; temp = null; //STRING try { temp = new SimpleType("java.lang.String"); } catch (OpenDataException ignored) { } STRING = temp; temp = null; //DATE try { temp = new SimpleType("java.util.Date"); } catch (OpenDataException ignored) { } DATE = temp; temp = null; //VOID try { temp = new SimpleType("java.lang.Void"); } catch (OpenDataException ignored) { } VOID = temp; temp = null; } private transient int m_hashCode = 0; private SimpleType(String className) throws OpenDataException { super(className, className, className); } /** * Checks if thisSimpleType
object is value of
* the given object
*
* @param object The object to check
* @return boolean
*/
public boolean isValue(Object object)
{
if (object == null) return false;
return getClassName().equals(object.getClass().getName());
}
public Object readResolve() throws ObjectStreamException
{
//TODO: need a better way of doing this
if (getClassName().equals(String.class.getName()))
return SimpleType.STRING;
if (getClassName().equals(java.math.BigDecimal.class.getName()))
return SimpleType.BIGDECIMAL;
if (getClassName().equals(java.math.BigInteger.class.getName()))
return SimpleType.BIGINTEGER;
if (getClassName().equals(Boolean.class.getName()))
return SimpleType.BOOLEAN;
if (getClassName().equals(Byte.class.getName()))
return SimpleType.BYTE;
if (getClassName().equals(Character.class.getName()))
return SimpleType.CHARACTER;
if (getClassName().equals(Double.class.getName()))
return SimpleType.DOUBLE;
if (getClassName().equals(Float.class.getName()))
return SimpleType.FLOAT;
if (getClassName().equals(Integer.class.getName()))
return SimpleType.INTEGER;
if (getClassName().equals(Long.class.getName()))
return SimpleType.LONG;
if (getClassName().equals(javax.management.ObjectName.class.getName()))
return SimpleType.OBJECTNAME;
if (getClassName().equals(Short.class.getName()))
return SimpleType.SHORT;
if (getClassName().equals(Void.class.getName()))
return SimpleType.VOID;
if (getClassName().equals(java.util.Date.class.getName()))
return SimpleType.DATE;
return null;
}
/**
* Check the given object for equality
*
* @return boolean if object is equal
*/
public boolean equals(Object object)
{
if (!(object instanceof SimpleType)) return false;
SimpleType otherType = (SimpleType)object;
return (this.getClassName().equals(otherType.getClassName()));
}
/**
* Retrieve the hashCode
*
* @return int The computed hasCode
*/
public int hashCode()
{
if (m_hashCode == 0)
{
int result = getClassName().hashCode();
m_hashCode = result;
}
return m_hashCode;
}
/**
* Returns a human readable representation of this SimpleType object
*
* @return String the String representation
*/
public String toString()
{
return (getClass().getName() + "(name = " + getTypeName() + ")");
}
}
mx4j-3.0.2/src/core/javax/management/openmbean/TabularData.java 100644 0 0 3655 10513545721 21500 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package javax.management.openmbean;
import java.util.Collection;
import java.util.Set;
/**
*
* @version $Revision: 1.7 $
*/
/**
* The TabularData interface specifies the behaviour of a specific type of complex open data objects which represent tabular data structures
*/
public interface TabularData
{
/**
* Calculates the index that would be used in this TabularData instance to refer to the specified CompositeData value parameter, if it were added. * This method checks for the type validity of the specified value, but does not check if the calculated index is already used to refer to a value in this TabularData instance * * @param index the CompositeData value whose index in this TabularData instance is to be calculated. It must be of the same composite type as this instances' rowType and cannot be null. * @return object[] value that the specified value would have in this TabulatData instance * @throws NullPointerException if index is null * @throws InvalidOpenTypeException if index does not conform to this TabularData instance's rowType */ public Object[] calculateIndex(CompositeData index); public void clear(); public boolean containsKey(Object[] key); public boolean containsValue(CompositeData value); public boolean equals(Object object); public CompositeData get(Object[] key); public TabularType getTabularType(); public int hashCode(); public boolean isEmpty(); public Set keySet(); public void put(CompositeData value); public void putAll(CompositeData[] values); public CompositeData remove(Object[] key); public int size(); public String toString(); public Collection values(); } mx4j-3.0.2/src/core/javax/management/openmbean/TabularDataSupport.java 100644 0 0 52516 10513545721 23115 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.openmbean; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * * @version $Revision: 1.10 $ */ /** * The TabularDataSupport class is the open data class which implements the TabularData and the * Map interfaces, and which is internally based on a hash map data structure */ public class TabularDataSupport implements TabularData, Map, Cloneable, Serializable { private static final long serialVersionUID = 5720150593236309827L; private Map dataMap; private TabularType tabularType; private transient String[] m_indexNames; /** * Creates an empty TabularDataSupport instance whose open-type is tabularType, and whose underlying HashMap has a default initial capacity (101) and default load factor (0.75). * * @param tabularType the TabularTypeBackUP describing this TabularData instance, cannot be null */ public TabularDataSupport(TabularType tabularType) { this(tabularType, 101, 0.75f); } /** * Creates an empty TabularDataSupport instance whose open-type is tabularType, and whose underlying HashMap has the specified initial capacity and load factor * * @param tabularType - the tabular type describing this instance, cannot be null; * @param initialCapacity - the initial capacity of the Map * @param loadFactor - the load factor of the Map * @throws IllegalArgumentException if the initialCapacity is less than zero, the load factor is negative or the tabularType is null */ public TabularDataSupport(TabularType tabularType, int initialCapacity, float loadFactor) { if (tabularType == null) throw new IllegalArgumentException("TabularTypeBackUP instance cannot be null."); if (initialCapacity < 0) throw new IllegalArgumentException("The initialCapacity cannot be a negative number."); if (loadFactor < 0) throw new IllegalArgumentException("The load factor cannot be a negative number."); this.tabularType = tabularType; this.dataMap = new HashMap(initialCapacity, loadFactor); initialize(); } /** * can be called by the readObject method to initialize the deserialized instance */ private void initialize() { // get the index names list from the tabular type as these will act as the unique index into each row of the TabularData instance List tabularIndexList = tabularType.getIndexNames(); m_indexNames = (String[])tabularIndexList.toArray(new String[tabularIndexList.size()]); } /** * get the TabularType that this instance contains * * @return TabularType describing this TabularData instance */ public TabularType getTabularType() { return tabularType; } /** *
Calculates the index that would be used in this TabularData instance to refer to the specified composite data value parameter is it were added * to this instance.This method checks for the type validity of the specified value, but does not check if the calculated index is already used to refer to a * value, in this tabular data instance
* * @param value - the CompositeData value whose index in this TabularData instance is to be calculated, must be of the same composite type as this instance's row type; * must not be null. * @return - the index that the specified value would have in this tabularData instance * @throws NullPointerException if value is null * @throws InvalidOpenTypeException if value does not conform to this tabular data instances' row type definition */ public Object[] calculateIndex(CompositeData value) { if (value == null) throw new NullPointerException("CompositeData object cannot be null"); if (!(value.getCompositeType().equals(tabularType.getRowType()))) throw new InvalidOpenTypeException("Invalid CompositeData object, its' tabularType is not equal to the row type of this TabularType instance"); return Collections.unmodifiableList(Arrays.asList(value.getAll(m_indexNames))).toArray(); } /** * returns true if and only if this tabularData instance contains a compositeData value (i.e. a row) whose index is the specified key. If key cannot be cast to a one dimension * array of Object instances, this method returns false, otherwise it returns the result of the call this.containsKey((Object[]) key) * * @param key - the index value * @return true if a CompositeData value is found false otherwise, false if key cannot be cast to an Object[] */ public boolean containsKey(Object key) { if (!(key instanceof Object[])) return false; return containsKey((Object[])key); } /** * Returns true if and only if this TabularData instance contains a CompositeData value (ie a row) whose index is the specified key. If key is null or does not conform to this * TabularData instance's TabularType definition, this method simply returns false. * * @param key the index value whose presence in this TabularData instance is to be tested * @return true if it is found false otherwise */ public boolean containsKey(Object[] key) { if (key == null) return false; return dataMap.containsKey(Arrays.asList(key)); } /** * Returns true if and only if this TabularData instance contains the specified CompositeData value. If value is null or does not conform to * this TabularData instance's row type definition, this method simply returns false. * * @param value - the row value whose presence in this TabularData instance is to be tested * @return true if this instance contains the specified value */ public boolean containsValue(CompositeData value) { return dataMap.containsValue(value); } /** * Returns true if and only if this TabularData instance contains the specified value. * * @param value - the row value whose presence in this TabularData instance is to be tested * @return true if this TabularData instance contains the specified row value */ public boolean containsValue(Object value) { return dataMap.containsValue(value); } /** * This method simply calls get((Object[]) key). * * @param key - the key for which to lookup the value * @return the Object found for key "key" */ public Object get(Object key) { return get((Object[])key); } /** * This method validates the key Object[] parameter. It cannot be null, or empty. It must be the same length as the indexNames of the tabularType passed into this instances * constructor, and must be a valid value i.e the value returned by the method call OpenType isValue(Object obj) must be true * * @param key - the Object[] key stored as a key in this instance * @return - the CompositeData value corresponding to the key * @throws NullPointerException if key is null or empty * @throws InvalidKeyException if an item in the array returns false for call OpenType isValue(Object o) */ public CompositeData get(Object[] key) { validateKeys(key); return (CompositeData)dataMap.get(Arrays.asList(key)); } /** * This method simply calls put((CompositeData) value) and therefore ignores its key parameter which can be null * * @return the value that is put * @throws ClassCastException if value is not an instanceof CompositeData */ public Object put(Object key, Object value) { put((CompositeData)value); return value; } /** * Adds "value" to this TabularData instance, if value's composite type is the same as this instance's row type * (ie the composite type returned by this.getTabularType().getRowType()), and if there is not already an existing value in this TabularData * instance whose index is the same as the one calculated for the value to be added. The index for value is calculated according to this TabularData instance's * TabularType definition @see javax.management.openmbean.TabularType#getIndexNames() * * This method calls calculateIndex(CompositeData value) which validates value the returned Object[] is then converted into an unmodifiableList and stored * * @param value - the composite data value to be added as a new row to this TabularData instance; must be of the same composite type as this instance's row type; must not be null. * @throws NullPointerException if value is null * @throws InvalidOpenTypeException if value does not conform to this TabularData instance's row type definition * @throws KeyAlreadyExistsException if the underlying HashMap already contains the calculated key */ public void put(CompositeData value) { // calculateIndex method tests for null and invalid rowType List list = Collections.unmodifiableList(Arrays.asList(calculateIndex(value))); if (dataMap.containsKey(list)) throw new KeyAlreadyExistsException("The list of index names already exists in this instance"); dataMap.put(list, value); } /** * This method simply calls remove((Object[]) key). * * @param key - the Object to remove note no checks are done if key can be cast to Object[] hence if not a ClassCastException will be thrown * @throws ClassCastException if key cannot be cast to an Object[] */ public Object remove(Object key) { return remove((Object[])key); } /** * Method validates the key checking for null, zero length and if items in the key are invalid as returned by @see OpenType isValue(Object obj) * * @param key - the index of the value to get in this TabularData instance; must be valid with this TabularData instance's row type definition; must not be null. * @return previous value associated with specified key, or null if there was no mapping for key * @throws NullPointerException if key is null * @throws InvalidKeyException if the key does not conform to this TabularData instance's TabularType definition */ public CompositeData remove(Object[] key) { validateKeys(key); return (CompositeData)dataMap.remove(Arrays.asList(key)); } /** * Add all the values contained in the specified map t to this TabularData instance. This method converts the collection of values contained in this map into an * array of CompositeData values, if possible, and then calls the method putAll(CompositeData[]). Note that the keys used in the specified map t are ignored. * This method allows, for example to add the content of another TabularData instance with the same row type (but possibly different index names) into this instance. * * @param t - the map whose values are to be added as new rows to this TabularData instance; if t is null or empty, this method returns without doing anything * @throws NullPointerException - if a "value" in t is null * @throws ClassCastException - if a value in t is not an instanceof CompositeData this is a wrapper around the RuntimeException ArrayStoreException * which is generated when an attempt has been made to store the wrong type of object into an array of objects. * @throws InvalidOpenTypeException - if a value in t does not conform to this TabularData instance's row type definition * @throws KeyAlreadyExistsException - if the index for a value in t, calculated according to this TabularData instance's TabularType definition * already maps to an existing value in this instance, or two values in t have the same index. */ public void putAll(Map t) { if (t == null || t.size() == 0) return; CompositeData[] compositeData; try { compositeData = (CompositeData[])t.values().toArray(new CompositeData[t.size()]); } catch (ArrayStoreException e) { throw new ClassCastException("The values contained in t must all be of type CompositeData"); } putAll(compositeData); } /** * Adds all the elements in values to this TabularData instance. If any element in values does not satisfy the constraints defined in put, or if any two elements in values * have the same index calculated according to this TabularData instance's TabularType definition, then an exception describing the failure is thrown * and no element of values is added, thus leaving this TabularData instance unchanged. * * @param values - the array of composite data values to be added as new rows to this TabularData instance; if values is null or empty, this method returns without doing anything * @throws NullPointerException - if an element of values is null * @throws InvalidOpenTypeException - if an element of values does not conform to this TabularData instance's row type definition (ie its TabularType definition) * @throws KeyAlreadyExistsException - if the index for an element of values, calculated according to this TabularData instance's TabularType definition already * maps to an existing value in this instance, or two elements of values have the same index */ public void putAll(CompositeData[] values) { // validate values if (values == null || values.length == 0) return; /** creating a list to store all the keys obtained from method calculateIndex this is to check that no keys are duplicated */ List storeList = validateNoDuplicates(values); /** Once we have validated that there are no duplicated keys we can add them to the global map if a duplicate is found an exception is thrown leaving instance unchanged */ for (int i = 0; i < values.length; i++) { dataMap.put(storeList.get(i), values[i]); } } /** * test that the list returned from calculateIndex for each CompositeData object has no duplicates */ private List validateNoDuplicates(CompositeData[] values) { List storeList = new ArrayList(); for (int i = 0; i < values.length; i++) { List list = Collections.unmodifiableList(Arrays.asList(calculateIndex(values[i]))); /** check no duplicate keys if there is we have an invalid key */ if (storeList.contains(list)) throw new KeyAlreadyExistsException("value at [" + i + "] has the same index values as: " + storeList.indexOf(list)); /** store it to check the next values are not duplicated */ storeList.add(list); } return storeList; } /** * clears this instances internal map */ public void clear() { dataMap.clear(); } /** * @return the size of the map */ public int size() { return dataMap.size(); } /** * @return true if the map is empty false if not empty */ public boolean isEmpty() { return dataMap.isEmpty(); } /** * Returns a set view of the keys contained in the underlying map of this TabularDataSupport instance, and used to index the rows. * Each key contained in this set is an unmodifiable List. The set is backed by the underlying map of this TabularDataSupport instance, * so changes to the TabularDataSupport instance are reflected in the set, and vice-versa. The set supports element removal, which removes the * corresponding row from this TabularDataSupport instance, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. * It does not support the add or addAll operations * * @return a set view of the keys used to index the rows of this TabularDataSupport instance */ public Set keySet() { return dataMap.keySet(); } /** * Returns a collection view of the rows contained in this TabularDataSupport instance. The collection is backed by the underlying map, * so changes to the TabularDataSupport instance are reflected in the collection, and vice-versa. The collection supports element removal, * which removes the corresponding index to row mapping from this TabularDataSupport instance, via the Iterator.remove, Collection.remove, removeAll, * retainAll, and clear operations. It does not support the add or addAll operations * * @return a collection view of the values contained in this TabularDataSupport instance. */ public Collection values() { return dataMap.values(); } /** * Returns a collection view of the index to row mappings contained in this TabularDataSupport instance. Each element in the returned collection is a Map.Entry. * The collection is backed by the underlying map of this TabularDataSupport instance, in so changes to the TabularDataSupport instance are reflected the collection, and vice-versa. * The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. * It does not support the add or addAll operations. *NOTE Do not use the SetValue method of Map.Entry elements contained in the returned collection view. * Doing so would corrupt the index to row mappings contained in this TabularDataSupport instance
* * @return a collection view of the mappings contained in this map */ public Set entrySet() { return dataMap.entrySet(); } /** * Returns a clone of this TabularDataSupport instance: the clone is obtained by calling super.clone(), * and then cloning the underlying map. Only a shallow clone of the underlying map is made, i.e. no cloning of the indexes and row values is made as they are immutable!! * * @return a copy of the TabularDataSupport */ public Object clone() { TabularDataSupport dataSupportClone = null; try { dataSupportClone = (TabularDataSupport)super.clone(); dataSupportClone.dataMap = (HashMap)((HashMap)dataMap).clone(); } catch (CloneNotSupportedException e) { // shouldn't happen return null; } return dataSupportClone; } /** * Compares the specified obj parameter with this TabularDataSupport instance for equality * * @return true if and only if all of the following statements are true: *Currently this class must be registered in the MBeanServer before any relations can be created or added
*/ public void isActive() throws RelationServiceNotRegisteredException { Logger logger = getLogger(); if (m_server == null) { logger.error("RelationService has not been registered in the MBeanServer"); throw new RelationServiceNotRegisteredException("Relation Service is not registered"); } } /** * @return true - if the purgeFlag has been set, false if updates of a relation must be called explicitly * @see #purgeRelations */ public boolean getPurgeFlag() { return m_purgeFlag; } /** * @param purgeFlag - a flag that when set to true indicates to theRelationService
that it must update all relations
* when it recieves a unregistration notification
* if false this will not occur and purgeRelations must be called explicitly
*/
public void setPurgeFlag(boolean purgeFlag)
{
m_purgeFlag = purgeFlag;
}
/**
* @param relationTypeName - a string giving relations a type name this must be a unique name
* @param roleInfos - an array of RoleInfo objects.
* Which are used to define the roles a relation plays a part in. It defines attributes
* such as cardinality, role reading and writing...
* The RelationService will then use these RoleInfo to maintain the relation
* @throws IllegalArgumentException - thrown if any of the parameters are null
* @throws InvalidRelationTypeException - thrown if the role name, contained in the RoleInfo, already exists.
*
* This method creates a relationType (a RelationTypeSupport Object) from the parameters passed in.
*The RelationTypeSupport represents an internal relation
*/ public void createRelationType(String relationTypeName, RoleInfo[] roleInfos) throws IllegalArgumentException, InvalidRelationTypeException { if (relationTypeName == null) throw new IllegalArgumentException("Illegal Null Relation Type Name value"); if (roleInfos == null) throw new IllegalArgumentException("Illegal Null RoleInfo"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Creating Relation Type with relationTypeName: " + relationTypeName); RelationTypeSupport relationType = new RelationTypeSupport(relationTypeName, roleInfos); // created a new RelationType add it to our map addRelationTypeToMap(relationTypeName, relationType); } /* Adds a relationTypeName as the key to a Map and the RelationType as the value */ private void addRelationTypeToMap(String relationTypeName, RelationType relationType) throws InvalidRelationTypeException { Logger logger = getLogger(); // synchronize all activities to map. synchronized (m_relationTypeNameToRelationTypeObject) { if ((m_relationTypeNameToRelationTypeObject.get(relationTypeName)) != null) { logger.warn("Cannot addRelationType as a relationType of the same name: " + relationTypeName + " already exists in the RelationService"); throw new InvalidRelationTypeException("RelationType with name: " + relationTypeName + " already exists in the RelationService"); } // set the RelationTypeSupport internal flag to true indicating that the relationType has been declared in the relation service if (relationType instanceof RelationTypeSupport) { ((RelationTypeSupport)relationType).setRelationServiceFlag(true); } // store the instance in the map m_relationTypeNameToRelationTypeObject.put(relationTypeName, relationType); } } /* returns the RelationType stored in the Map given the relationTypeName */ private RelationType getRelationType(String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException { RelationType relationType; synchronized (m_relationTypeNameToRelationTypeObject) { relationType = ((RelationType)(m_relationTypeNameToRelationTypeObject.get(relationTypeName))); // exception is caught by calling classes testing for RelationTypeNotFound. if (relationType == null) { throw new RelationTypeNotFoundException("No RelationType found for relationTypeName: " + relationTypeName); } return relationType; } } /** * @param relationType - an Object implementing the RelationType interface a utility implementation is provided by the *RelationTypeSupport
class
* @throws IllegalArgumentException if a null RelationType is passed in as a parameter or if that RelationType has no RoleInfo defined
* @throws InvalidRelationTypeException if the RoleInfo obtained from the RelationType is
* - empty
* - null
* - the RoleName is already in use
* This method makes an externally defined relation type available through the relationService
*The RelationType is immutable, hence the returned values should never change while the relationType is registered * with the realtion service
*/ public void addRelationType(RelationType relationType) throws IllegalArgumentException, InvalidRelationTypeException { if (relationType == null) throw new IllegalArgumentException("Relation Type should not be null."); // check type name String relationTypeName = relationType.getRelationTypeName(); if (relationTypeName == null) throw new IllegalArgumentException("RelationTypeName must not be null"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Adding a RelationType"); List roleInfoList = relationType.getRoleInfos(); if (roleInfoList == null) { logger.warn("Cannot add RelationType: " + relationType.getClass().getName() + " RoleInfo information was not provided with the RelationType."); throw new InvalidRelationTypeException("No RoleInfo provided with Relation Type"); } // build the roleInfo[] to validate the RoleInfo RoleInfo[] roleInfos = new RoleInfo[roleInfoList.size()]; int index = 0; for (Iterator i = roleInfoList.iterator(); i.hasNext();) { RoleInfo currentRoleInfo = (RoleInfo)i.next(); roleInfos[index] = currentRoleInfo; index++; } // need to validateRoleInfos before adding RelationTypeSupport.checkRoleInfos(roleInfos); // validated add the RelationType addRelationTypeToMap(relationTypeName, relationType); } /** * @return a list containing all the relationTypeNames registered with the relation service */ public List getAllRelationTypeNames() { List result; synchronized (m_relationTypeNameToRelationTypeObject) { result = new ArrayList(m_relationTypeNameToRelationTypeObject.keySet()); } // return all relationTypeNames or an empty list if none return result; } /** * @param relationTypeName - the string name representation of this RelationType * @return - List containing the RoleInfos for this RelationType Object * @throws IllegalArgumentException - if the relationTypeName is null * @throws RelationTypeNotFoundException - if the Relationtype for the given relationTypeName is not found */ public List getRoleInfos(String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException { if (relationTypeName == null) throw new IllegalArgumentException("Illegal relationType name is null."); RelationType relationType = getRelationType(relationTypeName); // returns a List of RoleInfo objects return relationType.getRoleInfos(); } /** * @param relationTypeName - string name representing the RelationType * @param roleInfoName - string name representing the RoleInfo object * @return - the corresponding RoleInfo Object for the given parameters * @throws IllegalArgumentException - if either the relationtypeName or the roleInfoName is null * @throws RelationTypeNotFoundException - if the RelationType is not in the realtion service * @throws RoleInfoNotFoundException - if the RoleInfo has not been found */ public RoleInfo getRoleInfo(String relationTypeName, String roleInfoName) throws IllegalArgumentException, RelationTypeNotFoundException, RoleInfoNotFoundException { if (relationTypeName == null) throw new IllegalArgumentException("Null relation type name"); if (roleInfoName == null) throw new IllegalArgumentException("Null RoleInfo name"); // gets the RelationType then gets the RoleInfo object return (getRelationType(relationTypeName).getRoleInfo(roleInfoName)); } /** * @param relationTypeName - a string name representing the Relationtype Object * @throws IllegalArgumentException - if the relationTypeName is null * @throws RelationServiceNotRegisteredException * - if the RelationService has not been registered in the MBeanServer * @throws RelationTypeNotFoundException - if the RelationType has not been found * *This method removes a RelationType, it's name(represented by the relationTypeName) and any relationIds associated with it, * and all MBeans referenced in it's roles
*Note: this will not remove any mbeans registered with the MBeanServer this must be done if required via the MBeanServer. * Any Mbeans registered with the MBean server will continue to be accessed via the MBeanServer, they will no longer be able to be * referenced, queried via the relation service though.
*/ public void removeRelationType(String relationTypeName) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationTypeNotFoundException { Logger logger = getLogger(); isActive(); if (relationTypeName == null) throw new IllegalArgumentException("Illegal: relationType name cannot be null."); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Removing RelationType with relationTypeName: " + relationTypeName); // will throw RelationTypeNotFoundException if not found getRelationType(relationTypeName); // no need to clone as relationIdList is internal and get its values from a private method. List relationIdList = getRelationIds(relationTypeName); removeRelationTypeObject(relationTypeName); removeRelationTypeName(relationTypeName); if (relationIdList != null) { for (Iterator i = relationIdList.iterator(); i.hasNext();) { String currentRelationId = (String)i.next(); try { // removed the relationType now remove the relation removeRelation(currentRelationId); } catch (RelationNotFoundException ex) { throw new RuntimeOperationsException(null, ex.toString()); } } } } private void removeRelationTypeObject(String relationTypeName) { synchronized (m_relationTypeNameToRelationTypeObject) { m_relationTypeNameToRelationTypeObject.remove(relationTypeName); } } private List getRelationIds(String relationTypeName) { synchronized (m_relationTypeNameToRelationIds) { return ((List)(m_relationTypeNameToRelationIds.get(relationTypeName))); } } /** * @param relationId - the id through which this relation is referenced * @param relationTypeName - a unique name for the RelationType * @param roleList - a list of roles to be associated with this relation * @throws IllegalArgumentException - if the relationId, or relationTypeName is null * @throws RelationServiceNotRegisteredException * - if the relationService has not been registered in the MBeanServer * @throws RoleNotFoundException - if a role defined in the RoleList is null or empty * @throws InvalidRelationIdException - if the relationId is already in use. * @throws RelationTypeNotFoundException - if the relationType is not found * @throws InvalidRoleValueException - if cardinality is not correct i.e min cardinality is greater than max cardinality * *According to the RI spec this method is used only to create internal relations - hence creates an InternalRelation
*This creates a relation represented by a RelationSupport Object, and a RelationNotification, * with type RELATION_BASIC_CREATION, is sent
*/ public void createRelation(String relationId, String relationTypeName, RoleList roleList) throws IllegalArgumentException, RelationServiceNotRegisteredException, RoleNotFoundException, InvalidRelationIdException, RelationTypeNotFoundException, InvalidRoleValueException { isActive(); if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); if (relationTypeName == null) throw new IllegalArgumentException("Null Relation Type Name"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) { logger.debug("Creating an InternalRelation with ID: " + relationId + " and relationType name: " + relationTypeName); } // creating InternalRelation to represent the internal relations InternalRelation internalRelation = new InternalRelation(relationId, m_relationServiceObjectName, relationTypeName, roleList); try { if (getRelationObject(relationId) != null) { logger.warn("There is a Relation already registered in the RelationServcie with ID: " + relationId); throw new InvalidRelationIdException("There is already a relation with id: " + relationId); } } catch (RelationNotFoundException ex) {/*Do nothing as should not be found*/ } RelationType relationType = getRelationType(relationTypeName); ArrayList roleInfoList = (ArrayList)(buildRoleInfoList(relationType, roleList)); if (!(roleInfoList.isEmpty())) { initializeMissingCreateRoles(roleInfoList, internalRelation, relationId, relationTypeName); } synchronized (m_relationIdToRelationObject) { m_relationIdToRelationObject.put(relationId, internalRelation); } addRelationId(relationId, relationTypeName); addRelationTypeName(relationId, relationTypeName); updateRoles(roleList, relationId); try { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("sending RelationCreation notification to all listeners"); sendRelationCreationNotification(relationId); } catch (RelationNotFoundException ex) { throw new RuntimeOperationsException(null, "Unable to send notification as Relation not found"); } } /* updates roles given the roleList and the relationId */ private void updateRoles(RoleList roleList, String relationId) throws RelationServiceNotRegisteredException, IllegalArgumentException { if (roleList == null) throw new IllegalArgumentException("Null RoleList"); if (relationId == null) throw new IllegalArgumentException("Null relationId"); for (Iterator i = roleList.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); ArrayList tempList = new ArrayList(); try { updateRoleMap(relationId, currentRole, tempList); } catch (RelationNotFoundException ex) { throw new RuntimeOperationsException(null, "Cannot update the roleMap as Relation not found"); } } } private List buildRoleInfoList(RelationType relationType, List roleList) throws InvalidRoleValueException, RoleNotFoundException { List roleInfoList = relationType.getRoleInfos(); if (roleList != null) { for (Iterator i = roleList.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); String currentRoleName = currentRole.getRoleName(); List currentRoleValue = currentRole.getRoleValue(); RoleInfo roleInfo; try { roleInfo = relationType.getRoleInfo(currentRoleName); } catch (RoleInfoNotFoundException ex) { throw new RoleNotFoundException(ex.getMessage()); } int problemType = (checkRoleCardinality(currentRoleName, currentRoleValue, roleInfo)).intValue(); if (problemType != 0) { throwRoleProblemException(problemType, currentRoleName); } roleInfoList.remove(roleInfoList.indexOf(roleInfo)); } } return roleInfoList; } private void addRelationTypeName(String relationId, String relationTypeName) { synchronized (m_relationTypeNameToRelationIds) { ArrayList idList = (ArrayList)m_relationTypeNameToRelationIds.get(relationTypeName); boolean isNewRelation = false; if (idList == null) { isNewRelation = true; idList = new ArrayList(); } idList.add(relationId); if (isNewRelation) m_relationTypeNameToRelationIds.put(relationTypeName, idList); } } private void addRelationObjectName(String relationId, ObjectName relationObjectName) { synchronized (m_relationIdToRelationObject) { m_relationIdToRelationObject.put(relationId, relationObjectName); } } private void addRelationId(String relationId, String relationTypeName) { synchronized (m_relationIdToRelationTypeName) { m_relationIdToRelationTypeName.put(relationId, relationTypeName); } } // method gets called only for internal relations private void initializeMissingCreateRoles(List roleInfoList, InternalRelation internalRelation, String relationId, String relationTypeName) throws RelationTypeNotFoundException, RelationServiceNotRegisteredException, InvalidRoleValueException, RoleNotFoundException, IllegalArgumentException { isActive(); if (roleInfoList == null) throw new IllegalArgumentException("RoleInfoList is Null"); if (relationId == null) throw new IllegalArgumentException("RelationId is Null."); if (relationTypeName == null) throw new IllegalArgumentException("Relation Type Name is Null."); for (Iterator i = roleInfoList.iterator(); i.hasNext();) { RoleInfo currentRoleInfo = (RoleInfo)i.next(); String roleName = currentRoleInfo.getName(); ArrayList temp = new ArrayList(); Role role = new Role(roleName, temp); try { internalRelation.setRole(role); } catch (RelationNotFoundException ex) { throw new RuntimeOperationsException(null, ex.getMessage()); } } } private Integer checkRoleCardinality(String roleName, List roleValue, RoleInfo roleInfo) { if (roleName == null) throw new IllegalArgumentException("Null Role Name"); if (roleValue == null) throw new IllegalArgumentException("Null roleValue List"); if (roleInfo == null) throw new IllegalArgumentException("Null RoleInfo"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("checking role cardinality"); if (!(roleName.equals(roleInfo.getName()))) { logger.warn("Role does not have a valid roleName"); return new Integer(RoleStatus.NO_ROLE_WITH_NAME); } if (!(roleInfo.checkMinDegree(roleValue.size()))) { logger.warn("Minimum number of references defined in the RoleInfo has fallen below minimum"); return (new Integer(RoleStatus.LESS_THAN_MIN_ROLE_DEGREE)); } if (!(roleInfo.checkMaxDegree(roleValue.size()))) { logger.warn("Maximum number of references defined in the RoleInfo has gone above the maximum"); return new Integer(RoleStatus.MORE_THAN_MAX_ROLE_DEGREE); } String referencedClassName = roleInfo.getRefMBeanClassName(); for (Iterator i = roleValue.iterator(); i.hasNext();) { ObjectName currentObjectName = (ObjectName)i.next(); if (currentObjectName == null) { logger.warn("The mbean with RoleName: " + roleName + " is not registered in the MBeanServer"); return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED); } if (!(m_server.isRegistered(currentObjectName))) { logger.warn("The mbean with ObjectName: " + currentObjectName.getCanonicalName() + " is not registered in the MBeanServer"); return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED); } try { if (!(m_server.isInstanceOf(currentObjectName, referencedClassName))) { logger.warn("The class referenced: " + currentObjectName.toString() + " does not match the class expected: " + referencedClassName + " in RoleInfo: " + roleInfo.toString()); return new Integer(RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS); } } catch (InstanceNotFoundException ex) { return null; } } return new Integer(0); } /** * @param relationMBeanObjectName - ObjectName of the relation MBean to be added * @throws IllegalArgumentException - if parameter is null * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered in the MBean Server * @throws NoSuchMethodException - If the MBean does not implement the Relation interface * @throws InvalidRelationIdException - if there is no relation identifier (ID) in the MBean * - if relation identifier (ID) is already used in the Relation Service * @throws InstanceNotFoundException - if the MBean for given ObjectName has not been registered * @throws InvalidRelationServiceException * - if no Relation Service name in MBean * - if the Relation Service name in the MBean is not the one of the current Relation Service * @throws RelationTypeNotFoundException - if no relation type name in MBean * - if the relation type name in MBean does not correspond to a relation type created in the Relation Service * @throws RoleNotFoundException - if a value is provided for a role that does not exist in the relation type * @throws InvalidRoleValueException - if the number of referenced MBeans in a role is less than expected minimum degree * - if the number of referenced MBeans in a role exceeds expected maximum degree * - if one referenced MBean in the value is not an Object of the MBean class expected for that role * - if an MBean provided for a role does not exist * *Adds an MBean created by the user (and registered by him in the MBean Server) as a relation in the Relation Service
*To be added as a relation, the MBean must conform to the following: *
If the relation is represented by an MBean (created by the user and added as a relation in the Relation Service), * returns the ObjectName of the MBean
*/ public ObjectName isRelationMBean(String relationId) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id."); Object result = getRelationObject(relationId); if (result instanceof ObjectName) { return ((ObjectName)result); } return null; } /** *Returns the relation id associated to the given ObjectName if the MBean has been added as a relation in the Relation Service
* * @param objectName - the ObjectName of supposed relation * @return - the relation id (String) or null (if the ObjectName is not a relation handled by the Relation Service) * @throws IllegalArgumentException - if the parameter is null */ public String isRelation(ObjectName objectName) throws IllegalArgumentException { if (objectName == null) throw new IllegalArgumentException("Null ObjectName"); return (getMBeanObjectName(objectName)); } /** *Checks if there is a relation identified in Relation Service with given relation id.
* * @param relationId - the relation id identifying the relation * @return boolean: true if there is a relation, false otherwise * @throws IllegalArgumentException - if parameter is null */ public Boolean hasRelation(String relationId) throws IllegalArgumentException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); Boolean hasRelation = null; try { Object result = getRelationObject(relationId); if (result != null) hasRelation = Boolean.TRUE; } catch (RelationNotFoundException ex) { hasRelation = Boolean.FALSE; } return hasRelation; } /** *Returns all the relation ids for all the relations handled by the Relation Service
* * @return an arrayList containing the relation ids */ public List getAllRelationIds() { synchronized (m_relationIdToRelationObject) { return (new ArrayList(m_relationIdToRelationObject.keySet())); } } /** *Checks if given Role can be read in a relation of the given type
* * @param roleName - name of role to be checked * @param relationTypeName - name of the relation type * @return - an Integer wrapping an integer corresponding to possible problems represented as constants in RoleUnresolved: *Checks if given Role can be set in a relation of given type
* * @param role - role to be checked * @param relationTypeName - name of relation type * @param isInitialized - flag to specify that the checking is done for the initialization of a role, write access shall not be verified * @return - an Integer wrapping an integer corresponding to possible problems represented as constants in RoleUnresolved: *Sends a notification (RelationNotification) for a relation creation. The notification type is: *
Sends a notification (RelationNotification) for a role update in the given relation. The notification type is: *
The source object is the Relation Service itself.
*This method is called in relation MBean setRole() (for given role) and setRoles() (for each role) methods * (implementation provided in RelationSupport class)
*It is also called in Relation Service setRole() (for given role) and setRoles() (for each role) methods
* * @param relationId - the relation identifier of the updated relation * @param newRole - new role (name and new value) * @param oldRoleValues - old role value (ArrayList of ObjectName objects) * @throws IllegalArgumentException - if null parameter * @throws RelationNotFoundException - if there is no relation for given relation id */ public void sendRoleUpdateNotification(String relationId, Role newRole, List oldRoleValues) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null RelationId"); if (newRole == null) throw new IllegalArgumentException("Null Role"); if (oldRoleValues == null) throw new IllegalArgumentException("Null List of role values"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending a roleUpdateNotification of Relation with ID: " + relationId); String roleName = newRole.getRoleName(); List newRoleValues = newRole.getRoleValue(); String newRoleValueMessage = Role.roleValueToString(newRoleValues); String oldRoleValueMessage = Role.roleValueToString(oldRoleValues); StringBuffer message = new StringBuffer("Value of the role "); message.append(roleName); message.append(" has changed\nOld value:\n"); message.append(oldRoleValueMessage); message.append("\nNew value:\n"); message.append(newRoleValueMessage); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification message: " + message.toString()); String relationTypeName = getRelationTypeNameFromMap(relationId); // determine if this is a relation update or a relation mbean update ObjectName relationObjectName = isRelationMBean(relationId); String notificationType; if (relationObjectName != null) notificationType = RelationNotification.RELATION_MBEAN_UPDATE; else notificationType = RelationNotification.RELATION_BASIC_UPDATE; long sequenceNumber = getNotificationSequenceNumber().longValue(); Date currentDate = new Date(); long timeStamp = currentDate.getTime(); RelationNotification notification = new RelationNotification(notificationType, this, sequenceNumber, timeStamp, message.toString(), relationId, relationTypeName, relationObjectName, roleName, newRoleValues, oldRoleValues); sendNotification(notification); } /** *Sends a notification (RelationNotification) for a relation removal. The notification type is: *
It is called in Relation Service removeRelation() method
* * @param relationId - relation identifier of the updated relation * @param unregisteredMBeanList - ArrayList of ObjectNames of MBeans expected to be unregistered due to relation removal (can be null) * @throws IllegalArgumentException - if relationId is null * @throws RelationNotFoundException - if there is no relation for given relation id */ public void sendRelationRemovalNotification(String relationId, List unregisteredMBeanList) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null RelationId"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("sending relationRemovalNotification of ID: " + relationId); StringBuffer message = new StringBuffer("Removal of relation "); message.append(relationId); String relationTypeName = getRelationTypeNameFromMap(relationId); ObjectName relationObjectName = isRelationMBean(relationId); String notificationType; if (relationObjectName != null) notificationType = RelationNotification.RELATION_MBEAN_REMOVAL; else notificationType = RelationNotification.RELATION_BASIC_REMOVAL; long sequenceNumber = getNotificationSequenceNumber().longValue(); Date currentDate = new Date(); long timeStamp = currentDate.getTime(); RelationNotification notification = new RelationNotification(notificationType, this, sequenceNumber, timeStamp, message.toString(), relationId, relationTypeName, relationObjectName, unregisteredMBeanList); sendNotification(notification); } /** *Handles update of the Relation Service role map for the update of given role in given relation
*It is called in relation MBean setRole() (for given role) and setRoles()(for each role) methods * (implementation provided in RelationSupport class).
*It is also called in Relation Service setRole() (for given role) and setRoles() (for each role) methods.
*To allow the Relation Service to maintain the consistency (in case of MBean unregistration) and to be able to * perform queries, this method must be called when a role is updated.
* * @param relationId - relation identifier of the updated relation * @param role - new role (name and new value) * @param oldRoleValues - old role value (ArrayList of ObjectName objects) * @throws IllegalArgumentException - if null parameter * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered in the MBean Server * @throws RelationNotFoundException - if no relation for given id */ public void updateRoleMap(String relationId, Role role, List oldRoleValues) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException { isActive(); if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); if (role == null) throw new IllegalArgumentException("Null Role"); if (oldRoleValues == null) throw new IllegalArgumentException("Null Role value list."); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Updating the RelationService RoleMap"); String roleName = role.getRoleName(); List newRoleValue = role.getRoleValue(); // clone as the list is to be modified later, cast to ArrayList as List does not define clone() List oldValues = (ArrayList)(((ArrayList)oldRoleValues).clone()); // List of ObjectNames of new referenced MBeans List newReferenceList = new ArrayList(); for (Iterator i = newRoleValue.iterator(); i.hasNext();) { ObjectName currentObjectName = (ObjectName)i.next(); // Check if this ObjectName was already present in oldValueList int currentObjectNamePosition = oldValues.indexOf(currentObjectName); // we have a new Reference if (currentObjectNamePosition == -1) { // returns true if we have a new reference, false if the MBean is already referenced if (addNewMBeanReference(currentObjectName, relationId, roleName)) { // add to new references list newReferenceList.add(currentObjectName); } } else { // MBean referenced in an old value remove oldValues.remove(currentObjectNamePosition); } } List obsoleteReferenceList = getObsoleteReferenceList(oldValues, relationId, roleName); // update listeners as to the new references updateUnregistrationListener(newReferenceList, obsoleteReferenceList); } private List getObsoleteReferenceList(List oldValues, String relationId, String roleName) throws IllegalArgumentException { List obsoleteReferenceList = new ArrayList(); for (Iterator i = oldValues.iterator(); i.hasNext();) { ObjectName currentObjectName = (ObjectName)i.next(); if (removeMBeanReference(currentObjectName, relationId, roleName)) { obsoleteReferenceList.add(currentObjectName); } } return obsoleteReferenceList; } private boolean removeMBeanReference(ObjectName objectName, String relationId, String roleName) throws IllegalArgumentException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); if (objectName == null) throw new IllegalArgumentException("Null ObjectName"); if (roleName == null) throw new IllegalArgumentException("Null Role Name."); // first check if we have any references for MBean HashMap mbeanReferenceMap = (HashMap)getReferencedMBeansFromMap(objectName); // no references nothing to remove if (mbeanReferenceMap == null) return true; // we have references get the roleNames for the relationId ArrayList roleNames = (ArrayList)(mbeanReferenceMap.get(relationId)); //check the roleNames is not null before removing if (roleNames != null) { // roleName found remove it if (roleNames.indexOf(roleName) != -1) roleNames.remove(roleNames.indexOf(roleName)); // no more references remove the relationId key if (roleNames.isEmpty()) mbeanReferenceMap.remove(relationId); } if (mbeanReferenceMap.isEmpty()) { // now we can remove the MBean ObejctName with all references removed removeObjectName(objectName); return true; } return false; } private Map getReferencedMBeansFromMap(ObjectName objectName) { synchronized (m_referencedMBeanObjectNameToRelationIds) { return ((HashMap)m_referencedMBeanObjectNameToRelationIds.get(objectName)); } } private boolean addNewMBeanReference(ObjectName objectName, String relationId, String roleName) throws IllegalArgumentException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); if (roleName == null) throw new IllegalArgumentException("Null Role Name"); if (objectName == null) throw new IllegalArgumentException("Null ObjectName."); // get the ObjectNames of the referenced ObjectName HashMap mbeanReferenceMap; synchronized (m_referencedMBeanObjectNameToRelationIds) { mbeanReferenceMap = ((HashMap)m_referencedMBeanObjectNameToRelationIds.get(objectName)); } // it is null, add it to our map and return true - we have a new reference if (mbeanReferenceMap == null) { mbeanReferenceMap = new HashMap(); } List roleNames = (List) mbeanReferenceMap.get(relationId); if (roleNames == null) { roleNames = new ArrayList(); roleNames.add(roleName); mbeanReferenceMap.put(relationId, roleNames); addObjectNameToMBeanReference(objectName, mbeanReferenceMap); return true; } else { roleNames.add(roleName); addObjectNameToMBeanReference(objectName, mbeanReferenceMap); // not a new MBeanReference return false return false; } } private void addObjectNameToMBeanReference(ObjectName objectName, HashMap mbeanReferenceMap) { // get the mapfirst, then update it synchronized (m_referencedMBeanObjectNameToRelationIds) { Map temp = (Map)m_referencedMBeanObjectNameToRelationIds.get(objectName); if (temp != null) { mbeanReferenceMap.putAll(temp); } m_referencedMBeanObjectNameToRelationIds.put(objectName, mbeanReferenceMap); } } /** *Removes given relation from the Relation Service.
*A RelationNotification notification is sent, its type being: *
For MBeans referenced in such relation, nothing will be done
* * @param relationId - relation id of the relation to be removed * @throws IllegalArgumentException - if null parameter * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered in the MBean Server * @throws RelationNotFoundException - if no relation corresponding to given relation id */ public void removeRelation(String relationId) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException { isActive(); if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Removing a Relation from the RelationService."); Object result = getRelationObject(relationId); if (result instanceof ObjectName) { // add the objectName to List List obsoleteReferences = new ArrayList(); obsoleteReferences.add(result); // update Listener with the list of ObjectNames to be deregistered updateUnregistrationListener(null, obsoleteReferences); } // notify all listeners a relation has been removed sendRelationRemovalNotification(relationId, null); List nonReferencedObjectNameList = getNonReferencedMBeans(relationId); // remove ObjectNames from global Map removeNonReferencedMBeans(nonReferencedObjectNameList); // remove relationId for our nonReferencedMBeans removeRelationId(relationId); // we have an MBean remove it from our Map if (result instanceof ObjectName) removeRelationMBean((ObjectName)result); // get the corresponding relationTypeName for the relationId String relationTypeName = getRelationTypeNameFromMap(relationId); // remove relationId from our Map removeRelationIdToRelationTypeName(relationId); // get all the corresponding relationIds List relationIdsList = getRelationIds(relationTypeName); // we have relationIds for the removed relationTypeName remove them from our Map if (relationIdsList != null) { relationIdsList.remove(relationId); if (relationIdsList.isEmpty()) { // now we can remove the relationTypeName removeRelationTypeName(relationTypeName); } } } private void removeRelationMBean(ObjectName objectName) { synchronized (m_relationMBeanObjectNameToRelationId) { m_relationMBeanObjectNameToRelationId.remove(objectName); } } private void removeNonReferencedMBeans(List nonReferencedMBeansList) { synchronized (m_referencedMBeanObjectNameToRelationIds) { for (Iterator i = nonReferencedMBeansList.iterator(); i.hasNext();) { ObjectName currentObjectName = (ObjectName)i.next(); m_referencedMBeanObjectNameToRelationIds.remove(currentObjectName); } } } private List getNonReferencedMBeans(String relationId) { List referencedMBeanList = new ArrayList(); List nonReferencedObjectNameList = new ArrayList(); synchronized (m_referencedMBeanObjectNameToRelationIds) { for (Iterator i = (m_referencedMBeanObjectNameToRelationIds.keySet()).iterator(); i.hasNext();) { ObjectName currentObjectName = (ObjectName)i.next(); HashMap relationIdMap = (HashMap)(m_referencedMBeanObjectNameToRelationIds.get(currentObjectName)); if (relationIdMap.containsKey(relationId)) { relationIdMap.remove(relationId); referencedMBeanList.add(currentObjectName); } if (relationIdMap.isEmpty()) nonReferencedObjectNameList.add(currentObjectName); } } return nonReferencedObjectNameList; } private void removeRelationTypeName(String relationTypeName) { synchronized (m_relationTypeNameToRelationIds) { m_relationTypeNameToRelationIds.remove(relationTypeName); } } private String getRelationTypeNameFromMap(String relationId) { synchronized (m_relationIdToRelationTypeName) { return ((String)m_relationIdToRelationTypeName.get(relationId)); } } private void removeRelationIdToRelationTypeName(String relationId) { synchronized (m_relationIdToRelationTypeName) { m_relationIdToRelationTypeName.remove(relationId); } } private String getMBeanObjectName(ObjectName objectName) { synchronized (m_relationMBeanObjectNameToRelationId) { return ((String)m_relationMBeanObjectNameToRelationId.get(objectName)); } } private void removeRelationId(String relationId) { synchronized (m_relationIdToRelationObject) { m_relationIdToRelationObject.remove(relationId); } } private void updateUnregistrationListener(List newReferenceList, List obsoleteReferences) throws RelationServiceNotRegisteredException { if (newReferenceList != null && obsoleteReferences != null) { // nothing to do if (newReferenceList.isEmpty() && obsoleteReferences.isEmpty()) return; } isActive(); if (newReferenceList != null || obsoleteReferences != null) { boolean isNewListener = false; if (m_notificationFilter == null) { m_notificationFilter = new MBeanServerNotificationFilter(); isNewListener = true; } synchronized (m_notificationFilter) { // we have new references - update (Enable in NotificationFilter) if (newReferenceList != null) updateNewReferences(newReferenceList); // we have obsolete references - update (disable from notificationFilter) if (obsoleteReferences != null) updateObsoleteReferences(obsoleteReferences); ObjectName mbeanServerDelegateName = null; try { mbeanServerDelegateName = new ObjectName("JMImplementation:type=MBeanServerDelegate"); } catch (MalformedObjectNameException ignored) { } if (isNewListener) { try { m_server.addNotificationListener(mbeanServerDelegateName, this, m_notificationFilter, null); } catch (InstanceNotFoundException ex) { throw new RelationServiceNotRegisteredException(ex.getMessage()); } } } } } private void updateObsoleteReferences(List obsoleteReferences) { for (Iterator i = obsoleteReferences.iterator(); i.hasNext();) { ObjectName name = (ObjectName)i.next(); m_notificationFilter.disableObjectName(name); } } private void updateNewReferences(List newReferencesList) { for (Iterator i = newReferencesList.iterator(); i.hasNext();) { ObjectName name = (ObjectName)i.next(); m_notificationFilter.enableObjectName(name); } } // if null we have an instance of the internalRelation otherwise we have an MBean and can use the proxy private Relation getRelation(String relationId) throws RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null relation id passed into getRelation."); Relation relation; // if this is null we have a Relation not an ObjectName so we can return the Relation if (isRelationMBean(relationId) == null) { synchronized (m_relationIdToRelationObject) { relation = (Relation)m_relationIdToRelationObject.get(relationId); return relation; } } final ObjectName relationObjectName = (ObjectName)m_relationIdToRelationObject.get(relationId); // oops no relation at all if (relationObjectName == null) { throw new RelationNotFoundException("Relation not found with ID: " + relationId); } // good we have a relation lets return the proxy m_proxy = (RelationSupportMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, relationObjectName, RelationSupportMBean.class, false); return m_proxy; } // will return an ObjectName or a Relation object private Object getRelationObject(String relationId) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); Object relationObject; synchronized (m_relationIdToRelationObject) { relationObject = m_relationIdToRelationObject.get(relationId); if (relationObject == null) { // if this happens is caught by method looking for a null. throw new RelationNotFoundException("Null Relation"); } // we return either an ObjectName or an InternalRelation return relationObject; } } /** *Purges the relations
* *Depending on the purgeFlag value, this method is either called automatically when a notification is received for the * unregistration of an MBean referenced in a relation (if the flag is set to true), or not (if the flag is set to false).
* *In that case it is up to the user to call it to maintain the consistency of the relations. To be kept in mind that if an MBean is * unregistered and the purge not done immediately, if the ObjectName is reused and assigned to another MBean referenced in a relation, * calling manually this purgeRelations() method will cause trouble, as will consider the ObjectName as corresponding to the unregistered MBean, * not seeing the new one.
* * *Retrieves the relations where a given MBean is referenced.
* * @param mbeanObjectName - ObjectName of MBean * @param relationTypeName - can be null; if specified, only the relations of that type will be considered in the search. Else all relation types are considered. * @param roleName - can be null; if specified, only the relations where the MBean is referenced in that role will be returned. Else all roles are considered. * @return - HashMap, where the keys are the relation ids of the relations where the MBean is referenced, and the value is, for each key, * an ArrayList of role names (as an MBean can be referenced in several roles in the same relation). * @throws IllegalArgumentException - if mbeanObjectName is null */ public Map findReferencingRelations(ObjectName mbeanObjectName, String relationTypeName, String roleName) throws IllegalArgumentException { if (mbeanObjectName == null) throw new IllegalArgumentException("Cannot find references for a null ObjectName"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("finding referencing relations for MBean with ObjectName: " + mbeanObjectName.getCanonicalName() + " and relationTypeName: " + relationTypeName + " and roleName: " + roleName); HashMap result = new HashMap(); HashMap relationIdMap = (HashMap)getReferencedMBeansFromMap(mbeanObjectName); if (relationIdMap != null) { Set allRelationIds = relationIdMap.keySet(); List relationIdList; if (relationTypeName == null) { relationIdList = new ArrayList(allRelationIds); } else { relationIdList = findReferencesFromIds(allRelationIds, relationTypeName); } for (Iterator i = relationIdList.iterator(); i.hasNext();) { String currentRelationId = (String)i.next(); ArrayList currentRoleNameList = (ArrayList)relationIdMap.get(currentRelationId); if (roleName == null) { result.put(currentRelationId, currentRoleNameList.clone()); } else if (currentRoleNameList.contains(roleName)) { ArrayList roleNameList = new ArrayList(); roleNameList.add(roleName); result.put(currentRelationId, roleNameList); } } } return result; } private ArrayList findReferencesFromIds(Set allRelationIds, String relationTypeName) { ArrayList relationIdList = new ArrayList(); for (Iterator i = allRelationIds.iterator(); i.hasNext();) { String currentRelationId = (String)i.next(); String currentRelationTypeName = getRelationTypeNameFromMap(currentRelationId); if (currentRelationTypeName.equals(relationTypeName)) { relationIdList.add(currentRelationId); } } return relationIdList; } /** *Retrieves the MBeans associated to given one in a relation.
* * @param mbeanObjectName - ObjectName of MBean * @param relationTypeName - can be null; if specified, only the relations of that type will be considered in the search. Else all relation types are considered * @param roleName - can be null; if specified, only the relations where the MBean is referenced in that role will be considered. Else all roles are considered. * @return - HashMap, where the keys are the ObjectNames of the MBeans associated to given MBean, and the value is, for each key, an ArrayList of the * relation ids of the relations where the key MBean is associated to given one (as they can be associated in * several different relations). * @throws IllegalArgumentException - if mbeanObjectName is null */ public Map findAssociatedMBeans(ObjectName mbeanObjectName, String relationTypeName, String roleName) throws IllegalArgumentException { if (mbeanObjectName == null) throw new IllegalArgumentException("mbean ObjectName cannot be null."); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("finding associated relations for MBean with ObjectName: " + mbeanObjectName.getCanonicalName() + " and relationTypeName: " + relationTypeName + " and roleName: " + roleName); Map relationIdsToRoleNames = findReferencingRelations(mbeanObjectName, relationTypeName, roleName); Map result = new HashMap(); for (Iterator i = (relationIdsToRoleNames.keySet()).iterator(); i.hasNext();) { String currentRelationId = (String)i.next(); HashMap objectNamesToRoleMap; try { objectNamesToRoleMap = (HashMap)(getReferencedMBeans(currentRelationId)); } catch (RelationNotFoundException ex) { logger.warn("Relation with ID: " + currentRelationId + " not found."); throw new RuntimeOperationsException(null, "Relation Not Found"); } for (Iterator iter = (objectNamesToRoleMap.keySet()).iterator(); iter.hasNext();) { ObjectName objectName = (ObjectName)iter.next(); if (!(objectName.equals(mbeanObjectName))) { ArrayList currentRelationIdList = (ArrayList) result.get(objectName); if (currentRelationIdList == null) { currentRelationIdList = new ArrayList(); result.put(objectName, currentRelationIdList); } currentRelationIdList.add(currentRelationId); } } } return result; } /** *Returns the relation ids for relations of the given type.
* * @param relationTypeName - relation type name * @return - arrayList of relationIds * @throws IllegalArgumentException - if relationTypeName is null * @throws RelationTypeNotFoundException - if there is no relation type with that name */ public List findRelationsOfType(String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException { if (relationTypeName == null) throw new IllegalArgumentException("relation type name cannot be null."); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("finding relations matching relationTypeName: " + relationTypeName); // throws RelationTypeNotFoundException if not found getRelationType(relationTypeName); List relationIdList = getRelationIds(relationTypeName); if (relationIdList == null) return new ArrayList(); return new ArrayList(relationIdList); } /** *Retrieves role value for given role name in given relation
* * @param relationId - the relation identifier * @param roleName - the name of the role * @return - an ArrayList of ObjectName objects being the role value * @throws IllegalArgumentException - if null parameter * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered * @throws RelationNotFoundException - if no relation with given id * @throws RoleNotFoundException - if there is no role with given name or * the role is not readable */ public List getRole(String relationId, String roleName) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException, RoleNotFoundException { isActive(); if (relationId == null) throw new IllegalArgumentException("RelationId cannot have a null value."); if (roleName == null) throw new IllegalArgumentException("Role Name cannot have a null value."); Relation relationObject = getRelation(relationId); return relationObject.getRole(roleName); } /** *Retrieves values of roles with given names in given relation
* * @param relationId - the relation identifier * @param roleNames - array of names of roles to be retrieved * @return - a RoleResult object, including a RoleList (for roles succcessfully retrieved) and a RoleUnresolvedList (for roles not retrieved). * @throws IllegalArgumentException - if either parameter is null * @throws RelationNotFoundException - if no relation with given id * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered in the MBean Server */ public RoleResult getRoles(String relationId, String[] roleNames) throws IllegalArgumentException, RelationNotFoundException, RelationServiceNotRegisteredException { if (relationId == null) throw new IllegalArgumentException("Illegal Argument relationId is null."); if (roleNames == null) throw new IllegalArgumentException("Array of Roles Names should not be null"); isActive(); Relation relation = getRelation(relationId); return relation.getRoles(roleNames); } /** *Returns all roles present in the relation
* * @param relationId - the relation identifier * @return - a RoleResult object, including a RoleList (for roles succcessfully retrieved) and a RoleUnresolvedList (for roles not readable). * @throws IllegalArgumentException - if the relation id is null * @throws RelationNotFoundException - if no relation for given id * @throws RelationServiceNotRegisteredException * - if the Relation Service is not registered in the MBean Server */ public RoleResult getAllRoles(String relationId) throws IllegalArgumentException, RelationNotFoundException, RelationServiceNotRegisteredException { if (relationId == null) throw new IllegalArgumentException("RelationId cannot be null"); //Object relationObject = getRelationObject(relationId); Relation relation = getRelation(relationId); return relation.getAllRoles(); } /** *Retrieves the number of MBeans currently referenced in the given role.
* * @param relationId - relation id * @param roleName - name of role * @return - the number of currently referenced MBeans in that role * @throws IllegalArgumentException - if a null parameter * @throws RelationNotFoundException - if no relation with given id * @throws RoleNotFoundException - if there is no role with given name */ public Integer getRoleCardinality(String relationId, String roleName) throws IllegalArgumentException, RelationNotFoundException, RoleNotFoundException { if (relationId == null) throw new IllegalArgumentException("Relation Id is null."); if (roleName == null) throw new IllegalArgumentException("Role Name is null."); Object relationObject = getRelationObject(relationId); if (relationObject instanceof InternalRelation) return (((InternalRelation)relationObject).getRoleCardinality(roleName)); else return m_proxy.getRoleCardinality(roleName); } /** *Sets the given role in given relation
*Will check the role according to its corresponding role definition provided in relation's relation type
*The Relation Service will keep track of the change to keep the consistency of relations by handling referenced MBean unregistrations
* * @param relationId - the relation identifier * @param role - role to be set (name and new value) * @throws IllegalArgumentException - if null parameter * @throws RelationServiceNotRegisteredException * - if relation service is not registered in the MBean Server * @throws RelationNotFoundException - if no relation with given id * @throws RoleNotFoundException - if the role does not exist or is not writable * @throws InvalidRoleValueException - if value provided for role is not valid i.e. *Sets the given roles in given relation
*Will check the role according to its corresponding role definition provided in relation's relation type
*The Relation Service keeps track of the changes to keep the consistency of relations by handling referenced MBean unregistrations
* * @param relationId - the relation identifier * @param roleList - the list of roles to be set * @return - RoleResult object, including a RoleList(for roles succcessfully set) and a RoleUnresolvedList(for roles not set). * @throws RelationServiceNotRegisteredException * - if the realtionService has not been registered in the mbean server * @throws IllegalArgumentException - if any of the parameters are null * @throws RelationNotFoundException - if no relation for the given id has been found */ public RoleResult setRoles(String relationId, RoleList roleList) throws RelationServiceNotRegisteredException, IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Relation Id is null"); if (roleList == null) throw new IllegalArgumentException("RoleList is null"); isActive(); Relation relation = getRelation(relationId); try { return relation.setRoles(roleList); } catch (RelationTypeNotFoundException ex) { throw new RuntimeOperationsException(null, "Unable to find a RelationTypeName for relation ID: " + relationId); } } /** *Retrieves MBeans referenced in the various roles of the relation
* * @param relationId - the relation identifier * @return - a hashMap mapping as key the MBean ObjectName and an arrayList of String roleNames. * @throws IllegalArgumentException - if relation id is null * @throws RelationNotFoundException - if no relation for given relation id */ public Map getReferencedMBeans(String relationId) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("getting MBeans referenced for ID: " + relationId); Relation relation = getRelation(relationId); return relation.getReferencedMBeans(); } /** *Returns name of associated relation type for given relation
* * @param relationId - the relation identifier * @return - the name of the associated relation type * @throws IllegalArgumentException - if null parameter * @throws RelationNotFoundException - if no relation for given relation id */ public String getRelationTypeName(String relationId) throws IllegalArgumentException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null Relation Id"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("getting the relationType for ID: " + relationId); Relation relation = getRelation(relationId); return relation.getRelationTypeName(); } /** *Invoked when a JMX notification occurs. Currently handles notifications for unregistration of MBeans, * either referenced in a relation role or being a relation itself.
* * @param notification - the notification needs to be of type MBeanServerNotification * @param handback - An opaque object which helps the listener to associate information regarding the MBean emitter (can be null). */ public void handleNotification(Notification notification, Object handback) { if (notification == null) throw new IllegalArgumentException("Null Notification"); if (notification instanceof MBeanServerNotification) { String notificationType = notification.getType(); if (notificationType.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) { ObjectName mbeanName = ((MBeanServerNotification)notification).getMBeanName(); // handle unregistration by purging relations handleUnregistration(notification, mbeanName); // remove mbeans now handleMBeanRemoval(mbeanName); } } } private void handleMBeanRemoval(ObjectName mbeanName) { String relationId = getMBeanObjectName(mbeanName); if (relationId != null) { try { // we have a relationId now removeRelation removeRelation(relationId); } catch (Exception ex) { throw new RuntimeOperationsException(null, ex.getMessage()); } } } private void handleUnregistration(Notification notification, ObjectName objectName) { boolean isReferenced = false; synchronized (m_referencedMBeanObjectNameToRelationIds) { // check the mbeanObjectName can be found if (m_referencedMBeanObjectNameToRelationIds.containsKey(objectName)) { // it does so add it to our list of deregistrations synchronized (m_deregisteredNotificationList) { m_deregisteredNotificationList.add(notification); } isReferenced = true; } if (isReferenced && m_purgeFlag) { try { // purge the RelationService purgeRelations(); } catch (Exception ex) { throw new RuntimeOperationsException(null, ex.getMessage()); } } } } /** *Returns a NotificationInfo object containing the name of the Java class of the notification and the notification types sent
* * @return - the array of possible notifications */ public MBeanNotificationInfo[] getNotificationInfo() { MBeanNotificationInfo[] notificationInfo = new MBeanNotificationInfo[1]; String[] notificationTypes = new String[6]; notificationTypes[0] = RelationNotification.RELATION_BASIC_CREATION; notificationTypes[1] = RelationNotification.RELATION_MBEAN_CREATION; notificationTypes[2] = RelationNotification.RELATION_BASIC_UPDATE; notificationTypes[3] = RelationNotification.RELATION_MBEAN_UPDATE; notificationTypes[4] = RelationNotification.RELATION_BASIC_REMOVAL; notificationTypes[5] = RelationNotification.RELATION_MBEAN_REMOVAL; String notificationDescription = "Sent when a relation is created, updated or deleted."; notificationInfo[0] = new MBeanNotificationInfo(notificationTypes, "RelationNotification", notificationDescription); return notificationInfo; } /** *Implementation of interface MBeanRegistration @see MBeanRegistration
*Allows the MBean to perform any operations it needs before being registered in the MBean server. If the name of the MBean is * not specified, the MBean can provide a name for its registration. If any exception is raised, the MBean will not be registered * in the MBean server.
* * @param server - The MBean server in which the MBean will be registered * @param name - The object name of the MBean. This name is null if the name parameter to one of the createMBean or registerMBean * methods in the @see MBeanServer interface is null. In that case, this method must return a non-null ObjectName for the new MBean. * @return - The name under which the MBean is to be registered. This value must not be null. If the name parameter is * not null, it will usually but not necessarily be the returned value * @throws Exception - This exception will be caught by the MBean server and re-thrown as an * @see javax.management.MBeanRegistrationException or a @see RuntimeMBeanException. */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { m_server = server; m_relationServiceObjectName = name == null ? new ObjectName(m_server.getDefaultDomain(), "service", "Relation") : name; return m_relationServiceObjectName; } /** *Allows the MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed
* * @param registrationDone - Indicates whether or not the MBean has been successfully registered in the MBean server. * The value false means that the registration phase has failed * @see MBeanRegistration */ public void postRegister(Boolean registrationDone) { Logger logger = getLogger(); boolean done = registrationDone.booleanValue(); if (!done) { m_server = null; logger.warn("Relation service was NOT registered"); } else { if (logger.isEnabledFor(Logger.DEBUG)) { logger.debug("Relation service postRegistered"); } } } /** *Allows the MBean to perform any operations it needs before being unregistered by the MBean server. * * @throws Exception - This exception will be caught by the MBean server and re-thrown as an * @see MBeanRegistration
*The impmentation does nothing but log registration of the relation service
* @see javax.management.MBeanRegistrationException or a @see RuntimeMBeanException */ public void preDeregister() throws Exception { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) { logger.debug("Relation service preDeregistered"); } } /** *logs nothing but log postRegisration
*Implementation of MBeanRegistration
*/ public void postDeregister() { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.DEBUG)) { logger.debug("Relation service postDeregistered"); } } static void throwRoleProblemException(int problemType, String roleName) throws IllegalArgumentException, RoleNotFoundException, InvalidRoleValueException { switch (problemType) { case RoleStatus.NO_ROLE_WITH_NAME: throw new RoleNotFoundException("RoleName: " + roleName + " does not exist in the relation"); case RoleStatus.ROLE_NOT_READABLE: throw new RoleNotFoundException("RoleName: " + roleName + " is not readable"); case RoleStatus.ROLE_NOT_WRITABLE: throw new RoleNotFoundException("RoleName: " + roleName + " is not writable"); case RoleStatus.LESS_THAN_MIN_ROLE_DEGREE: throw new InvalidRoleValueException("RoleName: " + roleName + " has references less than the expected minimum."); case RoleStatus.MORE_THAN_MAX_ROLE_DEGREE: throw new InvalidRoleValueException("RoleName: " + roleName + " has references more than the expected maximum."); case RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS: throw new InvalidRoleValueException("RoleName: " + roleName + " has a MBean reference to a MBean not of the expected class of references for that role."); case RoleStatus.REF_MBEAN_NOT_REGISTERED: throw new InvalidRoleValueException("RoleName: " + roleName + " has a reference to null MBean or to a MBean not registered."); } } private Logger getLogger() { return Log.getLogger(getClass().getName()); } // inner class to represent internal relations defined in the relationService final class InternalRelation extends RelationSupport { InternalRelation(String relationId, ObjectName relationServiceObjectName, String relationTypeName, RoleList roleList) throws InvalidRoleValueException, IllegalArgumentException { super(relationId, relationServiceObjectName, relationTypeName, roleList); } // checks role can be read int getReadingProblemType(Role role, String roleName, String relationTypeName) { if (roleName == null) throw new IllegalArgumentException("Null RoleName"); if (role == null) return (RoleStatus.NO_ROLE_WITH_NAME); else { try { return ((checkRoleReading(roleName, relationTypeName)).intValue()); } catch (RelationTypeNotFoundException ex) { throw new RuntimeOperationsException(null, ex.getMessage()); } } } // overridden from RelationSupport int getRoleWritingValue(Role role, String relationTypeName, Boolean toBeInitialized) throws RelationTypeNotFoundException { try { // check role is writable return (checkRoleWriting(role, relationTypeName, toBeInitialized)).intValue(); } catch (RelationTypeNotFoundException ex) { throw new RuntimeOperationsException(null, ex.getMessage()); } } // sends role update notification void sendUpdateRoleNotification(String relationId, Role role, List oldRoleValue) throws RelationServiceNotRegisteredException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null RelationId passed into sendUpdateRoleNotification"); if (role == null) throw new IllegalArgumentException("Null role passed into sendUpdateRoleNotification"); if (oldRoleValue == null) throw new IllegalArgumentException("Null list of role Values passed into sendUpdateRoleNotification"); sendRoleUpdateNotification(relationId, role, oldRoleValue); } void updateRelationServiceMap(String relationId, Role role, List oldRoleValue) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException { if (relationId == null) throw new IllegalArgumentException("Null RelationId passed into updateRelationServiceMap"); if (role == null) throw new IllegalArgumentException("Null role passed into updateRelationServiceMap"); if (oldRoleValue == null) throw new IllegalArgumentException("Null list of role Values passed into updateRelationServiceMap"); updateRoleMap(relationId, role, oldRoleValue); } } } mx4j-3.0.2/src/core/javax/management/relation/RelationServiceMBean.java 100644 0 0 15710 10513545721 23201 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.util.List; import java.util.Map; import javax.management.InstanceNotFoundException; import javax.management.ObjectName; /** * @version $Revision: 1.6 $ */ public interface RelationServiceMBean { public void isActive() throws RelationServiceNotRegisteredException; public boolean getPurgeFlag(); public void setPurgeFlag(boolean purgeFlag); public void createRelationType(String relationTypeName, RoleInfo[] roleInfos) throws IllegalArgumentException, InvalidRelationTypeException; public void addRelationType(RelationType relationTypeObject) throws IllegalArgumentException, InvalidRelationTypeException; public List getAllRelationTypeNames(); public List getRoleInfos(String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException; public RoleInfo getRoleInfo(String relationTypeName, String roleInfoName) throws IllegalArgumentException, RelationTypeNotFoundException, RoleInfoNotFoundException; public void removeRelationType(String relationTypeName) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationTypeNotFoundException; public void createRelation(String relationId, String relationTypeName, RoleList roleList) throws IllegalArgumentException, RelationServiceNotRegisteredException, RoleNotFoundException, InvalidRelationIdException, RelationTypeNotFoundException, InvalidRoleValueException; public void addRelation(ObjectName relationObjectName) throws IllegalArgumentException, RelationServiceNotRegisteredException, NoSuchMethodException, InvalidRelationIdException, InstanceNotFoundException, InvalidRelationServiceException, RelationTypeNotFoundException, RoleNotFoundException, InvalidRoleValueException; public ObjectName isRelationMBean(String relationId) throws IllegalArgumentException, RelationNotFoundException; public String isRelation(ObjectName objectName) throws IllegalArgumentException; public Boolean hasRelation(String relationId) throws IllegalArgumentException; public List getAllRelationIds(); public Integer checkRoleReading(String roleName, String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException; public Integer checkRoleWriting(Role role, String relationTypeName, Boolean initializeRoleFlag) throws IllegalArgumentException, RelationTypeNotFoundException; public void sendRelationCreationNotification(String relationId) throws IllegalArgumentException, RelationNotFoundException; public void sendRoleUpdateNotification(String relationId, Role newRole, List oldRoleValues) throws IllegalArgumentException, RelationNotFoundException; public void sendRelationRemovalNotification(String relationId, List unregisteredMBeanList) throws IllegalArgumentException, RelationNotFoundException; public void updateRoleMap(String relationId, Role newRole, List oldRoleValues) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException; public void removeRelation(String relationId) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException; public void purgeRelations() throws RelationServiceNotRegisteredException; public Map findReferencingRelations(ObjectName mbeanObjectName, String relationTypeName, String roleName) throws IllegalArgumentException; public Map findAssociatedMBeans(ObjectName mbeanObjectName, String relationTypeName, String roleName) throws IllegalArgumentException; public List findRelationsOfType(String relationTypeName) throws IllegalArgumentException, RelationTypeNotFoundException; public List getRole(String relationId, String roleName) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException, RoleNotFoundException; public RoleResult getRoles(String relationId, String[] roleNames) throws IllegalArgumentException, RelationNotFoundException, RelationServiceNotRegisteredException; public RoleResult getAllRoles(String relationId) throws IllegalArgumentException, RelationNotFoundException, RelationServiceNotRegisteredException; public Integer getRoleCardinality(String relationId, String roleName) throws IllegalArgumentException, RelationNotFoundException, RoleNotFoundException; public void setRole(String relationId, Role role) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException, RoleNotFoundException, InvalidRoleValueException, RelationTypeNotFoundException; public RoleResult setRoles(String relationId, RoleList roleList) throws RelationServiceNotRegisteredException, IllegalArgumentException, RelationNotFoundException; public Map getReferencedMBeans(String relationId) throws IllegalArgumentException, RelationNotFoundException; public String getRelationTypeName(String relationId) throws IllegalArgumentException, RelationNotFoundException; } mx4j-3.0.2/src/core/javax/management/relation/RelationServiceNotRegisteredException.java 100644 0 0 1176 10513545721 26635 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.6 $ */ public class RelationServiceNotRegisteredException extends RelationException { private static final long serialVersionUID = 8454744887157122910L; public RelationServiceNotRegisteredException() { super(); } public RelationServiceNotRegisteredException(String message) { super(message); } } mx4j-3.0.2/src/core/javax/management/relation/RelationSupport.java 100644 0 0 51215 10513545721 22352 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import javax.management.RuntimeOperationsException; import mx4j.log.Log; import mx4j.log.Logger; /** * @version $Revision: 1.17 $ */ public class RelationSupport implements RelationSupportMBean, MBeanRegistration { private String m_relationId; private String m_relationTypeName; private ObjectName m_relationServiceObjectName; private MBeanServer m_server; private RelationServiceMBean m_proxy; private Boolean m_isInRelationService = Boolean.FALSE; private Map m_roleNameToRole = new HashMap(); public RelationSupport(String relationId, ObjectName relationServiceObjectName, MBeanServer server, String relationTypeName, RoleList roleList) throws InvalidRoleValueException, IllegalArgumentException { init(relationId, relationServiceObjectName, relationTypeName, roleList); // note the server may at this stage be null; m_server = server; m_proxy = (RelationServiceMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, m_relationServiceObjectName, RelationServiceMBean.class, false); } private void init(String relationId, ObjectName relationServiceObjectName, String relationTypeName, RoleList roleList) throws InvalidRoleValueException { if (relationId == null) throw new IllegalArgumentException("Illegal Null RelationId"); if (relationServiceObjectName == null) throw new IllegalArgumentException("Illegal Null RelationService ObjectName"); if (relationTypeName == null) throw new IllegalArgumentException("Illegal Null RelationTypeName"); if (roleList == null) roleList = new RoleList(); m_relationId = relationId; m_relationServiceObjectName = relationServiceObjectName; m_relationTypeName = relationTypeName; //checks if role are not already in Map if not add them initializeRoleList(roleList); } public RelationSupport(String relationId, ObjectName relationServiceObjectName, String relationTypeName, RoleList roleList) throws InvalidRoleValueException, IllegalArgumentException { init(relationId, relationServiceObjectName, relationTypeName, roleList); } public List getRole(String roleName) throws IllegalArgumentException, RoleNotFoundException, RelationServiceNotRegisteredException { Logger logger = getLogger(); if (roleName == null) throw new IllegalArgumentException("Role name cannot be null"); if (logger.isEnabledFor(Logger.WARN)) logger.warn("getting roles whith RoleName: " + roleName + " from RelationSupport"); Role role = getRoleFromRoleName(roleName); // check role reading int problemType = getReadingProblemType(role, roleName, m_relationTypeName); // no clone read only role found can return the list if (problemType == 0) return (role.getRoleValue()); else { if (problemType == RoleStatus.NO_ROLE_WITH_NAME) { logger.warn("RoleName: " + roleName + " not found"); throw new RoleNotFoundException("RoleName: " + roleName + " does not exist in the relation"); } else if (problemType == RoleStatus.ROLE_NOT_READABLE) { logger.warn("Role with roleName: " + roleName + " cannot be read."); throw new RoleNotFoundException("RoleName: " + roleName + " is not readable"); } } // need to return something to satisfy compiler, if we get here !! return null; } int getReadingProblemType(Role role, String roleName, String relationTypeName) throws RelationServiceNotRegisteredException, IllegalArgumentException { if (roleName == null) throw new IllegalArgumentException("Null Role Name."); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("Checking the Role reading..."); if (role == null) return (RoleStatus.NO_ROLE_WITH_NAME); try { return (m_proxy.checkRoleReading(roleName, relationTypeName)).intValue(); } catch (RelationTypeNotFoundException ex) { logger.warn("Unable to find the Relation Type with name " + relationTypeName); throw new RuntimeOperationsException(null, "Relation Type with name: " + relationTypeName + " was not found"); } } public RoleResult getRoles(String[] roleNames) throws IllegalArgumentException, RelationServiceNotRegisteredException { if (roleNames == null) throw new IllegalArgumentException("Null RoleName Array."); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("Getting roles"); RoleList roleList = new RoleList(); RoleUnresolvedList unresolvedList = new RoleUnresolvedList(); for (int i = 0; i < roleNames.length; i++) { String currentRoleName = roleNames[i]; Role role = getRoleFromRoleName(currentRoleName); // check role reading for each role int problemType = getReadingProblemType(role, currentRoleName, m_relationTypeName); // no problems - the role can read add it to roleList if (problemType == 0) roleList.add((Role)(role.clone())); // we have a problem add the role to roleUnresolvedList with the problemType else unresolvedList.add((new RoleUnresolved(currentRoleName, null, problemType))); } return (new RoleResult(roleList, unresolvedList)); } // can do here is get the list create a String[] of roleNames pass this to getRole(String[] roleNames) public RoleResult getAllRoles() throws RelationServiceNotRegisteredException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("getting all roles"); List roleNameList = getAllRoleNamesList(); String[] roleNames = new String[roleNameList.size()]; int index = 0; for (Iterator i = roleNameList.iterator(); i.hasNext();) { roleNames[index] = (String)i.next(); index++; } return (getRoles(roleNames)); } public RoleList retrieveAllRoles() { synchronized (m_roleNameToRole) { return (new RoleList(new ArrayList(m_roleNameToRole.values()))); } } private ArrayList getAllRolesList() { synchronized (m_roleNameToRole) { return (new ArrayList(m_roleNameToRole.values())); } } public void setRole(Role role) throws IllegalArgumentException, RoleNotFoundException, RelationTypeNotFoundException, InvalidRoleValueException, RelationServiceNotRegisteredException, RelationNotFoundException { if (role == null) throw new IllegalArgumentException("RelationSupport setRole has recieved a null Role."); String roleName = role.getRoleName(); Role oldRole = getRoleFromRoleName(roleName); List oldRoleValue; Boolean toBeInitialized; // no role found therefore we have a new role and a new List to hold it if (oldRole == null) { toBeInitialized = new Boolean(true); oldRoleValue = new ArrayList(); } else { // role found we do not need to initialize the role toBeInitialized = new Boolean(false); oldRoleValue = oldRole.getRoleValue(); } // check if the role is writable int problemType = getRoleWritingValue(role, m_relationTypeName, toBeInitialized); if (problemType == 0) { if (!(toBeInitialized.booleanValue())) { // new role send an update notification sendUpdateRoleNotification(m_relationId, role, oldRoleValue); updateRelationServiceMap(m_relationId, role, oldRoleValue); } addRolesToRoleMap(roleName, role); } else { RelationService.throwRoleProblemException(problemType, roleName); } } // checks if the role is writable int getRoleWritingValue(Role role, String relationTypeName, Boolean toBeInitialized) throws RelationTypeNotFoundException { if (m_proxy == null) throw new IllegalArgumentException("Please check the RelationService is running"); return (m_proxy.checkRoleWriting(role, relationTypeName, toBeInitialized).intValue()); } public RoleResult setRoles(RoleList roleList) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationTypeNotFoundException, RelationNotFoundException { Logger logger = getLogger(); if (roleList == null) throw new IllegalArgumentException("RoleList cannot be null"); if (logger.isEnabledFor(Logger.WARN)) logger.warn("setting roles"); RoleList newRoleList = new RoleList(); RoleUnresolvedList roleUnresolvedList = new RoleUnresolvedList(); List oldRoleValue; Boolean needsInitializing; for (Iterator i = roleList.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); String roleName = currentRole.getRoleName(); Role oldRole = getRoleFromRoleName(roleName); if (oldRole == null) { needsInitializing = new Boolean(true); oldRoleValue = new ArrayList(); } else { needsInitializing = new Boolean(false); oldRoleValue = oldRole.getRoleValue(); } int problemType = getRoleWritingValue(currentRole, m_relationTypeName, needsInitializing); if (problemType == 0) { if (!(needsInitializing.booleanValue())) { // send notification update RelationService map sendUpdateRoleNotification(m_relationId, currentRole, oldRoleValue); updateRelationServiceMap(m_relationId, currentRole, oldRoleValue); } // add the roles addRolesToRoleMap(roleName, currentRole); newRoleList.add(currentRole); } else { if (logger.isEnabledFor(Logger.WARN)) logger.warn("We have some unresolved roles adding them to RoleUnresolvedList"); roleUnresolvedList.add(new RoleUnresolved(roleName, currentRole.getRoleValue(), problemType)); } } return (new RoleResult(newRoleList, roleUnresolvedList)); } // check role conforms to defined cardinality public Integer getRoleCardinality(String roleName) throws IllegalArgumentException, RoleNotFoundException { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("checking role cardinality with role named: " + roleName); if (roleName == null) throw new IllegalArgumentException("Role name should not be null."); Role role = getRoleFromRoleName(roleName); if (role == null) { int problemType = RoleStatus.NO_ROLE_WITH_NAME; try { // send the role cardinality error to the RelationService RelationService.throwRoleProblemException(problemType, roleName); } catch (InvalidRoleValueException ex) { new RuntimeOperationsException(null, "Invalid role value"); } } List roleValue = role.getRoleValue(); return new Integer(roleValue.size()); } public void handleMBeanUnregistration(ObjectName objectName, String roleName) throws IllegalArgumentException, RoleNotFoundException, InvalidRoleValueException, RelationServiceNotRegisteredException, RelationTypeNotFoundException, RelationNotFoundException { Logger logger = getLogger(); if (objectName == null) throw new IllegalArgumentException("ObjectName is null"); if (roleName == null) throw new IllegalArgumentException("Null roleName"); if (logger.isEnabledFor(Logger.WARN)) { logger.warn("MBean with ObjectName: " + objectName.getCanonicalName() + " has been unregistered from the" + " MBeanServer. Setting new Role values"); } Role newRole = createNewRole(roleName, objectName); setRole(newRole); } private Role createNewRole(String roleName, ObjectName objectName) throws RoleNotFoundException { // get role stored in the Map Role role = getRoleFromRoleName(roleName); if (role == null) throw new RoleNotFoundException("No role found for role name: " + roleName); // needs to be cloned as will be modified, need to cast role.getRoleValue as list does not implement Cloneable ArrayList newRoleValue = (ArrayList)((ArrayList)role.getRoleValue()).clone(); newRoleValue.remove(objectName); Role newRole = new Role(roleName, newRoleValue); return newRole; } public Map getReferencedMBeans() { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("getting mbeanReferenced in RelationService"); HashMap referencedMBeansMap = new HashMap(); for (Iterator i = (getAllRolesList()).iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); String currentRoleName = currentRole.getRoleName(); // get the roleValues for each Role List mbeanList = currentRole.getRoleValue(); for (Iterator iter = mbeanList.iterator(); iter.hasNext();) { ObjectName currentObjectName = (ObjectName)iter.next(); List mbeanRoleNameList = (List)(referencedMBeansMap.get(currentObjectName)); boolean newReference = false; if (mbeanRoleNameList == null) { // we have new references newReference = true; mbeanRoleNameList = new ArrayList(); } mbeanRoleNameList.add(currentRoleName); // we have a new reference add it to our map. if (newReference) referencedMBeansMap.put(currentObjectName, mbeanRoleNameList); } } return referencedMBeansMap; } private Role getRoleFromRoleName(String roleName) { synchronized (m_roleNameToRole) { return ((Role)m_roleNameToRole.get(roleName)); } } public String getRelationTypeName() { return m_relationTypeName; } public ObjectName getRelationServiceName() { return m_relationServiceObjectName; } public String getRelationId() { return m_relationId; } public Boolean isInRelationService() { return m_isInRelationService; } public void setRelationServiceManagementFlag(Boolean isHandledByRelationService) throws IllegalArgumentException { if (isHandledByRelationService == null) throw new IllegalArgumentException("Null flag"); m_isInRelationService = isHandledByRelationService; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { if (server == null) throw new IllegalArgumentException("MBean Server is null cannot pre-register."); if (name == null) throw new IllegalArgumentException("Cannot register a null ObjectName"); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.WARN)) logger.warn("pre Registering the RelationSupport"); m_server = server; m_proxy = (RelationServiceMBean)MBeanServerInvocationHandler.newProxyInstance(m_server, m_relationServiceObjectName, RelationServiceMBean.class, false); return name; } public void postRegister(Boolean registrationDone) { Logger logger = getLogger(); boolean done = registrationDone.booleanValue(); if (!done) { m_server = null; logger.warn("RelationSupport was NOT registered"); } else { if (logger.isEnabledFor(Logger.TRACE)) { logger.trace("RelationSupport postRegistered"); } } } public void preDeregister() throws Exception { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.debug("RelationSupport preDeregistered"); } } public void postDeregister() { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) { logger.debug("RelationSupport postDeregistered"); } } private List getAllRoleNamesList() { synchronized (m_roleNameToRole) { return (new ArrayList(m_roleNameToRole.keySet())); } } private void initializeRoleList(RoleList roleList) throws InvalidRoleValueException { if (roleList == null) return; for (Iterator i = roleList.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); String currentRoleName = currentRole.getRoleName(); // our map already holds the current roleName cannot re-use it let the user know if (m_roleNameToRole.containsKey(currentRoleName)) { throw new InvalidRoleValueException("RoleName already in use."); } // no existing roleName found add the values in the RoleList addRolesToRoleMap(currentRoleName, currentRole); } } private void addRolesToRoleMap(String roleName, Role role) { synchronized (m_roleNameToRole) { m_roleNameToRole.put(roleName, role.clone()); } } void updateRelationServiceMap(String relationId, Role role, List oldRoleValue) throws IllegalArgumentException, RelationServiceNotRegisteredException, RelationNotFoundException { Logger logger = getLogger(); if (m_proxy != null) m_proxy.updateRoleMap(relationId, role, oldRoleValue); else { logger.warn("The RelationService cannot be registered."); throw new RelationServiceNotRegisteredException("Please check the RelationService is registered in the server"); } } void sendUpdateRoleNotification(String relationId, Role role, List oldRoleValue) throws RelationServiceNotRegisteredException, RelationNotFoundException { Logger logger = getLogger(); if (relationId == null) throw new IllegalArgumentException("Null RelationId passed into sendUpdateRoleNotification"); if (role == null) throw new IllegalArgumentException("Null role passed into sendUpdateRoleNotification"); if (oldRoleValue == null) throw new IllegalArgumentException("Null list of role Values passed into sendUpdateRoleNotification"); if (m_proxy != null) m_proxy.sendRoleUpdateNotification(relationId, role, oldRoleValue); else { logger.warn("cannot send an update notification as RelationService may not be registered, please check."); throw new RelationServiceNotRegisteredException("Please check the relation service has been registered in the MBeanServer"); } } private Logger getLogger() { return Log.getLogger(getClass().getName()); } } mx4j-3.0.2/src/core/javax/management/relation/RelationSupportMBean.java 100644 0 0 777 10513545721 23224 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.4 $ */ public interface RelationSupportMBean extends Relation { public Boolean isInRelationService(); public void setRelationServiceManagementFlag(Boolean flag) throws IllegalArgumentException; } mx4j-3.0.2/src/core/javax/management/relation/RelationType.java 100644 0 0 1140 10513545721 21567 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.io.Serializable; import java.util.List; /** * @version $Revision: 1.6 $ */ public interface RelationType extends Serializable { public String getRelationTypeName(); public RoleInfo getRoleInfo(String roleInfoName) throws IllegalArgumentException, RoleInfoNotFoundException; public List getRoleInfos(); } mx4j-3.0.2/src/core/javax/management/relation/RelationTypeNotFoundException.java 100644 0 0 1246 10513545721 25132 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.6 $ */ public class RelationTypeNotFoundException extends RelationException { private static final long serialVersionUID = 1274155316284300752L; // Thrown when there is no relation type with the given name public RelationTypeNotFoundException() { super(); } public RelationTypeNotFoundException(String message) { super(message); } } mx4j-3.0.2/src/core/javax/management/relation/RelationTypeSupport.java 100644 0 0 10671 10513545721 23215 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.RuntimeOperationsException; /** * @version $Revision: 1.10 $ */ public class RelationTypeSupport implements RelationType { private static final long serialVersionUID = 4611072955724144607L; private String typeName; private Map roleName2InfoMap = new HashMap(); private boolean isInRelationService; public RelationTypeSupport(String relationTypeName, RoleInfo[] roleInfo) throws IllegalArgumentException, InvalidRelationTypeException { if (relationTypeName == null || roleInfo == null) throw new IllegalArgumentException("Illegal Null Value"); this.typeName = relationTypeName; // determines if the roleInfo[] are valid checkRoleInfos(roleInfo); // no exceptions thrown in validate add the roleInfos to our HashMap addRoleInfos(roleInfo); } protected RelationTypeSupport(String relationTypeName) { if (relationTypeName == null) throw new IllegalArgumentException("Null RelationType Name"); this.typeName = relationTypeName; } private void addRoleInfos(RoleInfo[] roleInfos) throws IllegalArgumentException { if (roleInfos == null) throw new IllegalArgumentException("Null RoleInfo[]"); synchronized (roleName2InfoMap) { for (int i = 0; i < roleInfos.length; i++) { RoleInfo currentRoleInfo = roleInfos[i]; addRoleNameToRoleInfo(currentRoleInfo.getName(), currentRoleInfo); } } } public String getRelationTypeName() { return typeName; } public RoleInfo getRoleInfo(String roleInfoName) throws RoleInfoNotFoundException, IllegalArgumentException { if (roleInfoName == null) throw new IllegalArgumentException("roleInfo Name cannot have a null value"); RoleInfo roleInfo = (RoleInfo)(roleName2InfoMap.get(roleInfoName)); if (roleInfo == null) { throw new RoleInfoNotFoundException("No role info for role named " + roleInfoName); } return roleInfo; } public List getRoleInfos() { return new ArrayList(roleName2InfoMap.values()); } protected void addRoleInfo(RoleInfo roleInfo) throws IllegalArgumentException, InvalidRelationTypeException { if (roleInfo == null) throw new IllegalArgumentException("Cannot add a null roleInfo in the relation service"); if (isInRelationService) throw new RuntimeOperationsException(null, "RoleInfo cannot be added as the relation type is already declared in the relation service"); String roleName = roleInfo.getName(); // roleName already present cannot have conflicting names if (roleName2InfoMap.containsKey(roleName)) { throw new InvalidRelationTypeException("Already a roleInfo declared for roleName " + roleName); } // no problems add the roleName as the key in our Map and the roleInfo as the value addRoleNameToRoleInfo(roleName, roleInfo); } private void addRoleNameToRoleInfo(String roleName, RoleInfo roleInfo) { synchronized (roleName2InfoMap) { roleName2InfoMap.put(roleName, roleInfo); } } // validates the the RoleInfo[] conforms static void checkRoleInfos(RoleInfo[] roleInfo) throws IllegalArgumentException, InvalidRelationTypeException { if (roleInfo == null) throw new IllegalArgumentException("RoleInfo is null."); if (roleInfo.length == 0) throw new InvalidRelationTypeException("RoleInfo is empty"); ArrayList roleNameList = new ArrayList(); for (int i = 0; i < roleInfo.length; ++i) { RoleInfo currentRoleInfo = roleInfo[i]; if (currentRoleInfo == null) throw new InvalidRelationTypeException("Null roleInfo"); String roleName = currentRoleInfo.getName(); if (roleNameList.contains(roleName)) { throw new InvalidRelationTypeException("Two RoleInfos provided for role " + roleName); } roleNameList.add(roleName); } } void setRelationServiceFlag(boolean value) { isInRelationService = value; } } mx4j-3.0.2/src/core/javax/management/relation/Role.java 100644 0 0 6310 10513545721 20055 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.management.ObjectName; /** * @version $Revision: 1.11 $ */ public class Role implements Serializable { private static final long serialVersionUID = -279985518429862552L; private String name; private List objectNameList; public Role(String roleName, List roleValueList) throws IllegalArgumentException { setRoleName(roleName); // loop and add the values to our global list setRoleValue(roleValueList); } public void setRoleName(String roleName) throws IllegalArgumentException { if (roleName == null) throw new IllegalArgumentException("Cannot have a null role name"); this.name = roleName; } public void setRoleValue(List roleValues) throws IllegalArgumentException { if (roleValues == null) throw new IllegalArgumentException("List of role values cannot be null"); if (objectNameList == null) { objectNameList = new ArrayList(); } objectNameList.clear(); objectNameList.addAll(roleValues); } public String getRoleName() { return name; } public List getRoleValue() { return new ArrayList(objectNameList); } public String toString() { StringBuffer roleToString = new StringBuffer("roleName: "); roleToString.append(name); roleToString.append("\nroleValue: "); String values = roleValueToString(objectNameList); roleToString.append(values); return roleToString.toString(); } public Object clone() { try { return new Role(name, objectNameList); } catch (IllegalArgumentException ignored) { // it never happens, no need to rethrow ! return null; } } public static String roleValueToString(List roleValues) throws IllegalArgumentException { StringBuffer valuesToString = new StringBuffer(); for (Iterator roleValuesIterator = roleValues.iterator(); roleValuesIterator.hasNext();) { ObjectName currentObjName = (ObjectName)roleValuesIterator.next(); valuesToString.append(currentObjName.toString()); if (roleValuesIterator.hasNext()) { valuesToString.append("\n"); } } return valuesToString.toString(); } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Role)) return false; final Role role = (Role)o; if (name != null ? !name.equals(role.name) : role.name != null) return false; if (objectNameList != null ? !objectNameList.equals(role.objectNameList) : role.objectNameList != null) return false; return true; } public int hashCode() { int result; result = (name != null ? name.hashCode() : 0); result = 29 * result + (objectNameList != null ? objectNameList.hashCode() : 0); return result; } } mx4j-3.0.2/src/core/javax/management/relation/RoleInfo.java 100644 0 0 13245 10513545721 20716 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.io.Serializable; import javax.management.NotCompliantMBeanException; /** * @version $Revision: 1.7 $ */ public class RoleInfo implements Serializable { private static final long serialVersionUID = 2504952983494636987L; public static int ROLE_CARDINALITY_INFINITY = -1; private String name; private String description; //name of the class of MBean(s) expected to be referenced in corresponding role private String referencedMBeanClassName; private boolean isWritable; private boolean isReadable; private int minDegree; private int maxDegree; public RoleInfo(String roleName, String mbeanClassName, boolean isReadable, boolean isWritable, int minNumber, int maxNumber, String description) throws IllegalArgumentException, InvalidRoleInfoException, ClassNotFoundException, NotCompliantMBeanException { initialize(roleName, mbeanClassName, isReadable, isWritable, minNumber, maxNumber, description); } public RoleInfo(String roleName, String mbeanClassName, boolean isReadable, boolean isWritable) throws IllegalArgumentException, ClassNotFoundException, NotCompliantMBeanException { try { // set cardinality to default 1, 1 initialize(roleName, mbeanClassName, isReadable, isWritable, 1, 1, null); } catch (InvalidRoleInfoException ignored) { } } public RoleInfo(String roleName, String mbeanClassName) throws IllegalArgumentException, ClassNotFoundException, NotCompliantMBeanException { try { // read, write and cardinality set default values initialize(roleName, mbeanClassName, true, true, 1, 1, null); } catch (InvalidRoleInfoException ignored) { } } public RoleInfo(RoleInfo info) throws IllegalArgumentException { if (info == null) { throw new IllegalArgumentException("RoleInfo cannot be null"); } try { initialize(info.getName(), info.getRefMBeanClassName(), info.isReadable(), info.isWritable(), info.getMinDegree(), info.getMaxDegree(), info.getDescription()); } catch (Exception ignored) { // The provided role info is valid, no reason why this one would fail } } private void initialize(String roleName, String mbeanClassName, boolean isReadable, boolean isWritable, int minNumber, int maxNumber, String description) throws IllegalArgumentException, InvalidRoleInfoException, ClassNotFoundException, NotCompliantMBeanException { if (roleName == null) throw new IllegalArgumentException("Null Role name"); if (mbeanClassName == null) throw new IllegalArgumentException("Null MBean class Name"); this.name = roleName; this.isReadable = isReadable; this.isWritable = isWritable; this.description = description; // check our cardinality is valid ie) Max is not less than Min checkValidCardinality(maxNumber, minNumber); this.maxDegree = maxNumber; this.minDegree = minNumber; this.referencedMBeanClassName = mbeanClassName; } public String getName() { return name; } public boolean isReadable() { return isReadable; } public boolean isWritable() { return isWritable; } public String getDescription() { return description; } public int getMinDegree() { return minDegree; } public int getMaxDegree() { return maxDegree; } public String getRefMBeanClassName() { return referencedMBeanClassName; } // return true if the given value is greater than or equal to the expected maximum public boolean checkMaxDegree(int maxNumber) { if (maxNumber >= ROLE_CARDINALITY_INFINITY && (maxDegree == ROLE_CARDINALITY_INFINITY || (maxNumber != ROLE_CARDINALITY_INFINITY && maxNumber <= maxDegree))) { return true; } return false; } // returns true if the given value is greater or equal to the expected minimum value public boolean checkMinDegree(int minNumber) { if (minNumber >= ROLE_CARDINALITY_INFINITY && (minDegree == ROLE_CARDINALITY_INFINITY || minNumber >= minDegree)) { return true; } return false; } public String toString() { StringBuffer result = new StringBuffer("Name: "); result.append(name); result.append("; isReadable: ").append(isReadable); result.append("; isWritable: ").append(isWritable); result.append("; description: ").append(description); result.append("; minimum degree: ").append(minDegree); result.append("; maximum degree: ").append(maxDegree); result.append("; MBean class: ").append(referencedMBeanClassName); return result.toString(); } private void checkValidCardinality(int maxNumber, int minNumber) throws InvalidRoleInfoException { if (maxNumber != ROLE_CARDINALITY_INFINITY && (minNumber == ROLE_CARDINALITY_INFINITY || minNumber > maxNumber)) { throw new InvalidRoleInfoException("Role cardinality is invalid"); } else if (minNumber < ROLE_CARDINALITY_INFINITY || maxNumber < ROLE_CARDINALITY_INFINITY) { throw new InvalidRoleInfoException("Role cardinality is invalid"); } } } mx4j-3.0.2/src/core/javax/management/relation/RoleInfoNotFoundException.java 100644 0 0 1132 10513545721 24222 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.6 $ */ public class RoleInfoNotFoundException extends RelationException { private static final long serialVersionUID = 4394092234999959939L; public RoleInfoNotFoundException() { super(); } public RoleInfoNotFoundException(String message) { super(message); } } mx4j-3.0.2/src/core/javax/management/relation/RoleList.java 100644 0 0 4416 10513545721 20716 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @version $Revision: 1.8 $ */ public class RoleList extends ArrayList { private static final long serialVersionUID = 5568344346499649313L; public RoleList() { } public RoleList(int initialCapacity) { super(initialCapacity); } public RoleList(List list) throws IllegalArgumentException { if (list == null) throw new IllegalArgumentException("list argument must not be null"); for (Iterator listIterator = list.iterator(); listIterator.hasNext();) { Object currentListItem = listIterator.next(); if (!(currentListItem instanceof Role)) { throw new IllegalArgumentException("Item added to the RoleList: " + currentListItem + " does not represent a Role"); } add((Role)currentListItem); } } public void add(Role role) throws IllegalArgumentException { if (role == null) { throw new IllegalArgumentException("A role cannot be null"); } super.add(role); } public void add(int index, Role role) throws IllegalArgumentException, IndexOutOfBoundsException { if (role == null) { throw new IllegalArgumentException("Cannot have a null role value"); } super.add(index, role); } public void set(int index, Role role) throws IllegalArgumentException, IndexOutOfBoundsException { if (role == null) { throw new IllegalArgumentException("Cannot have a null role"); } super.set(index, role); } public boolean addAll(RoleList roleList) throws IndexOutOfBoundsException { if (roleList == null) { return true; } return super.addAll(roleList); } public boolean addAll(int index, RoleList roleList) throws IllegalArgumentException, IndexOutOfBoundsException { if (roleList == null) { return true; } return super.addAll(index, roleList); } } mx4j-3.0.2/src/core/javax/management/relation/RoleNotFoundException.java 100644 0 0 1117 10513545721 23411 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.6 $ */ public class RoleNotFoundException extends RelationException { private static final long serialVersionUID = -2986406101364031481L; public RoleNotFoundException() { super(); } public RoleNotFoundException(String message) { super(message); } } mx4j-3.0.2/src/core/javax/management/relation/RoleResult.java 100644 0 0 3604 10513545721 21257 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.io.Serializable; import java.util.Iterator; /** * @version $Revision: 1.6 $ */ public class RoleResult implements Serializable { private static final long serialVersionUID = -6304063118040985512L; private RoleList roleList; private RoleUnresolvedList unresolvedRoleList; public RoleResult(RoleList roleList, RoleUnresolvedList unresolvedList) { setRoles(roleList); setRolesUnresolved(unresolvedList); } public RoleList getRoles() { return roleList == null ? null : (RoleList)roleList.clone(); } public RoleUnresolvedList getRolesUnresolved() { return unresolvedRoleList == null ? null : (RoleUnresolvedList)unresolvedRoleList.clone(); } public void setRoles(RoleList list) { if (list != null) { if (roleList == null) { roleList = new RoleList(); } for (Iterator i = list.iterator(); i.hasNext();) { Role currentRole = (Role)i.next(); roleList.add(currentRole.clone()); } } else { roleList = null; } } public void setRolesUnresolved(RoleUnresolvedList list) { if (list != null) { if (unresolvedRoleList == null) { unresolvedRoleList = new RoleUnresolvedList(); } for (Iterator i = list.iterator(); i.hasNext();) { RoleUnresolved currentUnresolvedRole = (RoleUnresolved)i.next(); unresolvedRoleList.add(currentUnresolvedRole.clone()); } } else { unresolvedRoleList = null; } } } mx4j-3.0.2/src/core/javax/management/relation/RoleStatus.java 100644 0 0 2271 10513545721 21263 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; /** * @version $Revision: 1.4 $ */ public class RoleStatus { public static final int NO_ROLE_WITH_NAME = 1; public static final int ROLE_NOT_READABLE = 2; public static final int ROLE_NOT_WRITABLE = 3; public static final int LESS_THAN_MIN_ROLE_DEGREE = 4; public static final int MORE_THAN_MAX_ROLE_DEGREE = 5; public static final int REF_MBEAN_OF_INCORRECT_CLASS = 6; public static final int REF_MBEAN_NOT_REGISTERED = 7; public static boolean isRoleStatus(int roleStatusType) { if (roleStatusType != NO_ROLE_WITH_NAME && roleStatusType != ROLE_NOT_READABLE && roleStatusType != ROLE_NOT_WRITABLE && roleStatusType != LESS_THAN_MIN_ROLE_DEGREE && roleStatusType != MORE_THAN_MAX_ROLE_DEGREE && roleStatusType != REF_MBEAN_OF_INCORRECT_CLASS && roleStatusType != REF_MBEAN_NOT_REGISTERED) { return false; } return true; } } mx4j-3.0.2/src/core/javax/management/relation/RoleUnresolved.java 100644 0 0 5235 10513545721 22131 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.management.ObjectName; /** * @version $Revision: 1.11 $ */ public class RoleUnresolved implements Serializable { private static final long serialVersionUID = -48350262537070138L; private String roleName; private List roleValue; private int problemType; public RoleUnresolved(String roleName, List roleValues, int problemType) throws IllegalArgumentException { setRoleName(roleName); setRoleValue(roleValues); setProblemType(problemType); } public int getProblemType() { return problemType; } public String getRoleName() { return roleName; } public List getRoleValue() { // During serialization I can get any type of List return roleValue == null ? null : new ArrayList(roleValue); } public void setRoleName(String name) throws IllegalArgumentException { if (name == null) throw new IllegalArgumentException("Role Name cannot be null"); roleName = name; } public void setRoleValue(List list) { if (list != null) { if (roleValue == null) { roleValue = new ArrayList(); } roleValue.clear(); roleValue.addAll(list); } else { roleValue = null; } } public void setProblemType(int type) throws IllegalArgumentException { if (!(RoleStatus.isRoleStatus(type))) { throw new IllegalArgumentException("Problem Type unknown"); } problemType = type; } public Object clone() { // NB we do not (and cannot) implement Cloneable so we do our own copy return new RoleUnresolved(roleName, roleValue, problemType); } public String toString() { StringBuffer roleBuff = new StringBuffer(); roleBuff.append("Role Name: ").append(roleName); if (roleValue != null) { roleBuff.append("\nRole Values:"); for (Iterator i = roleValue.iterator(); i.hasNext();) { ObjectName objectName = (ObjectName)i.next(); roleBuff.append(objectName); if (i.hasNext()) { roleBuff.append(", "); } } } roleBuff.append("\nProblem Type:"); roleBuff.append(problemType); return roleBuff.toString(); } } mx4j-3.0.2/src/core/javax/management/relation/RoleUnresolvedList.java 100644 0 0 5041 10513545721 22760 0 ustar 0 0 /** * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.relation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @version $Revision: 1.7 $ */ public class RoleUnresolvedList extends ArrayList { private static final long serialVersionUID = 4054902803091433324L; public RoleUnresolvedList() { } public RoleUnresolvedList(int initialCapacity) { super(initialCapacity); } // method accepts any list but list may only contain elements of RoleUnresolved public RoleUnresolvedList(List list) throws IllegalArgumentException { if (list == null) { throw new IllegalArgumentException("List cannot be null"); } for (Iterator i = list.iterator(); i.hasNext();) { Object currentIteration = i.next(); if (!(currentIteration instanceof RoleUnresolved)) { throw new IllegalArgumentException("All elements in the list must be an instance of RoleUnresolved"); } add((RoleUnresolved)currentIteration); } } public void add(RoleUnresolved roleUnresolved) throws IllegalArgumentException { if (roleUnresolved == null) { throw new IllegalArgumentException("RoleUnresolved cannot be null"); } super.add(roleUnresolved); } public void add(int index, RoleUnresolved roleUnresolved) throws IllegalArgumentException, IndexOutOfBoundsException { if (roleUnresolved == null) { throw new IllegalArgumentException("RoleUnresolved cannot be null"); } super.add(index, roleUnresolved); } public void set(int index, RoleUnresolved roleUnresolved) throws IllegalArgumentException, IndexOutOfBoundsException { if (roleUnresolved == null) { throw new IllegalArgumentException("RoleUnresolved cannot be null"); } super.set(index, roleUnresolved); } public boolean addAll(RoleUnresolvedList roleUnresolvedList) throws IndexOutOfBoundsException { if (roleUnresolvedList == null) return true; return super.addAll(roleUnresolvedList); } public boolean addAll(int index, RoleUnresolvedList roleUnresolvedList) throws IllegalArgumentException, IndexOutOfBoundsException { if (roleUnresolvedList == null) return true; return super.addAll(index, roleUnresolvedList); } } mx4j-3.0.2/src/core/javax/management/remote/JMXAuthenticator.java 100644 0 0 722 10513545721 22004 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import javax.security.auth.Subject; /** * @version $Revision: 1.3 $ */ public interface JMXAuthenticator { public Subject authenticate(Object credentials) throws SecurityException; } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectionNotification.java 100644 0 0 2350 10513545721 23657 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import javax.management.Notification; /** * @version $Revision: 1.6 $ */ public class JMXConnectionNotification extends Notification { public static final String OPENED = "jmx.remote.connection.opened"; public static final String CLOSED = "jmx.remote.connection.closed"; public static final String FAILED = "jmx.remote.connection.failed"; public static final String NOTIFS_LOST = "jmx.remote.connection.notifs.lost"; private static final long serialVersionUID = -2331308725952627538l; /** * @serial The connection ID for this notification */ private String connectionId; public JMXConnectionNotification(String type, Object source, String connectionId, long sequenceNumber, String message, Object userData) { super(type, source, sequenceNumber, System.currentTimeMillis(), message); setUserData(userData); this.connectionId = connectionId; } public String getConnectionId() { return connectionId; } } mx4j-3.0.2/src/core/javax/management/remote/JMXConnector.java 100644 0 0 2760 10513545721 21150 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.Map; import javax.management.ListenerNotFoundException; import javax.management.MBeanServerConnection; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.security.auth.Subject; /** * @version $Revision: 1.6 $ */ public interface JMXConnector { public static final String CREDENTIALS = "jmx.remote.credentials"; public void connect() throws IOException, SecurityException; public void connect(Map environment) throws IOException, SecurityException; public MBeanServerConnection getMBeanServerConnection() throws IOException; public MBeanServerConnection getMBeanServerConnection(Subject delegate) throws IOException; public void close() throws IOException; public String getConnectionId() throws IOException; public void addConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback); public void removeConnectionNotificationListener(NotificationListener listener) throws ListenerNotFoundException; public void removeConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException; } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorFactory.java 100644 0 0 2624 10513545721 22477 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.HashMap; import java.util.Map; import mx4j.remote.ProviderFactory; /** * @version $Revision: 1.11 $ */ public class JMXConnectorFactory { public static final String DEFAULT_CLASS_LOADER = "jmx.remote.default.class.loader"; public static final String PROTOCOL_PROVIDER_PACKAGES = "jmx.remote.protocol.provider.pkgs"; public static final String PROTOCOL_PROVIDER_CLASS_LOADER = "jmx.remote.protocol.provider.class.loader"; private JMXConnectorFactory() { } public static JMXConnector connect(JMXServiceURL url) throws IOException { return connect(url, null); } public static JMXConnector connect(JMXServiceURL url, Map environment) throws IOException { JMXConnector connector = newJMXConnector(url, environment); connector.connect(environment); return connector; } public static JMXConnector newJMXConnector(JMXServiceURL url, Map env) throws IOException { Map envCopy = env == null ? new HashMap() : new HashMap(env); JMXConnector connector = ProviderFactory.newJMXConnector(url, envCopy); return connector; } } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorProvider.java 100644 0 0 766 10513545721 22647 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.Map; /** * @version $Revision: 1.5 $ */ public interface JMXConnectorProvider { public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException; } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorServer.java 100644 0 0 11477 10513545721 22364 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.MBeanNotificationInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; /** * @version $Revision: 1.9 $ */ public abstract class JMXConnectorServer extends NotificationBroadcasterSupport implements JMXConnectorServerMBean, MBeanRegistration { public static final String AUTHENTICATOR = "jmx.remote.authenticator"; private static final MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[]{new MBeanNotificationInfo (new String[]{JMXConnectionNotification.OPENED, JMXConnectionNotification.CLOSED, JMXConnectionNotification.FAILED}, JMXConnectionNotification.class.getName(), "Notifications emitted by the JMXConnectorServer MBean upon opening, closing or failing of a connection")}; private static long notificationSequenceNumber; private MBeanServer server; private ObjectName name; private final HashSet connections = new HashSet(); public JMXConnectorServer() { } public JMXConnectorServer(MBeanServer server) { this.server = server; } public ObjectName preRegister(MBeanServer server, ObjectName name) { if (name == null) throw new NullPointerException("ObjectName cannot be null"); if (this.server == null) this.server = server; this.name = name; return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { if (isActive()) stop(); } public void postDeregister() { } public MBeanNotificationInfo[] getNotificationInfo() { return notifications; } public MBeanServer getMBeanServer() { return server; } public void setMBeanServerForwarder(MBeanServerForwarder forwarder) throws IllegalArgumentException { if (forwarder.getMBeanServer() == null) { if (server == null) throw new IllegalStateException("This JMXConnectorServer is not attached to an MBeanServer"); } forwarder.setMBeanServer(server); this.server = forwarder; } public JMXConnector toJMXConnector(Map environment) throws IOException { JMXServiceURL address = getAddress(); return JMXConnectorFactory.newJMXConnector(address, environment); } public String[] getConnectionIds() { Set copy = null; synchronized (connections) { copy = (Set)connections.clone(); } return (String[])copy.toArray(new String[copy.size()]); } protected void connectionOpened(String connectionId, String message, Object userData) { synchronized (connections) { boolean added = connections.add(connectionId); if (!added) throw new IllegalStateException("Duplicate connection ID: " + connectionId); } Object source = name; if (source == null) source = this; JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.OPENED, source, connectionId, getNextSequenceNumber(), message, userData); sendNotification(notification); } protected void connectionClosed(String connectionId, String message, Object userData) { synchronized (connections) { boolean removed = connections.remove(connectionId); if (!removed) throw new IllegalStateException("Connection ID not present: " + connectionId); } Object source = name; if (source == null) source = this; JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.CLOSED, source, connectionId, getNextSequenceNumber(), message, userData); sendNotification(notification); } protected void connectionFailed(String connectionId, String message, Object userData) { synchronized (connections) { boolean removed = connections.remove(connectionId); if (!removed) throw new IllegalStateException("Connection ID not present: " + connectionId); } Object source = name; if (source == null) source = this; JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.FAILED, source, connectionId, getNextSequenceNumber(), message, userData); sendNotification(notification); } private long getNextSequenceNumber() { synchronized (JMXConnectorServer.class) { return ++notificationSequenceNumber; } } } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorServerFactory.java 100644 0 0 2413 10513545721 23662 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import mx4j.remote.ProviderFactory; /** * @version $Revision: 1.7 $ */ public class JMXConnectorServerFactory { public static final String DEFAULT_CLASS_LOADER = "jmx.remote.default.class.loader"; public static final String DEFAULT_CLASS_LOADER_NAME = "jmx.remote.default.class.loader.name"; public static final String PROTOCOL_PROVIDER_PACKAGES = "jmx.remote.protocol.provider.pkgs"; public static final String PROTOCOL_PROVIDER_CLASS_LOADER = "jmx.remote.protocol.provider.class.loader"; private JMXConnectorServerFactory() { } public static JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { Map env = environment == null ? new HashMap() : new HashMap(environment); JMXConnectorServer connector = ProviderFactory.newJMXConnectorServer(url, env, server); return connector; } } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorServerMBean.java 100644 0 0 1600 10513545721 23232 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.Map; /** * @version $Revision: 1.5 $ */ public interface JMXConnectorServerMBean { public JMXServiceURL getAddress(); public Map getAttributes(); public String[] getConnectionIds(); public JMXConnector toJMXConnector(Map environment) throws IOException, UnsupportedOperationException, IllegalStateException; public boolean isActive(); public void start() throws IOException, IllegalStateException; public void stop() throws IOException; public void setMBeanServerForwarder(MBeanServerForwarder forwarder) throws IllegalArgumentException; } mx4j-3.0.2/src/core/javax/management/remote/JMXConnectorServerProvider.java 100644 0 0 1101 10513545721 24036 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; import java.util.Map; import javax.management.MBeanServer; /** * @version $Revision: 1.3 $ */ public interface JMXConnectorServerProvider { public JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException; } mx4j-3.0.2/src/core/javax/management/remote/JMXPrincipal.java 100644 0 0 2246 10513545721 21136 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.Serializable; import java.security.Principal; /** * @version $Revision: 1.6 $ */ public class JMXPrincipal implements Principal, Serializable { /** * @serial The name of this principal */ private String name; public JMXPrincipal(String name) { if (name == null) throw new NullPointerException("Principal name cannot be null"); this.name = name; } public String getName() { return name; } public int hashCode() { return getName().hashCode(); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; try { JMXPrincipal other = (JMXPrincipal)obj; return getName().equals(other.getName()); } catch (ClassCastException x) { } return false; } public String toString() { return getName(); } } mx4j-3.0.2/src/core/javax/management/remote/JMXProviderException.java 100644 0 0 1532 10513545721 22663 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; /** * @version $Revision: 1.5 $ */ public class JMXProviderException extends IOException { /** * @serial The Throwable cause */ private Throwable cause; private static final long serialVersionUID = -3166703627550447198l; public JMXProviderException() { } public JMXProviderException(String message) { super(message); } public JMXProviderException(String message, Throwable cause) { super(message); this.cause = cause; } public Throwable getCause() { return cause; } } mx4j-3.0.2/src/core/javax/management/remote/JMXServerErrorException.java 100644 0 0 1326 10513545721 23352 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.IOException; /** * @version $Revision: 1.5 $ */ public class JMXServerErrorException extends IOException { /** * @serial The Error cause */ private Error cause; private static final long serialVersionUID = 3996732239558744666l; public JMXServerErrorException(String message, Error error) { super(message); this.cause = error; } public Throwable getCause() { return cause; } } mx4j-3.0.2/src/core/javax/management/remote/JMXServiceURL.java 100644 0 0 17232 10513545721 21221 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.Serializable; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.UnknownHostException; /** * @version $Revision: 1.12 $ */ public class JMXServiceURL implements Serializable { private static final long serialVersionUID = 8173364409860779292l; /** * @serial The protocol */ private String protocol; /** * @serial The host */ private String host; /** * @serial The port */ private int port; /** * @serial The path */ private String urlPath; private transient int hash; public JMXServiceURL(String url) throws MalformedURLException { if (url == null) throw new NullPointerException("Null JMXServiceURL string"); parse(url); } public JMXServiceURL(String protocol, String host, int port) throws MalformedURLException { this(protocol, host, port, null); } public JMXServiceURL(String protocol, String host, int port, String urlPath) throws MalformedURLException { if (port < 0) throw new MalformedURLException("Port number cannot be less than zero"); setProtocol(protocol); setHost(host); setPort(port); setURLPath(urlPath); } private String resolveHost() throws MalformedURLException { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException x) { throw new MalformedURLException("Cannot resolve local host name"); } } public String getProtocol() { return protocol; } private void setProtocol(String protocol) { if (protocol != null) this.protocol = protocol.toLowerCase(); else this.protocol = "jmxmp"; // Default required by the spec } public String getHost() { return host; } private void setHost(String host) throws MalformedURLException { if (host != null) this.host = host.toLowerCase(); else this.host = resolveHost().toLowerCase(); // Default required by the spec } public int getPort() { return port; } private void setPort(int port) { this.port = port; } public String getURLPath() { return urlPath; } private void setURLPath(String urlPath) { if (urlPath != null) { if (urlPath.length() > 0 && !urlPath.startsWith("/")) urlPath = "/" + urlPath; this.urlPath = urlPath; } else { this.urlPath = ""; // Default required by the spec } } public int hashCode() { if (hash == 0) { hash = getProtocol().hashCode(); String host = getHost(); hash = 29 * hash + (host != null ? host.hashCode() : 0); hash = 29 * hash + getPort(); String path = getURLPath(); hash = 29 * hash + (path != null ? path.hashCode() : 0); } return hash; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof JMXServiceURL)) return false; JMXServiceURL other = (JMXServiceURL)obj; if (!getProtocol().equalsIgnoreCase(other.getProtocol())) return false; String host = getHost(); String otherHost = other.getHost(); if (host != null ? !host.equalsIgnoreCase(otherHost) : otherHost != null) return false; if (getPort() != other.getPort()) return false; String path = getURLPath(); String otherPath = other.getURLPath(); if (path != null ? !path.equals(otherPath) : otherPath != null) return false; return true; } public String toString() { StringBuffer buffer = new StringBuffer("service:jmx:"); buffer.append(getProtocol()).append("://"); buffer.append(getHost()); int port = getPort(); if (port > 0) buffer.append(":").append(port); String path = getURLPath(); if (path != null) { if (!path.startsWith("/")) buffer.append("/"); buffer.append(path); } return buffer.toString(); } private void parse(String url) throws MalformedURLException { String prefix = "service:jmx:"; if (url.length() <= prefix.length()) throw new MalformedURLException("JMXServiceURL " + url + " must start with " + prefix); String servicejmx = url.substring(0, prefix.length()); if (!servicejmx.equalsIgnoreCase(prefix)) throw new MalformedURLException("JMXServiceURL " + url + " must start with " + prefix); String parse = url.substring(prefix.length()); String hostSeparator = "://"; int index = parse.indexOf(hostSeparator); if (index < 0) throw new MalformedURLException("No protocol defined for JMXServiceURL " + url); String protocol = parse.substring(0, index); checkProtocol(url, protocol); setProtocol(protocol); String hostAndMore = parse.substring(index + hostSeparator.length()); index = hostAndMore.indexOf('/'); if (index < 0) { parseHostAndPort(url, hostAndMore); setURLPath(null); } else { String hostAndPort = hostAndMore.substring(0, index); parseHostAndPort(url, hostAndPort); String pathAndMore = hostAndMore.substring(index); if (pathAndMore.length() > 0) { checkURLPath(url, pathAndMore); String path = "/".equals(pathAndMore) ? "" : pathAndMore; // Special case setURLPath(path); } } } private void parseHostAndPort(String url, String hostAndPort) throws MalformedURLException { if (hostAndPort.length() == 0) { setHost(null); setPort(0); return; } int colon = hostAndPort.indexOf(':'); if (colon == 0) throw new MalformedURLException("No host defined for JMXServiceURL " + url); if (colon > 0) { String host = hostAndPort.substring(0, colon); checkHost(url, host); setHost(host); String portString = hostAndPort.substring(colon + 1); try { int port = Integer.parseInt(portString); setPort(port); } catch (NumberFormatException x) { throw new MalformedURLException("Invalid port " + portString + " for JMXServiceURL " + url); } } else { checkHost(url, hostAndPort); setHost(hostAndPort); setPort(0); } } private void checkProtocol(String url, String protocol) throws MalformedURLException { if (protocol.length() == 0) throw new MalformedURLException("No protocol defined for JMXServiceURL " + url); if (!protocol.trim().equals(protocol)) throw new MalformedURLException("No leading or trailing white space allowed in protocol for JMXServiceURL " + url); } private void checkHost(String url, String host) throws MalformedURLException { if (host.length() == 0) throw new MalformedURLException("No host defined for JMXServiceURL " + url); if (!host.trim().equals(host)) throw new MalformedURLException("No leading or trailing white space allowed in host for JMXServiceURL " + url); } private void checkURLPath(String url, String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Invalid path for JMXServiceURL " + url); if (!path.trim().equals(path)) throw new MalformedURLException("No leading or trailing white space allowed in path for JMXServiceURL " + url); } } mx4j-3.0.2/src/core/javax/management/remote/MBeanServerForwarder.java 100644 0 0 1032 10513545721 22653 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import javax.management.MBeanServer; /** * @version $Revision: 1.3 $ */ public interface MBeanServerForwarder extends MBeanServer { public MBeanServer getMBeanServer(); public void setMBeanServer(MBeanServer server) throws IllegalArgumentException; } mx4j-3.0.2/src/core/javax/management/remote/NotificationResult.java 100644 0 0 4366 10513545721 22470 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * @version $Revision: 1.4 $ */ public class NotificationResult implements Serializable { private static final long serialVersionUID = 1191800228721395279l; /** * @serial The earliest sequence number */ private final long earliestSequenceNumber; /** * @serial The next sequence number */ private final long nextSequenceNumber; /** * @serial The notifications */ private final TargetedNotification[] targetedNotifications; public NotificationResult(long earliestSequenceNumber, long nextSequenceNumber, TargetedNotification[] targetedNotifications) { // Checks required by the specification (javadocs) if (earliestSequenceNumber < 0) throw new IllegalArgumentException("Earliest sequence number cannot be negative"); if (nextSequenceNumber < 0) throw new IllegalArgumentException("Next sequence number cannot be negative"); if (targetedNotifications == null) throw new IllegalArgumentException("TargetedNotification array cannot be null"); this.earliestSequenceNumber = earliestSequenceNumber; this.nextSequenceNumber = nextSequenceNumber; this.targetedNotifications = targetedNotifications; } public long getEarliestSequenceNumber() { return earliestSequenceNumber; } public long getNextSequenceNumber() { return nextSequenceNumber; } public TargetedNotification[] getTargetedNotifications() { return targetedNotifications; } public String toString() { StringBuffer buffer = new StringBuffer("NotificationResult[earliest="); buffer.append(getEarliestSequenceNumber()).append(", next="); buffer.append(getNextSequenceNumber()).append(", notifications="); TargetedNotification[] notifs = getTargetedNotifications(); List list = notifs == null ? null : Arrays.asList(notifs); buffer.append(list).append("]"); return buffer.toString(); } } mx4j-3.0.2/src/core/javax/management/remote/SubjectDelegationPermission.java 100644 0 0 1316 10513545721 24277 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.security.BasicPermission; /** * @version $Revision: 1.3 $ */ public final class SubjectDelegationPermission extends BasicPermission { public SubjectDelegationPermission(String name) { super(name); } public SubjectDelegationPermission(String name, String actions) { super(name, actions); if (actions != null) throw new IllegalArgumentException("The permission's actions must be null"); } } mx4j-3.0.2/src/core/javax/management/remote/TargetedNotification.java 100644 0 0 2175 10513545721 22745 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote; import java.io.Serializable; import javax.management.Notification; /** * @version $Revision: 1.4 $ */ public class TargetedNotification implements Serializable { /** * @serial The notification to transmit */ private final Notification notif; /** * @serial The listener's ID for the notification */ private final Integer id; public TargetedNotification(Notification notif, Integer id) { this.notif = notif; this.id = id; } public Notification getNotification() { return notif; } public Integer getListenerID() { return id; } public String toString() { StringBuffer buffer = new StringBuffer("TargetedNotification[id="); buffer.append(getListenerID()).append(", notification="); buffer.append(getNotification()).append("]"); return buffer.toString(); } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIConnection.java 100644 0 0 14636 10513545721 22122 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.rmi.MarshalledObject; import java.rmi.Remote; 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.4 $ */ public interface RMIConnection extends Remote { public String getConnectionId() throws IOException; public void close() throws IOException; public ObjectInstance createMBean(String className, ObjectName name, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException; public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException; public ObjectInstance createMBean(String className, ObjectName name, MarshalledObject params, String[] signature, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException; public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, MarshalledObject params, String[] signature, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException; public void unregisterMBean(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, MBeanRegistrationException, IOException; public ObjectInstance getObjectInstance(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, IOException; public Set queryMBeans(ObjectName name, MarshalledObject query, Subject delegationSubject) throws IOException; public Set queryNames(ObjectName name, MarshalledObject query, Subject delegationSubject) throws IOException; public boolean isRegistered(ObjectName name, Subject delegationSubject) throws IOException; public Integer getMBeanCount(Subject delegationSubject) throws IOException; public Object getAttribute(ObjectName name, String attribute, Subject delegationSubject) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException; public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegationSubject) throws InstanceNotFoundException, ReflectionException, IOException; public void setAttribute(ObjectName name, MarshalledObject attribute, Subject delegationSubject) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException; public AttributeList setAttributes(ObjectName name, MarshalledObject attributes, Subject delegationSubject) throws InstanceNotFoundException, ReflectionException, IOException; public Object invoke(ObjectName name, String operationName, MarshalledObject params, String[] signature, Subject delegationSubject) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException; public String getDefaultDomain(Subject delegationSubject) throws IOException; public String[] getDomains(Subject delegationSubject) throws IOException; public MBeanInfo getMBeanInfo(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException; public boolean isInstanceOf(ObjectName name, String className, Subject delegationSubject) throws InstanceNotFoundException, IOException; public void addNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegationSubject) throws InstanceNotFoundException, IOException; public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public void removeNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public Integer[] addNotificationListeners(ObjectName[] names, MarshalledObject[] filters, Subject[] delegationSubjects) throws InstanceNotFoundException, IOException; public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException; public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException; } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIConnectionImpl.java 100644 0 0 24073 10513545721 22740 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.rmi.MarshalledObject; import java.rmi.server.Unreferenced; import java.security.AccessControlContext; 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.NotificationResult; import javax.security.auth.Subject; import mx4j.remote.rmi.RMIConnectionInvoker; import mx4j.remote.rmi.RMIConnectionSubjectInvoker; /** * @version $Revision: 1.10 $ */ public class RMIConnectionImpl implements RMIConnection, Unreferenced { private final RMIServerImpl server; private final String connectionId; private final ClassLoader defaultClassLoader; private final Subject subject; private final Map environment; private RMIConnection chain; private AccessControlContext context; public RMIConnectionImpl(RMIServerImpl rmiServer, String connectionId, ClassLoader defaultClassLoader, Subject subject, Map environment) { this.server = rmiServer; this.connectionId = connectionId; this.defaultClassLoader = defaultClassLoader; this.subject = subject; this.environment = environment; } public String getConnectionId() throws IOException { // Do not forward to the chain return connectionId; } public void close() throws IOException { // Forward the call to the chain, to free resources getChain().close(); server.clientClosed(this); } public void unreferenced() { try { close(); } catch (IOException ignored) { } } private synchronized RMIConnection getChain() { if (chain == null) { // TODO: here we hardcode the server invocation chain. Maybe worth to remove this hardcoding ? RMIConnection serverInvoker = new RMIConnectionInvoker(server.getMBeanServer(), defaultClassLoader, environment); chain = RMIConnectionSubjectInvoker.newInstance(serverInvoker, subject, context, environment); } return chain; } public void addNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegate) throws InstanceNotFoundException, IOException { getChain().addNotificationListener(name, listener, filter, handback, delegate); } public Integer[] addNotificationListeners(ObjectName[] names, MarshalledObject[] filters, Subject[] delegates) throws InstanceNotFoundException, IOException { return getChain().addNotificationListeners(names, filters, delegates); } public ObjectInstance createMBean(String className, ObjectName name, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return getChain().createMBean(className, name, delegationSubject); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return getChain().createMBean(className, name, loaderName, delegationSubject); } public ObjectInstance createMBean(String className, ObjectName name, MarshalledObject params, String[] signature, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException { return getChain().createMBean(className, name, params, signature, delegationSubject); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, MarshalledObject params, String[] signature, Subject delegationSubject) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException { return getChain().createMBean(className, name, loaderName, params, signature, delegationSubject); } public void unregisterMBean(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, MBeanRegistrationException, IOException { getChain().unregisterMBean(name, delegationSubject); } public ObjectInstance getObjectInstance(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, IOException { return getChain().getObjectInstance(name, delegationSubject); } public Set queryMBeans(ObjectName name, MarshalledObject query, Subject delegationSubject) throws IOException { return getChain().queryMBeans(name, query, delegationSubject); } public Set queryNames(ObjectName name, MarshalledObject query, Subject delegationSubject) throws IOException { return getChain().queryNames(name, query, delegationSubject); } public boolean isRegistered(ObjectName name, Subject delegationSubject) throws IOException { return getChain().isRegistered(name, delegationSubject); } public Integer getMBeanCount(Subject delegationSubject) throws IOException { return getChain().getMBeanCount(delegationSubject); } public Object getAttribute(ObjectName name, String attribute, Subject delegate) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { return getChain().getAttribute(name, attribute, delegate); } public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegationSubject) throws InstanceNotFoundException, ReflectionException, IOException { return getChain().getAttributes(name, attributes, delegationSubject); } public void setAttribute(ObjectName name, MarshalledObject attribute, Subject delegationSubject) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, IOException { getChain().setAttribute(name, attribute, delegationSubject); } public AttributeList setAttributes(ObjectName name, MarshalledObject attributes, Subject delegationSubject) throws InstanceNotFoundException, ReflectionException, IOException { return getChain().setAttributes(name, attributes, delegationSubject); } public Object invoke(ObjectName name, String operationName, MarshalledObject params, String[] signature, Subject delegationSubject) throws InstanceNotFoundException, MBeanException, ReflectionException, IOException { return getChain().invoke(name, operationName, params, signature, delegationSubject); } public String getDefaultDomain(Subject delegationSubject) throws IOException { return getChain().getDefaultDomain(delegationSubject); } public String[] getDomains(Subject delegationSubject) throws IOException { return getChain().getDomains(delegationSubject); } public MBeanInfo getMBeanInfo(ObjectName name, Subject delegationSubject) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { return getChain().getMBeanInfo(name, delegationSubject); } public boolean isInstanceOf(ObjectName name, String className, Subject delegationSubject) throws InstanceNotFoundException, IOException { return getChain().isInstanceOf(name, className, delegationSubject); } public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getChain().removeNotificationListener(name, listener, delegate); } public void removeNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getChain().removeNotificationListener(name, listener, filter, handback, delegationSubject); } public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException { getChain().removeNotificationListeners(name, listenerIDs, delegationSubject); } public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException { return getChain().fetchNotifications(clientSequenceNumber, maxNotifications, timeout); } void setContext(AccessControlContext context) { this.context = context; } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIConnector.java 100644 0 0 16410 10513545721 21745 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; 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.JMXConnectorFactory; 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.remote.rmi.ClientExceptionCatcher; import mx4j.remote.rmi.ClientInvoker; import mx4j.remote.rmi.ClientUnmarshaller; import mx4j.remote.rmi.RMIHeartBeat; import mx4j.remote.rmi.RMIRemoteNotificationClientHandler; /** * @version $Revision: 1.26 $ */ public class RMIConnector implements JMXConnector, Serializable { private static final long serialVersionUID = 817323035842634473l; /** * @serial */ private final JMXServiceURL jmxServiceURL; /** * @serial */ private RMIServer rmiServer; private transient RMIConnection connection; private transient boolean connected; private transient boolean closed; private transient ClassLoader defaultClassLoader; private transient String connectionId; private transient ConnectionNotificationEmitter emitter; private transient HeartBeat heartbeat; private transient RemoteNotificationClientHandler notificationHandler; public RMIConnector(JMXServiceURL url, Map environment) { if (url == null) throw new IllegalArgumentException("JMXServiceURL cannot be null"); this.jmxServiceURL = url; this.rmiServer = null; initialize(environment); } public RMIConnector(RMIServer server, Map environment) { if (server == null) throw new IllegalArgumentException("RMIServer cannot be null"); this.jmxServiceURL = null; this.rmiServer = server; initialize(environment); } private void initialize(Map environment) { this.defaultClassLoader = findDefaultClassLoader(environment); this.emitter = new ConnectionNotificationEmitter(this); } private ClassLoader findDefaultClassLoader(Map environment) { if (environment == null) return null; Object loader = environment.get(JMXConnectorFactory.DEFAULT_CLASS_LOADER); if (loader != null && !(loader instanceof ClassLoader)) throw new IllegalArgumentException("Environment property " + JMXConnectorFactory.DEFAULT_CLASS_LOADER + " must be a ClassLoader"); return (ClassLoader)loader; } public void connect() throws IOException, SecurityException { connect(null); } public void connect(Map environment) throws IOException, SecurityException { synchronized (this) { if (connected) return; if (closed) throw new IOException("This RMIConnector has already been closed"); // Spec says, about default ClassLoader, to look here: // 1. Environment at connect(); if null, // 2. Environment at creation; if null, // 3. Context classloader at connect(). ClassLoader loader = findDefaultClassLoader(environment); if (loader != null) defaultClassLoader = loader; else if (defaultClassLoader == null) defaultClassLoader = Thread.currentThread().getContextClassLoader(); Map env = environment == null ? new HashMap() : environment; String protocol = jmxServiceURL.getProtocol(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, env); if (resolver == null) throw new IOException("Unsupported protocol: " + protocol); if (rmiServer == null) rmiServer = (RMIServer)resolver.lookupClient(jmxServiceURL, env); rmiServer = (RMIServer)resolver.bindClient(rmiServer, env); Object credentials = env.get(CREDENTIALS); this.connection = rmiServer.newClient(credentials); connected = true; this.connectionId = connection.getConnectionId(); this.heartbeat = new RMIHeartBeat(connection, emitter, env); this.notificationHandler = new RMIRemoteNotificationClientHandler(connection, defaultClassLoader, emitter, heartbeat, env); this.heartbeat.start(); this.notificationHandler.start(); } emitter.sendConnectionNotificationOpened(); } public void close() throws IOException { synchronized (this) { if (closed) return; connected = false; closed = true; if (notificationHandler != null) notificationHandler.stop(); if (heartbeat != null) heartbeat.stop(); if (connection != null) connection.close(); connection = null; rmiServer = null; } emitter.sendConnectionNotificationClosed(); } public String getConnectionId() throws IOException { return connectionId; } public MBeanServerConnection getMBeanServerConnection() throws IOException { return getMBeanServerConnection(null); } public MBeanServerConnection getMBeanServerConnection(Subject delegate) throws IOException { if (!connected) throw new IOException("Connection has not been established"); // TODO: here we hardcode the client invocation chain. Maybe worth remove this hardcoding ? ClientInvoker invoker = new ClientInvoker(connection, notificationHandler, delegate); MBeanServerConnection unmarshaller = ClientUnmarshaller.newInstance(invoker, defaultClassLoader); MBeanServerConnection catcher = ClientExceptionCatcher.newInstance(unmarshaller); return catcher; } public void addConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { emitter.addNotificationListener(listener, filter, handback); } public void removeConnectionNotificationListener(NotificationListener listener) throws ListenerNotFoundException { emitter.removeNotificationListener(listener); } public void removeConnectionNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { emitter.removeNotificationListener(listener, filter, handback); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); if (jmxServiceURL == null && rmiServer == null) throw new InvalidObjectException("Nor the JMXServiceURL nor the RMIServer were specified for this RMIConnector"); initialize(null); } private void writeObject(ObjectOutputStream oos) throws IOException { if (jmxServiceURL == null && rmiServer == null) throw new InvalidObjectException("Nor the JMXServiceURL nor the RMIServer were specified for this RMIConnector"); oos.defaultWriteObject(); } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIConnectorServer.java 100644 0 0 16272 10513545721 23142 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.remote.ConnectionResolver; import mx4j.remote.MX4JRemoteUtils; /** * @version $Revision: 1.16 $ */ public class RMIConnectorServer extends JMXConnectorServer { public static final String JNDI_REBIND_ATTRIBUTE = "jmx.remote.jndi.rebind"; public static final String RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE = "jmx.remote.rmi.client.socket.factory"; public static final String RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE = "jmx.remote.rmi.server.socket.factory"; private JMXServiceURL url; private final Map environment; private RMIServerImpl rmiServer; private final ClassLoader defaultClassLoader; private boolean active; private boolean stopped; public RMIConnectorServer(JMXServiceURL url, Map environment) throws IOException { this(url, environment, null, null); } public RMIConnectorServer(JMXServiceURL url, Map environment, MBeanServer server) throws IOException { this(url, environment, null, server); } public RMIConnectorServer(JMXServiceURL url, Map environment, RMIServerImpl rmiServer, MBeanServer server) throws IOException { super(server); if (url == null) throw new IllegalArgumentException("JMXServiceURL cannot be null"); this.url = url; this.environment = environment == null ? new HashMap() : new HashMap(environment); this.rmiServer = rmiServer; this.defaultClassLoader = findDefaultClassLoader(this.environment, server); } private ClassLoader findDefaultClassLoader(Map environment, MBeanServer server) throws IllegalArgumentException { Object loader = environment.get(JMXConnectorServerFactory.DEFAULT_CLASS_LOADER); Object loaderName = environment.get(JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME); if (loader != null && loaderName != null) throw new IllegalArgumentException("Environment properties " + JMXConnectorServerFactory.DEFAULT_CLASS_LOADER + " and " + JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME + " cannot be both defined"); if (loader != null) { if (!(loader instanceof ClassLoader)) throw new IllegalArgumentException("Environment property " + JMXConnectorServerFactory.DEFAULT_CLASS_LOADER + " must be a ClassLoader"); else return (ClassLoader)loader; } if (loaderName != null) { if (!(loaderName instanceof ObjectName)) throw new IllegalArgumentException("Environment property " + JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME + " must be an ObjectName"); ObjectName name = (ObjectName)loaderName; try { if (!server.isInstanceOf(name, ClassLoader.class.getName())) throw new InstanceNotFoundException(); return server.getClassLoader((ObjectName)loader); } catch (InstanceNotFoundException x) { throw new IllegalArgumentException("ObjectName " + name + " defined by environment property " + JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME + " must name a ClassLoader"); } } return Thread.currentThread().getContextClassLoader(); } public JMXServiceURL getAddress() { return url; } public Map getAttributes() { Map env = MX4JRemoteUtils.removeNonSerializableEntries(environment); return Collections.unmodifiableMap(env); } public boolean isActive() { return active; } private boolean isStopped() { return stopped; } public synchronized void start() throws IOException { Logger logger = getLogger(); if (isActive()) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("This RMIConnectorServer has already been started"); return; } if (isStopped()) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("This RMIConnectorServer has already been stopped"); throw new IOException("This RMIConnectorServer has already been stopped"); } MBeanServer server = getMBeanServer(); if (server == null) throw new IllegalStateException("This RMIConnectorServer is not attached to an MBeanServer"); JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (rmiServer == null) { if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); rmiServer = (RMIServerImpl)resolver.createServer(address, environment); } rmiServer.setRMIConnectorServer(this); rmiServer.setMBeanServer(server); rmiServer.setDefaultClassLoader(defaultClassLoader); rmiServer.export(); // Replace the JMXServiceURL, as it can now contain the encoded stub/ior url = resolver.bindServer(rmiServer, address, environment); active = true; if (logger.isEnabledFor(Logger.INFO)) logger.info("RMIConnectorServer started at: " + url); } public synchronized void stop() throws IOException { if (isStopped()) return; stopped = true; active = false; if (rmiServer != null) rmiServer.close(); JMXServiceURL address = getAddress(); String protocol = address.getProtocol(); ConnectionResolver resolver = ConnectionResolver.newConnectionResolver(protocol, environment); if (resolver == null) throw new MalformedURLException("Unsupported protocol: " + protocol); resolver.unbindServer(rmiServer, address, environment); resolver.destroyServer(rmiServer, address, environment); Logger logger = getLogger(); if (logger.isEnabledFor(Logger.INFO)) logger.info("RMIConnectorServer stopped at: " + address); } public JMXConnector toJMXConnector(Map env) throws IOException { if (!isActive()) throw new IllegalStateException("This JMXConnectorServer has not been started"); return super.toJMXConnector(env); } protected void connectionOpened(String connectionId, String message, Object userData) { super.connectionOpened(connectionId, message, userData); } protected void connectionClosed(String connectionId, String message, Object userData) { super.connectionClosed(connectionId, message, userData); } protected void connectionFailed(String connectionId, String message, Object userData) { super.connectionFailed(connectionId, message, userData); } private Logger getLogger() { return Log.getLogger(getClass().getName()); } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIIIOPServerImpl.java 100644 0 0 3121 10513545721 22537 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.rmi.Remote; import java.util.Map; import javax.rmi.CORBA.Stub; import javax.rmi.PortableRemoteObject; import javax.security.auth.Subject; /** * @version $Revision: 1.8 $ */ public class RMIIIOPServerImpl extends RMIServerImpl { public RMIIIOPServerImpl(Map env) throws IOException { super(env); } protected void export() throws IOException { PortableRemoteObject.exportObject(this); } protected String getProtocol() { return "iiop"; } public Remote toStub() throws IOException { Remote remote = PortableRemoteObject.toStub(this); if (!(remote instanceof Stub)) throw new IOException("Could not find IIOP stub"); return remote; } protected RMIConnection makeClient(String connectionId, Subject subject) throws IOException { RMIConnectionImpl client = new RMIConnectionImpl(this, connectionId, getDefaultClassLoader(), subject, getEnvironment()); client.setContext(getContext()); PortableRemoteObject.exportObject(client); return client; } protected void closeClient(RMIConnection client) throws IOException { PortableRemoteObject.unexportObject(client); } protected void closeServer() throws IOException { PortableRemoteObject.unexportObject(this); } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIJRMPServerImpl.java 100644 0 0 4442 10513545721 22556 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.rmi.Remote; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.RemoteObject; import java.rmi.server.UnicastRemoteObject; import java.util.Map; import javax.security.auth.Subject; /** * @version $Revision: 1.10 $ */ public class RMIJRMPServerImpl extends RMIServerImpl { private final int port; private final RMIClientSocketFactory clientFactory; private final RMIServerSocketFactory serverFactory; public RMIJRMPServerImpl(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf, Map env) throws IOException { super(env); this.port = port; this.clientFactory = csf; this.serverFactory = ssf; } protected void export() throws IOException { UnicastRemoteObject.exportObject(this, port, clientFactory, serverFactory); } protected String getProtocol() { return "rmi"; } public Remote toStub() throws IOException { return RemoteObject.toStub(this); } protected RMIConnection makeClient(String connectionId, Subject subject) throws IOException { RMIConnectionImpl client = new RMIConnectionImpl(this, connectionId, getDefaultClassLoader(), subject, getEnvironment()); client.setContext(getContext()); UnicastRemoteObject.exportObject(client, port, clientFactory, serverFactory); return client; } protected void closeClient(RMIConnection client) throws IOException { // The force parameter must be true, since a connector can be closed by the client code. // In this case there is a remote call pending (close() itself) and the object will not be exported. UnicastRemoteObject.unexportObject(client, true); } protected void closeServer() throws IOException { // The force parameter must be true, since a when I close a server I don't want that a pending call // to newClient() will avoid to unexport this server. UnicastRemoteObject.unexportObject(this, true); } } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIServer.java 100644 0 0 1126 10513545721 21237 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; /** * @version $Revision: 1.6 $ */ public interface RMIServer extends Remote { public String getVersion() throws RemoteException; public RMIConnection newClient(Object credentials) throws IOException, SecurityException; } mx4j-3.0.2/src/core/javax/management/remote/rmi/RMIServerImpl.java 100644 0 0 17524 10513545721 22112 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.remote.rmi; import java.io.IOException; import java.lang.ref.WeakReference; import java.rmi.Remote; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.management.MBeanServer; import javax.management.remote.JMXAuthenticator; import javax.management.remote.JMXConnectorServer; import javax.security.auth.Subject; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.remote.MX4JRemoteUtils; /** * @version $Revision: 1.14 $ */ public abstract class RMIServerImpl implements RMIServer { private ClassLoader defaultClassLoader; private MBeanServer server; private Map environment; private RMIConnectorServer connector; private Map connections = new HashMap(); private final AccessControlContext context; public RMIServerImpl(Map environment) { this.environment = new HashMap(environment); this.context = AccessController.getContext(); } AccessControlContext getContext() { return context; } public abstract Remote toStub() throws IOException; protected abstract void export() throws IOException; protected abstract String getProtocol(); protected abstract RMIConnection makeClient(String connectionId, Subject subject) throws IOException; protected abstract void closeClient(RMIConnection client) throws IOException; protected abstract void closeServer() throws IOException; public ClassLoader getDefaultClassLoader() { return defaultClassLoader; } public void setDefaultClassLoader(ClassLoader defaultClassLoader) { this.defaultClassLoader = defaultClassLoader; } public synchronized void setMBeanServer(MBeanServer server) { this.server = server; } public synchronized MBeanServer getMBeanServer() { return server; } public String getVersion() { return "1.0 MX4J"; } public synchronized RMIConnection newClient(Object credentials) throws IOException, SecurityException { final Subject subject = authenticate(getEnvironment(), credentials); final String connectionId = MX4JRemoteUtils.createConnectionID(getProtocol(), null, -1, subject); try { RMIConnection client = makeClient(connectionId, subject); WeakReference weak = new WeakReference(client); synchronized (connections) { connections.put(connectionId, weak); } connector.connectionOpened(connectionId, "Opened connection " + client, null); return client; } catch (IOException x) { throw x; } catch (RuntimeException x) { throw x; } catch (Exception x) { throw new IOException(x.toString()); } } private Subject authenticate(Map env, final Object credentials) throws SecurityException { Logger logger = getLogger(); Subject subject = null; final JMXAuthenticator authenticator = (JMXAuthenticator)env.get(JMXConnectorServer.AUTHENTICATOR); if (authenticator != null) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Authenticating new client using JMXAuthenticator " + authenticator); try { // We must check that the code that provided the JMXAuthenticator // has the permission to create a Subject subject = (Subject)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return authenticator.authenticate(credentials); } }, getContext()); if (subject == null) throw new SecurityException("JMXAuthenticator returned null Subject"); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Authentication successful"); } catch (SecurityException x) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Authentication failed", x); throw x; } catch (Throwable x) { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Authentication failed", x); throw new SecurityException(x.toString()); } } return subject; } protected void clientClosed(RMIConnection client) throws IOException { // Here we arrive when // 1. The server is closed // 2. The client is closed // We must ensure the connection is in both cases removed from the list of active connections String connectionID = client.getConnectionId(); WeakReference weak = null; synchronized (connections) { weak = (WeakReference)connections.remove(connectionID); } // TODO: maybe I am overzealous here, I could return silently if (weak == null) throw new IOException("Could not find active connection with ID " + connectionID); RMIConnection connection = (RMIConnection)weak.get(); if (connection != client) throw new IOException("Could not find active connection " + client); closeClient(client); connector.connectionClosed(client.getConnectionId(), "Closed connection " + client, null); } public synchronized void close() throws IOException { // The process of closing the server does: // 1. closeServer() --> unexports the server // 2. for each client in connections: // connection.close() // clientClosed(client) // closeClient(client) --> unexports the client // The process of closing the client does: // 1. connection.close() // clientClosed(client) // closeClient(client) --> unexports the client IOException serverException = null; try { closeServer(); } catch (IOException x) { serverException = x; } try { closeConnections(); } catch (IOException x) { if (serverException != null) throw serverException; throw x; } } private void closeConnections() throws IOException { IOException clientException = null; synchronized (connections) { while (!connections.isEmpty()) { // Yes, create an iterator every time. // While expensive, this is needed because connection.close() must // be able to modify the connections Map, and we don't want // to get ConcurrentModificationExceptions Iterator entries = connections.entrySet().iterator(); Map.Entry entry = (Map.Entry)entries.next(); WeakReference weak = (WeakReference)entry.getValue(); RMIConnection connection = (RMIConnection)weak.get(); if (connection == null) { // We can use the iterator to remove the entry, // since we don't call close(), that modifies the collection entries.remove(); continue; } else { try { connection.close(); } catch (IOException x) { if (clientException == null) clientException = x; } } } } if (clientException != null) throw clientException; } private Logger getLogger() { return Log.getLogger(getClass().getName()); } Map getEnvironment() { return environment; } void setRMIConnectorServer(RMIConnectorServer cntorServer) { this.connector = cntorServer; } } mx4j-3.0.2/src/core/javax/management/timer/Timer.java 100644 0 0 35336 10513545721 17571 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.timer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import mx4j.log.Log; import mx4j.log.Logger; import mx4j.timer.TimeQueue; import mx4j.timer.TimerTask; /** * @version $Revision: 1.19 $ */ public class Timer extends NotificationBroadcasterSupport implements TimerMBean, MBeanRegistration { public static final long ONE_SECOND = 1000; public static final long ONE_MINUTE = 60 * ONE_SECOND; public static final long ONE_HOUR = 60 * ONE_MINUTE; public static final long ONE_DAY = 24 * ONE_HOUR; public static final long ONE_WEEK = 7 * ONE_DAY; private TimeQueue queue = new TimeQueue(); private boolean isActive; private int notificationID; private HashMap tasks = new HashMap(); private boolean sendPastNotification; private ObjectName objectName; private Logger getLogger() { return Log.getLogger(getClass().getName()); } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { Logger logger = getLogger(); objectName = name; if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " preRegistered successfully"); return name; } public void postRegister(Boolean registrationDone) { Logger logger = getLogger(); boolean done = registrationDone.booleanValue(); if (!done) { logger.warn("Timer service " + objectName + " was not registered"); } else { if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " postRegistered successfully."); } } public void preDeregister() throws Exception { Logger logger = getLogger(); stop(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " preDeregistered successfully"); } public void postDeregister() { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " postDeregistered successfully"); } public void start() { if (!isActive()) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Starting Timer service " + objectName); queue.clear(); queue.start(); ArrayList tasks = updateTasks(); scheduleTasks(tasks); isActive = true; if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " started successfully"); } } public void stop() { if (isActive()) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Stopping Timer service " + objectName); queue.stop(); queue.clear(); isActive = false; if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Timer service " + objectName + " stopped successfully"); } } public boolean isActive() { return isActive; } public Integer addNotification(String type, String message, Object userData, Date date) throws IllegalArgumentException { return addNotification(type, message, userData, date, 0, 0, false); } public Integer addNotification(String type, String message, Object userData, Date date, long period) throws IllegalArgumentException { return addNotification(type, message, userData, date, period, 0, false); } public Integer addNotification(String type, String message, Object userData, Date date, long period, long occurrences) throws IllegalArgumentException { return addNotification(type, message, userData, date, period, occurrences, false); } public Integer addNotification(String type, String message, Object userData, Date date, long period, long occurrences, boolean fixedRate) throws IllegalArgumentException { if (date == null) throw new IllegalArgumentException("Notification date cannot be null"); if (period < 0) throw new IllegalArgumentException("Period cannot be negative"); if (occurrences < 0) throw new IllegalArgumentException("Occurrences cannot be negative"); long now = System.currentTimeMillis(); if (isActive()) { // Check for the validity of the notification times, as the Timer is active // Notification in the past, assume it's now if (date.getTime() < now) date = new Date(now); // Periodic limited, the last notification is in the past if (period > 0 && occurrences > 0) { long lastTime = date.getTime() + (occurrences - 1) * period; if (lastTime < now) throw new IllegalArgumentException("Last date for periodic notification is before current date"); } } // Anyway, register the notification, no matter if the Timer is active Integer id = addNotificationImpl(type, message, userData, date, period, occurrences, fixedRate); // If the Timer is active, schedule the notification if (isActive()) { TimerTask task = getTask(id); updateTask(task, now); if (!task.isFinished()) { queue.schedule(task); } } return id; } private Integer addNotificationImpl(String type, String message, Object userData, Date date, long period, long occurrences, boolean fixedRate) { Logger logger = getLogger(); Integer id = createNotificationID(); TimerNotification notification = new TimerNotification(type, this, 0, System.currentTimeMillis(), message, id); notification.setUserData(userData); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Adding timer notification: " + notification + " on Timer service " + objectName); TimerTask task = createTimerTask(notification, date, period, occurrences, fixedRate); synchronized (this) { tasks.put(id, task); } return id; } private TimerTask createTimerTask(TimerNotification notification, Date date, long period, long occurrences, boolean fixedRate) { return new TimerTask(notification, date, period, occurrences, fixedRate) { public void run() { // Send the notification TimerNotification notification = getNotification(); TimerNotification toSend; synchronized(notification) { toSend = new TimerNotification(notification.getType(), notification.getSource(), notification.getSequenceNumber(), notification.getTimeStamp(), notification.getMessage(), notification.getNotificationID()); toSend.setUserData(notification.getUserData()); notification.setSequenceNumber(notification.getSequenceNumber() + 1); } sendNotification(toSend); } }; } private ArrayList updateTasks() { ArrayList list = new ArrayList(); boolean sendPast = getSendPastNotifications(); long now = System.currentTimeMillis(); synchronized (this) { for (Iterator i = tasks.entrySet().iterator(); i.hasNext();) { Map.Entry entry = getNextNonFinishedTaskEntry(i); if (entry == null) break; TimerTask task = (TimerTask)entry.getValue(); if (!sendPast) { updateTask(task, now); if (task.isFinished()) continue; } list.add(task); } return list; } } private void updateTask(TimerTask task, long now) { long time = task.getNextExecutionTime(); while (time < now && !task.isFinished()) { if (task.isPeriodic()) { task.setNextExecutionTime(time + task.getPeriod()); time = task.getNextExecutionTime(); } else { task.setFinished(true); } } } private void scheduleTasks(ArrayList tasks) { synchronized (this) { for (int i = 0; i < tasks.size(); ++i) { TimerTask task = (TimerTask)tasks.get(i); queue.schedule(task); } } } public void removeNotification(Integer id) throws InstanceNotFoundException { Logger logger = getLogger(); synchronized (this) { TimerTask t = getTask(id); if (t == null) throw new InstanceNotFoundException("Cannot find notification to remove with id: " + id); queue.unschedule(t); tasks.remove(id); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification " + t.getNotification() + " removed successfully from Timer service " + objectName); } } public void removeNotifications(String type) throws InstanceNotFoundException { Logger logger = getLogger(); boolean found = false; synchronized (this) { for (Iterator i = tasks.entrySet().iterator(); i.hasNext();) { Map.Entry entry = getNextNonFinishedTaskEntry(i); if (entry == null) break; TimerTask t = (TimerTask)entry.getValue(); TimerNotification n = t.getNotification(); if (n.getType().equals(type)) { queue.unschedule(t); i.remove(); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification " + n + " removed successfully from Timer service " + objectName); found = true; } } } if (!found) throw new InstanceNotFoundException("Cannot find timer notification to remove with type: " + type + " from Timer service " + objectName); } public void removeAllNotifications() { synchronized (this) { queue.clear(); tasks.clear(); notificationID = 0; } } public Vector getAllNotificationIDs() { Vector vector = new Vector(); synchronized (this) { for (Iterator i = tasks.entrySet().iterator(); i.hasNext();) { Map.Entry entry = getNextNonFinishedTaskEntry(i); if (entry == null) break; vector.add(entry.getKey()); } } return vector; } public Vector getNotificationIDs(String type) { Vector vector = new Vector(); synchronized (this) { for (Iterator i = tasks.entrySet().iterator(); i.hasNext();) { Map.Entry entry = getNextNonFinishedTaskEntry(i); if (entry == null) break; TimerTask t = (TimerTask)entry.getValue(); TimerNotification n = t.getNotification(); if (n.getType().equals(type)) { vector.add(entry.getKey()); } } } return vector; } public boolean getSendPastNotifications() { return sendPastNotification; } public void setSendPastNotifications(boolean value) { sendPastNotification = value; } public int getNbNotifications() { int count = 0; synchronized (this) { for (Iterator i = tasks.entrySet().iterator(); i.hasNext();) { Map.Entry entry = getNextNonFinishedTaskEntry(i); if (entry == null) break; ++count; } return count; } } public boolean isEmpty() { synchronized (this) { return getNbNotifications() == 0; } } public String getNotificationType(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : t.getNotification().getType(); } } public String getNotificationMessage(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : t.getNotification().getMessage(); } } public Object getNotificationUserData(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : t.getNotification().getUserData(); } } public Date getDate(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : new Date(t.getDate()); } } public Long getPeriod(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : new Long(t.getPeriod()); } } public Long getNbOccurences(Integer id) { synchronized (this) { TimerTask t = getTask(id); return t == null ? null : new Long(t.getOccurrences()); } } private Integer createNotificationID() { synchronized (this) { return new Integer(++notificationID); } } private TimerTask getTask(Integer id) { Logger logger = getLogger(); synchronized (this) { TimerTask t = (TimerTask)tasks.get(id); if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Retrieving task with id " + id + ": " + t); if (t != null && t.isFinished()) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Task with id " + id + " is expired, removing it"); tasks.remove(id); t = null; } return t; } } private Map.Entry getNextNonFinishedTaskEntry(Iterator i) { Logger logger = getLogger(); synchronized (this) { if (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); TimerTask t = (TimerTask)entry.getValue(); if (t.isFinished()) { if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Found an expired notification, removing it: " + t); i.remove(); return getNextNonFinishedTaskEntry(i); } return entry; } return null; } } public void sendNotification(Notification n) { Logger logger = getLogger(); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Start sending notifications from Timer service " + objectName); super.sendNotification(n); if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Finished sending notifications from Timer service " + objectName); } public Boolean getFixedRate(Integer id) { return new Boolean(getTask(id).getFixedRate()); } } mx4j-3.0.2/src/core/javax/management/timer/TimerAlarmClock.java 100644 0 0 1254 10513545721 21472 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.timer; import java.util.Date; import java.util.TimerTask; /** * This class is here only to provide signature compatibility for * {@link TimerAlarmClockNotification}. * * @version $Revision: 1.3 $ */ class TimerAlarmClock extends TimerTask { public TimerAlarmClock(Timer timer, Date nextOccurrence) { } public TimerAlarmClock(Timer timer, long timeout) { } public void run() { } } mx4j-3.0.2/src/core/javax/management/timer/TimerAlarmClockNotification.java 100644 0 0 1443 10513545721 24041 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.timer; /** * Do not use, it is kept only for backward compatibility reasons. * This is a JMXRI class that creeped into the public JMX API by mistake. * MX4J does not use it. * * @version $Revision: 1.4 $ * @deprecated */ public class TimerAlarmClockNotification extends javax.management.Notification { private static final long serialVersionUID = 0xbcd1186b37930f5fL; /** * Do not use * * @deprecated */ public TimerAlarmClockNotification(TimerAlarmClock timer) { super("", timer, 0); } } mx4j-3.0.2/src/core/javax/management/timer/TimerMBean.java 100644 0 0 13722 10513545721 20467 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management.timer; import java.util.Date; import java.util.Vector; import javax.management.InstanceNotFoundException; /** * Management interface for the {@link Timer} class. * * @version $Revision: 1.6 $ */ public interface TimerMBean { /** * Shortcut for {@link #addNotification(String,String,Object,Date,long,long,boolean) addNotification(type, message, userData, date, 0L, 0L, false)} */ public Integer addNotification(String type, String message, Object userData, Date date) throws IllegalArgumentException; /** * Shortcut for {@link #addNotification(String,String,Object,Date,long,long,boolean) addNotification(type, message, userData, date, period, 0L, false)} */ public Integer addNotification(String type, String message, Object userData, Date date, long period) throws IllegalArgumentException; /** * Shortcut for {@link #addNotification(String,String,Object,Date,long,long,boolean) addNotification(type, message, userData, date, period, occurences, false)} */ public Integer addNotification(String type, String message, Object userData, Date date, long period, long occurences) throws IllegalArgumentException; /** * Adds a notification to this Timer.createMBeanAttributeInfo
, if the MBeans has manageable attributes createMBeanOperationInfo
, if the MBeans has manageable operations createMBeanNotificationInfo
, if the MBeans has manageable notifications createMBeanConstructorInfo
, if the MBeans has manageable constructors getMBeanDescription
* public class SimpleDynamic extends AbstractDynamicMBean * { * protected MBeanAttributeInfo[] createMBeanAttributeInfo() * { * return new MBeanAttributeInfo[] * { * new MBeanAttributeInfo("Name", String.class.getName(), "The name", true, true, false) * }; * } * * protected String getMBeanDescription() * { * return "A simple DynamicMBean"; * } * * public String getName() { ... } * * public void setName(String name) { ... } * } ** It is responsibility of the developer to specify the metadata and implement the methods specified by the * metadata, that will be invoked via reflection by the AbstractDynamicMBean class. For this reason, the methods * belonging to the MBean implementation (in the case above
getName()
and setName(...)
)
* must be public.
*
* @version $Revision: 1.7 $
*/
public abstract class AbstractDynamicMBean implements DynamicMBean
{
private MBeanInfo info;
private Object resource;
/**
* Only subclasses can create a new instance of an AbstractDynamicMBean.
*
* @see #createMBeanConstructorInfo
*/
protected AbstractDynamicMBean()
{
}
/**
* Returns the value of the manageable attribute, as specified by the DynamicMBean interface.
*
* @see #createMBeanAttributeInfo
*/
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException
{
if (attribute == null) throw new AttributeNotFoundException("Attribute " + attribute + " not found");
Object resource = null;
MBeanInfo info = null;
synchronized (this)
{
resource = getResourceOrThis();
info = getMBeanInfo();
}
MBeanAttributeInfo[] attrs = info.getAttributes();
if (attrs == null || attrs.length == 0) throw new AttributeNotFoundException("No attributes defined for this MBean");
for (int i = 0; i < attrs.length; ++i)
{
MBeanAttributeInfo attr = attrs[i];
if (attr == null) continue;
if (attribute.equals(attr.getName()))
{
if (!attr.isReadable()) throw new ReflectionException(new NoSuchMethodException("No getter defined for attribute: " + attribute));
// Found, invoke via reflection
String prefix = null;
if (attr.isIs())
prefix = "is";
else
prefix = "get";
try
{
return invoke(resource, prefix + attr.getName(), new Class[0], new Object[0]);
}
catch (InvalidAttributeValueException x)
{
throw new ReflectionException(x);
}
}
}
throw new AttributeNotFoundException("Attribute " + attribute + " not found");
}
/**
* Returns the manageable attributes, as specified by the DynamicMBean interface.
*/
public AttributeList getAttributes(String[] attributes)
{
AttributeList list = new AttributeList();
if (attributes != null)
{
for (int i = 0; i < attributes.length; ++i)
{
String attribute = attributes[i];
try
{
Object result = getAttribute(attribute);
list.add(new Attribute(attribute, result));
}
catch (AttributeNotFoundException ignored)
{
}
catch (MBeanException ignored)
{
}
catch (ReflectionException ignored)
{
}
}
}
return list;
}
/**
* Returns the MBeaInfo, as specified by the DynamicMBean interface; the default implementation caches the value
* returned by {@link #createMBeanInfo} (that is thus called only once).
*
* @see #createMBeanInfo
* @see #setMBeanInfo
*/
public synchronized MBeanInfo getMBeanInfo()
{
if (info == null) setMBeanInfo(createMBeanInfo());
return info;
}
/**
* Returns the value of the manageable operation as specified by the DynamicMBean interface
*
* @see #createMBeanOperationInfo
*/
public Object invoke(String method, Object[] arguments, String[] params) throws MBeanException, ReflectionException
{
if (method == null) throw new IllegalArgumentException("Method name cannot be null");
if (arguments == null) arguments = new Object[0];
if (params == null) params = new String[0];
Object resource = null;
MBeanInfo info = null;
synchronized (this)
{
resource = getResourceOrThis();
info = getMBeanInfo();
}
MBeanOperationInfo[] opers = info.getOperations();
if (opers == null || opers.length == 0) throw new ReflectionException(new NoSuchMethodException("No operations defined for this MBean"));
for (int i = 0; i < opers.length; ++i)
{
MBeanOperationInfo oper = opers[i];
if (oper == null) continue;
if (method.equals(oper.getName()))
{
MBeanParameterInfo[] parameters = oper.getSignature();
if (params.length != parameters.length) continue;
String[] signature = new String[parameters.length];
for (int j = 0; j < signature.length; ++j)
{
MBeanParameterInfo param = parameters[j];
if (param == null)
signature[j] = null;
else
signature[j] = param.getType();
}
if (Utils.arrayEquals(params, signature))
{
// Found the right operation
try
{
Class[] classes = Utils.loadClasses(resource.getClass().getClassLoader(), signature);
return invoke(resource, method, classes, arguments);
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
catch (InvalidAttributeValueException x)
{
throw new ReflectionException(x);
}
}
}
}
throw new ReflectionException(new NoSuchMethodException("Operation " + method + " with signature " + Arrays.asList(params) + " is not defined for this MBean"));
}
/**
* Sets the value of the manageable attribute, as specified by the DynamicMBean interface.
*
* @see #createMBeanAttributeInfo
*/
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
if (attribute == null) throw new AttributeNotFoundException("Attribute " + attribute + " not found");
Object resource = null;
MBeanInfo info = null;
synchronized (this)
{
resource = getResourceOrThis();
info = getMBeanInfo();
}
MBeanAttributeInfo[] attrs = info.getAttributes();
if (attrs == null || attrs.length == 0) throw new AttributeNotFoundException("No attributes defined for this MBean");
for (int i = 0; i < attrs.length; ++i)
{
MBeanAttributeInfo attr = attrs[i];
if (attr == null) continue;
if (attribute.getName().equals(attr.getName()))
{
if (!attr.isWritable()) throw new ReflectionException(new NoSuchMethodException("No setter defined for attribute: " + attribute));
try
{
String signature = attr.getType();
Class cls = Utils.loadClass(resource.getClass().getClassLoader(), signature);
invoke(resource, "set" + attr.getName(), new Class[]{cls}, new Object[]{attribute.getValue()});
return;
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
}
throw new AttributeNotFoundException("Attribute " + attribute + " not found");
}
/**
* Sets the manageable attributes, as specified by the DynamicMBean interface.
*/
public AttributeList setAttributes(AttributeList attributes)
{
AttributeList list = new AttributeList();
if (attributes != null)
{
for (int i = 0; i < attributes.size(); ++i)
{
Attribute attribute = (Attribute)attributes.get(i);
try
{
setAttribute(attribute);
list.add(attribute);
}
catch (AttributeNotFoundException ignored)
{
}
catch (InvalidAttributeValueException ignored)
{
}
catch (MBeanException ignored)
{
}
catch (ReflectionException ignored)
{
}
}
}
return list;
}
/**
* @deprecated Replaced by {@link #invoke(Object,String,Class[],Object[])}. {@link #createMBeanAttributeInfo}
{@link #createMBeanConstructorInfo}
{@link #createMBeanOperationInfo}
{@link #createMBeanNotificationInfo}
{@link #getMBeanClassName}
{@link #getMBeanDescription}
* The MX4J implementation will look, for every standard MBean, for a class with name composed by
* the fully qualified MBean class name + "MBeanDescription".
* If such a class is found, the MX4J implementation will call its methods to retrieve description
* information about the MBean itself.
* MBean descriptions are built-in in DynamicMBean, but not in standard MBeans.
* The XDoclet tool is used to automate the process of
* generating the MBeanDescription classes for a given MBean, along with the MBean interface.
*
* @version $Revision: 1.5 $
*/
public interface MBeanDescription
{
/**
* Should return the description of the MBean.
* For example: "This MBean is the rmiregistry service"
*/
public String getMBeanDescription();
/**
* Should return the description for the given constructor of the MBean.
* For example: "Creates an rmiregistry instance on the specified port"
*/
public String getConstructorDescription(Constructor ctor);
/**
* Should return the name of the constructor's parameter for the given constructor and parameter index.
* For example: "port"
*/
public String getConstructorParameterName(Constructor ctor, int index);
/**
* Should return the description for the constructor's parameter for the given constructor and parameter index.
* For example: "The port on which the rmiregistry will wait on for client requests"
*/
public String getConstructorParameterDescription(Constructor ctor, int index);
/**
* Should return the description for the specified attribute.
* For example: "The port on which the rmiregistry will wait on for client requests"
*/
public String getAttributeDescription(String attribute);
/**
* Should return the description for the specified operation.
* For example: "Binds the given object to the given name"
*/
public String getOperationDescription(Method operation);
/**
* Should return the name of the operation's parameter for the given operation and parameter index.
* For example: "bindName"
*/
public String getOperationParameterName(Method method, int index);
/**
* Should return the description for the operations's parameter for the given operation and parameter index.
* For example: "The name to which the object will be bound to"
*/
public String getOperationParameterDescription(Method method, int index);
}
mx4j-3.0.2/src/core/mx4j/MBeanDescriptionAdapter.java 100644 0 0 5075 10513545721 17472 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* Default implementation for the MBeanDescription interface.
*
* @version $Revision: 1.5 $
*/
public class MBeanDescriptionAdapter implements MBeanDescription
{
public String getMBeanDescription()
{
return "Manageable Bean";
}
public String getConstructorDescription(Constructor ctor)
{
return "Constructor exposed for management";
}
public String getConstructorParameterName(Constructor ctor, int index)
{
switch (index)
{
case 0:
return "param1";
case 1:
return "param2";
case 2:
return "param3";
case 3:
return "param4";
default:
return "param" + (index + 1);
}
}
public String getConstructorParameterDescription(Constructor ctor, int index)
{
switch (index)
{
case 0:
return "Constructor's parameter n. 1";
case 1:
return "Constructor's parameter n. 2";
case 2:
return "Constructor's parameter n. 3";
case 3:
return "Constructor's parameter n. 4";
default:
return "Constructor's parameter n. " + (index + 1);
}
}
public String getAttributeDescription(String attribute)
{
return "Attribute exposed for management";
}
public String getOperationDescription(Method operation)
{
return "Operation exposed for management";
}
public String getOperationParameterName(Method method, int index)
{
switch (index)
{
case 0:
return "param1";
case 1:
return "param2";
case 2:
return "param3";
case 3:
return "param4";
default:
return "param" + (index + 1);
}
}
public String getOperationParameterDescription(Method method, int index)
{
switch (index)
{
case 0:
return "Operation's parameter n. 1";
case 1:
return "Operation's parameter n. 2";
case 2:
return "Operation's parameter n. 3";
case 3:
return "Operation's parameter n. 4";
default:
return "Operation's parameter n. " + (index + 1);
}
}
}
mx4j-3.0.2/src/core/mx4j/MX4JSystemKeys.java 100644 0 0 10202 10513545721 15572 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j;
/**
* This class holds the system property keys that the MX4J implementation uses to plugin
* custom components.
* The naming convention is that, for a defined constant, the corrispondent system property
* is obtained by converting the constant name to lowercase and by replacing the underscores
* with dots so that, for example, the constant MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY
* correspond to the system property key mx4j.mbeanserver.classloader.repository
*
* @version $Revision: 1.7 $
*/
public final class MX4JSystemKeys
{
/**
* Specifies a full qualified class name of a class implementing the {@link mx4j.server.MBeanRepository}
* interface, that will be used by the MBeanServer to store information about registered MBeans.
*/
public static final String MX4J_MBEANSERVER_REPOSITORY = "mx4j.mbeanserver.repository";
/**
* Specifies a full qualified class name of a class extending the {@link mx4j.server.ModifiableClassLoaderRepository}
* class, that will be used by the MBeanServer to store ClassLoader MBeans that wants to be registered in
* the MBeanServer's ClassLoaderRepository.
*/
public static final String MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY = "mx4j.mbeanserver.classloader.repository";
/**
* Specifies the level of logging performed by the MX4J JMX implementation.
* Possible value are (case insensitive), from most verbose to least verbose:
*
* * @version $Revision: 1.3 $ */ public class CommonsLogger extends Logger { private org.apache.commons.logging.Log log = null; public CommonsLogger() { } protected void setCategory(String category) { super.setCategory(category); log = org.apache.commons.logging.LogFactory.getLog(getCategory()); } protected void log(int priority, Object message, Throwable t) { switch (priority) { case Logger.FATAL: if (t == null) log.fatal(message); else log.fatal(message, t); break; case Logger.ERROR: if (t == null) log.error(message); else log.error(message, t); break; case Logger.WARN: if (t == null) log.warn(message); else log.warn(message, t); break; case Logger.INFO: if (t == null) log.info(message); else log.info(message, t); break; case Logger.DEBUG: if (t == null) log.debug(message); else log.debug(message, t); break; case Logger.TRACE: if (t == null) log.trace(message); else log.trace(message, t); break; } } } mx4j-3.0.2/src/core/mx4j/log/FileLogger.java 100644 0 0 1251 10513545721 15573 0 ustar 0 0 /* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package mx4j.log; /** * This logger logs to a file.
* It's used by the ModelMBean implementation.
* Since the constructor takes a parameter, cannot be used as prototype for logging redirection.
*
* @version $Revision: 1.5 $
*/
public class FileLogger extends Logger
{
public FileLogger(String location)
{
// TODO
}
protected void log(int priority, Object message, Throwable t)
{
// TODO
}
}
mx4j-3.0.2/src/core/mx4j/log/Log.java 100644 0 0 17026 10513545721 14324 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeOperationsException;
import mx4j.MX4JSystemKeys;
/**
* Main class for the log service.
* The system property 'mx4j.log.priority' controls the priority of the standard logging, and defaults to 'warn'. * Possible values are, from least to greatest priority, the following (case insensitive): *
category
;
* if {@link #redirectTo} has been called then a new instance of the prototype Logger, associated with the given
* category, is returned. This requires the prototype Logger class to have a public parameterless
* constructor.
*/
public static Logger getLogger(String category)
{
if (category == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Category cannot be null"));
}
synchronized (m_loggerCache)
{
Logger logger = (Logger)m_loggerCache.get(category);
if (logger == null)
{
// Try to see if a delegate for this category overrides other settings
Logger prototype = null;
synchronized (m_prototypeMap)
{
prototype = (Logger)m_prototypeMap.get(category);
}
if (prototype == null)
{
// Try to see if a prototype for all categories has been set
if (m_prototype != null)
{
logger = createLogger(m_prototype, category);
}
else
{
logger = createLogger(null, category);
}
}
else
{
logger = createLogger(prototype, category);
}
// cache it
m_loggerCache.put(category, logger);
}
return logger;
}
}
private static Logger createLogger(Logger prototype, String category)
{
Logger logger = null;
try
{
logger = prototype == null ? new Logger() : (Logger)prototype.getClass().newInstance();
}
catch (Exception x)
{
x.printStackTrace();
logger = new Logger();
}
logger.setCategory(category);
logger.setPriority(m_defaultPriority);
return logger;
}
/**
* Tells to the log service to use the given delegate
Logger to perform logging.
* Use a null delegate to remove redirection.
*
* @see #getLogger
*/
public static void redirectTo(Logger prototype)
{
m_prototype = prototype;
// Clear the cache, as we want requests for new loggers to be generated again.
synchronized (m_loggerCache)
{
m_loggerCache.clear();
}
}
/**
* Tells to the log service to use the given delegate
Logger to perform logging for the given
* category (that cannot be null).
* Settings made using this method overrides the ones made with {@link #redirectTo(Logger) redirectTo}, meaning
* that it is possible to redirect all the log to a certain delegate but certain categories.
* Use a null delegate to remove redirection for the specified category.
*
* @see #getLogger
*/
public static void redirectTo(Logger prototype, String category)
{
if (category == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Category cannot be null"));
}
if (prototype == null)
{
// Remove the redirection
synchronized (m_prototypeMap)
{
m_prototypeMap.remove(category);
}
// Clear the cache for this category
synchronized (m_loggerCache)
{
m_loggerCache.remove(category);
}
}
else
{
// Put or replace
synchronized (m_prototypeMap)
{
m_prototypeMap.put(category, prototype);
}
// Clear the cache for this category
synchronized (m_loggerCache)
{
m_loggerCache.remove(category);
}
}
}
}
mx4j-3.0.2/src/core/mx4j/log/Log4JLogger.java 100644 0 0 3705 10513545721 15641 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* Log that redirects log calls to a Log4J Logger.
*
* @version $Revision: 1.7 $
* @see org.apache.log4j.Logger at Apache's Log4J
*/
public class Log4JLogger extends mx4j.log.Logger
{
private Logger m_logger;
/**
* This constructor is called to create instances of this Logger, following the prototype pattern.
*/
public Log4JLogger()
{
}
protected void setCategory(String category)
{
super.setCategory(category);
m_logger = Logger.getLogger(getCategory());
}
protected void log(int priority, Object message, Throwable t)
{
// Convert MX4J priority to log4j priority
Level l = convertPriority(priority);
m_logger.log(l, message, t);
}
/**
* Converts MX4J priority to Log4J priority
*/
protected Level convertPriority(int mx4jPriority)
{
Level log4jPriority = Level.DEBUG;
switch (mx4jPriority)
{
case mx4j.log.Logger.FATAL:
log4jPriority = Level.FATAL;
break;
case mx4j.log.Logger.ERROR:
log4jPriority = Level.ERROR;
break;
case mx4j.log.Logger.WARN:
log4jPriority = Level.WARN;
break;
case mx4j.log.Logger.INFO:
log4jPriority = Level.INFO;
break;
case mx4j.log.Logger.DEBUG:
log4jPriority = Level.DEBUG;
break;
case mx4j.log.Logger.TRACE:
log4jPriority = Level.DEBUG;
break;
default:
log4jPriority = Level.INFO;
break;
}
return log4jPriority;
}
}
mx4j-3.0.2/src/core/mx4j/log/Logger.java 100644 0 0 4656 10513545721 15007 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
/**
* Base class for logging objects.
*
* @version $Revision: 1.5 $
*/
public class Logger
{
public static final int TRACE = 0;
public static final int DEBUG = TRACE + 10;
public static final int INFO = DEBUG + 10;
public static final int WARN = INFO + 10;
public static final int ERROR = WARN + 10;
public static final int FATAL = ERROR + 10;
private int m_priority = WARN;
private String m_category;
protected Logger()
{
}
public void setPriority(int priority)
{
m_priority = priority;
}
public int getPriority()
{
return m_priority;
}
public String getCategory()
{
return m_category;
}
protected void setCategory(String category)
{
m_category = category;
}
public final boolean isEnabledFor(int priority)
{
return priority >= getPriority();
}
public final void fatal(Object message)
{
log(FATAL, message, null);
}
public final void fatal(Object message, Throwable t)
{
log(FATAL, message, t);
}
public final void error(Object message)
{
log(ERROR, message, null);
}
public final void error(Object message, Throwable t)
{
log(ERROR, message, t);
}
public final void warn(Object message)
{
log(WARN, message, null);
}
public final void warn(Object message, Throwable t)
{
log(WARN, message, t);
}
public final void info(Object message)
{
log(INFO, message, null);
}
public final void info(Object message, Throwable t)
{
log(INFO, message, t);
}
public final void debug(Object message)
{
log(DEBUG, message, null);
}
public final void debug(Object message, Throwable t)
{
log(DEBUG, message, t);
}
public final void trace(Object message)
{
log(TRACE, message, null);
}
public final void trace(Object message, Throwable t)
{
log(TRACE, message, t);
}
protected void log(int priority, Object message, Throwable t)
{
if (isEnabledFor(priority))
{
System.out.println(message);
if (t != null)
{
t.printStackTrace(System.out);
}
}
}
}
mx4j-3.0.2/src/core/mx4j/log/LoggerBroadcaster.java 100644 0 0 13735 10513545721 17177 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
/**
* This broadcaster MBean allows to redirect MX4J internal logging to registered JMX listeners.
* Simply register this MBean in the MBeanServer, register one or more listener (eventually with filters
* on the notification type), then call (directly or through MBeanServer) one of the start
* operations. From this moment, MX4J internal logging is redirected to this MBean, and from here to all registered
* listeners, basing on their filters.
*
* @version $Revision: 1.7 $
*/
public class LoggerBroadcaster extends NotificationBroadcasterSupport implements MBeanRegistration, LoggerBroadcasterMBean
{
private long m_sequence;
private boolean m_registered;
private int m_recursionLevel;
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception
{
return name;
}
public void postRegister(Boolean registrationDone)
{
if (!registrationDone.booleanValue())
{
return;
}
m_registered = true;
}
public void preDeregister() throws Exception
{
}
public void postDeregister()
{
m_registered = false;
}
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
// PENDING: for JMX 1.2 this has to be changed
super.removeNotificationListener(listener);
}
public void sendNotification(Notification n)
{
// Since I use a broadcaster to log, it happens that log requests of the broadcaster itself are redirected
// to the broadcaster, which broadcast to itself generating other log requests, an endless loop.
// Here I stop reentrant calls: maxRecursionLevel == 1 means that initial log requests are broadcasted, but log
// requests happening during this broadcast aren't; maxRecursionLevel == 2 means that initial log requests are
// broadcasted, and also log requests happening during this broadcast, while log requests happening during
// broadcast of log requests due to broacasting of the initial log request aren't.
int maxRecursionLevel = 1;
synchronized (this)
{
if (m_recursionLevel < maxRecursionLevel)
{
++m_recursionLevel;
super.sendNotification(n);
--m_recursionLevel;
}
}
}
public void start()
{
Logger logger = createLoggerPrototype();
Log.redirectTo(logger);
}
public void start(String category)
{
Logger logger = createLoggerPrototype();
Log.redirectTo(logger, category);
}
public void stop()
{
Log.redirectTo(null);
}
public void stop(String category)
{
Log.redirectTo(null, category);
}
private boolean isRegistered()
{
return m_registered;
}
public MBeanNotificationInfo[] getNotificationInfo()
{
String[] types = new String[]{"mx4j.logger.trace",
"mx4j.logger.debug",
"mx4j.logger.info",
"mx4j.logger.warn",
"mx4j.logger.error",
"mx4j.logger.fatal"};
MBeanNotificationInfo notifs = new MBeanNotificationInfo(types, "javax.management.Notification", "MX4J Logger MBean notifications");
return new MBeanNotificationInfo[]{notifs};
}
protected Logger createLoggerPrototype()
{
return new LoggerNotifier(this);
}
public static class LoggerNotifier extends Logger
{
private static LoggerBroadcaster m_loggerBroadcaster;
private LoggerNotifier(LoggerBroadcaster mbean)
{
m_loggerBroadcaster = mbean;
}
public LoggerNotifier()
{
}
protected void log(int priority, Object message, Throwable t)
{
// Notify listeners
notify(priority, message, t);
}
private void notify(int priority, Object message, Throwable t)
{
if (m_loggerBroadcaster.isRegistered())
{
long sequence = 0;
synchronized (this)
{
sequence = ++m_loggerBroadcaster.m_sequence;
}
String type = null;
switch (priority)
{
case TRACE:
type = "mx4j.logger.trace";
break;
case DEBUG:
type = "mx4j.logger.debug";
break;
case INFO:
type = "mx4j.logger.info";
break;
case WARN:
type = "mx4j.logger.warn";
break;
case ERROR:
type = "mx4j.logger.error";
break;
case FATAL:
type = "mx4j.logger.fatal";
break;
default:
type = "mx4j.logger." + priority;
break;
}
String msg = message == null ? "" : message.toString();
// TODO: the source must be the object name of the MBean if the listener was registered through MBeanServer
Notification n = new Notification(type, this, sequence, msg);
if (t != null)
{
n.setUserData(t);
}
m_loggerBroadcaster.sendNotification(n);
}
}
}
}
mx4j-3.0.2/src/core/mx4j/log/LoggerBroadcasterMBean.java 100644 0 0 1706 10513545721 20055 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
import javax.management.ListenerNotFoundException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
/**
* Management interface for the LoggerBroadcaster MBean.
*
* @version $Revision: 1.5 $
* @see LoggerBroadcaster
*/
public interface LoggerBroadcasterMBean
{
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback);
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException;
public void start();
public void start(String category);
public void stop();
public void stop(String category);
}
mx4j-3.0.2/src/core/mx4j/log/MBeanLogger.java 100644 0 0 5563 10513545721 15710 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.log;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ServiceNotFoundException;
/**
* This logger forwards log requests to an MBean, that must have an operation with signature
*
* public void log(int priority, Object message, Throwable exception);
*
* It's used by the ModelMBean implementation.
* Since the constructor takes parameters, cannot be used as prototype for logging redirection.
*
* @version $Revision: 1.7 $
*/
public class MBeanLogger extends Logger
{
private MBeanServer m_server;
private ObjectName m_name;
public MBeanLogger(MBeanServer server, ObjectName objectName) throws MBeanException
{
if (server == null)
{
throw new MBeanException(new IllegalArgumentException("MBeanServer cannot be null"));
}
if (objectName == null)
{
throw new MBeanException(new IllegalArgumentException("ObjectName cannot be null"));
}
m_server = server;
m_name = objectName;
boolean found = false;
try
{
MBeanInfo info = m_server.getMBeanInfo(m_name);
MBeanOperationInfo[] opers = info.getOperations();
if (opers != null)
{
for (int i = 0; i < opers.length; ++i)
{
MBeanOperationInfo oper = opers[i];
if (oper.getName().equals("log"))
{
MBeanParameterInfo[] params = oper.getSignature();
if (params.length == 3)
{
if (params[0].getType().equals("int") &&
params[1].getType().equals("java.lang.Object") &&
params[2].getType().equals("java.lang.Throwable"))
{
found = true;
break;
}
}
}
}
}
}
catch (Exception x)
{
x.printStackTrace();
}
if (!found)
{
throw new MBeanException(new ServiceNotFoundException("MBean does not have an operation log(int,Object,Throwable)"));
}
}
protected void log(int priority, Object message, Throwable t)
{
try
{
m_server.invoke(m_name, "log", new Object[]{new Integer(priority), message, t}, new String[]{"int", "java.lang.Object", "java.lang.Throwable"});
}
catch (Exception x)
{
x.printStackTrace();
}
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JCounterMonitor.java 100644 0 0 27414 10513545721 20145 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import java.math.BigInteger;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.monitor.MonitorNotification;
import mx4j.log.Logger;
/**
* @version $Revision: 1.6 $
*/
public class MX4JCounterMonitor extends MX4JMonitor implements MX4JCounterMonitorMBean
{
private static Integer ZERO = new Integer(0);
private Number threshold = ZERO;
private Number offset = ZERO;
private Number modulus = ZERO;
private boolean notify;
private boolean differenceMode;
public MX4JCounterMonitor() throws NotCompliantMBeanException
{
super(MX4JCounterMonitorMBean.class);
}
protected MX4JCounterMonitor(Class management) throws NotCompliantMBeanException
{
super(management);
}
public MBeanNotificationInfo[] getNotificationInfo()
{
// TODO
return new MBeanNotificationInfo[0];
}
public synchronized Number getInitThreshold()
{
return threshold;
}
public void setInitThreshold(Number threshold) throws IllegalArgumentException
{
if (threshold == null || compare(threshold, ZERO) < 0) throw new IllegalArgumentException("Threshold cannot be " + threshold);
this.threshold = threshold;
}
public synchronized Number getOffset()
{
return offset;
}
public void setOffset(Number offset) throws IllegalArgumentException
{
if (offset == null || compare(offset, ZERO) < 0) throw new IllegalArgumentException("Offset cannot be " + offset);
this.offset = offset;
}
public Number getModulus()
{
return modulus;
}
public void setModulus(Number modulus) throws IllegalArgumentException
{
if (modulus == null || compare(modulus, ZERO) < 0) throw new IllegalArgumentException("Modulus cannot be " + modulus);
this.modulus = modulus;
}
public boolean getNotify()
{
return notify;
}
public void setNotify(boolean notify)
{
this.notify = notify;
}
public boolean getDifferenceMode()
{
return differenceMode;
}
public void setDifferenceMode(boolean mode)
{
this.differenceMode = mode;
}
public Number getDerivedGauge(ObjectName name)
{
CounterMonitorInfo info = (CounterMonitorInfo)getMonitorInfo(name);
return info.getGauge();
}
public long getDerivedGaugeTimeStamp(ObjectName name)
{
CounterMonitorInfo info = (CounterMonitorInfo)getMonitorInfo(name);
return info.getTimestamp();
}
public Number getThreshold(ObjectName name)
{
CounterMonitorInfo info = (CounterMonitorInfo)getMonitorInfo(name);
return info.getThreshold();
}
protected int compare(Number left, Number right)
{
if (left instanceof BigInteger && right instanceof BigInteger) return ((BigInteger)left).compareTo((BigInteger)right);
if (left.longValue() == right.longValue()) return 0;
return left.longValue() > right.longValue() ? 1 : -1;
}
protected Number sum(Number left, Number right)
{
if (left instanceof BigInteger && right instanceof BigInteger) return ((BigInteger)left).add((BigInteger)right);
if (left instanceof BigInteger) return ((BigInteger)left).add(BigInteger.valueOf(right.longValue()));
if (right instanceof BigInteger) return ((BigInteger)right).add(BigInteger.valueOf(left.longValue()));
if (left instanceof Long || right instanceof Long) return new Long(left.longValue() + right.longValue());
if (left instanceof Integer || right instanceof Integer) return new Integer(left.intValue() + right.intValue());
if (left instanceof Short || right instanceof Short) return new Short((short)(left.shortValue() + right.shortValue()));
if (left instanceof Byte || right instanceof Byte) return new Byte((byte)(left.byteValue() + right.byteValue()));
return null;
}
protected Number sub(Number left, Number right)
{
if (left instanceof BigInteger && right instanceof BigInteger) return ((BigInteger)left).subtract((BigInteger)right);
if (left instanceof BigInteger) return ((BigInteger)left).subtract(BigInteger.valueOf(right.longValue()));
if (left instanceof Long || right instanceof Long) return new Long(left.longValue() - right.longValue());
if (left instanceof Integer || right instanceof Integer) return new Integer(left.intValue() - right.intValue());
if (left instanceof Short || right instanceof Short) return new Short((short)(left.shortValue() - right.shortValue()));
if (left instanceof Byte || right instanceof Byte) return new Byte((byte)(left.byteValue() - right.byteValue()));
return null;
}
protected void monitor(ObjectName name, String attribute, Object value, MonitorInfo monitorInfo)
{
if (!(value instanceof Number))
{
sendErrorNotification(monitorInfo, MonitorNotification.OBSERVED_ATTRIBUTE_TYPE_ERROR, "Attribute type must be a Number, not " + value.getClass(), name, attribute);
return;
}
// Spec requires that types of gauge, threshold, offset and modulus be affine
Number threshold = null;
Number offset = null;
Number modulus = null;
synchronized (this)
{
threshold = getThreshold(name);
offset = getOffset();
modulus = getModulus();
}
Number counter = (Number)value;
Class gaugeClass = counter.getClass();
if (threshold != ZERO && threshold.getClass() != gaugeClass)
{
sendErrorNotification(monitorInfo, MonitorNotification.THRESHOLD_ERROR, "Threshold type " + threshold.getClass() + " must be of same type of the attribute " + gaugeClass, name, attribute);
return;
}
if (offset != ZERO && offset.getClass() != gaugeClass)
{
sendErrorNotification(monitorInfo, MonitorNotification.THRESHOLD_ERROR, "Offset type " + offset.getClass() + " must be of same type of the attribute " + gaugeClass, name, attribute);
return;
}
if (modulus != ZERO && modulus.getClass() != gaugeClass)
{
sendErrorNotification(monitorInfo, MonitorNotification.THRESHOLD_ERROR, "Modulus type " + modulus.getClass() + " must be of same type of the attribute " + gaugeClass, name, attribute);
return;
}
Logger logger = getLogger();
// Contains previous gauge and threshold
CounterMonitorInfo info = (CounterMonitorInfo)monitorInfo;
// see if the counter rolled over (the value went down)
Number lastCounter = info.getCounter();
boolean rolledOver = (lastCounter != null) ? compare(counter, lastCounter) < 0 : false;
// calculate V[t] using rules from spec
Number vt;
if (getDifferenceMode())
{
if (lastCounter == null)
{
// we had no previous sample so the value is ZERO
vt = ZERO;
}
else
{
vt = sub(counter, lastCounter);
if (rolledOver)
{
// the delta was negative so add the modulus
vt = sum(vt, modulus);
}
// if we rolled over reset the threshold
if (rolledOver)
{
threshold = getInitThreshold();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Threshold has been rolled over, new value = " + threshold);
}
}
}
else
{
vt = counter;
// if we rolled over and have a modulus that is greater than the threshold, reset it
if (rolledOver && compare(modulus, ZERO) > 0 && compare(threshold, modulus) > 0)
{
threshold = getInitThreshold();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Threshold has been rolled over, new value = " + threshold);
}
}
if (logger.isEnabledFor(Logger.DEBUG))
{
logger.debug("Computing gauge, previous values are: " + info);
logger.debug("Current values are: threshold=" + threshold + ", offset=" + offset + ", modulus=" + modulus);
logger.debug("V[t] = " + vt + ", rolledOver = " + rolledOver);
}
info.setGauge(vt);
boolean notified;
if (compare(vt, threshold) >= 0)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Threshold exceeded: V[t]=" + vt + ", threshold=" + threshold);
// send any notification that is needed
if (getNotify())
{
if (info.isThresholdNotified())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Threshold exceeded already notified");
}
else
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending threshold exceeded notification");
sendNotification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, "Threshold " + threshold + " exceeded: " + vt, name, attribute, counter, threshold);
}
notified = true;
}
else
{
notified = false;
}
// adjust the threshold upward
if (compare(offset, ZERO) > 0)
{
do
{
threshold = sum(threshold, offset);
} while (compare(vt, threshold) >= 0);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Threshold has been offset, new value = " + threshold);
}
}
else
{
// cancel any notification status
notified = false;
}
CounterMonitorInfo newInfo = (CounterMonitorInfo)createMonitorInfo();
newInfo.setThresholdNotified(notified);
newInfo.setCounter(counter);
newInfo.setGauge(vt);
newInfo.setTimestamp(System.currentTimeMillis());
newInfo.setThreshold(threshold);
putMonitorInfo(name, newInfo);
}
protected MonitorInfo createMonitorInfo()
{
return new CounterMonitorInfo();
}
protected class CounterMonitorInfo extends MonitorInfo
{
private boolean thresholdNotified;
private Number counter = null;
private Number gauge = ZERO;
private long timestamp;
private Number threshold = ZERO;
public void setThreshold(Number threshold)
{
this.threshold = threshold;
}
public Number getThreshold()
{
if (threshold == ZERO) return getInitThreshold();
return threshold;
}
public void setThresholdNotified(boolean thresholdNotified)
{
this.thresholdNotified = thresholdNotified;
}
public boolean isThresholdNotified()
{
return thresholdNotified;
}
public void setCounter(Number counter)
{
this.counter = counter;
}
public Number getCounter()
{
return counter;
}
public void setGauge(Number gauge)
{
this.gauge = gauge;
}
public Number getGauge()
{
return gauge;
}
public void setTimestamp(long timestamp)
{
this.timestamp = timestamp;
}
public long getTimestamp()
{
return timestamp;
}
public void clearNotificationStatus()
{
super.clearNotificationStatus();
thresholdNotified = false;
}
public String toString()
{
StringBuffer buffer = new StringBuffer(super.toString());
buffer.append(", thresholdNotified=").append(isThresholdNotified());
buffer.append(", gauge=").append(getGauge());
buffer.append(", counter=").append(getCounter());
buffer.append(", threshold=").append(threshold);
return buffer.toString();
}
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JCounterMonitorMBean.java 100644 0 0 2067 10513545721 21025 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.ObjectName;
/**
* @version $Revision: 1.3 $
*/
public interface MX4JCounterMonitorMBean extends MX4JMonitorMBean
{
public Number getDerivedGauge(ObjectName objectName);
public long getDerivedGaugeTimeStamp(ObjectName objectName);
public Number getThreshold(ObjectName objectName);
public Number getInitThreshold();
public void setInitThreshold(Number value) throws IllegalArgumentException;
public Number getOffset();
public void setOffset(Number value) throws IllegalArgumentException;
public Number getModulus();
public void setModulus(Number value) throws IllegalArgumentException;
public boolean getNotify();
public void setNotify(boolean value);
public boolean getDifferenceMode();
public void setDifferenceMode(boolean value);
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JGaugeMonitor.java 100644 0 0 25434 10513545721 17556 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.monitor.MonitorNotification;
import mx4j.log.Logger;
/**
* @version $Revision: 1.3 $
*/
public class MX4JGaugeMonitor extends MX4JMonitor implements MX4JGaugeMonitorMBean
{
private static Integer ZERO = new Integer(0);
private Number highThreshold = ZERO;
private Number lowThreshold = ZERO;
private boolean notifyHigh;
private boolean notifyLow;
private boolean differenceMode;
public MX4JGaugeMonitor() throws NotCompliantMBeanException
{
super(MX4JGaugeMonitorMBean.class);
}
protected MX4JGaugeMonitor(Class management) throws NotCompliantMBeanException
{
super(management);
}
public MBeanNotificationInfo[] getNotificationInfo()
{
// TODO
return new MBeanNotificationInfo[0];
}
public synchronized Number getHighThreshold()
{
return highThreshold;
}
public synchronized Number getLowThreshold()
{
return lowThreshold;
}
public void setThresholds(Number highValue, Number lowValue) throws IllegalArgumentException
{
if (highValue == null) throw new IllegalArgumentException("High Threshold cannot be null");
if (lowValue == null) throw new IllegalArgumentException("Low Threshold cannot be null");
if (highValue.getClass() != lowValue.getClass()) throw new IllegalArgumentException("Thresholds must be of the same type");
if (compare(highValue, lowValue) < 0) throw new IllegalArgumentException("High threshold cannot be lower than low threshold");
highThreshold = highValue;
lowThreshold = lowValue;
}
public synchronized boolean getNotifyHigh()
{
return notifyHigh;
}
public synchronized boolean getNotifyLow()
{
return notifyLow;
}
public synchronized void setNotifyHigh(boolean notifyHigh)
{
this.notifyHigh = notifyHigh;
}
public synchronized void setNotifyLow(boolean notifyLow)
{
this.notifyLow = notifyLow;
}
public synchronized boolean getDifferenceMode()
{
return differenceMode;
}
public synchronized void setDifferenceMode(boolean differenceMode)
{
this.differenceMode = differenceMode;
}
public Number getDerivedGauge(ObjectName objectName)
{
GaugeMonitorInfo info = (GaugeMonitorInfo)getMonitorInfo(objectName);
return info.getGauge();
}
public long getDerivedGaugeTimeStamp(ObjectName objectName)
{
GaugeMonitorInfo info = (GaugeMonitorInfo)getMonitorInfo(objectName);
return info.getTimestamp();
}
protected MonitorInfo createMonitorInfo()
{
return new GaugeMonitorInfo();
}
protected int compare(Number left, Number right)
{
if (left instanceof BigDecimal && right instanceof BigDecimal) return ((BigDecimal)left).compareTo((BigDecimal)right);
if (left instanceof BigInteger && right instanceof BigInteger) return ((BigInteger)left).compareTo((BigInteger)right);
return new Double(left.doubleValue()).compareTo(new Double(right.doubleValue()));
}
protected Number sub(Number left, Number right)
{
if (left instanceof BigDecimal && right instanceof BigDecimal) return ((BigDecimal)left).subtract((BigDecimal)right);
if (left instanceof BigDecimal) return ((BigDecimal)left).subtract(new BigDecimal(right.doubleValue()));
if (left instanceof BigInteger && right instanceof BigInteger) return ((BigInteger)left).subtract((BigInteger)right);
if (left instanceof BigInteger) return ((BigInteger)left).subtract(BigInteger.valueOf(right.longValue()));
if (left instanceof Double || right instanceof Double) return new Double(left.doubleValue() - right.doubleValue());
if (left instanceof Float || right instanceof Float) return new Float(left.floatValue() - right.floatValue());
if (left instanceof Long || right instanceof Long) return new Long(left.longValue() - right.longValue());
if (left instanceof Integer || right instanceof Integer) return new Integer(left.intValue() - right.intValue());
if (left instanceof Short || right instanceof Short) return new Short((short)(left.shortValue() - right.shortValue()));
if (left instanceof Byte || right instanceof Byte) return new Byte((byte)(left.byteValue() - right.byteValue()));
return null;
}
protected void monitor(ObjectName name, String attribute, Object value, MonitorInfo monitorInfo)
{
if (!(value instanceof Number))
{
sendErrorNotification(monitorInfo, MonitorNotification.OBSERVED_ATTRIBUTE_TYPE_ERROR, "Attribute type must be a Number, not " + value.getClass(), name, attribute);
return;
}
Number gauge = (Number)value;
// Spec requires that types of gauge, high threshold and low threshold be affine
Number high = null;
Number low = null;
synchronized (this)
{
high = getHighThreshold();
low = getLowThreshold();
}
Class gaugeClass = gauge.getClass();
if (high != ZERO && high.getClass() != gaugeClass)
{
sendErrorNotification(monitorInfo, MonitorNotification.THRESHOLD_ERROR, "Threshold type " + high.getClass() + " must be of same type of the attribute " + gaugeClass, name, attribute);
return;
}
if (low != ZERO && low.getClass() != gaugeClass)
{
sendErrorNotification(monitorInfo, MonitorNotification.THRESHOLD_ERROR, "Offset type " + low.getClass() + " must be of same type of the attribute " + gaugeClass, name, attribute);
return;
}
Logger logger = getLogger();
// Contains previous gauge
GaugeMonitorInfo info = (GaugeMonitorInfo)monitorInfo;
if (logger.isEnabledFor(Logger.DEBUG))
{
logger.debug("Computing gauge, previous values are: " + info);
logger.debug("Current values are: gauge=" + gauge + ", highThreshold=" + high + ", lowThreshold=" + low);
}
if (getDifferenceMode())
{
Number diffGauge = sub(gauge, info.getGauge());
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("CounterMonitor in difference mode, difference gauge=" + diffGauge);
compareAndSendNotification(diffGauge, low, high, info, name, attribute);
}
else
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("CounterMonitor in absolute mode, gauge=" + gauge);
compareAndSendNotification(gauge, low, high, info, name, attribute);
}
info.setGauge(gauge);
info.setTimestamp(System.currentTimeMillis());
}
private void compareAndSendNotification(Number gauge, Number low, Number high, GaugeMonitorInfo info, ObjectName name, String attribute)
{
Logger logger = getLogger();
if (info.isHighNotified() && compare(gauge, low) > 0)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("High threshold " + high + " already notified, gauge " + gauge + " not below low threshold " + low);
return;
}
if (info.isLowNotified() && compare(gauge, high) < 0)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Low threshold " + low + " already notified, gauge " + gauge + " not above high threshold " + high);
return;
}
if (compare(gauge, high) >= 0)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Gauge above high threshold: gauge=" + gauge + ", high threshold=" + high + ", low threshold=" + low);
info.setLowNotified(false);
if (getNotifyHigh())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending high threshold exceeded notification");
info.setHighNotified(true);
sendNotification(MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED, "High threshold " + high + " exceeded: " + gauge, name, attribute, gauge, high);
}
else
{
info.setHighNotified(false);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("GaugeMonitor is configured in non-high-notification mode");
}
}
else if (compare(gauge, low) <= 0)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Gauge below low threshold: gauge=" + gauge + ", low threshold=" + low + ", high threshold=" + high);
info.setHighNotified(false);
if (getNotifyLow())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending low threshold exceeded notification");
info.setLowNotified(true);
sendNotification(MonitorNotification.THRESHOLD_LOW_VALUE_EXCEEDED, "Low threshold " + low + " exceeded: " + gauge, name, attribute, gauge, low);
}
else
{
info.setLowNotified(false);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("GaugeMonitor is configured in non-low-notification mode");
}
}
else
{
info.setHighNotified(false);
info.setLowNotified(false);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Gauge between thresholds: gauge=" + gauge + ", low threshold=" + low + ", high threshold=" + high);
}
}
protected class GaugeMonitorInfo extends MonitorInfo
{
private Number gauge = ZERO;
private long timestamp;
private boolean highNotified;
private boolean lowNotified;
public Number getGauge()
{
return gauge;
}
public void setGauge(Number gauge)
{
this.gauge = gauge;
}
public long getTimestamp()
{
return timestamp;
}
public void setTimestamp(long timestamp)
{
this.timestamp = timestamp;
}
public boolean isHighNotified()
{
return highNotified;
}
public void setHighNotified(boolean highNotified)
{
this.highNotified = highNotified;
}
public boolean isLowNotified()
{
return lowNotified;
}
public void setLowNotified(boolean lowNotified)
{
this.lowNotified = lowNotified;
}
public void clearNotificationStatus() {
super.clearNotificationStatus();
highNotified = false;
lowNotified = false;
}
public String toString()
{
StringBuffer buffer = new StringBuffer(super.toString());
buffer.append(", gauge=").append(getGauge());
buffer.append(", lowNotified=").append(isLowNotified());
buffer.append(", highNotified=").append(isHighNotified());
return buffer.toString();
}
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JGaugeMonitorMBean.java 100644 0 0 1673 10513545721 20440 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.ObjectName;
/**
* @version $Revision: 1.3 $
*/
public interface MX4JGaugeMonitorMBean extends MX4JMonitorMBean
{
public Number getDerivedGauge(ObjectName objectName);
public long getDerivedGaugeTimeStamp(ObjectName objectName);
public Number getHighThreshold();
public Number getLowThreshold();
public void setThresholds(Number highValue, Number lowValue) throws IllegalArgumentException;
public boolean getNotifyHigh();
public void setNotifyHigh(boolean value);
public boolean getNotifyLow();
public void setNotifyLow(boolean value);
public boolean getDifferenceMode();
public void setDifferenceMode(boolean value);
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JMonitor.java 100644 0 0 25314 10513545721 16602 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.StandardMBean;
import javax.management.monitor.MonitorNotification;
import mx4j.log.Log;
import mx4j.log.Logger;
import mx4j.timer.TimeQueue;
import mx4j.timer.TimeTask;
/**
* The class that implements the Monitor behavior of the JMX specification.
* IMPLEMENTATION NOTE:
* There is one single thread that handles monitoring, for all monitor objects.
* There is one single task per each monitor object that runs.
* The queue will have possibly many tasks per each monitor type.
* Each monitor handles many MBeans, but only one attribute; however, both MBeans and attribute can be changed,
* though it would be a strange way to use the monitor.
*
* @version $Revision: 1.6 $
*/
public abstract class MX4JMonitor extends StandardMBean implements MX4JMonitorMBean, MBeanRegistration, NotificationEmitter
{
private static final TimeQueue queue = new TimeQueue();
private static int references = 0;
private static int sequenceNumber;
private NotificationBroadcasterSupport emitter;
private MBeanServer server;
private boolean active;
private List observeds = new ArrayList();
private volatile String attribute;
private volatile long granularity = 10 * 1000; // Spec says default is 10 seconds
private boolean errorNotified;
private final TimeTask task = new MonitorTask();
private final Map infos = new HashMap();
protected MX4JMonitor(Class management) throws NotCompliantMBeanException
{
super(management);
}
// TODO: override descriptions for this MBean
public ObjectName preRegister(MBeanServer server, ObjectName name)
{
this.server = server;
return name;
}
public void postRegister(Boolean registrationDone)
{
}
public void preDeregister()
{
stop();
}
public void postDeregister()
{
server = null;
}
protected NotificationBroadcasterSupport createNotificationEmitter()
{
return new NotificationBroadcasterSupport();
}
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException
{
emitter.addNotificationListener(listener, filter, handback);
}
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException
{
emitter.removeNotificationListener(listener);
}
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
emitter.removeNotificationListener(listener, filter, handback);
}
public void sendNotification(Notification notification)
{
emitter.sendNotification(notification);
}
public synchronized void start()
{
if (isActive()) return;
active = true;
for (Iterator i = infos.values().iterator(); i.hasNext();)
{
MonitorInfo info = (MonitorInfo)i.next();
info.clearNotificationStatus();
}
startMonitor();
}
public synchronized void stop()
{
if (!isActive()) return;
active = false;
stopMonitor();
}
public synchronized boolean isActive()
{
return active;
}
public synchronized void addObservedObject(ObjectName name) throws IllegalArgumentException
{
if (name == null) throw new IllegalArgumentException("Observed ObjectName cannot be null");
if (!containsObservedObject(name))
{
observeds.add(name);
putMonitorInfo(name, createMonitorInfo());
}
}
public synchronized void removeObservedObject(ObjectName name)
{
observeds.remove(name);
removeMonitorInfo(name);
}
public synchronized boolean containsObservedObject(ObjectName name)
{
return observeds.contains(name);
}
public synchronized ObjectName[] getObservedObjects()
{
return (ObjectName[])observeds.toArray(new ObjectName[observeds.size()]);
}
public synchronized void clearObservedObjects()
{
observeds.clear();
}
public synchronized String getObservedAttribute()
{
return attribute;
}
public synchronized void setObservedAttribute(String attribute)
{
this.attribute = attribute;
}
public synchronized long getGranularityPeriod()
{
return granularity;
}
public synchronized void setGranularityPeriod(long granularity) throws IllegalArgumentException
{
if (granularity <= 0) throw new IllegalArgumentException("Granularity must be greater than zero");
this.granularity = granularity;
}
protected void startMonitor()
{
synchronized (queue)
{
if (references == 0) queue.start();
++references;
}
if (emitter == null) this.emitter = createNotificationEmitter();
queue.schedule(task);
}
protected void stopMonitor()
{
queue.unschedule(task);
synchronized (queue)
{
if (--references == 0) queue.stop();
}
}
protected Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
protected void sendNotification(String type, String message, ObjectName name, String attribute, Object gauge, Object trigger)
{
int sequence = 0;
synchronized (MX4JMonitor.class)
{
sequence = ++sequenceNumber;
}
Notification notification = createMonitorNotification(type, sequence, message, name, attribute, gauge, trigger);
sendNotification(notification);
}
protected Notification createMonitorNotification(String type, long sequence, String message, ObjectName observed, String attribute, Object gauge, Object trigger)
{
return new MX4JMonitorNotification(type, this, sequence, System.currentTimeMillis(), message, observed, attribute, gauge, trigger);
}
protected abstract void monitor(ObjectName name, String attribute, Object value, MonitorInfo info);
protected abstract MonitorInfo createMonitorInfo();
protected synchronized MonitorInfo getMonitorInfo(ObjectName name)
{
return (MonitorInfo)infos.get(name);
}
protected synchronized void putMonitorInfo(ObjectName name, MonitorInfo info)
{
infos.put(name, info);
}
protected synchronized void removeMonitorInfo(ObjectName name)
{
infos.remove(name);
}
protected void sendErrorNotification(MonitorInfo info, String type, String message, ObjectName observed, String attribute)
{
if (!info.isErrorNotified())
{
info.setErrorNotified(true);
sendNotification(type, message, observed, attribute, null, null);
}
}
private class MonitorTask extends TimeTask
{
protected boolean isPeriodic()
{
return true;
}
protected long getPeriod()
{
return getGranularityPeriod();
}
public boolean getFixedRate()
{
return true;
}
public void run()
{
if (!isActive()) return;
long start = System.currentTimeMillis();
String attribute = getObservedAttribute();
if (server == null)
{
if (!errorNotified)
{
errorNotified = true;
sendNotification(MonitorNotification.RUNTIME_ERROR, "Monitors must be registered in the MBeanServer", null, attribute, null, null);
}
}
else
{
errorNotified = false;
// If no attribute, sleep and try again
if (attribute != null)
{
ObjectName[] names = getObservedObjects();
// If no names, sleep and try again
for (int i = 0; i < names.length; i++)
{
ObjectName name = names[i];
MonitorInfo info = getMonitorInfo(name);
if (info == null) continue;
try
{
Object value = server.getAttribute(name, attribute);
// If no value, sleep and try again
if (value != null)
{
monitor(name, attribute, value, info);
}
}
catch (InstanceNotFoundException x)
{
sendErrorNotification(info, MonitorNotification.OBSERVED_OBJECT_ERROR, "Could not find observed MBean", name, attribute);
}
catch (AttributeNotFoundException x)
{
sendErrorNotification(info, MonitorNotification.OBSERVED_ATTRIBUTE_ERROR, "Could not find observed attribute " + attribute, name, attribute);
}
catch (MBeanException x)
{
sendErrorNotification(info, MonitorNotification.RUNTIME_ERROR, x.toString(), name, attribute);
}
catch (ReflectionException x)
{
sendErrorNotification(info, MonitorNotification.RUNTIME_ERROR, x.toString(), name, attribute);
}
}
}
}
long end = System.currentTimeMillis();
long elapsed = end - start;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Monitored attribute " + attribute + " in " + elapsed + " ms");
}
}
protected class MonitorInfo
{
private boolean errorNotified;
public boolean isErrorNotified()
{
return errorNotified;
}
public void setErrorNotified(boolean errorNotified)
{
this.errorNotified = errorNotified;
}
public String toString()
{
return "errorNotified=" + isErrorNotified();
}
public void clearNotificationStatus()
{
errorNotified = false;
}
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JMonitorMBean.java 100644 0 0 1653 10513545721 17465 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.ObjectName;
/**
* @version $Revision: 1.2 $
*/
public interface MX4JMonitorMBean
{
public void start();
public void stop();
public boolean isActive();
public void addObservedObject(ObjectName object) throws IllegalArgumentException;
public void removeObservedObject(ObjectName object);
public boolean containsObservedObject(ObjectName object);
public ObjectName[] getObservedObjects();
public String getObservedAttribute();
public void setObservedAttribute(String attribute);
public long getGranularityPeriod();
public void setGranularityPeriod(long period) throws java.lang.IllegalArgumentException;
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JMonitorNotification.java 100644 0 0 3355 10513545721 21132 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.Notification;
import javax.management.ObjectName;
/**
* @version $Revision: 1.3 $
*/
public class MX4JMonitorNotification extends Notification
{
private final ObjectName observedObject;
private final String observedAttribute;
private final Object derivedGauge;
private final Object trigger;
public MX4JMonitorNotification(String type, Object source, long sequenceNumber, long timeStamp, String message, ObjectName monitoredName, String attribute, Object gauge, Object trigger)
{
super(type, source, sequenceNumber, timeStamp, message);
this.observedObject = monitoredName;
this.observedAttribute = attribute;
this.derivedGauge = gauge;
this.trigger = trigger;
}
public ObjectName getObservedObject()
{
return observedObject;
}
public Object getDerivedGauge()
{
return derivedGauge;
}
public String getObservedAttribute()
{
return observedAttribute;
}
public Object getTrigger()
{
return trigger;
}
public String toString()
{
StringBuffer buffer = new StringBuffer("[");
buffer.append(super.toString()).append(", ");
buffer.append("observed=").append(getObservedObject()).append(", ");
buffer.append("gauge=").append(getDerivedGauge()).append(", ");
buffer.append("attribute=").append(getObservedAttribute()).append(", ");
buffer.append("trigger=").append(getTrigger()).append("]");
return buffer.toString();
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JStringMonitor.java 100644 0 0 15757 10513545721 20003 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.monitor.MonitorNotification;
import mx4j.log.Logger;
/**
* @version $Revision: 1.3 $
*/
public class MX4JStringMonitor extends MX4JMonitor implements MX4JStringMonitorMBean
{
private static final String EMPTY = "";
private String stringToCompare = EMPTY;
private boolean notifyMatch;
private boolean notifyDiffer;
public MX4JStringMonitor() throws NotCompliantMBeanException
{
super(MX4JStringMonitorMBean.class);
}
public MX4JStringMonitor(Class management) throws NotCompliantMBeanException
{
super(management);
}
public MBeanNotificationInfo[] getNotificationInfo()
{
// TODO
return new MBeanNotificationInfo[0];
}
public synchronized String getStringToCompare()
{
return stringToCompare;
}
public synchronized void setStringToCompare(String value) throws IllegalArgumentException
{
if (value == null) throw new IllegalArgumentException("String to compare cannot be null");
this.stringToCompare = value;
}
public synchronized boolean getNotifyMatch()
{
return notifyMatch;
}
public synchronized void setNotifyMatch(boolean notifyMatch)
{
this.notifyMatch = notifyMatch;
}
public synchronized boolean getNotifyDiffer()
{
return notifyDiffer;
}
public synchronized void setNotifyDiffer(boolean notifyDiffer)
{
this.notifyDiffer = notifyDiffer;
}
public String getDerivedGauge(ObjectName objectName)
{
StringMonitorInfo info = (StringMonitorInfo)getMonitorInfo(objectName);
return info.getGauge();
}
public long getDerivedGaugeTimeStamp(ObjectName objectName)
{
StringMonitorInfo info = (StringMonitorInfo)getMonitorInfo(objectName);
return info.getTimestamp();
}
protected MonitorInfo createMonitorInfo()
{
return new StringMonitorInfo();
}
protected int compare(String left, String right)
{
return left == null ? right == null ? 0 : -1 : right == null ? 1 : left.compareTo(right);
}
protected void monitor(ObjectName name, String attribute, Object value, MonitorInfo monitorInfo)
{
if (!(value instanceof String))
{
sendErrorNotification(monitorInfo, MonitorNotification.OBSERVED_ATTRIBUTE_TYPE_ERROR, "Attribute type must be a String, not " + value.getClass(), name, attribute);
return;
}
String gauge = (String)value;
String reference = null;
synchronized (this)
{
reference = getStringToCompare();
}
Logger logger = getLogger();
StringMonitorInfo info = (StringMonitorInfo)monitorInfo;
if (logger.isEnabledFor(Logger.DEBUG))
{
logger.debug("Computing gauge, previous values are: " + info);
logger.debug("Current values are: gauge=" + gauge + ", stringToCompare=" + reference);
}
compareAndSendNotification(gauge, reference, info, name, attribute);
info.setGauge(gauge);
info.setTimestamp(System.currentTimeMillis());
}
private void compareAndSendNotification(String gauge, String reference, StringMonitorInfo info, ObjectName name, String attribute)
{
Logger logger = getLogger();
boolean equals = compare(gauge, reference) == 0;
if (info.isDifferNotified() && !equals)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Difference already notified, gauge=" + gauge + ", string-to-compare=" + reference);
return;
}
if (info.isMatchNotified() && equals)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Match already notified, gauge=" + gauge + ", string-to-compare=" + reference);
return;
}
if (equals)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Gauge matches, gauge=" + gauge + ", string-to-compare=" + reference);
info.setDifferNotified(false);
if (getNotifyMatch())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending string match notification");
info.setMatchNotified(true);
sendNotification(MonitorNotification.STRING_TO_COMPARE_VALUE_MATCHED, "Gauge " + gauge + " matched " + reference, name, attribute, gauge, reference);
}
else
{
info.setMatchNotified(false);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("StringMonitor is configured in non-match-notification mode");
}
}
else
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Gauge differs, gauge=" + gauge + ", string-to-compare=" + reference);
info.setMatchNotified(false);
if (getNotifyDiffer())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending string differ notification");
info.setDifferNotified(true);
sendNotification(MonitorNotification.STRING_TO_COMPARE_VALUE_DIFFERED, "Gauge " + gauge + " differs from " + reference, name, attribute, gauge, reference);
}
else
{
info.setDifferNotified(false);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("StringMonitor is configured in non-differ-notification mode");
}
}
}
protected class StringMonitorInfo extends MonitorInfo
{
private String gauge;
private long timestamp;
private boolean matchNotified;
private boolean differNotified;
public String getGauge()
{
return gauge;
}
public void setGauge(String gauge)
{
this.gauge = gauge;
}
public long getTimestamp()
{
return timestamp;
}
public void setTimestamp(long timestamp)
{
this.timestamp = timestamp;
}
public boolean isMatchNotified()
{
return matchNotified;
}
public void setMatchNotified(boolean matchNotified)
{
this.matchNotified = matchNotified;
}
public boolean isDifferNotified()
{
return differNotified;
}
public void setDifferNotified(boolean differNotified)
{
this.differNotified = differNotified;
}
public void clearNotificationStatus()
{
super.clearNotificationStatus();
differNotified = false;
matchNotified = false;
}
public String toString()
{
StringBuffer buffer = new StringBuffer(super.toString());
buffer.append(", gauge=").append(getGauge());
buffer.append(", matchNotified=").append(isMatchNotified());
buffer.append(", differNotified=").append(isDifferNotified());
return buffer.toString();
}
}
}
mx4j-3.0.2/src/core/mx4j/monitor/MX4JStringMonitorMBean.java 100644 0 0 1467 10513545721 20657 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.monitor;
import javax.management.ObjectName;
/**
* @version $Revision: 1.3 $
*/
public interface MX4JStringMonitorMBean extends MX4JMonitorMBean
{
public String getDerivedGauge(ObjectName objectName);
public long getDerivedGaugeTimeStamp(ObjectName objectName);
public String getStringToCompare();
public void setStringToCompare(String value) throws IllegalArgumentException;
public boolean getNotifyMatch();
public void setNotifyMatch(boolean value);
public boolean getNotifyDiffer();
public void setNotifyDiffer(boolean value);
}
mx4j-3.0.2/src/core/mx4j/persist/FilePersister.java 100644 0 0 11306 10513545721 17266 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.persist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.RuntimeOperationsException;
import mx4j.loading.ClassLoaderObjectInputStream;
/**
* A persister object that stores to files.
*
* @version $Revision: 1.10 $
*/
public class FilePersister extends Persister
{
private File m_store;
/**
* Creates a new FilePersister.
*
* @param location the directory where the file will be written (must already exist);
* if null the name is used as a location
* @param name the file name used to store information
*/
public FilePersister(String location, String name) throws MBeanException
{
if (name == null)
{
throw new MBeanException(new IllegalArgumentException("Persist name cannot be null"));
}
if (location != null)
{
File dir = new File(location);
if (!dir.exists())
{
throw new MBeanException(new FileNotFoundException(location));
}
m_store = new File(dir, name);
}
else
{
m_store = new File(name);
}
}
/**
* Returns the path where the information is stored.
*/
public String getFileName()
{
return m_store.getAbsolutePath();
}
public Object load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException
{
FileInputStream fin = null;
ObjectInputStream clois = null;
Object result = null;
synchronized (this)
{
try
{
// Create the inputStream
fin = new FileInputStream(m_store);
// Use the ClassLoaderObjectInputStream
clois = new ClassLoaderObjectInputStream(fin, Thread.currentThread().getContextClassLoader());
try
{
// Try load the object using the ContextClassLoader
result = clois.readObject();
}
catch (ClassNotFoundException ex)
{
// Close previous streams, FileInputStream does not support reset(),
// so I have to create a new one
try
{
clois.close();
}
catch (IOException ignored)
{
}
throw new MBeanException(ex);
/*
// Try using the DefaultLoaderRepository
fin = new FileInputStream(m_store);
clois = new ClassLoaderObjectInputStream(fin);
try
{
result = clois.readObject();
}
catch(ClassNotFoundException e)
{
throw new MBeanException(e);
}
*/
}
}
catch (IOException ex)
{
throw new MBeanException(ex);
}
finally
{
try
{
if (clois != null) clois.close();
}
catch (IOException ignored)
{
}
}
}
return result;
}
public void store(Object data) throws MBeanException, RuntimeOperationsException, InstanceNotFoundException
{
if (data == null) throw new RuntimeOperationsException(new IllegalArgumentException("Cannot store a null object."));
if (!(data instanceof Serializable)) throw new MBeanException(new NotSerializableException(data.getClass().getName() + " must implement java.io.Serializable"));
FileOutputStream fos = null;
ObjectOutputStream oos = null;
synchronized (this)
{
try
{
fos = new FileOutputStream(m_store);
oos = new ObjectOutputStream(fos);
}
catch (IOException ex)
{
throw new MBeanException(ex);
}
try
{
//write out the data
oos.writeObject(data);
// flush the stream
oos.flush();
}
catch (IOException ex)
{
throw new MBeanException(ex);
}
finally
{
try
{
oos.close();
}
catch (IOException ex)
{/* unable to close the stream nothing to do*/
}
}
}
}
}
mx4j-3.0.2/src/core/mx4j/persist/MBeanPersister.java 100644 0 0 2745 10513545721 17360 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.persist;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.RuntimeOperationsException;
/**
* A persister that delegates the persistence to a registered persister MBean.
*
* @version $Revision: 1.7 $
*/
public class MBeanPersister extends Persister
{
private MBeanServer m_server;
private ObjectName m_name;
private PersisterMBean m_proxy;
/**
* Creates a new MBeanPersister that delegates persistence to a persister MBean
* registered in the specified MBeanServer with the specified ObjectName.
*/
public MBeanPersister(MBeanServer server, ObjectName name)
{
m_server = server;
m_name = name;
m_proxy = (PersisterMBean)MBeanServerInvocationHandler.newProxyInstance(server, name, PersisterMBean.class, false);
}
public Object load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException
{
return m_proxy.load();
}
public void store(Object data) throws MBeanException, RuntimeOperationsException, InstanceNotFoundException
{
m_proxy.store(data);
}
}
mx4j-3.0.2/src/core/mx4j/persist/Persister.java 100644 0 0 727 10513545721 16433 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.persist;
/**
* This class has the only purpose of making the PersisterMBean interface a management interface.
*
* @version $Revision: 1.5 $
*/
public abstract class Persister implements PersisterMBean
{
}
mx4j-3.0.2/src/core/mx4j/persist/PersisterMBean.java 100644 0 0 1723 10513545721 17353 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.persist;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.RuntimeOperationsException;
/**
* Management interface for components able to persist information to a storage media.
*
* @version $Revision: 1.6 $
*/
public interface PersisterMBean
{
/**
* Loads the information persisted on the storage media.
*
* @see #store
*/
public Object load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException;
/**
* Store the given information to the storage media.
*
* @see #load
*/
public void store(Object data) throws MBeanException, RuntimeOperationsException, InstanceNotFoundException;
}
mx4j-3.0.2/src/core/mx4j/remote/AbstractHeartBeat.java 100644 0 0 6676 10513545721 17631 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import java.util.Map;
/**
* Base implementation for the HeartBeat interface.
*
* @version $Revision: 1.4 $
*/
public abstract class AbstractHeartBeat implements HeartBeat, Runnable
{
private final ConnectionNotificationEmitter emitter;
private long pulsePeriod;
private int maxRetries;
private Thread thread;
private volatile boolean stopped;
/**
* Creates a new HeartBeat.
*
* @param emitter The NotificationEmitter that sends connection failures notifications.
* @param environment The environment that may contain properties that specify heart beat's behavior
* @see #sendConnectionNotificationFailed
* @see MX4JRemoteConstants#CONNECTION_HEARTBEAT_PERIOD
* @see MX4JRemoteConstants#CONNECTION_HEARTBEAT_RETRIES
*/
protected AbstractHeartBeat(ConnectionNotificationEmitter emitter, Map environment)
{
this.emitter = emitter;
if (environment != null)
{
try
{
pulsePeriod = ((Long)environment.get(MX4JRemoteConstants.CONNECTION_HEARTBEAT_PERIOD)).longValue();
}
catch (Exception ignored)
{
}
try
{
maxRetries = ((Integer)environment.get(MX4JRemoteConstants.CONNECTION_HEARTBEAT_RETRIES)).intValue();
}
catch (Exception ignored)
{
}
}
if (pulsePeriod <= 0) pulsePeriod = 5000;
if (maxRetries <= 0) maxRetries = 3;
}
public long getPulsePeriod()
{
return pulsePeriod;
}
public int getMaxRetries()
{
return maxRetries;
}
/**
* Subclasses will implement this method using protocol specific connections.
* Normally the method {@link javax.management.MBeanServerConnection#getDefaultDomain} is used
* to "ping" the server side.
*/
protected abstract void pulse() throws IOException;
public void start() throws IOException
{
thread = new Thread(this, "Connection HeartBeat");
thread.setDaemon(true);
thread.start();
}
public void stop() throws IOException
{
if (stopped) return;
stopped = true;
thread.interrupt();
}
public void run()
{
try
{
int retries = 0;
while (!stopped && !thread.isInterrupted())
{
try
{
Thread.sleep(pulsePeriod);
try
{
pulse();
retries = 0;
}
catch (IOException x)
{
if (retries++ == maxRetries)
{
// The connection has died
sendConnectionNotificationFailed();
break;
}
}
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
}
}
}
finally
{
stopped = true;
}
}
/**
* Sends the connection failed notification using the emitter specified in
* {@link #AbstractHeartBeat}
*/
protected void sendConnectionNotificationFailed()
{
emitter.sendConnectionNotificationFailed();
}
}
mx4j-3.0.2/src/core/mx4j/remote/AbstractRemoteNotificationClientHandler.java 100644 0 0 42766 10513545721 24251 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.remote.NotificationResult;
import javax.management.remote.TargetedNotification;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* Base implementation of the RemoteNotificationClientHandler interface.
*
* @version $Revision: 1.7 $
*/
public abstract class AbstractRemoteNotificationClientHandler implements RemoteNotificationClientHandler
{
private static int fetcherID;
private static int delivererID;
private final ConnectionNotificationEmitter emitter;
private final HeartBeat heartbeat;
private final Map tuples = new HashMap();
private NotificationFetcherThread fetcherThread;
private NotificationDelivererThread delivererThread;
/**
* Creates a new remote notification client-side handler.
* It uses an emitter, an heartbeat and an environment to perform the job.
* All 3 can be null, but the corrispondent methods must be overridden
*
* @param emitter The NotificationEmitter that emits connection failures notifications
* @param heartbeat The heart beat is used to get the retry parameters in case of connection failure
* @param environment Contains environment variables used to configure this handler
* @see MX4JRemoteConstants#FETCH_NOTIFICATIONS_MAX_NUMBER
* @see MX4JRemoteConstants#FETCH_NOTIFICATIONS_SLEEP
* @see MX4JRemoteConstants#FETCH_NOTIFICATIONS_TIMEOUT
* @see #sendConnectionNotificationLost
* @see #getMaxRetries
* @see #getRetryPeriod
*/
protected AbstractRemoteNotificationClientHandler(ConnectionNotificationEmitter emitter, HeartBeat heartbeat, Map environment)
{
this.emitter = emitter;
this.heartbeat = heartbeat;
this.fetcherThread = new NotificationFetcherThread(environment);
this.delivererThread = new NotificationDelivererThread(environment);
}
/**
* Returns whether this client handler is fetching notifications or not.
*
* @see #start
* @see #stop
*/
public boolean isActive()
{
return fetcherThread.isActive();
}
public void start()
{
if (isActive()) return;
delivererThread.start();
fetcherThread.start();
}
public void stop()
{
if (!isActive()) return;
fetcherThread.stop();
delivererThread.stop();
synchronized (tuples)
{
tuples.clear();
}
}
private synchronized static int getFetcherID()
{
return ++fetcherID;
}
private synchronized static int getDelivererID()
{
return ++delivererID;
}
public boolean contains(NotificationTuple tuple)
{
synchronized (tuples)
{
return tuples.containsValue(tuple);
}
}
public void addNotificationListener(Integer id, NotificationTuple tuple)
{
if (!isActive()) start();
synchronized (tuples)
{
tuples.put(id, tuple);
}
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Adding remote NotificationListener " + tuple);
}
public Integer[] getNotificationListeners(NotificationTuple tuple)
{
synchronized (tuples)
{
ArrayList ids = new ArrayList();
for (Iterator i = tuples.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
if (entry.getValue().equals(tuple)) ids.add(entry.getKey());
}
if (ids.size() > 0) return (Integer[])ids.toArray(new Integer[ids.size()]);
}
return null;
}
public Integer getNotificationListener(NotificationTuple tuple)
{
synchronized (tuples)
{
for (Iterator i = tuples.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
if (entry.getValue().equals(tuple)) return (Integer)entry.getKey();
}
}
return null;
}
public void removeNotificationListeners(Integer[] ids)
{
Logger logger = getLogger();
synchronized (tuples)
{
for (int i = 0; i < ids.length; ++i)
{
Integer id = ids[i];
NotificationTuple tuple = (NotificationTuple)tuples.remove(id);
if (tuple != null && logger.isEnabledFor(Logger.DEBUG)) logger.debug("Removing remote NotificationListener " + tuple);
}
}
}
/**
* Calls the server side to fetch notifications.
*/
protected abstract NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) throws IOException;
/**
* Returns the period between two retries if the connection with the server side fails.
* This implementation returns the heartbeat pulse period, but can be overridden.
*
* @see #getMaxRetries
* @see #AbstractRemoteNotificationClientHandler
*/
protected long getRetryPeriod()
{
return heartbeat.getPulsePeriod();
}
/**
* Returns the maximum number of attempts that should be made before declaring a connection
* failed.
* This implementation returns the heartbeat max retries, but can be overridden.
*
* @see #getRetryPeriod
* @see #AbstractRemoteNotificationClientHandler
*/
protected int getMaxRetries()
{
return heartbeat.getMaxRetries();
}
/**
* Sends the {@link javax.management.remote.JMXConnectionNotification#NOTIFS_LOST} notification
* using the emitter passed to {@link AbstractRemoteNotificationClientHandler}
*/
protected void sendConnectionNotificationLost(long number)
{
emitter.sendConnectionNotificationLost(number);
}
protected int getNotificationsCount()
{
return delivererThread.getNotificationsCount();
}
private int deliverNotifications(TargetedNotification[] notifications)
{
return delivererThread.addNotifications(notifications);
}
private void sendNotification(TargetedNotification notification)
{
NotificationTuple tuple = null;
synchronized (tuples)
{
tuple = (NotificationTuple)tuples.get(notification.getListenerID());
}
// It may be possible that a notification arrived after the client already removed the listener
if (tuple == null) return;
Notification notif = notification.getNotification();
Logger logger = getLogger();
if (tuple.getInvokeFilter())
{
// Invoke the filter on client side
NotificationFilter filter = tuple.getNotificationFilter();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Filtering notification " + notif + ", filter = " + filter);
if (filter != null)
{
try
{
boolean deliver = filter.isNotificationEnabled(notif);
if (!deliver) return;
}
catch (Throwable x)
{
logger.warn("Throwable caught from isNotificationEnabled, filter = " + filter, x);
// And go on quietly
}
}
}
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Sending Notification " + notif + ", listener info is " + tuple);
NotificationListener listener = tuple.getNotificationListener();
try
{
listener.handleNotification(notif, tuple.getHandback());
}
catch (Throwable x)
{
logger.warn("Throwable caught from handleNotification, listener = " + listener, x);
// And return quietly
}
}
protected Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
private class NotificationFetcherThread implements Runnable
{
private long sequenceNumber;
private volatile boolean active;
private Thread thread;
private long timeout;
private int maxNumber;
private long sleep;
private NotificationFetcherThread(Map environment)
{
// Default server timeout is one minute
timeout = 60 * 1000;
// At most 25 notifications at time
maxNumber = 25;
// By default we don't sleep and we call the server again.
sleep = 0;
if (environment != null)
{
try
{
timeout = ((Long)environment.get(MX4JRemoteConstants.FETCH_NOTIFICATIONS_TIMEOUT)).longValue();
}
catch (Exception ignored)
{
}
try
{
maxNumber = ((Integer)environment.get(MX4JRemoteConstants.FETCH_NOTIFICATIONS_MAX_NUMBER)).intValue();
}
catch (Exception ignored)
{
}
try
{
sleep = ((Integer)environment.get(MX4JRemoteConstants.FETCH_NOTIFICATIONS_SLEEP)).intValue();
}
catch (Exception ignored)
{
}
}
}
private synchronized long getSequenceNumber()
{
return sequenceNumber;
}
private synchronized void setSequenceNumber(long sequenceNumber)
{
this.sequenceNumber = sequenceNumber;
}
private boolean isActive()
{
return active;
}
private synchronized void start()
{
active = true;
// Initialized to a negative value for the first fetchNotification call
sequenceNumber = -1;
thread = new Thread(this, "Notification Fetcher #" + getFetcherID());
thread.setDaemon(true);
thread.start();
}
private synchronized void stop()
{
active = false;
thread.interrupt();
}
public void run()
{
Logger logger = getLogger();
try
{
while (isActive() && !thread.isInterrupted())
{
try
{
long sequence = getSequenceNumber();
NotificationResult result = fetchNotifications(sequence, maxNumber, timeout);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Fetched Notifications: " + result);
long sleepTime = sleep;
if (result != null)
{
long nextSequence = result.getNextSequenceNumber();
TargetedNotification[] targeted = result.getTargetedNotifications();
int targetedLength = targeted == null ? 0 : targeted.length;
boolean notifsFilteredByServer = sequence >= 0 ? nextSequence - sequence != targetedLength : false;
boolean notifsLostByServer = sequence >= 0 && result.getEarliestSequenceNumber() > sequence;
if (notifsFilteredByServer)
{
// We lost some notification
sendConnectionNotificationLost(nextSequence - sequence - targetedLength);
}
if (notifsLostByServer)
{
// We lost some notification
sendConnectionNotificationLost(result.getEarliestSequenceNumber() - sequence);
}
setSequenceNumber(nextSequence);
int delivered = deliverNotifications(targeted);
if (delivered < targetedLength)
{
// We lost some notification
sendConnectionNotificationLost(targetedLength - delivered);
}
// If we got a maxNumber of notifications, probably the server has more to send, don't sleep
if (targeted != null && targeted.length == maxNumber) sleepTime = 0;
}
if (sleepTime > 0) Thread.sleep(sleepTime);
}
catch (IOException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Caught IOException from fetchNotifications", x);
break;
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
break;
}
catch (Throwable x)
{
if (logger.isEnabledFor(Logger.WARN)) logger.warn("Caught an unexpected exception", x);
}
}
}
finally
{
AbstractRemoteNotificationClientHandler.this.stop();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug(thread.getName() + " Thread exited");
}
}
/**
* Fetches notifications from the server side in a separate thread.
* Since it involves a remote call, IOExceptions must be handled carefully.
* If the connection fails for any reason, the thread will be a sleep and then
* retry for a configurable number of times.
* If the connection is really lost, the thread will exit.
*/
private NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) throws IOException, InterruptedException
{
Logger logger = getLogger();
int retries = 0;
while (true)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Fetching notifications, sequence is " + sequence + ", timeout is " + timeout);
try
{
return AbstractRemoteNotificationClientHandler.this.fetchNotifications(sequence, maxNumber, timeout);
}
catch (IOException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Could not fetch notifications, sleeping " + getRetryPeriod() + " and trying " + (getMaxRetries() - retries) + " more times", x);
Thread.sleep(getRetryPeriod());
if (retries++ == getMaxRetries()) throw x;
}
}
}
}
private class NotificationDelivererThread implements Runnable
{
private final List notificationQueue = new LinkedList();
private int capacity;
private volatile boolean active;
private Thread thread;
private NotificationDelivererThread(Map environment)
{
if (environment != null)
{
Object size = environment.get(MX4JRemoteConstants.NOTIFICATION_QUEUE_CAPACITY);
if (size instanceof Integer)
{
capacity = ((Integer)size).intValue();
if (capacity < 0) capacity = 0;
}
}
}
private int addNotifications(TargetedNotification[] notifications)
{
if (notifications == null || notifications.length == 0) return 0;
List notifs = Arrays.asList(notifications);
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Enqueuing notifications for delivery: " + notifs);
synchronized (this)
{
int size = notifs.size();
int added = size;
if (capacity > 0)
{
int room = capacity - notificationQueue.size();
if (room < size)
{
added = room;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification queue is full, enqueued " + room + " notifications out of " + size + ", exceeding will be lost");
}
notificationQueue.addAll(notifs.subList(0, added));
}
else
{
notificationQueue.addAll(notifs);
}
notifyAll();
return added;
}
}
private boolean isActive()
{
return active;
}
private synchronized void start()
{
active = true;
notificationQueue.clear();
thread = new Thread(this, "Notification Deliverer #" + getDelivererID());
thread.setDaemon(true);
thread.start();
}
private synchronized void stop()
{
active = false;
thread.interrupt();
}
public void run()
{
Logger logger = getLogger();
try
{
while (isActive() && !thread.isInterrupted())
{
try
{
TargetedNotification notification = null;
synchronized (this)
{
while (notificationQueue.isEmpty()) wait();
notification = (TargetedNotification)notificationQueue.remove(0);
}
sendNotification(notification);
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
break;
}
catch (Throwable x)
{
if (logger.isEnabledFor(Logger.WARN)) logger.warn("Caught an unexpected exception", x);
}
}
}
finally
{
active = false;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug(thread.getName() + " Thread exited");
}
}
private int getNotificationsCount()
{
synchronized (this)
{
return notificationQueue.size();
}
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/ClientProxy.java 100644 0 0 1656 10513545721 16557 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.management.MBeanServerConnection;
/**
* @version $Revision: 1.3 $
*/
public class ClientProxy implements InvocationHandler
{
private final MBeanServerConnection target;
protected ClientProxy(MBeanServerConnection target)
{
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
return method.invoke(target, args);
}
catch (InvocationTargetException x)
{
throw x.getTargetException();
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/ConnectionNotificationEmitter.java 100644 0 0 4440 10513545721 22271 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import javax.management.NotificationBroadcasterSupport;
import javax.management.remote.JMXConnectionNotification;
import javax.management.remote.JMXConnector;
/**
* @version $Revision: 1.4 $
*/
public class ConnectionNotificationEmitter extends NotificationBroadcasterSupport
{
private static long sequenceNumber;
private JMXConnector connector;
public ConnectionNotificationEmitter(JMXConnector connector)
{
this.connector = connector;
}
private long getNextNotificationNumber()
{
synchronized (ConnectionNotificationEmitter.class)
{
return sequenceNumber++;
}
}
private String getConnectionId()
{
try
{
return connector.getConnectionId();
}
catch (IOException x)
{
return null;
}
}
public void sendConnectionNotificationOpened()
{
JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.OPENED, connector, getConnectionId(), getNextNotificationNumber(), "Connection opened", null);
sendNotification(notification);
}
public void sendConnectionNotificationClosed()
{
JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.CLOSED, connector, getConnectionId(), getNextNotificationNumber(), "Connection closed", null);
sendNotification(notification);
}
public void sendConnectionNotificationFailed()
{
JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.FAILED, connector, getConnectionId(), getNextNotificationNumber(), "Connection failed", null);
sendNotification(notification);
}
public void sendConnectionNotificationLost(long howMany)
{
JMXConnectionNotification notification = new JMXConnectionNotification(JMXConnectionNotification.NOTIFS_LOST, connector, getConnectionId(), getNextNotificationNumber(), "Some notification (" + howMany + ") was lost", null);
sendNotification(notification);
}
}
mx4j-3.0.2/src/core/mx4j/remote/ConnectionResolver.java 100644 0 0 15024 10513545721 20132 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import java.util.Map;
import java.util.StringTokenizer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import mx4j.log.Logger;
/**
* ConnectionResolver handles the details of creating connections for different protocols.
* Subclasses for the specific protocol are instantiated using a mechanism very similar to the
* one specified by {@link javax.management.remote.JMXConnectorFactory}. Here a subclass
* has a fully qualified name specified like this:
* .resolver..Resolver, for example
* {@link mx4j.remote.resolver.rmi.Resolver}
* This class is used from both the client and the server.
* The former uses it to lookup stubs or connections to the server side; the latter uses it
* to create server instances and make them availale to clients, for example via JNDI.
* The client and server methods have not been splitted into 2 different interfaces because
* most of the times they share common code, although it may have been a better design.
*
* @version $Revision: 1.6 $
*/
public abstract class ConnectionResolver extends ProviderHelper
{
/**
* Returns a subclass of ConnectionResolver for the specified protocol.
*/
public static ConnectionResolver newConnectionResolver(String proto, Map environment)
{
String protocol = normalizeProtocol(proto);
String resolverPackages = findResolverPackageList();
ClassLoader classLoader = findResolverClassLoader(environment, JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER);
return loadResolver(resolverPackages, protocol, classLoader);
}
private static String findResolverPackageList()
{
String packages = findSystemPackageList(MX4JRemoteConstants.PROTOCOL_RESOLVER_PACKAGES);
if (packages == null)
packages = MX4JRemoteConstants.RESOLVER_PACKAGES;
else
packages += MX4JRemoteConstants.RESOLVER_PACKAGES_SEPARATOR + MX4JRemoteConstants.RESOLVER_PACKAGES;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Resolver packages list is: " + packages);
return packages;
}
private static ClassLoader findResolverClassLoader(Map environment, String loaderKey)
{
if (environment == null) return Thread.currentThread().getContextClassLoader();
Object object = environment.get(loaderKey);
if (object == null) return Thread.currentThread().getContextClassLoader();
if (!(object instanceof ClassLoader)) throw new IllegalArgumentException("Environment property " + loaderKey + " must be a ClassLoader");
return (ClassLoader)object;
}
private static ConnectionResolver loadResolver(String packages, String protocol, ClassLoader loader)
{
Logger logger = getLogger();
StringTokenizer tokenizer = new StringTokenizer(packages, MX4JRemoteConstants.RESOLVER_PACKAGES_SEPARATOR);
while (tokenizer.hasMoreTokens())
{
String pkg = tokenizer.nextToken().trim();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Resolver package: " + pkg);
if (pkg.length() == 0) continue;
String resolverClassName = constructClassName(pkg, protocol, MX4JRemoteConstants.RESOLVER_CLASS);
Class resolverClass = null;
try
{
resolverClass = loadClass(resolverClassName, loader);
}
catch (ClassNotFoundException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Resolver class " + resolverClassName + " not found, continuing with next package");
continue;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot load resolver class " + resolverClassName, x);
return null;
}
try
{
return (ConnectionResolver)resolverClass.newInstance();
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot instantiate resolver class " + resolverClassName, x);
return null;
}
}
// Nothing found
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Could not find resolver for protocol " + protocol + " in package list '" + packages + "'");
return null;
}
/**
* Looks up a connection with the server side as specified in the given JMXServiceURL.
* This method is used in implementations of {@link javax.management.remote.JMXConnector#connect()}.
*
* @see #bindClient
*/
public abstract Object lookupClient(JMXServiceURL url, Map environment) throws IOException;
/**
* Connects the client returned by {@link #lookupClient} to the server side.
*
* @return An object of the same type as the client passed in; normally the client object itself
*/
public abstract Object bindClient(Object client, Map environment) throws IOException;
/**
* Creates an instance of the server as specified in the given JMXServiceURL.
* It is only a factory method, it should just return a fresh instance of the server;
* other methods are responsible to make it available to clients (for example exporting it).
* This method is used in implementations of {@link javax.management.remote.JMXConnectorServer#start}.
*
* @see #bindServer
* @see #destroyServer
*/
public abstract Object createServer(JMXServiceURL url, Map environment) throws IOException;
/**
* Binds the server created by {@link #createServer} to a place specified by the JMXServiceURL.
*
* @return a new JMXServiceURL that specifies where the server has been bound to.
* @see #unbindServer
*/
public abstract JMXServiceURL bindServer(Object server, JMXServiceURL url, Map environment) throws IOException;
/**
* Unbinds the server bound by {@link #bindServer} from the place specified by the JMXServiceURL.
*
* @see #destroyServer
*/
public abstract void unbindServer(Object server, JMXServiceURL address, Map environment) throws IOException;
/**
* Destroys the server created by {@link #createServer}, by cleaning up resources it may have requested
* at creation time
*
* @see #createServer
*/
public abstract void destroyServer(Object server, JMXServiceURL url, Map environment) throws IOException;
}
mx4j-3.0.2/src/core/mx4j/remote/DefaultRemoteNotificationServerHandler.java 100644 0 0 33414 10513545721 24110 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.NotificationResult;
import javax.management.remote.TargetedNotification;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* Base implementation of the RemoteNotificationServerHandler interface.
*
* @version $Revision: 1.12 $
*/
public class DefaultRemoteNotificationServerHandler implements RemoteNotificationServerHandler
{
private static int listenerID;
private final NotificationListener listener;
private final Map tuples = new HashMap();
private final NotificationBuffer buffer;
private volatile boolean closed;
/**
* Creates a new remote notification server handler.
*
* @param environment Contains environment variables used to configure this handler
* @see MX4JRemoteConstants#NOTIFICATION_BUFFER_CAPACITY
* @see MX4JRemoteConstants#NOTIFICATION_PURGE_DISTANCE
*/
public DefaultRemoteNotificationServerHandler(Map environment)
{
listener = new ServerListener();
buffer = new NotificationBuffer(environment);
}
public Integer generateListenerID(ObjectName name, NotificationFilter filter)
{
synchronized (DefaultRemoteNotificationServerHandler.class)
{
return new Integer(++listenerID);
}
}
public NotificationListener getServerNotificationListener()
{
return listener;
}
public void addNotificationListener(Integer id, NotificationTuple tuple)
{
if (closed) return;
synchronized (tuples)
{
tuples.put(id, tuple);
}
}
public NotificationTuple removeNotificationListener(Integer id)
{
if (closed) return null;
synchronized (tuples)
{
return (NotificationTuple)tuples.remove(id);
}
}
public NotificationResult fetchNotifications(long sequenceNumber, int maxNotifications, long timeout) throws IOException
{
if (closed) throw new IOException("RemoteNotificationServerHandler is closed");
return buffer.getNotifications(sequenceNumber, maxNotifications, timeout);
}
public NotificationTuple[] close()
{
Logger logger = getLogger();
closed = true;
stopWaitingForNotifications(buffer);
synchronized (tuples)
{
NotificationTuple[] result = (NotificationTuple[])tuples.values().toArray(new NotificationTuple[tuples.size()]);
tuples.clear();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("RemoteNotificationServerHandler closed, returning: " + Arrays.asList(result));
return result;
}
}
/**
* When a connection is closed, it may be possible that a client RMI call is waiting in
* {@link #waitForNotifications}, so here we wake it up, letting the thread return to the
* client and free resources on client's side.
*
* @param lock The object on which {@link #notifyAll} should be called
*/
private void stopWaitingForNotifications(Object lock)
{
synchronized (lock)
{
lock.notifyAll();
}
}
/**
* Called when there are no notifications to send to the client.
* It is guaranteed that no notification can be added before this method waits on the given lock.
* It should wait on the given lock for the specified timeout, and return true
* to send notifications (if no notifications arrived, an empty notification array
* will be returned to the client), or false if no notifications should be sent to
* the client.
*
* @param lock The object on which {@link #wait} should be called
* @param timeout The amount of time to wait (guaranteed to be strictly greater than 0)
*/
protected boolean waitForNotifications(Object lock, long timeout)
{
Logger logger = getLogger();
long start = 0;
if (logger.isEnabledFor(Logger.DEBUG))
{
logger.debug("Waiting for notifications " + timeout + " ms");
start = System.currentTimeMillis();
}
synchronized (lock)
{
try
{
lock.wait(timeout);
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
}
}
if (logger.isEnabledFor(Logger.DEBUG))
{
long elapsed = System.currentTimeMillis() - start;
logger.debug("Waited for notifications " + elapsed + " ms");
}
return true;
}
/**
* This method filters the given notification array and returns a possibly smaller array containing
* only notifications that passed successfully the filtering.
* Default behavior is no filtering, but subclasses may choose to change this bahavior.
* For example, for RMI, one can assure that all notifications are truly serializable, and log those
* that are not.
*/
protected TargetedNotification[] filterNotifications(TargetedNotification[] notifications)
{
return notifications;
}
private void addNotification(Integer id, Notification notification)
{
buffer.add(new TargetedNotification(notification, id));
}
protected Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
private class ServerListener implements NotificationListener
{
public void handleNotification(Notification notification, Object handback)
{
Integer id = (Integer)handback;
addNotification(id, notification);
}
}
private class NotificationBuffer
{
private final List notifications = new LinkedList();
private int maxCapacity;
private int purgeDistance;
private long firstSequence;
private long lastSequence;
private long lowestExpectedSequence = -1;
private NotificationBuffer(Map environment)
{
if (environment != null)
{
try
{
Integer maxCapacityInteger = (Integer)environment.get(MX4JRemoteConstants.NOTIFICATION_BUFFER_CAPACITY);
if (maxCapacityInteger != null) maxCapacity = maxCapacityInteger.intValue();
}
catch (Exception ignored)
{
}
try
{
Integer purgeDistanceInteger = (Integer)environment.get(MX4JRemoteConstants.NOTIFICATION_PURGE_DISTANCE);
if (purgeDistanceInteger != null) purgeDistance = purgeDistanceInteger.intValue();
}
catch (Exception ignored)
{
}
}
if (maxCapacity <= 0) maxCapacity = 1024;
if (purgeDistance <= 0) purgeDistance = 128;
}
private int getSize()
{
synchronized (this)
{
return notifications.size();
}
}
private void add(TargetedNotification notification)
{
Logger logger = getLogger();
synchronized (this)
{
if (notifications.size() == maxCapacity)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification buffer full: " + this);
removeRange(0, 1);
}
notifications.add(notification);
++lastSequence;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Notification added to buffer: " + this);
notifyAll();
}
}
private void removeRange(int start, int end)
{
synchronized (this)
{
notifications.subList(start, end).clear();
firstSequence += end - start;
}
}
private long getFirstSequenceNumber()
{
synchronized (this)
{
return firstSequence;
}
}
private long getLastSequenceNumber()
{
synchronized (this)
{
return lastSequence;
}
}
private NotificationResult getNotifications(long sequenceNumber, int maxNotifications, long timeout)
{
Logger logger = getLogger();
synchronized (this)
{
NotificationResult result = null;
int size = 0;
if (sequenceNumber < 0)
{
// We loose the notifications between addNotificationListener() and fetchNotifications(), but c'est la vie.
long sequence = getLastSequenceNumber();
size = new Long(sequence + 1).intValue();
result = new NotificationResult(getFirstSequenceNumber(), sequence, new TargetedNotification[0]);
if (lowestExpectedSequence < 0) lowestExpectedSequence = sequence;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("First fetchNotification call: " + this + ", returning " + result);
}
else
{
long firstSequence = getFirstSequenceNumber();
int losts = 0;
int start = new Long(sequenceNumber - firstSequence).intValue();
// In the time between 2 fetches the buffer may have overflew, so that start < 0.
// It simply mean that we send the first notification we have (start = 0),
// and the client will emit a notification lost event.
if (start < 0)
{
losts = -start;
start = 0;
}
List sublist = null;
boolean send = false;
while (size == 0)
{
int end = notifications.size();
if (end - start > maxNotifications) end = start + maxNotifications;
sublist = notifications.subList(start, end);
size = sublist.size();
if (closed || send) break;
if (size == 0)
{
if (timeout <= 0) break;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("No notifications to send, waiting " + timeout + " ms");
// We wait for notifications to arrive. Since we release the lock on the buffer
// other threads can modify it. To avoid ConcurrentModificationException we compute
// again the sublist by coming up back to the while statement
send = waitForNotifications(this, timeout);
}
}
TargetedNotification[] notifications = (TargetedNotification[])sublist.toArray(new TargetedNotification[size]);
notifications = filterNotifications(notifications);
result = new NotificationResult(firstSequence, sequenceNumber + losts + size, notifications);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Non-first fetchNotification call: " + this + ", returning " + result);
int purged = purgeNotifications(sequenceNumber, size);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Purged " + purged + " notifications: " + this);
}
return result;
}
}
private int purgeNotifications(long sequenceNumber, int size)
{
// Record the lowest expected sequence number sent by the client.
// New clients will always have an initial big sequence number
// (they're initialized with getLastSequenceNumber()), while old
// clients can have lesser sequence numbers.
// Here we record the lesser of these sequence numbers, that is the
// sequence number of the oldest notification any client may ever ask.
// This way we can purge old notifications that have already been
// delivered to clients.
// The worst case is when a client has a long interval between fetchNotifications()
// calls, and another client has a short interval. The lowestExpectedSequence will
// grow with the second client, until a purge happens, so the first client can
// loose notifications. By tuning appropriately the purgeDistance and the interval
// between fetchNotifications() calls, it should never happen.
int result = 0;
synchronized (this)
{
if (sequenceNumber <= lowestExpectedSequence)
{
long lowest = Math.min(lowestExpectedSequence, sequenceNumber);
long firstSequence = getFirstSequenceNumber();
if (lowest - firstSequence > purgeDistance)
{
// Purge only half of the old notifications, for safety
int purgeSize = purgeDistance >> 1;
removeRange(0, purgeSize);
result = purgeSize;
}
long expected = Math.max(sequenceNumber + size, firstSequence);
lowestExpectedSequence = expected;
}
}
return result;
}
public String toString()
{
StringBuffer buffer = new StringBuffer("NotificationBuffer@");
buffer.append(Integer.toHexString(hashCode())).append("[");
buffer.append("first=").append(getFirstSequenceNumber()).append(", ");
buffer.append("last=").append(getLastSequenceNumber()).append(", ");
buffer.append("size=").append(getSize()).append(", ");
buffer.append("lowestExpected=").append(lowestExpectedSequence).append(", ");
buffer.append("maxCapacity=").append(maxCapacity).append(", ");
buffer.append("purgeDistance=").append(purgeDistance).append("]");
return buffer.toString();
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/HeartBeat.java 100644 0 0 2526 10513545721 16133 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
/**
* A continuous pulse from client to server that gives the information that
* the connection is alive and the server is up.
*
* @version $Revision: 1.4 $
*/
public interface HeartBeat
{
/**
* Starts the heart beat
*
* @throws IOException If there are problems contacting the server
* @see #stop
*/
public void start() throws IOException;
/**
* Stops the heart beat
*
* @throws IOException If there are problems contacting the server
* @see #start
*/
public void stop() throws IOException;
/**
* Returns the period of time in milliseconds between two heart beats
*
* @see MX4JRemoteConstants#CONNECTION_HEARTBEAT_PERIOD
* @see #getMaxRetries
*/
public long getPulsePeriod();
/**
* Returns the maximum number of retries this heart beat attempts after
* a first connection failure before declaring the connection or the server
* as dead.
*
* @see MX4JRemoteConstants#CONNECTION_HEARTBEAT_RETRIES
* @see #getPulsePeriod
*/
public int getMaxRetries();
}
mx4j-3.0.2/src/core/mx4j/remote/MX4JRemoteConstants.java 100644 0 0 12430 10513545721 20102 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
/**
* @version $Revision: 1.15 $
*/
public interface MX4JRemoteConstants
{
/**
* A vertical bar '|' as mandated by the spec
*/
public static final String PROVIDER_PACKAGES_SEPARATOR = "|";
/**
* MX4J provider packages list for JMXConnector and JMXConnectorServer factories
*/
public static final String PROVIDER_PACKAGES = "mx4j.remote.provider" + PROVIDER_PACKAGES_SEPARATOR + "mx4j.tools.remote.provider";
/**
* The string 'ClientProvider' as mandated by the spec
*/
public static final String CLIENT_PROVIDER_CLASS = "ClientProvider";
/**
* The string 'ServerProvider' as mandated by the spec
*/
public static final String SERVER_PROVIDER_CLASS = "ServerProvider";
/**
* The key that specifies resolver packages, very much like
* {@link javax.management.remote.JMXConnectorFactory#PROTOCOL_PROVIDER_PACKAGES}
*/
public static final String PROTOCOL_RESOLVER_PACKAGES = "mx4j.remote.resolver.pkgs";
/**
* A vertical bar '|'
*/
public static final String RESOLVER_PACKAGES_SEPARATOR = PROVIDER_PACKAGES_SEPARATOR;
/**
* MX4J provider packages list for {@link mx4j.remote.ConnectionResolver} subclasses
*/
public static final String RESOLVER_PACKAGES = "mx4j.remote.resolver" + RESOLVER_PACKAGES_SEPARATOR + "mx4j.tools.remote.resolver";
/**
* The string 'Resolver'
*/
public static final String RESOLVER_CLASS = "Resolver";
/**
* The reference implementation uses this property to specify the notification fetch timeout (in ms).
* MX4J will use the same for compatibility. DO NOT CHANGE IT unless the reference implementation changes it.
*/
public static final String FETCH_NOTIFICATIONS_TIMEOUT = "jmx.remote.x.client.fetch.timeout";
/**
* The reference implementation uses this property to specify the maximum number of notification to fetch.
* MX4J will use the same for compatibility. DO NOT CHANGE IT unless the reference implementation changes it.
*/
public static final String FETCH_NOTIFICATIONS_MAX_NUMBER = "jmx.remote.x.client.max.notifications";
/**
* The reference implementation uses this property to specify the notification buffer size.
* MX4J will use the same for compatibility. DO NOT CHANGE IT unless the reference implementation changes it.
*/
public static final String NOTIFICATION_BUFFER_CAPACITY = "jmx.remote.x.buffer.size";
/**
* MX4J's implementation uses this property to specify the distance between the lowest expected notification
* sequence number (sent by the client via fetchNotifications()) and the minimum sequence number of the
* notification buffer. When this difference is greater than the value of this property, old notifications
* are eliminated from the notification buffer
*/
public static final String NOTIFICATION_PURGE_DISTANCE = "jmx.remote.x.notification.purge.distance";
/**
* MX4J's implementation uses this property to specify the amount of time (in ms) the client should sleep
* between notification fetches. A value of 0 means there will be no sleep (fetches will be done one
* after the other).
*/
public static final String FETCH_NOTIFICATIONS_SLEEP = "jmx.remote.x.notification.fetch.sleep";
/**
* MX4J's implementation uses this property to specify the period (in ms) of the heartbeat pulse for
* {@link javax.management.remote.JMXConnector JMXConnectors} that use heartbeat to check if the
* connection with {@link javax.management.remote.JMXConnectorServer JMXConnectorServers} is still alive.
*
* @see #CONNECTION_HEARTBEAT_RETRIES
*/
public static final String CONNECTION_HEARTBEAT_PERIOD = "jmx.remote.x.connection.heartbeat.period";
/**
* MX4J's implementation uses this property to specify the number of retries of heartbeat pulses before
* declaring the connection between a {@link javax.management.remote.JMXConnector JMXConnector} and a
* {@link javax.management.remote.JMXConnectorServer JMXConnectorServer} failed, at which a
* {@link javax.management.remote.JMXConnectionNotification notification failed} is emitted.
*
* @see #CONNECTION_HEARTBEAT_PERIOD
*/
public static final String CONNECTION_HEARTBEAT_RETRIES = "jmx.remote.x.connection.heartbeat.retries";
/**
* MX4J's implementation uses this property to specify the maximum notification queue size
* on client size. If set to 0, or not present, the queue will have no limit.
* Specify this property when the server side is generating notifications at a fast rate,
* but clients can process them only at a slower rate. In this case notifications will queue
* up on client side, and if no limit is given to the queue, there is a potential risk of
* an OutOfMemoryError.
*/
public static final String NOTIFICATION_QUEUE_CAPACITY = "jmx.remote.x.queue.size";
/**
* @deprecated Use {@link mx4j.tools.remote.http.HTTPConnectorServer#WEB_CONTAINER_CONFIGURATION} instead
*/
public static final String HTTP_SERVER_CONFIGURATION = "jmx.remote.x.http.server.configuration";
}
mx4j-3.0.2/src/core/mx4j/remote/MX4JRemoteUtils.java 100644 0 0 41602 10513545721 17231 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.security.AccessControlContext;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.DomainCombiner;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.management.remote.SubjectDelegationPermission;
import javax.security.auth.AuthPermission;
import javax.security.auth.Policy;
import javax.security.auth.Subject;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* @version $Revision: 1.19 $
*/
public class MX4JRemoteUtils
{
private static int connectionNumber;
/**
* Returns a copy of the given Map that does not contain non-serializable entries
*/
public static Map removeNonSerializableEntries(Map map)
{
Map newMap = new HashMap(map.size());
for (Iterator i = map.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
if (isSerializable(entry)) newMap.put(entry.getKey(), entry.getValue());
}
return newMap;
}
private static boolean isSerializable(Object object)
{
if (object instanceof Map.Entry) return isSerializable(((Map.Entry)object).getKey()) && isSerializable(((Map.Entry)object).getValue());
if (object == null) return true;
if (object instanceof String) return true;
if (object instanceof Number) return true;
if (!(object instanceof Serializable)) return false;
return isTrulySerializable(object);
}
public static boolean isTrulySerializable(Object object)
{
// Give up and serialize the object
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.close();
return true;
}
catch (IOException ignored)
{
}
return false;
}
public static String createConnectionID(String protocol, String callerAddress, int callerPort, Subject subject)
{
// See JSR 160 specification at javax/management/remote/package-summary.html
StringBuffer buffer = new StringBuffer(protocol);
buffer.append(':');
if (callerAddress != null) buffer.append("//").append(callerAddress);
if (callerPort >= 0) buffer.append(':').append(callerPort);
buffer.append(' ');
if (subject != null)
{
Set principals = subject.getPrincipals();
for (Iterator i = principals.iterator(); i.hasNext();)
{
Principal principal = (Principal)i.next();
String name = principal.getName();
name = name.replace(' ', '_');
buffer.append(name);
if (i.hasNext()) buffer.append(';');
}
}
buffer.append(' ');
buffer.append("0x").append(Integer.toHexString(getNextConnectionNumber()).toUpperCase());
return buffer.toString();
}
private static synchronized int getNextConnectionNumber()
{
return ++connectionNumber;
}
private static Logger getLogger()
{
return Log.getLogger(MX4JRemoteUtils.class.getName());
}
public static Object subjectInvoke(Subject subject, Subject delegate, AccessControlContext context, Map environment, PrivilegedExceptionAction action) throws Exception
{
if (delegate != null)
{
if (subject == null) throw new SecurityException("There is no authenticated subject to delegate to");
checkSubjectDelegationPermission(delegate, getSubjectContext(subject, null, context, environment));
}
Logger logger = getLogger();
// If there is no authenticated subject, I leave the transport library to perform its job.
// In the RMIConnectorServer, the context at start() time is used by the RMI runtime to
// restrict permissions via a doPrivileged() call.
// In HTTP JMXConnectorServer, it's the HTTP server responsibility to give such semantic,
// if it wants to.
// Here, I just execute the action and trust the transport library to do its job right.
if (subject == null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("No authenticated subject, invoking action without using Subject.doAs");
return action.run();
}
// The precedent stack frames have normally AllPermission, since - for example in RMI - they
// are JDK domains or JMX/MX4J domains. Below I take the context, and I
// inject the JSR 160 domain with the authenticated Subject, then call Subject.doAsPrivileged()
// with, eventually, the delegate Subject.
// Must call Subject.doAs, since anyone down in the stack call can call Subject.getSubject()
// and expect to get the Subject or the delegate, even in absence of the SecurityManager
try
{
if (delegate == null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Invoking Subject.doAs using authenticated subject " + subject);
return Subject.doAsPrivileged(subject, action, getSubjectContext(subject, delegate, context, environment));
}
else
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Invoking Subject.doAs using delegate subject " + delegate);
return Subject.doAsPrivileged(delegate, action, getSubjectContext(subject, delegate, context, environment));
}
}
catch (PrivilegedActionException x)
{
throw x.getException();
}
}
private static void checkSubjectDelegationPermission(final Subject delegate, AccessControlContext context) throws SecurityException
{
Logger logger = getLogger();
SecurityManager sm = System.getSecurityManager();
if (sm == null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("No SecurityManager, skipping Subject delegation permission check");
return;
}
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
StringBuffer buffer = new StringBuffer();
Set principals = delegate.getPrincipals();
for (Iterator i = principals.iterator(); i.hasNext();)
{
Principal principal = (Principal)i.next();
buffer.setLength(0);
String permission = buffer.append(principal.getClass().getName()).append(".").append(principal.getName()).toString();
AccessController.checkPermission(new SubjectDelegationPermission(permission));
}
return null;
}
}, context);
}
/**
* Returns a suitable AccessControlContext that restricts access in a {@link Subject#doAsPrivileged} call
* based on the current JAAS authorization policy, and combined with the given context.
*
* This is needed because the server stack frames in a call to a JMXConnectorServer are,
* for example for RMI, like this:
*
* java.lang.Thread.run()
* [rmi runtime classes]
* javax.management.remote.rmi.RMIConnectionImpl
* [mx4j JSR 160 implementation code]
* javax.security.auth.Subject.doAsPrivileged()
* [mx4j JSR 160 implementation code]
* [mx4j JSR 3 implementation code]
* java.lang.SecurityManager.checkPermission()
*
* All protection domains in this stack frames have AllPermission, normally, so that when the JMX implementation
* checks for permissions, it will always pass the check.
*
* One solution would be to use a doPrivileged() call with a restricting context (normally created at the start()
* of the connector server), but this forces to grant to the code that starts the connector server all the
* permissions needed by clients, and furthermore, grants to clients the permissions needed to start the connector
* server.
*
* Therefore, a "special" ProtectionDomain will be injected in the AccessControlContext returned by this method.
* This special ProtectionDomain will have a CodeSource with null location and the principals specified by the
* subject passed as argument.
*
* The "injection" of this synthetic ProtectionDomain allows to give AllPermission to the JSR 3 and 160 classes
* and implementation, but still have the possibility to specify a JAAS policy with MBeanPermissions in this way:
*
* grant principal javax.management.remote.JMXPrincipal "mx4j"
* {
* permission javax.management.MBeanPermission "*", "getAttribute";
* };
*
* MX4J also offer an alternative implementation that checks if the given context has a
* {@link SubjectDelegationPermission} for the given subject; if so, the policy configuration is much simpler
* since does not require that the context has all the possible permissions needed by code down the stack.
* This also allows to specify separately the permissions to start the connector server
* and the permissions needed by clients.
*/
private static AccessControlContext getSubjectContext(final Subject subject, Subject delegate, final AccessControlContext context, Map environment)
{
final Logger logger = getLogger();
SecurityManager sm = System.getSecurityManager();
if (sm == null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("No security manager, injecting JSR 160 domain only");
// Just return the injected domain, to allow Subject.getSubject() return correct values
InjectingDomainCombiner combiner = new InjectingDomainCombiner(delegate != null ? delegate : subject);
return new AccessControlContext(new ProtectionDomain[]{combiner.getInjectedProtectionDomain()});
}
// Check if the caller can delegate to a subject
boolean combine = ((Boolean)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
// Here use the authenticated subject, not the delegate
checkSubjectDelegationPermission(subject, context);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Check for SubjectDelegationPermission passed, avoiding security domains combination");
return Boolean.FALSE;
}
catch (AccessControlException x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Check for SubjectDelegationPermission not passed, combining security domains");
return Boolean.TRUE;
}
}
}, context)).booleanValue();
if (combine)
{
final InjectingDomainCombiner combiner = new InjectingDomainCombiner(delegate != null ? delegate : subject);
AccessControlContext acc = (AccessControlContext)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return new AccessControlContext(context, combiner);
}
});
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
// Check this permission, that is required anyway, to combine the domains
AccessController.checkPermission(new AuthPermission("doAsPrivileged"));
}
catch (AccessControlException ignored)
{
}
return null;
}
}, acc);
ProtectionDomain[] combined = combiner.getCombinedDomains();
return new AccessControlContext(combined);
}
else
{
InjectingDomainCombiner combiner = new InjectingDomainCombiner(delegate != null ? delegate : subject);
return new AccessControlContext(new ProtectionDomain[]{combiner.getInjectedProtectionDomain()});
}
}
private static class InjectingDomainCombiner implements DomainCombiner
{
private static Constructor domainConstructor;
static
{
try
{
domainConstructor = ProtectionDomain.class.getConstructor(new Class[]{CodeSource.class, PermissionCollection.class, ClassLoader.class, Principal[].class});
}
catch (Exception x)
{
}
}
private ProtectionDomain domain;
private ProtectionDomain[] combined;
public InjectingDomainCombiner(Subject subject)
{
if (domainConstructor != null)
{
Principal[] principals = (Principal[])subject.getPrincipals().toArray(new Principal[0]);
try
{
Object[] args = new Object[]{new CodeSource((URL)null, (Certificate[])null), null, null, principals};
domain = (ProtectionDomain)domainConstructor.newInstance(args);
}
catch (Exception x)
{
}
}
if (domain == null)
{
// This is done for JDK 1.3 compatibility.
domain = new SubjectProtectionDomain(new CodeSource((URL)null, (Certificate[])null), subject);
}
}
public ProtectionDomain getInjectedProtectionDomain()
{
return domain;
}
public ProtectionDomain[] combine(ProtectionDomain[] current, ProtectionDomain[] assigned)
{
ProtectionDomain[] result = null;
if (current == null || current.length == 0)
{
if (assigned == null || assigned.length == 0)
{
result = new ProtectionDomain[1];
}
else
{
result = new ProtectionDomain[assigned.length + 1];
System.arraycopy(assigned, 0, result, 1, assigned.length);
}
}
else
{
if (assigned == null || assigned.length == 0)
{
result = new ProtectionDomain[current.length + 1];
System.arraycopy(current, 0, result, 1, current.length);
}
else
{
result = new ProtectionDomain[current.length + assigned.length + 1];
System.arraycopy(current, 0, result, 1, current.length);
System.arraycopy(assigned, 0, result, current.length + 1, assigned.length);
}
}
result[0] = domain;
this.combined = result;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE))
{
logger.trace("Security domains combination");
logger.trace("Current domains");
logger.trace(dumpDomains(current));
logger.trace("Assigned domains");
logger.trace(dumpDomains(assigned));
logger.trace("Combined domains");
logger.trace(dumpDomains(result));
}
return result;
}
private String dumpDomains(ProtectionDomain[] domains)
{
if (domains == null) return "null";
StringBuffer buffer = new StringBuffer();
for (int i = domains.length - 1; i >= 0; --i)
{
int k = domains.length - 1 - i;
while (k-- > 0) buffer.append(" ");
buffer.append(domains[i].getCodeSource().getLocation());
// Only work in JDK 1.4
// buffer.append(" - ");
// buffer.append(java.util.Arrays.asList(domains[i].getPrincipals()));
buffer.append("\n");
}
return buffer.toString();
}
public ProtectionDomain[] getCombinedDomains()
{
return combined;
}
private static class SubjectProtectionDomain extends ProtectionDomain
{
private final Subject subject;
public SubjectProtectionDomain(CodeSource codesource, Subject subject)
{
super(codesource, null);
this.subject = subject;
}
public boolean implies(Permission permission)
{
Policy policy = (Policy)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return Policy.getPolicy();
}
});
PermissionCollection permissions = policy.getPermissions(subject, getCodeSource());
return permissions.implies(permission);
}
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/NotificationTuple.java 100644 0 0 6755 10513545721 17744 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
/**
* @version $Revision: 1.5 $
*/
public class NotificationTuple
{
private static final NotificationFilter NO_FILTER = new NotificationFilter()
{
public boolean isNotificationEnabled(Notification notification)
{
return true;
}
public String toString()
{
return "no filter";
}
};
private static final Object NO_HANDBACK = new Object()
{
public String toString()
{
return "no handback";
}
};
private final ObjectName observed;
private final NotificationListener listener;
private final NotificationFilter filter;
private final Object handback;
private boolean invokeFilter;
public NotificationTuple(ObjectName observed, NotificationListener listener)
{
this(observed, listener, NO_FILTER, NO_HANDBACK);
}
public NotificationTuple(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
{
this.observed = observed;
this.listener = listener;
this.filter = filter;
this.handback = handback;
this.invokeFilter = false;
}
public ObjectName getObjectName()
{
return observed;
}
public NotificationListener getNotificationListener()
{
return listener;
}
public Object getHandback()
{
if (handback == NO_HANDBACK) return null;
return handback;
}
public NotificationFilter getNotificationFilter()
{
if (filter == NO_FILTER) return null;
return filter;
}
public void setInvokeFilter(boolean invoke)
{
this.invokeFilter = invoke;
}
public boolean getInvokeFilter()
{
if (!invokeFilter) return false;
NotificationFilter filter = getNotificationFilter();
if (filter == null) return false;
return true;
}
public boolean equals(Object obj)
{
if (this == obj) return true;
if (!(obj instanceof NotificationTuple)) return false;
final NotificationTuple other = (NotificationTuple)obj;
if (!observed.equals(other.observed)) return false;
if (!listener.equals(other.listener)) return false;
// Special treatment for special filter
if (filter == NO_FILTER) return true;
if (other.filter == NO_FILTER) return true;
if (filter != null ? !filter.equals(other.filter) : other.filter != null) return false;
if (handback != null ? !handback.equals(other.handback) : other.handback != null) return false;
return true;
}
public int hashCode()
{
int result;
result = observed.hashCode();
result = 29 * result + listener.hashCode();
result = 29 * result + (filter != null ? filter.hashCode() : 0);
result = 29 * result + (handback != null ? handback.hashCode() : 0);
return result;
}
public String toString()
{
StringBuffer buffer = new StringBuffer("NotificationTuple [");
buffer.append(observed).append(", ");
buffer.append(listener).append(", ");
buffer.append(filter).append(", ");
buffer.append(handback).append("]");
return buffer.toString();
}
}
mx4j-3.0.2/src/core/mx4j/remote/ProviderFactory.java 100644 0 0 30707 10513545721 17440 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorProvider;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXConnectorServerProvider;
import javax.management.remote.JMXProviderException;
import javax.management.remote.JMXServiceURL;
import mx4j.log.Logger;
/**
* @version $Revision: 1.8 $
*/
public class ProviderFactory extends ProviderHelper
{
public static JMXConnector newJMXConnector(JMXServiceURL url, Map env) throws IOException
{
// Yes, throw NPE if url is null (spec compliant)
String protocol = normalizeProtocol(url.getProtocol());
String providerPackages = findProviderPackageList(env, JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES);
ClassLoader classLoader = findProviderClassLoader(env, JMXConnectorFactory.PROTOCOL_PROVIDER_CLASS_LOADER);
List providers = loadProviders(JMXConnectorProvider.class, providerPackages, protocol, MX4JRemoteConstants.CLIENT_PROVIDER_CLASS, classLoader);
for (int i = 0; i < providers.size(); i++)
{
JMXConnectorProvider provider = (JMXConnectorProvider)providers.get(i);
try
{
return provider.newJMXConnector(url, Collections.unmodifiableMap(env));
}
catch (JMXProviderException x)
{
throw x;
}
catch (IOException x)
{
continue;
}
}
throw new MalformedURLException("Could not find provider for protocol " + protocol);
}
public static JMXConnectorServer newJMXConnectorServer(JMXServiceURL url, Map env, MBeanServer server) throws IOException
{
// Yes, throw NPE if url is null (spec compliant)
String protocol = normalizeProtocol(url.getProtocol());
String providerPackages = findProviderPackageList(env, JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES);
ClassLoader classLoader = findProviderClassLoader(env, JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER);
List providers = loadProviders(JMXConnectorServerProvider.class, providerPackages, protocol, MX4JRemoteConstants.SERVER_PROVIDER_CLASS, classLoader);
for (int i = 0; i < providers.size(); i++)
{
JMXConnectorServerProvider provider = (JMXConnectorServerProvider)providers.get(i);
try
{
return provider.newJMXConnectorServer(url, Collections.unmodifiableMap(env), server);
}
catch (JMXProviderException x)
{
throw x;
}
catch (IOException x)
{
continue;
}
}
throw new MalformedURLException("Could not find provider for protocol " + protocol);
}
/**
* public static JMXConnectorProvider newJMXConnectorProvider(JMXServiceURL url, Map env) throws IOException
* {
* // Yes, throw NPE if url is null (spec compliant)
* String protocol = normalizeProtocol(url.getProtocol());
* String providerPackages = findProviderPackageList(env, JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES);
* ClassLoader classLoader = findProviderClassLoader(env, JMXConnectorFactory.PROTOCOL_PROVIDER_CLASS_LOADER);
* JMXConnectorProvider provider = (JMXConnectorProvider)loadProvider(JMXConnectorProvider.class, providerPackages, protocol, MX4JRemoteConstants.CLIENT_PROVIDER_CLASS, classLoader);
* return provider;
* }
*
* public static JMXConnectorServerProvider newJMXConnectorServerProvider(JMXServiceURL url, Map env) throws IOException
* {
* // Yes, throw NPE if url is null (spec compliant)
* String protocol = normalizeProtocol(url.getProtocol());
* String providerPackages = findProviderPackageList(env, JMXConnectorServerFactory.PROTOCOL_PROVIDER_PACKAGES);
* ClassLoader classLoader = findProviderClassLoader(env, JMXConnectorServerFactory.PROTOCOL_PROVIDER_CLASS_LOADER);
* JMXConnectorServerProvider provider = (JMXConnectorServerProvider)loadProvider(JMXConnectorServerProvider.class, providerPackages, protocol, MX4JRemoteConstants.SERVER_PROVIDER_CLASS, classLoader);
* return provider;
* }
*/
private static String findEnvironmentProviderPackageList(Map environment, String key) throws JMXProviderException
{
String providerPackages = null;
if (environment != null)
{
Logger logger = getLogger();
Object pkgs = environment.get(key);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider packages in the environment: " + pkgs);
if (pkgs != null && !(pkgs instanceof String)) throw new JMXProviderException("Provider package list must be a string");
providerPackages = (String)pkgs;
}
return providerPackages;
}
private static String findProviderPackageList(Map environment, final String providerPkgsKey) throws JMXProviderException
{
// 1. Look in the environment
// 2. Look for system property
// 3. Use implementation's provider
String providerPackages = findEnvironmentProviderPackageList(environment, providerPkgsKey);
if (providerPackages == null)
{
providerPackages = findSystemPackageList(providerPkgsKey);
}
if (providerPackages != null && providerPackages.trim().length() == 0) throw new JMXProviderException("Provider package list cannot be an empty string");
if (providerPackages == null)
providerPackages = MX4JRemoteConstants.PROVIDER_PACKAGES;
else
providerPackages += MX4JRemoteConstants.PROVIDER_PACKAGES_SEPARATOR + MX4JRemoteConstants.PROVIDER_PACKAGES;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider packages list is: " + providerPackages);
return providerPackages;
}
private static ClassLoader findProviderClassLoader(Map environment, String providerLoaderKey)
{
Logger logger = getLogger();
ClassLoader classLoader = null;
if (environment != null)
{
Object loader = environment.get(providerLoaderKey);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider classloader in the environment: " + loader);
if (loader != null && !(loader instanceof ClassLoader)) throw new IllegalArgumentException("Provider classloader is not a ClassLoader");
classLoader = (ClassLoader)loader;
}
if (classLoader == null)
{
classLoader = Thread.currentThread().getContextClassLoader();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider classloader in the environment: " + classLoader);
}
// Add the classloader as required by the spec
environment.put(JMXConnectorFactory.PROTOCOL_PROVIDER_CLASS_LOADER, classLoader);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Provider classloader added to the environment");
return classLoader;
}
private static List loadProviders(Class providerType, String packages, String protocol, String className, ClassLoader loader) throws JMXProviderException
{
Logger logger = getLogger();
List result = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(packages, MX4JRemoteConstants.PROVIDER_PACKAGES_SEPARATOR);
while (tokenizer.hasMoreTokens())
{
String pkg = tokenizer.nextToken().trim();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider package: " + pkg);
// The spec states the package cannot be empty
if (pkg.length() == 0) throw new JMXProviderException("Empty package list not allowed: " + packages);
String providerClassName = constructClassName(pkg, protocol, className);
Class providerClass = null;
try
{
providerClass = loadClass(providerClassName, loader);
}
catch (ClassNotFoundException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Provider class " + providerClassName + " not found, " + (tokenizer.hasMoreTokens() ? "continuing with next package" : "no more packages to try"));
continue;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot load provider class " + providerClassName, x);
throw new JMXProviderException("Cannot load provider class " + providerClassName, x);
}
try
{
Object provider = providerClass.newInstance();
result.add(provider);
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot instantiate provider class " + providerClassName, x);
throw new JMXProviderException("Cannot instantiate provider class " + providerClassName, x);
}
}
try
{
List serviceProviders = fromServiceProviders(providerType, protocol, className, loader);
result.addAll(serviceProviders);
}
catch (IOException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Error retrieving service providers", x);
}
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Providers found are: " + result);
return result;
}
private static List fromServiceProviders(Class providerType, String protocol, String className, ClassLoader loader) throws IOException
{
String services = "META-INF/services/";
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Loading providers from " + services);
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
if (loader == null) loader = ClassLoader.getSystemClassLoader();
Enumeration providerURLs = loader.getResources(services + providerType.getName());
List providers = new ArrayList();
while (providerURLs.hasMoreElements())
{
final URL providerURL = (URL)providerURLs.nextElement();
InputStream stream = null;
try
{
stream = (InputStream)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception
{
return providerURL.openStream();
}
});
}
catch (PrivilegedActionException x)
{
Exception xx = x.getException();
if (xx instanceof IOException) throw (IOException)xx;
throw new IOException(xx.toString());
}
BufferedReader reader = null;
try
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Reading provider from " + providerURL);
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null)
{
int comment = line.indexOf('#');
if (comment >= 0) line = line.substring(0, comment);
line = line.trim();
if (line.length() == 0) continue;
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Found provider '" + line + "' in " + providerURL);
try
{
Class providerClass = loader.loadClass(line);
if (providerType.isAssignableFrom(providerClass))
{
Object providerInstance = providerClass.newInstance();
providers.add(providerInstance);
}
}
catch (Exception ignored)
{
// Skip this line and continue
}
}
}
finally
{
if (reader != null) reader.close();
}
}
return providers;
}
}
mx4j-3.0.2/src/core/mx4j/remote/ProviderHelper.java 100644 0 0 3726 10513545721 17231 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.security.AccessController;
import java.security.PrivilegedAction;
import mx4j.log.Log;
import mx4j.log.Logger;
/**
* @version $Revision: 1.5 $
*/
public abstract class ProviderHelper
{
protected static String normalizeProtocol(String protocol)
{
// Replace special chars as required by the spec
String normalized = protocol.replace('+', '.');
normalized = normalized.replace('-', '_');
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Normalizing protocol: " + protocol + " --> " + normalized);
return normalized;
}
protected static String findSystemPackageList(final String key)
{
Logger logger = getLogger();
String providerPackages = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(key);
}
});
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Packages in the system property '" + key + "': " + providerPackages);
return providerPackages;
}
protected static Class loadClass(String className, ClassLoader loader) throws ClassNotFoundException
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Loading class: " + className + " with classloader " + loader);
return loader.loadClass(className);
}
protected static String constructClassName(String packageName, String protocol, String className)
{
return new StringBuffer(packageName).append(".").append(protocol).append(".").append(className).toString();
}
protected static Logger getLogger()
{
return Log.getLogger(ProviderHelper.class.getName());
}
}
mx4j-3.0.2/src/core/mx4j/remote/RemoteNotificationClientHandler.java 100644 0 0 4051 10513545721 22526 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
/**
* Handles remote notification fetching on client side.
* It takes care of calling the server side with the correct protocol and to dispatch
* notifications to client-side listeners.
*
* @version $Revision: 1.10 $
* @see RemoteNotificationServerHandler
*/
public interface RemoteNotificationClientHandler
{
/**
* Starts notification fetching
*
* @see #stop
*/
public void start();
/**
* Stops notification fetching
*
* @see #start
*/
public void stop();
/**
* Returns whether the tuple is already present in this handler
*/
public boolean contains(NotificationTuple tuple);
/**
* Adds the given tuple with the given listener ID to this handler
*
* @see javax.management.MBeanServerConnection#addNotificationListener
* @see #removeNotificationListeners
*/
public void addNotificationListener(Integer id, NotificationTuple tuple);
/**
* Returns the IDs of the listeners for the given tuple
*
* @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.NotificationListener)
* @see #getNotificationListener
*/
public Integer[] getNotificationListeners(NotificationTuple tuple);
/**
* Returns the ID of the listener for the given tuple
*
* @see javax.management.MBeanServerConnection#removeNotificationListener(javax.management.ObjectName, javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
* @see #getNotificationListeners
*/
public Integer getNotificationListener(NotificationTuple tuple);
/**
* Removes the listeners with the given IDs from this handler
*
* @see #addNotificationListener
*/
public void removeNotificationListeners(Integer[] ids);
}
mx4j-3.0.2/src/core/mx4j/remote/RemoteNotificationServerHandler.java 100644 0 0 4101 10513545721 22552 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote;
import java.io.IOException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.NotificationResult;
/**
* Handles remote notification sending on server side.
* It takes care of collecting requests for listener addition and removal, and to send
* notifications back to the client side.
*
* @version $Revision: 1.7 $
* @see RemoteNotificationClientHandler
*/
public interface RemoteNotificationServerHandler
{
/**
* Returns a unique ID for a client-side NotificationListener
*
* @see #addNotificationListener
*/
public Integer generateListenerID(ObjectName name, NotificationFilter filter);
/**
* Returns the unique server side listener that will represent client-side listeners
* on MBeans.
*/
public NotificationListener getServerNotificationListener();
/**
* Adds the given tuple with the given listener ID to this handler
*
* @see #removeNotificationListener
*/
public void addNotificationListener(Integer id, NotificationTuple tuple);
/**
* Removes the listener with the given ID from this handler
*
* @see #addNotificationListener
*/
public NotificationTuple removeNotificationListener(Integer id);
/**
* Fetches notifications from the notification buffer in order to send them
* to the client side
*
* @throws IOException If this handler has already been closed
*/
public NotificationResult fetchNotifications(long sequenceNumber, int maxNotifications, long timeout) throws IOException;
/**
* Closes this handler, that will not accept anymore add or removal of listeners
*
* @return The NotificationTuples currently held
* @see #fetchNotifications
*/
public NotificationTuple[] close();
}
mx4j-3.0.2/src/core/mx4j/remote/provider/iiop/ClientProvider.java 100644 0 0 1731 10513545721 22014 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.provider.iiop;
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 javax.management.remote.rmi.RMIConnector;
/**
* @version $Revision: 1.4 $
*/
public class ClientProvider implements JMXConnectorProvider
{
public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException
{
String protocol = url.getProtocol();
if (!"iiop".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this);
return new RMIConnector(url, environment);
}
}
mx4j-3.0.2/src/core/mx4j/remote/provider/iiop/ServerProvider.java 100644 0 0 2104 10513545721 22037 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.provider.iiop;
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 javax.management.remote.rmi.RMIConnectorServer;
/**
* @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 (!"iiop".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this);
return new RMIConnectorServer(url, environment, server);
}
}
mx4j-3.0.2/src/core/mx4j/remote/provider/rmi/ClientProvider.java 100644 0 0 1727 10513545721 21650 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.provider.rmi;
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 javax.management.remote.rmi.RMIConnector;
/**
* @version $Revision: 1.5 $
*/
public class ClientProvider implements JMXConnectorProvider
{
public JMXConnector newJMXConnector(JMXServiceURL url, Map environment) throws IOException
{
String protocol = url.getProtocol();
if (!"rmi".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this);
return new RMIConnector(url, environment);
}
}
mx4j-3.0.2/src/core/mx4j/remote/provider/rmi/ServerProvider.java 100644 0 0 2102 10513545721 21664 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.provider.rmi;
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 javax.management.remote.rmi.RMIConnectorServer;
/**
* @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 (!"rmi".equals(protocol)) throw new MalformedURLException("Wrong protocol " + protocol + " for provider " + this);
return new RMIConnectorServer(url, environment, server);
}
}
mx4j-3.0.2/src/core/mx4j/remote/resolver/iiop/Resolver.java 100644 0 0 12050 10513545721 20707 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.resolver.iiop;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIIIOPServerImpl;
import javax.management.remote.rmi.RMIServer;
import javax.management.remote.rmi.RMIServerImpl;
import javax.rmi.CORBA.Stub;
import javax.rmi.PortableRemoteObject;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.ORB;
/**
* @version $Revision: 1.3 $
*/
public class Resolver extends mx4j.remote.resolver.rmi.Resolver
{
private static final String IOR_CONTEXT = "/ior/";
private ORB orb;
private static final String ORB_KEY = "java.naming.corba.orb";
//********************************************************************************************************************//
// CLIENT METHODS
protected RMIServer lookupStubInJNDI(JMXServiceURL url, Map environment) throws IOException
{
checkORB(environment);
return super.lookupStubInJNDI(url, environment);
}
protected RMIServer decodeStub(JMXServiceURL url, Map environment) throws IOException
{
String path = url.getURLPath();
String ior = IOR_CONTEXT;
if (path.startsWith(ior))
{
String encoded = path.substring(ior.length());
ORB orb = getORB(environment);
Object object = orb.string_to_object(encoded);
return narrowRMIServerStub(object);
}
throw new MalformedURLException("Unsupported binding: " + url);
}
protected RMIServer narrowRMIServerStub(Object stub)
{
return (RMIServer)PortableRemoteObject.narrow(stub, RMIServer.class);
}
public Object bindClient(Object client, Map environment) throws IOException
{
Stub stub = (Stub)client;
ORB orb = null;
try
{
orb = stub._orb();
}
catch (BAD_OPERATION x)
{
// The stub is not connected to an ORB, go on
}
if (orb == null)
{
orb = getORB(environment);
stub.connect(orb);
}
return stub;
}
//********************************************************************************************************************//
// SERVER METHODS
protected RMIServerImpl createRMIServer(JMXServiceURL url, Map environment) throws IOException
{
return new RMIIIOPServerImpl(environment);
}
public JMXServiceURL bindServer(Object server, JMXServiceURL url, Map environment) throws IOException
{
RMIServerImpl rmiServer = (RMIServerImpl)server;
Stub stub = (Stub)PortableRemoteObject.toStub(rmiServer);
stub.connect(getORB(environment));
return super.bindServer(server, url, environment);
}
protected String encodeStub(RMIServerImpl rmiServer, Map environment) throws IOException
{
Stub stub = (Stub)bindClient(rmiServer.toStub(), environment);
String ior = getORB(environment).object_to_string(stub);
return IOR_CONTEXT + ior;
}
private ORB checkORB(Map environment)
{
if (environment == null) return null;
Object candidateORB = environment.get(ORB_KEY);
if (candidateORB != null)
{
// Throw as required by the spec
if (!(candidateORB instanceof ORB)) throw new IllegalArgumentException("Property " + ORB_KEY + " must specify a " + ORB.class.getName() + ", not " + candidateORB.getClass().getName());
return (ORB)candidateORB;
}
return null;
}
/**
* Creates a new ORB, if not already created.
* This method is accessed from both client and server.
*/
private synchronized ORB getORB(Map environment)
{
if (orb == null)
{
orb = checkORB(environment);
if (orb == null)
{
Properties props = new Properties();
// Using putAll() on a Properties is discouraged, since it expects only Strings
for (Iterator i = environment.entrySet().iterator(); i.hasNext();)
{
Map.Entry entry = (Map.Entry)i.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (key instanceof String && value instanceof String)
{
props.setProperty((String)key, (String)value);
}
}
orb = ORB.init((String[])null, props);
}
}
return orb;
}
protected boolean isEncodedForm(JMXServiceURL url)
{
String path = url.getURLPath();
if (path != null && path.startsWith(IOR_CONTEXT)) return true;
return super.isEncodedForm(url);
}
public void destroyServer(Object server, JMXServiceURL url, Map environment) throws IOException
{
if (!isEncodedForm(url)) return;
if (orb != null)
{
orb.shutdown(true);
orb.destroy();
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/resolver/rmi/Resolver.java 100644 0 0 23472 10513545721 20550 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.resolver.rmi;
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.rmi.Remote;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.util.Hashtable;
import java.util.Map;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.management.remote.rmi.RMIJRMPServerImpl;
import javax.management.remote.rmi.RMIServer;
import javax.management.remote.rmi.RMIServerImpl;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import mx4j.log.Logger;
import mx4j.remote.ConnectionResolver;
import mx4j.util.Base64Codec;
/**
* Resolver for RMI/JRMP protocol.
*
* @version $Revision: 1.3 $
*/
public class Resolver extends ConnectionResolver
{
private static final String JNDI_CONTEXT = "/jndi/";
private static final String STUB_CONTEXT = "/stub/";
//********************************************************************************************************************//
// CLIENT METHODS
public Object lookupClient(JMXServiceURL url, Map environment) throws IOException
{
return lookupRMIServerStub(url, environment);
}
public Object bindClient(Object client, Map environment) throws IOException
{
// JRMP does not need anything special
return client;
}
protected RMIServer lookupRMIServerStub(JMXServiceURL url, Map environment) throws IOException
{
Logger logger = getLogger();
String path = url.getURLPath();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("JMXServiceURL for lookup is: '" + url + "'");
if (path != null)
{
if (path.startsWith(JNDI_CONTEXT))
{
return lookupStubInJNDI(url, environment);
}
return decodeStub(url, environment);
}
throw new MalformedURLException("Unsupported lookup " + url);
}
protected RMIServer lookupStubInJNDI(JMXServiceURL url, Map environment) throws IOException
{
Logger logger = getLogger();
String path = url.getURLPath();
String name = path.substring(JNDI_CONTEXT.length());
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Looking up RMI stub in JNDI under name " + name);
InitialContext ctx = null;
try
{
ctx = new InitialContext(new Hashtable(environment));
Object stub = ctx.lookup(name);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Found RMI stub in JNDI " + stub);
return narrowRMIServerStub(stub);
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot lookup RMI stub in JNDI", x);
throw new IOException(x.toString());
}
finally
{
try
{
if (ctx != null) ctx.close();
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot close InitialContext", x);
}
}
}
protected RMIServer narrowRMIServerStub(Object stub)
{
return (RMIServer)stub;
}
protected RMIServer decodeStub(JMXServiceURL url, Map environment) throws IOException
{
String path = url.getURLPath();
if (path.startsWith(STUB_CONTEXT))
{
byte[] encoded = path.substring(STUB_CONTEXT.length()).getBytes();
if (!Base64Codec.isArrayByteBase64(encoded)) throw new IOException("Encoded stub form is not a valid Base64 sequence: " + url);
byte[] decoded = Base64Codec.decodeBase64(encoded);
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(bais);
return (RMIServer)ois.readObject();
}
catch (ClassNotFoundException x)
{
throw new IOException("Cannot decode stub from " + url + ": " + x);
}
finally
{
if (ois != null) ois.close();
}
}
throw new MalformedURLException("Unsupported binding: " + url);
}
//********************************************************************************************************************//
// SERVER METHODS
public Object createServer(JMXServiceURL url, Map environment) throws IOException
{
return createRMIServer(url, environment);
}
protected RMIServerImpl createRMIServer(JMXServiceURL url, Map environment) throws IOException
{
int port = url.getPort();
RMIClientSocketFactory clientFactory = (RMIClientSocketFactory)environment.get(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE);
RMIServerSocketFactory serverFactory = (RMIServerSocketFactory)environment.get(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE);
return new RMIJRMPServerImpl(port, clientFactory, serverFactory, environment);
}
public JMXServiceURL bindServer(Object server, JMXServiceURL url, Map environment) throws IOException
{
// See javax/management/remote/rmi/package-summary.html
RMIServerImpl rmiServer = (RMIServerImpl)server;
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("JMXServiceURL for binding is: '" + url + "'");
if (isEncodedForm(url))
{
String path = encodeStub(rmiServer, environment);
return new JMXServiceURL(url.getProtocol(), url.getHost(), url.getPort(), path);
}
else
{
String jndiURL = parseJNDIForm(url);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("JMXServiceURL path for binding is: '" + jndiURL + "'");
InitialContext ctx = null;
try
{
ctx = new InitialContext(new Hashtable(environment));
boolean rebind = Boolean.valueOf((String)environment.get(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE)).booleanValue();
if (rebind)
ctx.rebind(jndiURL, rmiServer.toStub());
else
ctx.bind(jndiURL, rmiServer.toStub());
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Bound " + rmiServer + " to " + jndiURL);
return url;
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot bind server " + rmiServer + " to " + jndiURL, x);
throw new IOException(x.toString());
}
finally
{
try
{
if (ctx != null) ctx.close();
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot close InitialContext", x);
}
}
}
}
protected String encodeStub(RMIServerImpl rmiServer, Map environment) throws IOException
{
Remote stub = rmiServer.toStub();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream(baos);
oos.writeObject(stub);
}
finally
{
if (oos != null) oos.close();
}
byte[] bytes = baos.toByteArray();
byte[] encoded = Base64Codec.encodeBase64(bytes);
// Since the bytes are base 64 bytes, the encoding in creating the string is not important: any will work
return STUB_CONTEXT + new String(encoded);
}
protected boolean isEncodedForm(JMXServiceURL url)
{
String path = url.getURLPath();
if (path == null || path.length() == 0 || "/".equals(path) || path.startsWith(STUB_CONTEXT)) return true;
return false;
}
private String parseJNDIForm(JMXServiceURL url) throws MalformedURLException
{
String path = url.getURLPath();
if (path.startsWith(JNDI_CONTEXT))
{
String jndiURL = path.substring(JNDI_CONTEXT.length());
if (jndiURL == null || jndiURL.length() == 0) throw new MalformedURLException("No JNDI URL specified: " + url);
return jndiURL;
}
throw new MalformedURLException("Unsupported binding: " + url);
}
public void unbindServer(Object server, JMXServiceURL url, Map environment) throws IOException
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("JMXServiceURL for unbinding is: '" + url + "'");
// The server was not bound to JNDI (the stub was encoded), just return
if (isEncodedForm(url))
{
return;
}
else
{
String jndiURL = parseJNDIForm(url);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("JMXServiceURL path for unbinding is: '" + jndiURL + "'");
InitialContext ctx = null;
try
{
ctx = new InitialContext(new Hashtable(environment));
ctx.unbind(jndiURL);
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Unbound " + server + " from " + jndiURL);
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot unbind server " + server + " to " + jndiURL, x);
throw new IOException(x.toString());
}
finally
{
try
{
if (ctx != null) ctx.close();
}
catch (NamingException x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot close InitialContext", x);
}
}
}
}
public void destroyServer(Object server, JMXServiceURL url, Map environment) throws IOException
{
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/ClientExceptionCatcher.java 100644 0 0 3057 10513545721 21452 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.rmi.NoSuchObjectException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXServerErrorException;
import mx4j.remote.ClientProxy;
/**
* @version $Revision: 1.3 $
*/
public class ClientExceptionCatcher extends ClientProxy
{
private ClientExceptionCatcher(MBeanServerConnection target)
{
super(target);
}
public static MBeanServerConnection newInstance(MBeanServerConnection target)
{
ClientExceptionCatcher handler = new ClientExceptionCatcher(target);
return (MBeanServerConnection)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[]{MBeanServerConnection.class}, handler);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
return super.invoke(proxy, method, args);
}
catch (NoSuchObjectException x)
{
// The connection has been already closed by the server
throw new IOException("Connection closed by the server");
}
catch (Exception x)
{
throw x;
}
catch (Error x)
{
throw new JMXServerErrorException("Error thrown during invocation", x);
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/ClientInvoker.java 100644 0 0 25210 10513545721 17652 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.io.NotSerializableException;
import java.rmi.MarshalledObject;
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.management.remote.rmi.RMIConnection;
import javax.security.auth.Subject;
import mx4j.remote.NotificationTuple;
import mx4j.remote.RemoteNotificationClientHandler;
/**
* An MBeanServerConnection that "converts" the MBeanServerConnection calls to {@link RMIConnection} calls,
* performing wrapping of parameters and/or the needed actions.
*
* @version $Revision: 1.10 $
* @see mx4j.remote.rmi.RMIConnectionInvoker
*/
public class ClientInvoker implements MBeanServerConnection
{
private final RMIConnection connection;
private final Subject delegate;
private final RemoteNotificationClientHandler notificationHandler;
public ClientInvoker(RMIConnection rmiConnection, RemoteNotificationClientHandler notificationHandler, Subject delegate)
{
this.connection = rmiConnection;
this.delegate = 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);
if (notificationHandler.contains(tuple)) return;
MarshalledObject f = null;
try
{
f = RMIMarshaller.marshal(filter);
}
catch (NotSerializableException x)
{
// Invoke the filter on client side
tuple.setInvokeFilter(true);
}
Integer[] ids = connection.addNotificationListeners(new ObjectName[]{observed}, new MarshalledObject[]{f}, new Subject[]{delegate});
notificationHandler.addNotificationListener(ids[0], 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
{
connection.removeNotificationListeners(observed, ids, delegate);
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
{
connection.removeNotificationListeners(observed, ids, delegate);
notificationHandler.removeNotificationListeners(ids);
}
catch (InstanceNotFoundException x)
{
notificationHandler.removeNotificationListeners(ids);
throw x;
}
catch (ListenerNotFoundException x)
{
notificationHandler.removeNotificationListeners(ids);
throw x;
}
}
public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, IOException
{
MarshalledObject f = RMIMarshaller.marshal(filter);
MarshalledObject h = RMIMarshaller.marshal(handback);
connection.addNotificationListener(observed, listener, f, h, 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
{
MarshalledObject f = RMIMarshaller.marshal(filter);
MarshalledObject h = RMIMarshaller.marshal(handback);
connection.removeNotificationListener(observed, listener, f, h, 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, delegate);
}
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, IOException
{
MarshalledObject arguments = RMIMarshaller.marshal(args);
return connection.createMBean(className, objectName, arguments, 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, delegate);
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, IOException
{
MarshalledObject arguments = RMIMarshaller.marshal(args);
return connection.createMBean(className, objectName, loaderName, arguments, 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
{
MarshalledObject attrib = RMIMarshaller.marshal(attribute);
connection.setAttribute(objectName, attrib, 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
{
MarshalledObject attribs = RMIMarshaller.marshal(attributes);
return connection.setAttributes(objectName, attribs, delegate);
}
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException, IOException
{
MarshalledObject arguments = RMIMarshaller.marshal(args);
return connection.invoke(objectName, methodName, arguments, 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
{
MarshalledObject query = RMIMarshaller.marshal(filter);
return connection.queryMBeans(patternName, query, delegate);
}
public Set queryNames(ObjectName patternName, QueryExp filter)
throws IOException
{
MarshalledObject query = RMIMarshaller.marshal(filter);
return connection.queryNames(patternName, query, delegate);
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/ClientUnmarshaller.java 100644 0 0 4445 10513545721 20661 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.management.MBeanServerConnection;
import mx4j.remote.ClientProxy;
/**
* An MBeanServerConnection proxy that performs the setting of the appropriate context classloader
* to allow classloading of classes sent by the server but not known to the client, in methods like
* {@link MBeanServerConnection#getAttribute}, {@link MBeanServerConnection#invoke} and so on.
*
* @version $Revision: 1.4 $
*/
public class ClientUnmarshaller extends ClientProxy
{
private final ClassLoader classLoader;
private ClientUnmarshaller(MBeanServerConnection target, ClassLoader loader)
{
super(target);
this.classLoader = loader;
}
public static MBeanServerConnection newInstance(MBeanServerConnection target, ClassLoader loader)
{
ClientUnmarshaller handler = new ClientUnmarshaller(target, loader);
return (MBeanServerConnection)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[]{MBeanServerConnection.class}, handler);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if (classLoader == null)
{
return chain(proxy, method, args);
}
else
{
ClassLoader old = Thread.currentThread().getContextClassLoader();
try
{
setContextClassLoader(classLoader);
return chain(proxy, method, args);
}
finally
{
setContextClassLoader(old);
}
}
}
private Object chain(Object proxy, Method method, Object[] args) throws Throwable
{
return super.invoke(proxy, method, args);
}
private void setContextClassLoader(final ClassLoader loader)
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
Thread.currentThread().setContextClassLoader(loader);
return null;
}
});
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/Marshaller.java 100644 0 0 1075 10513545721 17153 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.rmi.MarshalledObject;
/**
* IMPORTANT: see {@link RMIMarshaller}
*
* @version $Revision: 1.3 $
*/
public class Marshaller
{
public static Object unmarshal(MarshalledObject obj) throws IOException, ClassNotFoundException
{
return obj.get();
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIConnectionInvoker.java 100644 0 0 32752 10513545721 21114 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Map;
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.QueryExp;
import javax.management.ReflectionException;
import javax.management.loading.ClassLoaderRepository;
import javax.management.remote.NotificationResult;
import javax.management.remote.rmi.RMIConnection;
import javax.security.auth.Subject;
import mx4j.remote.NotificationTuple;
import mx4j.remote.RemoteNotificationServerHandler;
/**
* An RMIConnection that "converts" remote calls to {@link MBeanServer} calls,
* performing unwrapping of parameters and/or the needed actions.
*
* @version $Revision: 1.12 $
* @see mx4j.remote.rmi.ClientInvoker
*/
public class RMIConnectionInvoker implements RMIConnection
{
private final MBeanServer server;
private final ClassLoader defaultLoader;
private final RemoteNotificationServerHandler notificationHandler;
public RMIConnectionInvoker(MBeanServer server, ClassLoader defaultLoader, Map environment)
{
this.server = server;
this.defaultLoader = defaultLoader;
// TODO: here we hardcoded the handler for notifications. Maybe worth to make it pluggable ?
this.notificationHandler = new RMIRemoteNotificationServerHandler(environment);
}
public String getConnectionId() throws IOException
{
throw new Error("getConnectionId() must not be propagated along the invocation chain");
}
public ObjectInstance createMBean(String className, ObjectName name, Subject delegate)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException
{
return server.createMBean(className, name);
}
public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Subject delegate)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException
{
return server.createMBean(className, name, loaderName);
}
public ObjectInstance createMBean(String className, ObjectName name, MarshalledObject params, String[] signature, Subject delegate)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException
{
RepositoryClassLoader loader = (RepositoryClassLoader)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return new RepositoryClassLoader(server.getClassLoaderRepository());
}
});
Object[] args = (Object[])RMIMarshaller.unmarshal(params, loader, defaultLoader);
return server.createMBean(className, name, args, signature);
}
public ObjectInstance createMBean(String className, ObjectName name, final ObjectName loaderName, MarshalledObject params, String[] signature, Subject delegate)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException
{
try
{
ClassLoader loader = (ClassLoader)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws InstanceNotFoundException
{
return server.getClassLoader(loaderName);
}
});
Object[] args = (Object[])RMIMarshaller.unmarshal(params, loader, defaultLoader);
return server.createMBean(className, name, loaderName, args, signature);
}
catch (PrivilegedActionException x)
{
throw (InstanceNotFoundException)x.getException();
}
}
public void unregisterMBean(ObjectName name, Subject delegate) throws InstanceNotFoundException, MBeanRegistrationException, IOException
{
server.unregisterMBean(name);
}
public ObjectInstance getObjectInstance(ObjectName name, Subject delegate) throws InstanceNotFoundException, IOException
{
return server.getObjectInstance(name);
}
public Set queryMBeans(ObjectName name, MarshalledObject query, Subject delegate) throws IOException
{
QueryExp filter = (QueryExp)RMIMarshaller.unmarshal(query, null, defaultLoader);
return server.queryMBeans(name, filter);
}
public Set queryNames(ObjectName name, MarshalledObject query, Subject delegate) throws IOException
{
QueryExp filter = (QueryExp)RMIMarshaller.unmarshal(query, null, defaultLoader);
return server.queryNames(name, filter);
}
public boolean isRegistered(ObjectName name, Subject delegate) throws IOException
{
return server.isRegistered(name);
}
public Integer getMBeanCount(Subject delegate) throws IOException
{
return server.getMBeanCount();
}
public Object getAttribute(ObjectName name, String attribute, Subject delegate)
throws MBeanException,
AttributeNotFoundException,
InstanceNotFoundException,
ReflectionException,
IOException
{
return server.getAttribute(name, attribute);
}
public AttributeList getAttributes(ObjectName name, String[] attributes, Subject delegate)
throws InstanceNotFoundException, ReflectionException, IOException
{
return server.getAttributes(name, attributes);
}
public void setAttribute(ObjectName name, MarshalledObject attribute, Subject delegate)
throws InstanceNotFoundException,
AttributeNotFoundException,
InvalidAttributeValueException,
MBeanException,
ReflectionException,
IOException
{
Attribute attrib = (Attribute)RMIMarshaller.unmarshal(attribute, getClassLoaderFor(name), defaultLoader);
server.setAttribute(name, attrib);
}
public AttributeList setAttributes(ObjectName name, MarshalledObject attributes, Subject delegate)
throws InstanceNotFoundException,
ReflectionException,
IOException
{
AttributeList attribs = (AttributeList)RMIMarshaller.unmarshal(attributes, getClassLoaderFor(name), defaultLoader);
return server.setAttributes(name, attribs);
}
public Object invoke(ObjectName name, String operationName, MarshalledObject params, String[] signature, Subject delegate)
throws InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException
{
Object[] args = (Object[])RMIMarshaller.unmarshal(params, getClassLoaderFor(name), defaultLoader);
return server.invoke(name, operationName, args, signature);
}
public String getDefaultDomain(Subject delegate) throws IOException
{
return server.getDefaultDomain();
}
public String[] getDomains(Subject delegate) throws IOException
{
return server.getDomains();
}
public MBeanInfo getMBeanInfo(ObjectName name, Subject delegate) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException
{
return server.getMBeanInfo(name);
}
public boolean isInstanceOf(ObjectName name, String className, Subject delegate) throws InstanceNotFoundException, IOException
{
return server.isInstanceOf(name, className);
}
public void addNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegate)
throws InstanceNotFoundException, IOException
{
ClassLoader loader = getClassLoaderFor(name);
NotificationFilter f = (NotificationFilter)RMIMarshaller.unmarshal(filter, loader, defaultLoader);
Object h = RMIMarshaller.unmarshal(handback, loader, defaultLoader);
server.addNotificationListener(name, listener, f, h);
}
public void removeNotificationListener(ObjectName name, ObjectName listener, Subject delegate)
throws InstanceNotFoundException, ListenerNotFoundException, IOException
{
server.removeNotificationListener(name, listener);
}
public void removeNotificationListener(ObjectName name, ObjectName listener, MarshalledObject filter, MarshalledObject handback, Subject delegate)
throws InstanceNotFoundException, ListenerNotFoundException, IOException
{
ClassLoader loader = getClassLoaderFor(name);
NotificationFilter f = (NotificationFilter)RMIMarshaller.unmarshal(filter, loader, defaultLoader);
Object h = RMIMarshaller.unmarshal(handback, loader, defaultLoader);
server.removeNotificationListener(name, listener, f, h);
}
public Integer[] addNotificationListeners(ObjectName[] names, MarshalledObject[] filters, Subject[] delegates) throws InstanceNotFoundException, IOException
{
ArrayList ids = new ArrayList();
for (int i = 0; i < names.length; ++i)
{
ObjectName name = names[i];
MarshalledObject filter = filters[i];
NotificationFilter f = (NotificationFilter)RMIMarshaller.unmarshal(filter, getClassLoaderFor(name), defaultLoader);
Integer id = notificationHandler.generateListenerID(name, f);
NotificationListener listener = notificationHandler.getServerNotificationListener();
server.addNotificationListener(name, listener, f, id);
notificationHandler.addNotificationListener(id, new NotificationTuple(name, listener, f, id));
ids.add(id);
}
return (Integer[])ids.toArray(new Integer[ids.size()]);
}
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];
// Remove anyway, even if the server fails
NotificationTuple tuple = notificationHandler.removeNotificationListener(id);
if (tuple != null) server.removeNotificationListener(name, tuple.getNotificationListener(), tuple.getNotificationFilter(), tuple.getHandback());
}
}
public void close() throws IOException
{
NotificationTuple[] tuples = notificationHandler.close();
for (int i = 0; i < tuples.length; ++i)
{
NotificationTuple tuple = tuples[i];
try
{
server.removeNotificationListener(tuple.getObjectName(), tuple.getNotificationListener(), tuple.getNotificationFilter(), tuple.getHandback());
}
catch (InstanceNotFoundException ignored)
{
}
catch (ListenerNotFoundException ignored)
{
}
}
}
public NotificationResult fetchNotifications(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException
{
return notificationHandler.fetchNotifications(clientSequenceNumber, maxNotifications, timeout);
}
private ClassLoader getClassLoaderFor(final ObjectName name) throws InstanceNotFoundException
{
if (System.getSecurityManager() == null)
{
return server.getClassLoaderFor(name);
}
else
{
try
{
return (ClassLoader)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws InstanceNotFoundException
{
return server.getClassLoaderFor(name);
}
});
}
catch (PrivilegedActionException x)
{
throw (InstanceNotFoundException)x.getException();
}
}
}
private static class RepositoryClassLoader extends SecureClassLoader
{
private final ClassLoaderRepository repository;
private RepositoryClassLoader(ClassLoaderRepository repository)
{
this.repository = repository;
}
public Class loadClass(String name) throws ClassNotFoundException
{
return repository.loadClass(name);
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIConnectionProxy.java 100644 0 0 1741 10513545721 20572 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.management.remote.rmi.RMIConnection;
/**
* Base class for RMIConnection dynamic proxies.
*
* @version $Revision: 1.5 $
*/
public class RMIConnectionProxy implements InvocationHandler
{
private RMIConnection nested;
protected RMIConnectionProxy(RMIConnection nested)
{
this.nested = nested;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
return method.invoke(nested, args);
}
catch (InvocationTargetException x)
{
throw x.getTargetException();
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIConnectionSubjectInvoker.java 100644 0 0 7644 10513545721 22416 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.rmi.MarshalledObject;
import java.security.AccessControlContext;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Map;
import javax.management.ObjectName;
import javax.management.remote.JMXServerErrorException;
import javax.management.remote.rmi.RMIConnection;
import javax.security.auth.Subject;
import mx4j.remote.MX4JRemoteUtils;
/**
* An RMIConnection proxy that wraps the call into a {@link Subject#doAsPrivileged} invocation,
* in order to execute the code under subject-based security, and to perform subject delegation.
*
* @version $Revision: 1.10 $
*/
public class RMIConnectionSubjectInvoker extends RMIConnectionProxy
{
public static RMIConnection newInstance(RMIConnection nested, Subject subject, AccessControlContext context, Map environment)
{
RMIConnectionSubjectInvoker handler = new RMIConnectionSubjectInvoker(nested, subject, context, environment);
return (RMIConnection)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[]{RMIConnection.class}, handler);
}
private final Subject subject;
private final AccessControlContext context;
private Map environment;
private RMIConnectionSubjectInvoker(RMIConnection nested, Subject subject, AccessControlContext context, Map environment)
{
super(nested);
this.subject = subject;
this.context = context;
this.environment = environment;
}
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable
{
String methodName = method.getName();
if ("fetchNotifications".equals(methodName) || "close".equals(methodName) || "getConnectionId".equals(methodName)) return chain(proxy, method, args);
if ("addNotificationListeners".equals(methodName))
{
Subject[] delegates = (Subject[])args[args.length - 1];
if (delegates == null || delegates.length == 0) return chain(proxy, method, args);
if (delegates.length == 1) return subjectInvoke(proxy, method, args, delegates[0]);
ArrayList ids = new ArrayList();
for (int i = 0; i < delegates.length; ++i)
{
ObjectName name = ((ObjectName[])args[0])[i];
MarshalledObject filter = ((MarshalledObject[])args[1])[i];
Subject delegate = delegates[i];
Object[] newArgs = new Object[]{new ObjectName[]{name}, new MarshalledObject[]{filter}, new Subject[]{delegate}};
Integer id = ((Integer[])subjectInvoke(proxy, method, newArgs, delegate))[0];
ids.add(id);
}
return (Integer[])ids.toArray(new Integer[ids.size()]);
}
else
{
// For all other methods, the subject is always the last argument
Subject delegate = (Subject)args[args.length - 1];
return subjectInvoke(proxy, method, args, delegate);
}
}
private 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);
}
});
}
private Object chain(Object proxy, Method method, Object[] args) throws Exception
{
try
{
return super.invoke(proxy, method, args);
}
catch (Throwable x)
{
if (x instanceof Exception) throw (Exception)x;
throw new JMXServerErrorException("Error thrown during invocation", (Error)x);
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIHeartBeat.java 100644 0 0 1557 10513545721 17275 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.util.Map;
import javax.management.remote.rmi.RMIConnection;
import mx4j.remote.AbstractHeartBeat;
import mx4j.remote.ConnectionNotificationEmitter;
/**
* @version $Revision: 1.3 $
*/
public class RMIHeartBeat extends AbstractHeartBeat
{
private final RMIConnection connection;
public RMIHeartBeat(RMIConnection connection, ConnectionNotificationEmitter emitter, Map environment)
{
super(emitter, environment);
this.connection = connection;
}
protected void pulse() throws IOException
{
connection.getDefaultDomain(null);
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIMarshaller.java 100644 0 0 23057 10513545721 17547 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.rmi.MarshalledObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.SecureClassLoader;
/**
* Marshaller/Unmarshaller for RMI's MarshalledObjects.
*
* This class implements the JMX Remote Specification, chapter 2.
*
* Don't touch unless discussed on mx4j-devel@users.sourceforge.net, and unless
* you know what you're doing (included who wrote this javadoc).
*
*
* IMPLEMENTATION NOTES:
* MarshalledObject.get() loads the object it contains by using the first user-defined classloader it can find
* in the stack frames of the call.
* If the class cannot be found with that loader, then the RMI semantic is tried: first the thread context
* classloader, then dynamic code download (if there is a security manager).
* We need that MarshalledObject.get() unmarshals using the context classloader and not the first user-defined
* classloader, since this way we can implement correctly the JMX specification (see
* {@link #unmarshal(MarshalledObject, ClassLoader, ClassLoader)}).
* Here we load the {@link Marshaller} class using {@link MarshallerClassLoader} that can only load the
* {@link Marshaller} class.
* It is important that {@link MarshallerClassLoader} cannot load from the classpath (the system classloader)
* since that would break the JMX Remote Specification compliance.
* This URLClassLoader then becomes the first user-defined classloader in the stack frames, but it will fail
* to load anything else, thus allowing MarshalledObject.get() to use the thread context classloader.
* The stack trace will be something like:
*
* {@link Marshaller#unmarshal} [MarshallerClassLoader]
* ... reflection classes ... [Boot ClassLoader]
* {@link RMIMarshaller#unmarshal(MarshalledObject)} [System ClassLoader (normally)]
*
*
* Note that the classloader that loaded this class may be something totally different from URLClassLoader:
* this is the case for the OSGi.
* We just rely on the {@link ClassLoader#getResourceAsStream(java.lang.String)} semantic to load the
* {@link Marshaller} class' bytes.
*
* @version $Revision: 1.13 $
*/
class RMIMarshaller
{
private static final Method unmarshal = getUnmarshalMethod();
private static Method getUnmarshalMethod()
{
return (Method)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
String marshallerName = Marshaller.class.getName();
InputStream stream = Marshaller.class.getResourceAsStream(marshallerName.substring(marshallerName.lastIndexOf('.') + 1) + ".class");
if (stream == null) throw new Error("Could not load implementation class " + marshallerName);
BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
try
{
byte[] buffer = new byte[256];
int read = -1;
while ((read = bis.read(buffer)) >= 0) bos.write(buffer, 0, read);
bis.close();
bos.close();
}
catch (IOException x)
{
throw new Error(x.toString());
}
byte[] classBytes = baos.toByteArray();
MarshallerClassLoader loader = new MarshallerClassLoader(classBytes);
try
{
Class cls = loader.loadClass(marshallerName);
return cls.getMethod("unmarshal", new Class[]{MarshalledObject.class});
}
catch (ClassNotFoundException x)
{
throw new Error(x.toString());
}
catch (NoSuchMethodException x)
{
throw new Error(x.toString());
}
}
});
}
/**
* Returns a MarshalledObject obtained by marshalling the given object.
*/
public static MarshalledObject marshal(Object object) throws IOException
{
if (object == null) return null;
return new MarshalledObject(object);
}
/**
* Returns the unmarshalled object obtained unmarshalling the given MarshalledObject,
* using as context classloader first the given mbeanLoader, if not null, then with the given defaultLoader.
*/
public static Object unmarshal(MarshalledObject object, final ClassLoader mbeanLoader, final ClassLoader defaultLoader) throws IOException
{
if (object == null) return null;
if (mbeanLoader == null) return unmarshal(object, defaultLoader);
ClassLoader loader = (ClassLoader)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return new ExtendedClassLoader(mbeanLoader, defaultLoader);
}
});
return unmarshal(object, loader);
}
private static Object unmarshal(MarshalledObject object, ClassLoader loader) throws IOException
{
// if (loader != null)
// {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try
{
setContextClassLoader(loader);
return unmarshal(object);
}
catch (IOException x)
{
throw x;
}
catch (ClassNotFoundException ignored)
{
throw new IOException(ignored.toString());
}
finally
{
setContextClassLoader(old);
}
// }
// throw new IOException("Cannot unmarshal " + object);
}
private static Object unmarshal(MarshalledObject marshalled) throws IOException, ClassNotFoundException
{
try
{
return unmarshal.invoke(null, new Object[]{marshalled});
}
catch (InvocationTargetException x)
{
Throwable t = x.getTargetException();
if (t instanceof IOException) throw (IOException)t;
if (t instanceof ClassNotFoundException) throw (ClassNotFoundException)t;
throw new IOException(t.toString());
}
catch (Exception x)
{
throw new IOException(x.toString());
}
}
private static void setContextClassLoader(final ClassLoader loader)
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
Thread.currentThread().setContextClassLoader(loader);
return null;
}
});
}
private static class MarshallerClassLoader extends SecureClassLoader
{
private byte[] bytes;
/**
* Parent classloader is null, thus we can load JDK classes, but for example not the JMX classes.
* This will force usage of the context classloader for unmarshalling, and the context classloader
* must be able to find the JMX classes. For example, when invoking setAttribute(), the marshalled
* parameter is a javax.management.Attribute that may contain an object of a custom class.
* To unmarshal the custom class (seen only by the context classloader), we must be able to unmarshal
* first the Attribute class that so it must either be loadable by the context classloader or by
* one of its ancestor classloaders.
*/
private MarshallerClassLoader(byte[] classBytes)
{
super(null);
this.bytes = classBytes;
}
/**
* This method is overridden to define the {@link Marshaller} class and to delegate to the parent
* further loading.
* Classes from java.* packages (like java.lang.Object and java.rmi.MarshalledObject) are
* referenced by {@link Marshaller} itself.
* We don't load classes from javax.management.* packages, since we assume the context classloader
* can load those classes by itself or by one of its ancestor classloaders.
*/
public Class loadClass(final String name) throws ClassNotFoundException
{
if (name.startsWith(Marshaller.class.getName()))
{
try
{
return defineClass(name, bytes, 0, bytes.length, MarshallerClassLoader.this.getClass().getProtectionDomain());
}
catch (ClassFormatError x)
{
throw new ClassNotFoundException("Class Format Error", x);
}
}
else
{
return super.loadClass(name);
}
}
}
/**
* This is an implementation of the extended classloader as defined by the
* JMX Remote Specification, chapter 2.
*/
private static class ExtendedClassLoader extends SecureClassLoader
{
private final ClassLoader defaultLoader;
private ExtendedClassLoader(ClassLoader mbeanLoader, ClassLoader defaultLoader)
{
super(mbeanLoader);
this.defaultLoader = defaultLoader;
}
protected Class findClass(String name) throws ClassNotFoundException
{
return defaultLoader.loadClass(name);
}
protected URL findResource(String name)
{
return defaultLoader.getResource(name);
}
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIRemoteNotificationClientHandler.java 100644 0 0 4477 10513545721 23701 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import javax.management.remote.NotificationResult;
import javax.management.remote.rmi.RMIConnection;
import mx4j.remote.AbstractRemoteNotificationClientHandler;
import mx4j.remote.ConnectionNotificationEmitter;
import mx4j.remote.HeartBeat;
/**
* RMI-specific RemoteNotificationClientHandler.
*
* @version $Revision: 1.4 $
*/
public class RMIRemoteNotificationClientHandler extends AbstractRemoteNotificationClientHandler
{
private final RMIConnection connection;
private final ClassLoader defaultLoader;
public RMIRemoteNotificationClientHandler(RMIConnection connection, ClassLoader defaultLoader, ConnectionNotificationEmitter emitter, HeartBeat heartbeat, Map environment)
{
super(emitter, heartbeat, environment);
this.connection = connection;
this.defaultLoader = defaultLoader;
}
protected NotificationResult fetchNotifications(long sequence, int maxNumber, long timeout) throws IOException
{
ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
if (defaultLoader == null || defaultLoader.equals(currentLoader))
{
return invokeFetchNotifications(sequence, maxNumber, timeout);
}
else
{
try
{
setContextClassLoader(defaultLoader);
return invokeFetchNotifications(sequence, maxNumber, timeout);
}
finally
{
setContextClassLoader(currentLoader);
}
}
}
private NotificationResult invokeFetchNotifications(long sequence, int maxNumber, long timeout) throws IOException
{
return connection.fetchNotifications(sequence, maxNumber, timeout);
}
private void setContextClassLoader(final ClassLoader loader)
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
Thread.currentThread().setContextClassLoader(loader);
return null;
}
});
}
}
mx4j-3.0.2/src/core/mx4j/remote/rmi/RMIRemoteNotificationServerHandler.java 100644 0 0 2676 10513545721 23730 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.remote.rmi;
import java.util.ArrayList;
import java.util.Map;
import javax.management.remote.TargetedNotification;
import mx4j.log.Logger;
import mx4j.remote.DefaultRemoteNotificationServerHandler;
import mx4j.remote.MX4JRemoteUtils;
/**
* @version $Revision: 1.5 $
*/
class RMIRemoteNotificationServerHandler extends DefaultRemoteNotificationServerHandler
{
RMIRemoteNotificationServerHandler(Map environment)
{
super(environment);
}
protected TargetedNotification[] filterNotifications(TargetedNotification[] notifications)
{
Logger logger = null;
ArrayList list = new ArrayList();
for (int i = 0; i < notifications.length; ++i)
{
TargetedNotification notification = notifications[i];
if (MX4JRemoteUtils.isTrulySerializable(notification))
{
list.add(notification);
}
else
{
if (logger == null) logger = getLogger();
if (logger.isEnabledFor(Logger.INFO)) logger.info("Cannot send notification " + notification + " to the client: it is not serializable");
}
}
return (TargetedNotification[])list.toArray(new TargetedNotification[list.size()]);
}
}
mx4j-3.0.2/src/core/mx4j/server/BCELMBeanInvoker.java 100644 0 0 64262 10513545721 17302 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mx4j.log.Log;
import mx4j.log.Logger;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.ARRAYLENGTH;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
/**
* MBeanInvoker that generates on-the-fly implementations to call standard MBeans directly, instead of using reflection.
*
* It uses the BCEL to generate the required bytecode on-the-fly.
* The generated class is named "mx4j.server.BCELMBeanInvokerGenerated", and it's loaded into the JVM by a different
* classloader for each MBean. This classloader has the MBean classloader as parent.
* Below is an example of the generated code; beware that the management interface and all parameter's classes must be
* public, otherwise an IllegalAccessError is thrown and the invocation falls back to use reflection (but with a significant
* overhead - throwing an exception is expensive).
*
* public interface ServiceMBean
* {
* public void start();
* public Collection getServices(ServiceSelector selector);
* }
*
* public class BCELMBeanInvokerGenerated extends BCELMBeanInvoker
* {
* protected Object invokeImpl(MBeanMetaData metadata, String method, String[] signature, Object[] args)
* throws Throwable
* {
* if (method.equals("start") && args.length == 0)
* {
* try
* {
* ((ServiceMBean)metadata.mbean).start();
* return null;
* }
* catch (ClassCastException x) {}
* catch (IllegalAccessError x) {}
* }
* else if (method.equals("getServices") && args.length == 1)
* {
* try
* {
* return ((ServiceMBean)metadata.mbean).getServices((ServiceSelector)args[0]);
* }
* catch (ClassCastException x) {}
* catch (IllegalAccessError x) {}
* }
* return super.invokeImpl(metadata, method, signature, args);
* }
* }
*
*
* @version $Revision: 1.14 $
*/
public class BCELMBeanInvoker extends CachingReflectionMBeanInvoker
{
private static final String LOGGER_CATEGORY = BCELMBeanInvoker.class.getName();
/*
public static void main(String[] args) throws Exception
{
MBeanMetaData metadata = new MBeanMetaData();
metadata.classloader = ClassLoader.getSystemClassLoader();
metadata.management = Object.class;
Object generated = create(metadata);
System.out.println("generated = " + generated);
}
private static void dump(ClassGen classGen)
{
try
{
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File("C:\\Simon\\OpenSource\\mx4j\\mx4j\\classes\\core\\mx4j\\server\\BCELMBeanInvokerGenerated.class"));
classGen.getJavaClass().dump(fos);
fos.close();
}
catch (java.io.IOException x)
{
x.printStackTrace();
}
}
*/
protected BCELMBeanInvoker()
{
}
/**
* Creates a new MBeanInvoker created on-the-fly by using BCEL.
* It must be synchronized since BCEL is not thread safe, and uses static variables
* (refer to org.apache.bcel.generic.Type.getArgumentTypes(...) for further details)
*/
public synchronized static MBeanInvoker create(final MBeanMetaData metadata)
{
String parentName = BCELMBeanInvoker.class.getName();
final String name = parentName + "Generated";
ClassGen classGen = new ClassGen(name, // Qualified class name
parentName, // Qualified superclass name
"", // File name
Constants.ACC_PUBLIC | Constants.ACC_FINAL | Constants.ACC_SUPER, // Modifiers
null); // Implemented interfaces
classGen.addEmptyConstructor(Constants.ACC_PUBLIC);
classGen.addMethod(createInvokeImpl(metadata, classGen, name));
// For debug purposes only
// dump(classGen);
final byte[] bytes = classGen.getJavaClass().getBytes();
try
{
// Must shield clients, since creating a new classloader requires a permission
return (BCELMBeanInvoker)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception
{
Class cls = new BCELClassLoader(metadata.getClassLoader(), bytes).loadClass(name);
return cls.newInstance();
}
});
}
catch (Throwable x)
{
Logger logger = Log.getLogger(LOGGER_CATEGORY);
if (logger.isEnabledFor(Logger.INFO)) logger.info("Cannot create on-the-fly MBeanInvoker class, going with reflection MBeanInvoker", x);
return new CachingReflectionMBeanInvoker();
}
}
private static org.apache.bcel.classfile.Method createInvokeImpl(MBeanMetaData metadata, ClassGen classGen, String clsName)
{
InstructionList implementation = new InstructionList();
ObjectType metadataType = new ObjectType(MBeanMetaData.class.getName());
Type[] signature = new Type[]{metadataType, Type.STRING, new ArrayType(Type.STRING, 1), new ArrayType(Type.OBJECT, 1)};
// Method definition
MethodGen mthd = new MethodGen(Constants.ACC_PROTECTED, // Modifiers
Type.OBJECT, // Return type
signature, // Signature
new String[]{"metadata", "method", "params", "args"}, // Parameter names
"invokeImpl", // Method name
clsName, // Class name
implementation, // Implementation
classGen.getConstantPool()); // Pool
mthd.addException("java.lang.Throwable");
// Now I should create the implementation
InstructionFactory factory = new InstructionFactory(classGen);
Method[] methods = metadata.getMBeanInterface().getMethods();
List tests = new ArrayList();
List catches = new ArrayList();
for (int i = 0; i < methods.length; ++i)
{
Method method = methods[i];
catches.addAll(generateDirectInvokeBranch(classGen, mthd, implementation, factory, metadata.getMBeanInterface().getName(), method, tests));
}
// To close the last branch, I must jump to super.invokeImpl(), so I need its first instruction here
InstructionHandle invokeSuper = implementation.append(factory.createThis());
for (int i = 0; i < tests.size(); ++i)
{
BranchInstruction branch = (BranchInstruction)tests.get(i);
branch.setTarget(invokeSuper);
}
tests.clear();
for (int i = 0; i < catches.size(); ++i)
{
BranchInstruction branch = (BranchInstruction)catches.get(i);
branch.setTarget(invokeSuper);
}
catches.clear();
//
// return super.invokeImpl(metadata, method, params, args);
//
// Again, it's invokeImpl(super, args) instead of super.invokeImpl(args)
// Use 'this' as first argument, and invokespecial instead of invokevirtual to call super
// 'this' is created above, to close the last branch
implementation.append(factory.createLoad(metadataType, 1));
implementation.append(factory.createLoad(Type.STRING, 2));
implementation.append(factory.createLoad(new ArrayType(Type.STRING, 1), 3));
implementation.append(factory.createLoad(new ArrayType(Type.OBJECT, 1), 4));
implementation.append(factory.createInvoke(BCELMBeanInvoker.class.getName(), "invokeImpl", Type.OBJECT, signature, Constants.INVOKESPECIAL));
implementation.append(factory.createReturn(Type.OBJECT));
mthd.setMaxStack();
org.apache.bcel.classfile.Method method = mthd.getMethod();
// Reuse instruction handles
implementation.dispose();
return method;
}
private static List generateDirectInvokeBranch(ClassGen classGen, MethodGen methodGen, InstructionList implementation, InstructionFactory factory, String management, Method method, List tests)
{
ArrayList catches = new ArrayList();
//
// if (method.equals("") && args.length == )
//
// The first instruction, will be where I should go if the previous branch fails
InstructionHandle startTest = implementation.append(factory.createLoad(Type.STRING, 2));
// The first time it will be empty, the second time will be the first time's uninitialized jump instructions
for (int i = 0; i < tests.size(); ++i)
{
BranchInstruction branch = (BranchInstruction)tests.get(i);
// Initialize previous jump instruction to jump to the next branch
branch.setTarget(startTest);
}
tests.clear();
implementation.append(new PUSH(classGen.getConstantPool(), method.getName()));
implementation.append(factory.createInvoke(String.class.getName(), "equals", Type.BOOLEAN, new Type[]{Type.OBJECT}, Constants.INVOKEVIRTUAL));
// IFEQ compares the stack with 0, which means "if the previous comparison is false, ..."
BranchInstruction test1 = factory.createBranchInstruction(Constants.IFEQ, null);
tests.add(test1);
implementation.append(test1);
implementation.append(factory.createLoad(new ArrayType(Type.OBJECT, 1), 4));
implementation.append(new ARRAYLENGTH());
implementation.append(new PUSH(classGen.getConstantPool(), method.getParameterTypes().length));
// Here I should test if args.length == , if not equal then go to the next branch
// Create branch instructions with no offset, since it cannot be handled now, see above
BranchInstruction test2 = factory.createBranchInstruction(Constants.IF_ICMPNE, null);
tests.add(test2);
implementation.append(test2);
// Here I am on the right method, unless someone created 2 methods with same names and same number of
// parameters but of different type. In this last case if we're lucky it's the right method and we go
// via direct call, otherwise we will have a class cast exception and go via reflection
// Cast and invoke
// Put the metadata on the stack, to access its 'mbean' field, that will be put on the stack
// It's also the start of the try block
InstructionHandle tryStart = implementation.append(factory.createLoad(new ObjectType(MBeanMetaData.class.getName()), 1));
implementation.append(factory.createInvoke(MBeanMetaData.class.getName(), "getMBean", Type.OBJECT, new Type[0], Constants.INVOKEVIRTUAL));
// Cast the 'mbean' field to the proper type, the stack will contain the casted mbean
implementation.append(factory.createCheckCast(new ObjectType(management)));
// Now add all the arguments to the stack
Class[] signature = method.getParameterTypes();
Type[] invokeSignature = new Type[signature.length];
for (int i = 0; i < signature.length; ++i)
{
Class param = signature[i];
// Load all args on the stack
implementation.append(factory.createLoad(new ArrayType(Type.OBJECT, 1), 4));
// I want index 'i'
implementation.append(new PUSH(classGen.getConstantPool(), i));
// Now on the stack there is args[i]
implementation.append(factory.createArrayLoad(Type.OBJECT));
// Save the signature for the invocation
invokeSignature[i] = convertClassToType(param);
if (param.isPrimitive())
{
// On the stack I have the wrapper object, I have to convert them to primitive
replaceObjectWithPrimitive(param, implementation, factory);
}
else if (param.isArray())
{
// Cast args[i] to the proper class
implementation.append(factory.createCheckCast((ReferenceType)invokeSignature[i]));
}
else
{
// Cast args[i] to the proper class
implementation.append(factory.createCheckCast((ReferenceType)invokeSignature[i]));
}
}
Class returnClass = method.getReturnType();
Type returnType = convertClassToType(returnClass);
// On the stack we now have the casted mbean and all the casted arguments, invoke
implementation.append(factory.createInvoke(management, method.getName(), returnType, invokeSignature, Constants.INVOKEINTERFACE));
if (returnClass == Void.TYPE)
{
implementation.append(InstructionConstants.ACONST_NULL);
}
else if (returnClass.isArray())
{
// Thanks to the fact that we can assign any array to Object, we do nothing here
}
else if (returnClass.isPrimitive())
{
replacePrimitiveWithObject(returnClass, methodGen, implementation, factory);
}
InstructionHandle tryEnd = implementation.append(factory.createReturn(Type.OBJECT));
// In case of class cast exception, eat the exception and call super (hence using reflection)
// catch (ClassCastException x) {/* do nothing */}
// On the stack there is the exception, we assign it to local variable 'x'
ObjectType exceptionTypeCCE = new ObjectType("java.lang.ClassCastException");
LocalVariableGen x = methodGen.addLocalVariable("x", exceptionTypeCCE, null, null);
InstructionHandle handler = implementation.append(factory.createStore(exceptionTypeCCE, x.getIndex()));
x.setStart(handler);
x.setEnd(handler);
methodGen.addExceptionHandler(tryStart, tryEnd, handler, exceptionTypeCCE);
// This catch block is followed by another one, and I don't exit with a throw or a return
BranchInstruction skip = factory.createBranchInstruction(Constants.GOTO, null);
catches.add(skip);
implementation.append(skip);
// An IllegalAccessError is thrown if the MBean interface or a parameter class is not public
// We eat it and fall back to call super (hence using reflection)
// catch (IllegalAccessError x) {/* do nothing */}
ObjectType errorTypeIAE = new ObjectType("java.lang.IllegalAccessError");
x = methodGen.addLocalVariable("x", errorTypeIAE, null, null);
handler = implementation.append(factory.createStore(errorTypeIAE, x.getIndex()));
x.setStart(handler);
x.setEnd(handler);
methodGen.addExceptionHandler(tryStart, tryEnd, handler, errorTypeIAE);
// This catch block is followed by another one, and I don't exit with a throw or a return,
skip = factory.createBranchInstruction(Constants.GOTO, null);
catches.add(skip);
implementation.append(skip);
return catches;
}
private static Type convertClassToType(Class cls)
{
if (cls == void.class) return Type.VOID;
if (cls == boolean.class) return Type.BOOLEAN;
if (cls == byte.class) return Type.BYTE;
if (cls == char.class) return Type.CHAR;
if (cls == short.class) return Type.SHORT;
if (cls == int.class) return Type.INT;
if (cls == long.class) return Type.LONG;
if (cls == float.class) return Type.FLOAT;
if (cls == double.class) return Type.DOUBLE;
if (cls == Object.class) return Type.OBJECT;
if (cls == String.class) return Type.STRING;
if (cls.isArray())
{
int dimensions = 0;
Class c = null;
while ((c = cls.getComponentType()) != null)
{
++dimensions;
cls = c;
}
Type t = convertClassToType(cls);
return new ArrayType(t, dimensions);
}
return new ObjectType(cls.getName());
}
private static void replaceObjectWithPrimitive(Class type, InstructionList implementation, InstructionFactory factory)
{
// Put as first the most common ones
if (type == int.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Integer.class.getName())));
implementation.append(factory.createInvoke(Integer.class.getName(), "intValue", Type.INT, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == boolean.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Boolean.class.getName())));
implementation.append(factory.createInvoke(Boolean.class.getName(), "booleanValue", Type.BOOLEAN, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == long.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Long.class.getName())));
implementation.append(factory.createInvoke(Long.class.getName(), "longValue", Type.LONG, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == byte.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Byte.class.getName())));
implementation.append(factory.createInvoke(Byte.class.getName(), "byteValue", Type.BYTE, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == char.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Character.class.getName())));
implementation.append(factory.createInvoke(Character.class.getName(), "charValue", Type.CHAR, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == short.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Short.class.getName())));
implementation.append(factory.createInvoke(Short.class.getName(), "shortValue", Type.SHORT, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else if (type == float.class)
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Float.class.getName())));
implementation.append(factory.createInvoke(Float.class.getName(), "floatValue", Type.FLOAT, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
else
{
// Cast the operand in the stack and get the value
implementation.append(factory.createCheckCast(new ObjectType(Double.class.getName())));
implementation.append(factory.createInvoke(Double.class.getName(), "doubleValue", Type.DOUBLE, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
}
}
private static void replacePrimitiveWithObject(Class type, MethodGen methodGen, InstructionList implementation, InstructionFactory factory)
{
// Put as first the most common ones
if (type == int.class)
{
// Create a new instance of the wrapper
LocalVariableGen i = methodGen.addLocalVariable("i", Type.INT, null, null);
i.setStart(implementation.append(factory.createStore(Type.INT, i.getIndex())));
implementation.append(factory.createNew(new ObjectType(Integer.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.INT, i.getIndex()));
i.setEnd(implementation.append(factory.createInvoke(Integer.class.getName(), "", Type.VOID, new Type[]{Type.INT}, Constants.INVOKESPECIAL)));
}
else if (type == boolean.class)
{
// Create a new instance of the wrapper
LocalVariableGen b = methodGen.addLocalVariable("b", Type.BOOLEAN, null, null);
b.setStart(implementation.append(factory.createStore(Type.BOOLEAN, b.getIndex())));
implementation.append(factory.createNew(new ObjectType(Boolean.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.BOOLEAN, b.getIndex()));
b.setEnd(implementation.append(factory.createInvoke(Boolean.class.getName(), "", Type.VOID, new Type[]{Type.BOOLEAN}, Constants.INVOKESPECIAL)));
}
else if (type == long.class)
{
// Create a new instance of the wrapper
LocalVariableGen l = methodGen.addLocalVariable("l", Type.LONG, null, null);
l.setStart(implementation.append(factory.createStore(Type.LONG, l.getIndex())));
implementation.append(factory.createNew(new ObjectType(Long.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.LONG, l.getIndex()));
l.setEnd(implementation.append(factory.createInvoke(Long.class.getName(), "", Type.VOID, new Type[]{Type.LONG}, Constants.INVOKESPECIAL)));
}
else if (type == byte.class)
{
// Create a new instance of the wrapper
LocalVariableGen b = methodGen.addLocalVariable("b", Type.BYTE, null, null);
b.setStart(implementation.append(factory.createStore(Type.BYTE, b.getIndex())));
implementation.append(factory.createNew(new ObjectType(Byte.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.BYTE, b.getIndex()));
b.setEnd(implementation.append(factory.createInvoke(Byte.class.getName(), "", Type.VOID, new Type[]{Type.BYTE}, Constants.INVOKESPECIAL)));
}
else if (type == char.class)
{
// Create a new instance of the wrapper
LocalVariableGen c = methodGen.addLocalVariable("c", Type.CHAR, null, null);
c.setStart(implementation.append(factory.createStore(Type.CHAR, c.getIndex())));
implementation.append(factory.createNew(new ObjectType(Character.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.CHAR, c.getIndex()));
c.setEnd(implementation.append(factory.createInvoke(Character.class.getName(), "", Type.VOID, new Type[]{Type.CHAR}, Constants.INVOKESPECIAL)));
}
else if (type == short.class)
{
// Create a new instance of the wrapper
LocalVariableGen s = methodGen.addLocalVariable("s", Type.SHORT, null, null);
s.setStart(implementation.append(factory.createStore(Type.SHORT, s.getIndex())));
implementation.append(factory.createNew(new ObjectType(Short.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.SHORT, s.getIndex()));
s.setEnd(implementation.append(factory.createInvoke(Short.class.getName(), "", Type.VOID, new Type[]{Type.SHORT}, Constants.INVOKESPECIAL)));
}
else if (type == float.class)
{
// Create a new instance of the wrapper
LocalVariableGen f = methodGen.addLocalVariable("f", Type.FLOAT, null, null);
f.setStart(implementation.append(factory.createStore(Type.FLOAT, f.getIndex())));
implementation.append(factory.createNew(new ObjectType(Float.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.FLOAT, f.getIndex()));
f.setEnd(implementation.append(factory.createInvoke(Float.class.getName(), "", Type.VOID, new Type[]{Type.FLOAT}, Constants.INVOKESPECIAL)));
}
else
{
// Create a new instance of the wrapper
LocalVariableGen d = methodGen.addLocalVariable("d", Type.DOUBLE, null, null);
d.setStart(implementation.append(factory.createStore(Type.DOUBLE, d.getIndex())));
implementation.append(factory.createNew(new ObjectType(Double.class.getName())));
implementation.append(InstructionConstants.DUP);
implementation.append(factory.createLoad(Type.DOUBLE, d.getIndex()));
d.setEnd(implementation.append(factory.createInvoke(Double.class.getName(), "", Type.VOID, new Type[]{Type.DOUBLE}, Constants.INVOKESPECIAL)));
}
}
private Logger getLogger()
{
return Log.getLogger(LOGGER_CATEGORY);
}
protected Object invokeImpl(MBeanMetaData metadata, String method, String[] signature, Object[] args) throws Throwable
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.INFO))
{
logger.info("BCEL invocation failed for method " + method + "" + Arrays.asList(signature) + ", using reflection");
}
return super.invokeImpl(metadata, method, signature, args);
}
private static class BCELClassLoader extends SecureClassLoader
{
private byte[] m_bytes;
private BCELClassLoader(ClassLoader parent, byte[] bytecode)
{
super(parent);
m_bytes = bytecode;
}
protected Class findClass(final String name) throws ClassNotFoundException
{
try
{
return (Class)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws ClassNotFoundException
{
try
{
return defineClass(name, m_bytes, 0, m_bytes.length, BCELClassLoader.this.getClass().getProtectionDomain());
}
catch (ClassFormatError x)
{
throw new ClassNotFoundException("Class Format Error", x);
}
}
}, null);
}
catch (PrivilegedActionException x)
{
throw (ClassNotFoundException)x.getException();
}
}
}
}
mx4j-3.0.2/src/core/mx4j/server/CachingReflectionMBeanInvoker.java 100644 0 0 7365 10513545721 22125 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanOperationInfo;
import javax.management.ReflectionException;
import mx4j.util.MethodTernaryTree;
/**
* Caching MBeanInvoker that uses reflection to invoke on MBean instances.
* Attributes and operations lookup is cached to speedup invocations.
*
* @version $Revision: 1.3 $
*/
public class CachingReflectionMBeanInvoker extends ReflectionMBeanInvoker
{
private final Map attributes = new HashMap();
private final Map attributeNames = new HashMap();
private final MethodTernaryTree operations = new MethodTernaryTree();
private final MethodTernaryTree methods = new MethodTernaryTree();
protected MBeanOperationInfo getStandardOperationInfo(MBeanMetaData metadata, String method, String[] signature)
{
MBeanOperationInfo oper = null;
synchronized (operations)
{
oper = (MBeanOperationInfo)operations.get(method, signature);
}
if (oper != null) return oper;
// The MBeanOperationInfo is not in the cache, look it up
MBeanOperationInfo info = super.getStandardOperationInfo(metadata, method, signature);
if (info != null)
{
synchronized (operations)
{
operations.put(method, signature, oper);
}
}
return info;
}
protected MBeanAttributeInfo getStandardAttributeInfo(MBeanMetaData metadata, String attribute, boolean forWrite)
{
MBeanAttributeInfo attr = null;
synchronized (attributes)
{
attr = (MBeanAttributeInfo)attributes.get(attribute);
}
if (attr == null)
{
attr = super.getStandardAttributeInfo(metadata, attribute, forWrite);
if (attr == null) return null;
synchronized (attributes)
{
attributes.put(attribute, attr);
}
}
if (forWrite && attr.isWritable()) return attr;
if (!forWrite && attr.isReadable()) return attr;
return null;
}
protected String getMethodForAttribute(MBeanAttributeInfo attribute, boolean getter)
{
AttributeName attributeName = null;
String name = attribute.getName();
synchronized (attributeNames)
{
attributeName = (AttributeName)attributeNames.get(name);
}
if (attributeName == null)
{
attributeName = new AttributeName(super.getMethodForAttribute(attribute, true), super.getMethodForAttribute(attribute, false));
synchronized (attributeNames)
{
attributeNames.put(name, attributeName);
}
}
if (getter) return attributeName.getter;
return attributeName.setter;
}
protected Method getStandardManagementMethod(MBeanMetaData metadata, String name, String[] signature) throws ReflectionException
{
Method method = null;
synchronized (methods)
{
method = (Method)methods.get(name, signature);
}
if (method != null) return method;
// Method is not in cache, look it up
method = super.getStandardManagementMethod(metadata, name, signature);
synchronized (methods)
{
methods.put(name, signature, method);
}
return method;
}
private static class AttributeName
{
private final String getter;
private final String setter;
public AttributeName(String getter, String setter)
{
this.getter = getter;
this.setter = setter;
}
}
}
mx4j-3.0.2/src/core/mx4j/server/ChainedMBeanServer.java 100644 0 0 24123 10513545721 17751 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.io.ObjectInputStream;
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;
/**
* Base class for chained MBeanServers.
* By default this class delegates all method calls to the nested MBeanServer.
* Subclass it to add behavior to one or more (or all) methods.
*
* @version $Revision: 1.6 $
*/
public class ChainedMBeanServer implements MBeanServer
{
private MBeanServer m_server;
/**
* Creates a new ChainedMBeanServer that will delegate to an MBeanServer specified
* using {@link #setMBeanServer}
*/
public ChainedMBeanServer()
{
this(null);
}
/**
* Creates a new ChainedMBeanServer that delegates to the specified MBeanServer
.
*/
public ChainedMBeanServer(MBeanServer server)
{
setMBeanServer(server);
}
/**
* Returns the nested MBeanServer
*/
protected synchronized MBeanServer getMBeanServer()
{
return m_server;
}
protected synchronized void setMBeanServer(MBeanServer server)
{
m_server = server;
}
public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
getMBeanServer().addNotificationListener(observed, listener, filter, handback);
}
public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
getMBeanServer().addNotificationListener(observed, listener, filter, handback);
}
public ObjectInstance createMBean(String className, ObjectName objectName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
return getMBeanServer().createMBean(className, objectName);
}
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
return getMBeanServer().createMBean(className, objectName, args, parameters);
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
return getMBeanServer().createMBean(className, objectName, loaderName);
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
return getMBeanServer().createMBean(className, objectName, loaderName, args, parameters);
}
public ObjectInputStream deserialize(String className, byte[] bytes)
throws OperationsException, ReflectionException
{
return getMBeanServer().deserialize(className, bytes);
}
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] bytes)
throws InstanceNotFoundException, OperationsException, ReflectionException
{
return getMBeanServer().deserialize(className, loaderName, bytes);
}
public ObjectInputStream deserialize(ObjectName objectName, byte[] bytes)
throws InstanceNotFoundException, OperationsException
{
return getMBeanServer().deserialize(objectName, bytes);
}
public Object getAttribute(ObjectName objectName, String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException
{
return getMBeanServer().getAttribute(objectName, attribute);
}
public AttributeList getAttributes(ObjectName objectName, String[] attributes)
throws InstanceNotFoundException, ReflectionException
{
return getMBeanServer().getAttributes(objectName, attributes);
}
public String getDefaultDomain()
{
return getMBeanServer().getDefaultDomain();
}
public String[] getDomains()
{
return getMBeanServer().getDomains();
}
public Integer getMBeanCount()
{
return getMBeanServer().getMBeanCount();
}
public MBeanInfo getMBeanInfo(ObjectName objectName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException
{
return getMBeanServer().getMBeanInfo(objectName);
}
public ObjectInstance getObjectInstance(ObjectName objectName)
throws InstanceNotFoundException
{
return getMBeanServer().getObjectInstance(objectName);
}
public Object instantiate(String className)
throws ReflectionException, MBeanException
{
return getMBeanServer().instantiate(className);
}
public Object instantiate(String className, Object[] args, String[] parameters)
throws ReflectionException, MBeanException
{
return getMBeanServer().instantiate(className, args, parameters);
}
public Object instantiate(String className, ObjectName loaderName)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return getMBeanServer().instantiate(className, loaderName);
}
public Object instantiate(String className, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return getMBeanServer().instantiate(className, loaderName, args, parameters);
}
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException
{
return getMBeanServer().invoke(objectName, methodName, args, parameters);
}
public boolean isInstanceOf(ObjectName objectName, String className)
throws InstanceNotFoundException
{
return getMBeanServer().isInstanceOf(objectName, className);
}
public boolean isRegistered(ObjectName objectname)
{
return getMBeanServer().isRegistered(objectname);
}
public Set queryMBeans(ObjectName patternName, QueryExp filter)
{
return getMBeanServer().queryMBeans(patternName, filter);
}
public Set queryNames(ObjectName patternName, QueryExp filter)
{
return getMBeanServer().queryNames(patternName, filter);
}
public ObjectInstance registerMBean(Object mbean, ObjectName objectName)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
return getMBeanServer().registerMBean(mbean, objectName);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
getMBeanServer().removeNotificationListener(observed, listener);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
getMBeanServer().removeNotificationListener(observed, listener);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
getMBeanServer().removeNotificationListener(observed, listener, filter, handback);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
getMBeanServer().removeNotificationListener(observed, listener, filter, handback);
}
public void setAttribute(ObjectName objectName, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
getMBeanServer().setAttribute(objectName, attribute);
}
public AttributeList setAttributes(ObjectName objectName, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException
{
return getMBeanServer().setAttributes(objectName, attributes);
}
public void unregisterMBean(ObjectName objectName)
throws InstanceNotFoundException, MBeanRegistrationException
{
getMBeanServer().unregisterMBean(objectName);
}
public ClassLoader getClassLoaderFor(ObjectName mbeanName)
throws InstanceNotFoundException
{
return getMBeanServer().getClassLoaderFor(mbeanName);
}
public ClassLoader getClassLoader(ObjectName loaderName)
throws InstanceNotFoundException
{
return getMBeanServer().getClassLoader(loaderName);
}
public ClassLoaderRepository getClassLoaderRepository()
{
return getMBeanServer().getClassLoaderRepository();
}
}
mx4j-3.0.2/src/core/mx4j/server/ChainedMBeanServerBuilder.java 100644 0 0 5640 10513545721 21243 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.MBeanServer;
import javax.management.MBeanServerBuilder;
import javax.management.MBeanServerDelegate;
/**
* Base class for chained MBeanServerBuilders.
* By default this class delegates all method calls to the nested MBeanServerBuilder.
* See the MX4J documentation on how to use correctly this class.
*
* Example implementation:
*
* public class LoggingBuilder extends ChainedMBeanServerBuilder
* {
* public LoggingBuilder()
* {
* super(new MX4JMBeanServerBuilder());
* }
*
* public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate)
* {
* LoggingMBeanServer external = new LoggingMBeanServer();
* MBeanServer nested = getBuilder().newMBeanServer(defaultDomain, outer == null ? external : outer, delegate);
* external.setMBeanServer(nested);
* return external;
* }
* }
*
* public class LoggingMBeanServer extends ChainedMBeanServer
* {
* protected void setMBeanServer(MBeanServer server)
* {
* super.setMBeanServer(server);
* }
*
* public Object getAttribute(ObjectName objectName, String attribute)
* throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException
* {
* Object value = super.getAttribute(objectName, attribute);
* System.out.println("Value is: " + value);
* return value;
* }
*
* ...
* }
*
*
* @version $Revision: 1.3 $
*/
public class ChainedMBeanServerBuilder extends MBeanServerBuilder
{
private final MBeanServerBuilder builder;
/**
* Creates a new chained MBeanServerBuilder
*
* @param builder The MBeanServerBuilder this object delegates to.
*/
public ChainedMBeanServerBuilder(MBeanServerBuilder builder)
{
if (builder == null) throw new IllegalArgumentException();
this.builder = builder;
}
/**
* Forwards the call to the chained builder.
*
* @see MBeanServerBuilder#newMBeanServerDelegate
*/
public MBeanServerDelegate newMBeanServerDelegate()
{
return getMBeanServerBuilder().newMBeanServerDelegate();
}
/**
* Forwards the call to the chained builder.
*
* @see MBeanServerBuilder#newMBeanServer
*/
public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate)
{
return getMBeanServerBuilder().newMBeanServer(defaultDomain, outer, delegate);
}
/**
* Returns the chained MBeanServerBuilder this object delegates to.
*/
protected MBeanServerBuilder getMBeanServerBuilder()
{
return builder;
}
}
mx4j-3.0.2/src/core/mx4j/server/DefaultClassLoaderRepository.java 100644 0 0 6013 10513545721 22103 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.util.ArrayList;
import javax.management.loading.MLet;
/**
* Default implementation of a ClassLoaderRepository
*
* @version $Revision: 1.8 $
*/
public class DefaultClassLoaderRepository extends ModifiableClassLoaderRepository
{
private static final int WITHOUT = 1;
private static final int BEFORE = 2;
private ArrayList classLoaders = new ArrayList();
public Class loadClass(String className) throws ClassNotFoundException
{
return loadClassWithout(null, className);
}
public Class loadClassWithout(ClassLoader loader, String className) throws ClassNotFoundException
{
return loadClassFromRepository(loader, className, WITHOUT);
}
public Class loadClassBefore(ClassLoader loader, String className) throws ClassNotFoundException
{
return loadClassFromRepository(loader, className, BEFORE);
}
protected void addClassLoader(ClassLoader cl)
{
if (cl == null) return;
ArrayList loaders = getClassLoaders();
synchronized (loaders)
{
if (!loaders.contains(cl)) loaders.add(cl);
}
}
protected void removeClassLoader(ClassLoader cl)
{
if (cl == null) return;
ArrayList loaders = getClassLoaders();
synchronized (loaders)
{
loaders.remove(cl);
}
}
protected ArrayList cloneClassLoaders()
{
ArrayList loaders = getClassLoaders();
synchronized (loaders)
{
return (ArrayList)loaders.clone();
}
}
protected ArrayList getClassLoaders()
{
return classLoaders;
}
private Class loadClassFromRepository(ClassLoader loader, String className, int algorithm) throws ClassNotFoundException
{
ArrayList copy = cloneClassLoaders();
for (int i = 0; i < copy.size(); ++i)
{
try
{
ClassLoader cl = (ClassLoader)copy.get(i);
if (cl.equals(loader))
{
if (algorithm == BEFORE)
break;
else
continue;
}
return loadClass(cl, className);
}
catch (ClassNotFoundException ignored)
{
}
}
throw new ClassNotFoundException(className);
}
private Class loadClass(ClassLoader loader, String className) throws ClassNotFoundException
{
// This is an optimization: if the classloader is an MLet (and not a subclass)
// then the method MLet.loadClass(String, ClassLoaderRepository) is used.
if (loader.getClass() == MLet.class) return ((MLet)loader).loadClass(className, null);
return loader.loadClass(className);
}
private int getSize()
{
ArrayList loaders = getClassLoaders();
synchronized (loaders)
{
return loaders.size();
}
}
}
mx4j-3.0.2/src/core/mx4j/server/DefaultMBeanRepository.java 100644 0 0 2413 10513545721 20671 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.util.HashMap;
import java.util.Iterator;
import javax.management.ObjectName;
/**
* Default implementation of the MBeanRepository interface.
*
* @version $Revision: 1.5 $
*/
class DefaultMBeanRepository implements MBeanRepository
{
private HashMap m_map = new HashMap();
public MBeanMetaData get(ObjectName name)
{
return (MBeanMetaData)m_map.get(name);
}
public void put(ObjectName name, MBeanMetaData metadata)
{
m_map.put(name, metadata);
}
public void remove(ObjectName name)
{
m_map.remove(name);
}
public int size()
{
return m_map.size();
}
public Iterator iterator()
{
return m_map.values().iterator();
}
public Object clone()
{
try
{
DefaultMBeanRepository repository = (DefaultMBeanRepository)super.clone();
repository.m_map = (HashMap)m_map.clone();
return repository;
}
catch (CloneNotSupportedException ignored)
{
return null;
}
}
}
mx4j-3.0.2/src/core/mx4j/server/MBeanIntrospector.java 100644 0 0 57122 10513545721 17727 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.WeakHashMap;
import javax.management.DynamicMBean;
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.NotificationBroadcaster;
import javax.management.loading.MLet;
import mx4j.MBeanDescription;
import mx4j.MBeanDescriptionAdapter;
import mx4j.MX4JSystemKeys;
import mx4j.log.Log;
import mx4j.log.Logger;
import mx4j.util.Utils;
/**
* Introspector for MBeans.
* Main purposes of this class are:
*
* - Given an mbean, gather all information regarding it into a {@link MBeanMetaData} instance, see {@link #introspect}
*
- Given an introspected MBeanMetaData, decide if the MBean is compliant or not.
*
- Act as a factory for {@link MBeanInvoker}s
*
*
* The following system properties are used to control this class' behavior:
*
* - mx4j.strict.mbean.interface, if set to 'no' then are treated as standard MBeans also classes that implement
* management interfaces beloging to different packages or that are inner classes; otherwise are treated as MBeans
* only classes that implement interfaces whose name if the fully qualified name of the MBean class + "MBean"
*
- mx4j.mbean.invoker, if set to the qualified name of an implementation of the {@link MBeanInvoker} interface,
* then an instance of the class will be used to invoke methods on standard MBeans. By default the generated-on-the-fly
* MBeanInvoker is used; to revert to the version that uses reflection, for example,
* use mx4j.mbean.invoker = {@link CachingReflectionMBeanInvoker mx4j.server.CachingReflectionMBeanInvoker}
*
*
* @version $Revision: 1.34 $
*/
public class MBeanIntrospector
{
private static final MBeanDescriptionAdapter DEFAULT_DESCRIPTION = new MBeanDescriptionAdapter();
private static final MBeanConstructorInfo[] EMPTY_CONSTRUCTORS = new MBeanConstructorInfo[0];
private static final MBeanParameterInfo[] EMPTY_PARAMETERS = new MBeanParameterInfo[0];
private static final MBeanAttributeInfo[] EMPTY_ATTRIBUTES = new MBeanAttributeInfo[0];
private static final MBeanNotificationInfo[] EMPTY_NOTIFICATIONS = new MBeanNotificationInfo[0];
private static final MBeanOperationInfo[] EMPTY_OPERATIONS = new MBeanOperationInfo[0];
private boolean extendedMBeanInterfaces = false;
private boolean bcelAvailable = false;
private String mbeanInvokerClass = null;
private final WeakHashMap mbeanInfoCache = new WeakHashMap();
private final WeakHashMap mbeanInvokerCache = new WeakHashMap();
public MBeanIntrospector()
{
String strict = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_STRICT_MBEAN_INTERFACE);
}
});
if (strict != null && !Boolean.valueOf(strict).booleanValue())
{
extendedMBeanInterfaces = true;
}
// Try to see if BCEL classes are present
try
{
ClassLoader loader = getClass().getClassLoader();
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
loader.loadClass("org.apache.bcelAvailable.generic.Type");
bcelAvailable = true;
}
catch (Throwable ignored)
{
}
// See if someone specified which MBean invoker to use
mbeanInvokerClass = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEAN_INVOKER);
}
});
}
/**
* Introspect the given mbean, storing the results in the given metadata.
* It expects that the mbean field and the classloader field are not null
*
* @see #isMBeanCompliant
*/
public void introspect(MBeanMetaData metadata)
{
introspectType(metadata);
introspectMBeanInfo(metadata);
}
/**
* Returns whether the given already introspected metadata is compliant.
* Must be called after {@link #introspect}
*/
public boolean isMBeanCompliant(MBeanMetaData metadata)
{
return isMBeanClassCompliant(metadata) && isMBeanTypeCompliant(metadata) && isMBeanInfoCompliant(metadata);
}
/**
* Used by the test cases, invoked via reflection, keep it private.
* Introspect the mbean and returns if it's compliant
*/
private boolean testCompliance(MBeanMetaData metadata)
{
introspect(metadata);
return isMBeanCompliant(metadata);
}
private boolean isMBeanClassCompliant(MBeanMetaData metadata)
{
// No requirements on the implementation (can be abstract, non public and no accessible constructors)
// but the management interface must be public
Logger logger = getLogger();
if (metadata.getMBeanInterface() != null)
{
boolean isPublic = Modifier.isPublic(metadata.getMBeanInterface().getModifiers());
if (!isPublic && logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean interface is not public");
return isPublic;
}
return true;
}
private boolean isMBeanTypeCompliant(MBeanMetaData metadata)
{
Logger logger = getLogger();
if (metadata.isMBeanStandard() && metadata.isMBeanDynamic())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean is both standard and dynamic");
return false;
}
if (!metadata.isMBeanStandard() && !metadata.isMBeanDynamic())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean is not standard nor dynamic");
return false;
}
return true;
}
private boolean isMBeanInfoCompliant(MBeanMetaData metadata)
{
Logger logger = getLogger();
MBeanInfo info = metadata.getMBeanInfo();
if (info == null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBeanInfo is null");
return false;
}
if (info.getClassName() == null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBeanInfo.getClassName() is null");
return false;
}
return true;
}
private void introspectType(MBeanMetaData metadata)
{
// Some information is already provided (StandardMBean)
if (metadata.isMBeanStandard())
{
introspectStandardMBean(metadata);
return;
}
if (metadata.getMBean() instanceof DynamicMBean)
{
metadata.setMBeanDynamic(true);
return;
}
else
{
metadata.setMBeanDynamic(false);
// Continue and see if it's a plain standard MBean
}
// We have a plain standard MBean, introspect it
introspectStandardMBean(metadata);
}
private void introspectStandardMBean(MBeanMetaData metadata)
{
Class management = metadata.getMBeanInterface();
if (management != null)
{
// Be sure the MBean implements the management interface
if (management.isInstance(metadata.getMBean()))
{
metadata.setMBeanInvoker(createInvoker(metadata));
return;
}
else
{
// Not compliant, reset the values
metadata.setMBeanStandard(false);
metadata.setMBeanInterface(null);
metadata.setMBeanInvoker(null);
return;
}
}
else
{
Class cls = metadata.getMBean().getClass();
for (Class c = cls; c != null; c = c.getSuperclass())
{
Class[] intfs = c.getInterfaces();
for (int i = 0; i < intfs.length; ++i)
{
Class intf = intfs[i];
if (implementsMBean(c.getName(), intf.getName()))
{
// OK, found the MBean interface for this class
metadata.setMBeanStandard(true);
metadata.setMBeanInterface(intf);
metadata.setMBeanInvoker(createInvoker(metadata));
return;
}
}
}
// Management interface not found, it's not compliant, reset the values
metadata.setMBeanStandard(false);
metadata.setMBeanInterface(null);
metadata.setMBeanInvoker(null);
}
}
private void introspectMBeanInfo(MBeanMetaData metadata)
{
if (metadata.isMBeanDynamic())
{
metadata.setMBeanInfo(getDynamicMBeanInfo(metadata));
}
else if (metadata.isMBeanStandard())
{
metadata.setMBeanInfo(createStandardMBeanInfo(metadata));
}
else
{
// Not a valid MBean, reset the MBeanInfo: this will cause an exception later
metadata.setMBeanInfo(null);
}
}
private MBeanInfo getDynamicMBeanInfo(MBeanMetaData metadata)
{
Logger logger = getLogger();
MBeanInfo info = null;
try
{
info = ((DynamicMBean)metadata.getMBean()).getMBeanInfo();
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("getMBeanInfo threw: " + x.toString());
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Dynamic MBeanInfo is: " + info);
if (info == null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBeanInfo cannot be null");
return null;
}
return info;
}
private MBeanInfo createStandardMBeanInfo(MBeanMetaData metadata)
{
synchronized (mbeanInfoCache)
{
MBeanInfo info = (MBeanInfo)mbeanInfoCache.get(metadata.getMBean().getClass());
if (info != null) return info;
}
// This is a non-standard extension: description for standard MBeans
MBeanDescription description = createMBeanDescription(metadata);
MBeanConstructorInfo[] ctors = createMBeanConstructorInfo(metadata, description);
if (ctors == null) return null;
MBeanAttributeInfo[] attrs = createMBeanAttributeInfo(metadata, description);
if (attrs == null) return null;
MBeanOperationInfo[] opers = createMBeanOperationInfo(metadata, description);
if (opers == null) return null;
MBeanNotificationInfo[] notifs = createMBeanNotificationInfo(metadata);
if (notifs == null) return null;
MBeanInfo info = new MBeanInfo(metadata.getMBean().getClass().getName(), description.getMBeanDescription(), attrs, ctors, opers, notifs);
synchronized (mbeanInfoCache)
{
// Overwrite if already present, we've been unlucky
mbeanInfoCache.put(metadata.getMBean().getClass(), info);
}
return info;
}
private MBeanDescription createMBeanDescription(MBeanMetaData metadata)
{
// TODO: PERFORMANCE: looking up the MBeanDescription is a real performance hotspot for MBean registration
// TODO: PERFORMANCE: simply remarking the lookup yields to a 3.5x speedup (from 14 s to 4 s for 20k MBeans)
// TODO: PERFORMANCE: consider using a system property to disable lookup, and/or caching the lookup.
// This is a non-standard extension
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Looking for standard MBean description...");
// Use full qualified name only
String descrClassName = metadata.getMBeanInterface().getName() + "Description";
// Try to load the class
try
{
Class descrClass = null;
ClassLoader loader = metadata.getClassLoader();
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
// Optimize lookup of the description class in case of MLets: we lookup the description class
// only in the classloader of the mbean, not in the whole CLR (since MLets delegates to the CLR)
if (loader.getClass() == MLet.class)
descrClass = ((MLet)loader).loadClass(descrClassName, null);
else
descrClass = loader.loadClass(descrClassName);
Object descrInstance = descrClass.newInstance();
if (descrInstance instanceof MBeanDescription)
{
MBeanDescription description = (MBeanDescription)descrInstance;
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Found provided standard MBean description: " + description);
return description;
}
}
catch (ClassNotFoundException ignored)
{
}
catch (InstantiationException ignored)
{
}
catch (IllegalAccessException ignored)
{
}
MBeanDescription description = DEFAULT_DESCRIPTION;
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Cannot find standard MBean description, using default: " + description);
return description;
}
private MBeanOperationInfo[] createMBeanOperationInfo(MBeanMetaData metadata, MBeanDescription description)
{
ArrayList operations = new ArrayList();
Method[] methods = metadata.getMBeanInterface().getMethods();
for (int j = 0; j < methods.length; ++j)
{
Method method = methods[j];
if (!Utils.isAttributeGetter(method) && !Utils.isAttributeSetter(method))
{
String descr = description == null ? null : description.getOperationDescription(method);
Class[] params = method.getParameterTypes();
int paramsNumber = params.length;
MBeanParameterInfo[] paramsInfo = paramsNumber == 0 ? EMPTY_PARAMETERS : new MBeanParameterInfo[paramsNumber];
for (int k = 0; k < paramsNumber; ++k)
{
Class param = params[k];
String paramName = description == null ? null : description.getOperationParameterName(method, k);
String paramDescr = description == null ? null : description.getOperationParameterDescription(method, k);
paramsInfo[k] = new MBeanParameterInfo(paramName, param.getName(), paramDescr);
}
MBeanOperationInfo info = new MBeanOperationInfo(method.getName(), descr, paramsInfo, method.getReturnType().getName(), MBeanOperationInfo.UNKNOWN);
operations.add(info);
}
}
int opersNumber = operations.size();
return opersNumber == 0 ? EMPTY_OPERATIONS : (MBeanOperationInfo[])operations.toArray(new MBeanOperationInfo[opersNumber]);
}
private MBeanAttributeInfo[] createMBeanAttributeInfo(MBeanMetaData metadata, MBeanDescription description)
{
Logger logger = getLogger();
HashMap attributes = new HashMap();
HashMap getterNames = new HashMap();
Method[] methods = metadata.getMBeanInterface().getMethods();
for (int j = 0; j < methods.length; ++j)
{
Method method = methods[j];
if (Utils.isAttributeGetter(method))
{
String name = method.getName();
boolean isIs = name.startsWith("is");
String attribute = null;
if (isIs)
attribute = name.substring(2);
else
attribute = name.substring(3);
String descr = description == null ? null : description.getAttributeDescription(attribute);
MBeanAttributeInfo info = (MBeanAttributeInfo)attributes.get(attribute);
if (info != null)
{
// JMX spec does not allow overloading attributes.
// If an attribute with the same name already exists the MBean is not compliant
if (!info.getType().equals(method.getReturnType().getName()))
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
return null;
}
else
{
// They return the same value,
if (getterNames.get(name) != null)
{
// This is the case of an attribute being present in multiple interfaces
// Ignore all but the first, since they resolve to the same method anyways
continue;
}
// there is a chance that one is a get-getter and one is a is-getter
// for a boolean attribute. In this case, the MBean is not compliant.
if (info.isReadable())
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
return null;
}
// MBeanAttributeInfo is already present due to a setter method, just update its readability
info = new MBeanAttributeInfo(attribute, info.getType(), info.getDescription(), true, info.isWritable(), isIs);
}
}
else
{
info = new MBeanAttributeInfo(attribute, method.getReturnType().getName(), descr, true, false, isIs);
}
// Replace if exists
attributes.put(attribute, info);
getterNames.put(name, method);
}
else if (Utils.isAttributeSetter(method))
{
String name = method.getName();
String attribute = name.substring(3);
String descr = description == null ? null : description.getAttributeDescription(attribute);
MBeanAttributeInfo info = (MBeanAttributeInfo)attributes.get(attribute);
if (info != null)
{
// JMX spec does not allow overloading attributes.
// If an attribute with the same name already exists the MBean is not compliant
if (!info.getType().equals(method.getParameterTypes()[0].getName()))
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
return null;
}
else
{
// MBeanAttributeInfo is already present due to a getter method, just update its writability
info = new MBeanAttributeInfo(info.getName(), info.getType(), info.getDescription(), info.isReadable(), true, info.isIs());
}
}
else
{
info = new MBeanAttributeInfo(attribute, method.getParameterTypes()[0].getName(), descr, false, true, false);
}
// Replace if exists
attributes.put(attribute, info);
}
}
int size = attributes.size();
return size == 0 ? EMPTY_ATTRIBUTES : (MBeanAttributeInfo[])attributes.values().toArray(new MBeanAttributeInfo[size]);
}
private MBeanNotificationInfo[] createMBeanNotificationInfo(MBeanMetaData metadata)
{
MBeanNotificationInfo[] notifs = null;
Object mbean = metadata.getMBean();
if (mbean instanceof NotificationBroadcaster)
{
notifs = ((NotificationBroadcaster)mbean).getNotificationInfo();
}
if (notifs == null || notifs.length == 0) notifs = EMPTY_NOTIFICATIONS;
return notifs;
}
private MBeanConstructorInfo[] createMBeanConstructorInfo(MBeanMetaData metadata, MBeanDescription descrs)
{
Class mbeanClass = metadata.getMBean().getClass();
Constructor[] ctors = mbeanClass.getConstructors();
int ctorsNumber = ctors.length;
MBeanConstructorInfo[] constructors = ctorsNumber == 0 ? EMPTY_CONSTRUCTORS : new MBeanConstructorInfo[ctorsNumber];
for (int i = 0; i < ctorsNumber; ++i)
{
Constructor constructor = ctors[i];
String descr = descrs == null ? null : descrs.getConstructorDescription(constructor);
Class[] params = constructor.getParameterTypes();
int paramsNumber = params.length;
MBeanParameterInfo[] paramsInfo = paramsNumber == 0 ? EMPTY_PARAMETERS : new MBeanParameterInfo[paramsNumber];
for (int j = 0; j < paramsNumber; ++j)
{
Class param = params[j];
String paramName = descrs == null ? null : descrs.getConstructorParameterName(constructor, j);
String paramDescr = descrs == null ? null : descrs.getConstructorParameterDescription(constructor, j);
paramsInfo[j] = new MBeanParameterInfo(paramName, param.getName(), paramDescr);
}
String ctorName = constructor.getName();
MBeanConstructorInfo info = new MBeanConstructorInfo(ctorName, descr, paramsInfo);
constructors[i] = info;
}
return constructors;
}
private boolean implementsMBean(String clsName, String intfName)
{
if (intfName.equals(clsName + "MBean")) return true;
if (extendedMBeanInterfaces)
{
// Check also that the may be in different packages and/or inner classes
// Trim packages
int clsDot = clsName.lastIndexOf('.');
if (clsDot > 0) clsName = clsName.substring(clsDot + 1);
int intfDot = intfName.lastIndexOf('.');
if (intfDot > 0) intfName = intfName.substring(intfDot + 1);
// Try again
if (intfName.equals(clsName + "MBean")) return true;
// Trim inner classes
int clsDollar = clsName.lastIndexOf('$');
if (clsDollar > 0) clsName = clsName.substring(clsDollar + 1);
int intfDollar = intfName.lastIndexOf('$');
if (intfDollar > 0) intfName = intfName.substring(intfDollar + 1);
// Try again
if (intfName.equals(clsName + "MBean")) return true;
}
// Give up
return false;
}
private MBeanInvoker createInvoker(MBeanMetaData metadata)
{
MBeanInvoker invoker = null;
synchronized (mbeanInvokerCache)
{
invoker = (MBeanInvoker)mbeanInvokerCache.get(metadata.getMBeanInterface());
if (invoker != null) return invoker;
}
Logger logger = getLogger();
if (mbeanInvokerClass != null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Custom MBeanInvoker class is: " + mbeanInvokerClass);
try
{
invoker = (MBeanInvoker)Thread.currentThread().getContextClassLoader().loadClass(mbeanInvokerClass).newInstance();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Using custom MBeanInvoker: " + invoker);
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Cannot instantiate custom MBeanInvoker, using default", x);
}
}
if (invoker == null)
{
if (bcelAvailable)
{
invoker = BCELMBeanInvoker.create(metadata);
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Using default BCEL MBeanInvoker for MBean " + metadata.getObjectName() + ", " + invoker);
}
else
{
invoker = new CachingReflectionMBeanInvoker();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Using default Reflection MBeanInvoker for MBean " + metadata.getObjectName() + ", " + invoker);
}
}
synchronized (mbeanInvokerCache)
{
// Overwrite if already present: we've been unlucky
mbeanInvokerCache.put(metadata.getMBeanInterface(), invoker);
}
return invoker;
}
private Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
}
mx4j-3.0.2/src/core/mx4j/server/MBeanInvoker.java 100644 0 0 3310 10513545721 16617 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
/**
* Invokes methods on standard MBeans.
* Actually three implementations are available: two that uses reflection and one that generates on-the-fly a customized
* MBeanInvoker per each MBean and that is implemented with direct calls via bytecode generation.
* The default is the direct call version, that uses the BCEL to generate
* the required bytecode on-the-fly.
* In the future may be the starting point for MBean interceptors.
*
* @version $Revision: 1.6 $
*/
public interface MBeanInvoker
{
/**
* Invokes the specified operation on the MBean instance
*/
public Object invoke(MBeanMetaData metadata, String method, String[] signature, Object[] args) throws MBeanException, ReflectionException;
/**
* Returns the value of the specified attribute.
*/
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException;
/**
* Sets the value of the specified attribute.
*/
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException;
}
mx4j-3.0.2/src/core/mx4j/server/MBeanMetaData.java 100644 0 0 10371 10513545721 16707 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.management.MBeanInfo;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import mx4j.MX4JSystemKeys;
/**
* Objects of this class hold metadata information about MBeans.
*
* @version $Revision: 1.8 $
* @see Factory
*/
public interface MBeanMetaData
{
/**
* Sets the MBean instance
*
* @see #getMBean
*/
public void setMBean(Object mbean);
/**
* Returns the MBean instance
*
* @see #setMBean
*/
public Object getMBean();
/**
* Sets the classloader for the MBean
*
* @see #getClassLoader
*/
public void setClassLoader(ClassLoader loader);
/**
* Returns the classloader for the MBean
*
* @see #setClassLoader
*/
public ClassLoader getClassLoader();
/**
* Sets the ObjectName of the MBean
*
* @see #getObjectName
*/
public void setObjectName(ObjectName name);
/**
* Returns the ObjectName of the MBean
*
* @see #setObjectName
*/
public ObjectName getObjectName();
/**
* Sets the MBeanInfo of the MBean
*
* @see #getMBeanInfo
*/
public void setMBeanInfo(MBeanInfo info);
/**
* Returns the MBeanInfo of the MBean
*
* @see #setMBeanInfo
*/
public MBeanInfo getMBeanInfo();
/**
* Sets the management interface of the standard MBean
*
* @see #getMBeanInterface
*/
public void setMBeanInterface(Class management);
/**
* Returns the management interface of the standard MBean
*
* @see #setMBeanInterface
*/
public Class getMBeanInterface();
/**
* Sets whether the MBean is standard
*
* @see #isMBeanStandard
*/
public void setMBeanStandard(boolean value);
/**
* Returns whether the MBean is standard
*
* @see #setMBeanStandard
*/
public boolean isMBeanStandard();
/**
* Sets whether the MBean is dynamic
*
* @see #isMBeanDynamic
*/
public void setMBeanDynamic(boolean value);
/**
* Returns whether the MBean is dynamic
*
* @see #setMBeanDynamic
*/
public boolean isMBeanDynamic();
/**
* Sets the MBeanInvoker of the standard MBean
*
* @see #getMBeanInvoker
*/
public void setMBeanInvoker(MBeanInvoker invoker);
/**
* Returns the MBeanInvoker of the standard MBean
*
* @see #getMBeanInvoker
*/
public MBeanInvoker getMBeanInvoker();
/**
* Returns the ObjectInstance of the MBean
*
* @see #getMBeanInfo
* @see #getObjectName
*/
public ObjectInstance getObjectInstance();
/**
* Factory class that creates instance of the {@link MBeanMetaData} interface.
* The default implementation is {@link MX4JMBeanMetaData}, but it can be overridden
* by setting the system property defined by {@link MX4JSystemKeys#MX4J_MBEAN_METADATA}.
*/
public static class Factory
{
public static MBeanMetaData create()
{
String className = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEAN_METADATA);
}
});
if (className == null) className = "mx4j.server.MX4JMBeanMetaData";
try
{
try
{
ClassLoader loader = MBeanMetaData.class.getClassLoader();
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
return (MBeanMetaData)loader.loadClass(className).newInstance();
}
catch (ClassNotFoundException x)
{
// Not found with the current classloader, try the context classloader
return (MBeanMetaData)Thread.currentThread().getContextClassLoader().loadClass(className).newInstance();
}
}
catch (Exception x)
{
throw new Error(x.toString());
}
}
}
}
mx4j-3.0.2/src/core/mx4j/server/MBeanRepository.java 100644 0 0 2660 10513545721 17370 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.util.Iterator;
import javax.management.ObjectName;
/**
* The MBeanServer implementation delegates to implementations of this interface the storage of registered MBeans.
* All necessary synchronization code is taken care by the MBeanServer, so implementations can be coded without caring
* of synchronization issues.
*
* @version $Revision: 1.6 $
*/
public interface MBeanRepository extends Cloneable
{
/**
* Returns the metadata information associated with the given object name.
*
* @see #put
*/
public MBeanMetaData get(ObjectName name);
/**
* Inserts the given metadata associated with the given object name into this repository.
*
* @see #get
*/
public void put(ObjectName name, MBeanMetaData metadata);
/**
* Removes the metadata associated with the given object name from this repository.
*/
public void remove(ObjectName name);
/**
* Returns the size of this repository.
*/
public int size();
/**
* Returns an iterator on the metadata stored in this repository.
*/
public Iterator iterator();
/**
* Clones this MBean repository
*/
public Object clone();
}
mx4j-3.0.2/src/core/mx4j/server/MX4JMBeanMetaData.java 100644 0 0 4723 10513545721 17336 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.MBeanInfo;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
/**
* Default implementation of the MBeanMetaData interface.
*
* @version $Revision: 1.3 $
*/
class MX4JMBeanMetaData implements MBeanMetaData
{
private Object mbean;
private ClassLoader classloader;
private ObjectInstance instance;
private ObjectName name;
private MBeanInfo info;
private boolean dynamic;
private boolean standard;
private Class management;
private MBeanInvoker invoker;
public Object getMBean()
{
return mbean;
}
public void setMBean(Object mbean)
{
this.mbean = mbean;
}
public ClassLoader getClassLoader()
{
return classloader;
}
public void setClassLoader(ClassLoader classloader)
{
this.classloader = classloader;
}
public ObjectName getObjectName()
{
return name;
}
public void setObjectName(ObjectName name)
{
this.name = name;
}
public MBeanInfo getMBeanInfo()
{
return info;
}
public void setMBeanInfo(MBeanInfo info)
{
this.info = info;
}
public boolean isMBeanDynamic()
{
return dynamic;
}
public void setMBeanDynamic(boolean dynamic)
{
this.dynamic = dynamic;
}
public boolean isMBeanStandard()
{
return standard;
}
public void setMBeanStandard(boolean standard)
{
this.standard = standard;
}
public Class getMBeanInterface()
{
return management;
}
public void setMBeanInterface(Class management)
{
this.management = management;
}
public MBeanInvoker getMBeanInvoker()
{
return invoker;
}
public void setMBeanInvoker(MBeanInvoker invoker)
{
this.invoker = invoker;
}
public ObjectInstance getObjectInstance()
{
if (instance == null)
{
instance = new ObjectInstance(getObjectName(), getMBeanInfo().getClassName());
return instance;
}
if (isMBeanDynamic())
{
String clsName = getMBeanInfo().getClassName();
if (!instance.getClassName().equals(clsName)) instance = new ObjectInstance(getObjectName(), clsName);
}
return instance;
}
}
mx4j-3.0.2/src/core/mx4j/server/MX4JMBeanServer.java 100644 0 0 147514 10513545721 17172 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.BadAttributeValueExpException;
import javax.management.BadBinaryOpValueExpException;
import javax.management.BadStringOperationException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidApplicationException;
import javax.management.InvalidAttributeValueException;
import javax.management.JMRuntimeException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanPermission;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.MBeanServerPermission;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationEmitter;
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.RuntimeOperationsException;
import javax.management.loading.ClassLoaderRepository;
import javax.management.loading.PrivateClassLoader;
import mx4j.ImplementationException;
import mx4j.MX4JSystemKeys;
import mx4j.loading.ClassLoaderObjectInputStream;
import mx4j.log.Log;
import mx4j.log.Logger;
import mx4j.server.interceptor.ContextClassLoaderMBeanServerInterceptor;
import mx4j.server.interceptor.InvokerMBeanServerInterceptor;
import mx4j.server.interceptor.MBeanServerInterceptor;
import mx4j.server.interceptor.MBeanServerInterceptorConfigurator;
import mx4j.server.interceptor.NotificationListenerMBeanServerInterceptor;
import mx4j.server.interceptor.SecurityMBeanServerInterceptor;
import mx4j.util.Utils;
/**
* The MX4J MBeanServer implementation.
* The MBeanServer accomplishes these roles:
*
* - Returns information about the Agent
*
- Acts as a repository for MBeans
*
- Acts as an invoker, on behalf of the user, on MBeans
*
*
* The repository function is delegated to instances of {@link MBeanRepository} classes.
* This class acts as a factory for MBeanRepository instances, that can be controlled via the system property
* {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_REPOSITORY} to the qualified name of the implementation class.
*
* This class also acts as an invoker on MBeans. The architecture is interceptor-based, that is whenever you call
* from a client an MBeanServer method that will end up to call the MBean instance, the call is dispatched to
* the interceptor chain and eventually to the MBean.
* The interceptors are configurable via the MBean {@link MBeanServerInterceptorConfigurator}.
* When the call is about to arrive to the MBean instance, the last interceptor dispatches the call depending on
* the MBean type: if the MBean is a dynamic MBean, the call is dispatched directly; if the MBean is a standard
* MBean an {@link MBeanInvoker} is delegated to invoke on the MBean instance.
*
* @version $Revision: 1.31 $
*/
public class MX4JMBeanServer implements MBeanServer
{
private String defaultDomain;
private MBeanRepository mbeanRepository;
private MBeanServerDelegate delegate;
private ObjectName delegateName;
private MBeanIntrospector introspector;
private MBeanServerInterceptorConfigurator invoker;
private static long notifications;
private ModifiableClassLoaderRepository classLoaderRepository;
private Map domains = new HashMap();
private static final String[] EMPTY_PARAMS = new String[0];
private static final Object[] EMPTY_ARGS = new Object[0];
/**
* Create a new MBeanServer implementation with the specified default domain.
* If the default domain is null, then the empty string is assumed.
*
* @param defaultDomain The default domain to be used
* @throws SecurityException if access is not granted to create an MBeanServer instance
*/
public MX4JMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Creating MBeanServer instance...");
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking permission to create MBeanServer...");
sm.checkPermission(new MBeanServerPermission("newMBeanServer"));
}
if (defaultDomain == null) defaultDomain = "DefaultDomain";
this.defaultDomain = defaultDomain;
if (delegate == null) throw new JMRuntimeException("Delegate can't be null");
this.delegate = delegate;
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer default domain is: '" + this.defaultDomain + "'");
mbeanRepository = createMBeanRepository();
classLoaderRepository = createClassLoaderRepository();
// JMX 1.2 requires the CLR to have as first entry the classloader of this class
classLoaderRepository.addClassLoader(getClass().getClassLoader());
// The system classloader must be there as well, in case this class is in the bootclasspath
classLoaderRepository.addClassLoader(ClassLoader.getSystemClassLoader());
introspector = new MBeanIntrospector();
// This is the official name of the delegate, it is used as a source for MBeanServerNotifications
try
{
delegateName = new ObjectName("JMImplementation", "type", "MBeanServerDelegate");
}
catch (MalformedObjectNameException ignored)
{
}
try
{
ObjectName invokerName = new ObjectName(MBeanServerInterceptorConfigurator.OBJECT_NAME);
invoker = new MBeanServerInterceptorConfigurator(this);
ContextClassLoaderMBeanServerInterceptor ccl = new ContextClassLoaderMBeanServerInterceptor();
NotificationListenerMBeanServerInterceptor notif = new NotificationListenerMBeanServerInterceptor();
SecurityMBeanServerInterceptor sec = new SecurityMBeanServerInterceptor();
InvokerMBeanServerInterceptor inv = new InvokerMBeanServerInterceptor(outer == null ? this : outer);
invoker.addPreInterceptor(ccl);
invoker.addPreInterceptor(notif);
invoker.addPreInterceptor(sec);
invoker.addPostInterceptor(inv);
invoker.start();
// The interceptor stack is in place, register the configurator and all interceptors
privilegedRegisterMBean(invoker, invokerName);
ObjectName cclName = new ObjectName("JMImplementation", "interceptor", "contextclassloader");
ObjectName notifName = new ObjectName("JMImplementation", "interceptor", "notificationwrapper");
ObjectName secName = new ObjectName("JMImplementation", "interceptor", "security");
ObjectName invName = new ObjectName("JMImplementation", "interceptor", "invoker");
privilegedRegisterMBean(ccl, cclName);
privilegedRegisterMBean(notif, notifName);
privilegedRegisterMBean(sec, secName);
privilegedRegisterMBean(inv, invName);
}
catch (Exception x)
{
logger.error("MBeanServerInterceptorConfigurator cannot be registered", x);
throw new ImplementationException();
}
// Now register the delegate
try
{
privilegedRegisterMBean(delegate, delegateName);
}
catch (Exception x)
{
logger.error("MBeanServerDelegate cannot be registered", x);
throw new ImplementationException(x.toString());
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer instance created successfully");
}
/**
* Returns the ClassLoaderRepository for this MBeanServer.
* When first the ClassLoaderRepository is created in the constructor, the system property
* {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY} is tested;
* if it is non-null and defines a subclass of
* {@link ModifiableClassLoaderRepository}, then that class is used instead of the default one.
*/
public ClassLoaderRepository getClassLoaderRepository()
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission("-#-[-]", "getClassLoaderRepository"));
}
return getModifiableClassLoaderRepository();
}
private ModifiableClassLoaderRepository getModifiableClassLoaderRepository()
{
return classLoaderRepository;
}
public ClassLoader getClassLoader(ObjectName name) throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
name = secureObjectName(name);
if (name == null)
{
sm.checkPermission(new MBeanPermission("-#-[-]", "getClassLoader"));
}
else
{
MBeanMetaData metadata = findMBeanMetaData(name);
sm.checkPermission(new MBeanPermission(metadata.getMBeanInfo().getClassName(), "-", name, "getClassLoader"));
}
}
return getClassLoaderImpl(name);
}
public ClassLoader getClassLoaderFor(ObjectName name) throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
name = secureObjectName(name);
}
// If name is null, I get InstanceNotFoundException
MBeanMetaData metadata = findMBeanMetaData(name);
if (sm != null)
{
sm.checkPermission(new MBeanPermission(metadata.getMBeanInfo().getClassName(), "-", name, "getClassLoaderFor"));
}
return metadata.getMBean().getClass().getClassLoader();
}
/**
* Returns the MBean classloader corrispondent to the given ObjectName.
* If name
is null, the classloader of this class is returned.
*/
private ClassLoader getClassLoaderImpl(ObjectName name) throws InstanceNotFoundException
{
if (name == null)
{
return getClass().getClassLoader();
}
else
{
MBeanMetaData metadata = findMBeanMetaData(name);
if (metadata.getMBean() instanceof ClassLoader)
{
return (ClassLoader)metadata.getMBean();
}
else
{
throw new InstanceNotFoundException(name.getCanonicalName());
}
}
}
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] bytes)
throws InstanceNotFoundException, OperationsException, ReflectionException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name '" + className + "'"));
}
ClassLoader cl = getClassLoader(loaderName);
try
{
Class cls = cl.loadClass(className);
return deserializeImpl(cls.getClassLoader(), bytes);
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInputStream deserialize(String className, byte[] bytes)
throws OperationsException, ReflectionException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name '" + className + "'"));
}
// Find the classloader that can load the given className using the ClassLoaderRepository
try
{
Class cls = getClassLoaderRepository().loadClass(className);
return deserializeImpl(cls.getClassLoader(), bytes);
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInputStream deserialize(ObjectName objectName, byte[] bytes)
throws InstanceNotFoundException, OperationsException
{
ClassLoader cl = getClassLoaderFor(objectName);
return deserializeImpl(cl, bytes);
}
/**
* Deserializes the given bytes using the specified classloader.
*/
private ObjectInputStream deserializeImpl(ClassLoader classloader, byte[] bytes) throws OperationsException
{
if (bytes == null || bytes.length == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid byte array " + bytes));
}
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try
{
return new ClassLoaderObjectInputStream(bais, classloader);
}
catch (IOException x)
{
throw new OperationsException(x.toString());
}
}
private MBeanServerInterceptor getHeadInterceptor()
{
MBeanServerInterceptor head = invoker.getHeadInterceptor();
if (head == null) throw new IllegalStateException("No MBeanServer interceptor, probably the configurator has been stopped");
return head;
}
private Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
/**
* Creates a new repository for MBeans.
* The system property {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_REPOSITORY} is tested
* for a full qualified name of a class implementing the {@link MBeanRepository} interface.
* In case the system property is not defined or the class is not loadable or instantiable, a default
* implementation is returned.
*/
private MBeanRepository createMBeanRepository()
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking for system property " + MX4JSystemKeys.MX4J_MBEANSERVER_REPOSITORY);
String value = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEANSERVER_REPOSITORY);
}
});
if (value != null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Property found for custom MBeanServer registry; class is: " + value);
try
{
MBeanRepository registry = (MBeanRepository)Thread.currentThread().getContextClassLoader().loadClass(value).newInstance();
if (logger.isEnabledFor(Logger.TRACE))
{
logger.trace("Custom MBeanServer registry created successfully");
}
return registry;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE))
{
logger.trace("Custom MBeanServer registry could not be created", x);
}
}
}
return new DefaultMBeanRepository();
}
/**
* Creates a new ClassLoaderRepository for ClassLoader MBeans.
* The system property {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY}
* is tested for a full qualified name of a class
* extending the {@link ModifiableClassLoaderRepository} class.
* In case the system property is not defined or the class is not loadable or instantiable, a default
* implementation is returned.
*/
private ModifiableClassLoaderRepository createClassLoaderRepository()
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking for system property " + MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
String value = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
}
});
if (value != null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Property found for custom ClassLoaderRepository; class is: " + value);
try
{
ModifiableClassLoaderRepository repository = (ModifiableClassLoaderRepository)Thread.currentThread().getContextClassLoader().loadClass(value).newInstance();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Custom ClassLoaderRepository created successfully " + repository);
return repository;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Custom ClassLoaderRepository could not be created", x);
}
}
return new DefaultClassLoaderRepository();
}
/**
* Returns the repository of MBeans for this MBeanServer
*/
private MBeanRepository getMBeanRepository()
{
return mbeanRepository;
}
/**
* Looks up the metadata associated with the given ObjectName.
*
* @throws InstanceNotFoundException if the given ObjectName is not a registered MBean
*/
private MBeanMetaData findMBeanMetaData(ObjectName objectName) throws InstanceNotFoundException
{
MBeanMetaData metadata = null;
if (objectName != null)
{
objectName = normalizeObjectName(objectName);
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
metadata = repository.get(objectName);
}
}
if (metadata == null)
{
throw new InstanceNotFoundException("MBeanServer cannot find MBean with ObjectName " + objectName);
}
return metadata;
}
public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).getMBean();
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
addNotificationListener(observed, (NotificationListener)mbean, filter, handback);
}
public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
if (observed == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName cannot be null"));
}
if (listener == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("NotificationListener cannot be null"));
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.getMBean();
if (!(mbean instanceof NotificationBroadcaster))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationBroadcaster"));
}
addNotificationListenerImpl(metadata, listener, filter, handback);
}
private void addNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
getHeadInterceptor().addNotificationListener(metadata, listener, filter, handback);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).getMBean();
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
removeNotificationListener(observed, (NotificationListener)mbean);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
if (listener == null)
{
throw new ListenerNotFoundException("NotificationListener cannot be null");
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.getMBean();
if (!(mbean instanceof NotificationBroadcaster))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationBroadcaster"));
}
removeNotificationListenerImpl(metadata, listener);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).getMBean();
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
removeNotificationListener(observed, (NotificationListener)mbean, filter, handback);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
if (listener == null)
{
throw new ListenerNotFoundException("NotificationListener cannot be null");
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.getMBean();
if (!(mbean instanceof NotificationEmitter))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationEmitter"));
}
removeNotificationListenerImpl(metadata, listener, filter, handback);
}
private void removeNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener)
throws ListenerNotFoundException
{
getHeadInterceptor().removeNotificationListener(metadata, listener);
}
private void removeNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException
{
getHeadInterceptor().removeNotificationListener(metadata, listener, filter, handback);
}
public Object instantiate(String className)
throws ReflectionException, MBeanException
{
return instantiate(className, null, null);
}
public Object instantiate(String className, Object[] args, String[] parameters)
throws ReflectionException, MBeanException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Class name cannot be null or empty"));
}
try
{
Class cls = getModifiableClassLoaderRepository().loadClass(className);
return instantiateImpl(className, cls.getClassLoader(), null, parameters, args).getMBean();
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public Object instantiate(String className, ObjectName loaderName)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return instantiate(className, loaderName, null, null);
}
public Object instantiate(String className, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Class name cannot be null or empty"));
}
// loaderName can be null: means using this class' ClassLoader
loaderName = secureObjectName(loaderName);
if (loaderName != null && loaderName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName for the ClassLoader cannot be a pattern ObjectName: " + loaderName));
}
ClassLoader cl = getClassLoaderImpl(loaderName);
return instantiateImpl(className, cl, null, parameters, args).getMBean();
}
private MBeanMetaData instantiateImpl(String className, ClassLoader classloader, ObjectName name, String[] params, Object[] args)
throws ReflectionException, MBeanException
{
if (params == null) params = EMPTY_PARAMS;
if (args == null) args = EMPTY_ARGS;
MBeanMetaData metadata = createMBeanMetaData();
metadata.setClassLoader(classloader);
metadata.setObjectName(secureObjectName(name));
getHeadInterceptor().instantiate(metadata, className, params, args);
return metadata;
}
public ObjectInstance createMBean(String className, ObjectName objectName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
return createMBean(className, objectName, null, null);
}
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
try
{
Class cls = getModifiableClassLoaderRepository().loadClass(className);
MBeanMetaData metadata;
// todo we should change the interceptor stack so that an InstantiationException
// can be thrown directly and handled appropriately. However, I think
// that should wait until a major release so am hacking this in here
try
{
metadata = instantiateImpl(className, cls.getClassLoader(), objectName, parameters, args);
}
catch (ReflectionException e)
{
Exception target = e.getTargetException();
if (target instanceof InstantiationException)
{
throw new NotCompliantMBeanException();
}
else
{
throw e;
}
}
registerImpl(metadata, false);
return metadata.getObjectInstance();
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
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
{
loaderName = secureObjectName(loaderName);
ClassLoader cl = getClassLoaderImpl(loaderName);
MBeanMetaData metadata = instantiateImpl(className, cl, objectName, parameters, args);
registerImpl(metadata, false);
return metadata.getObjectInstance();
}
public ObjectInstance registerMBean(Object mbean, ObjectName objectName)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
return registerMBeanImpl(mbean, objectName, false);
}
private ObjectInstance registerMBeanImpl(Object mbean, ObjectName objectName, boolean privileged)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
if (mbean == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean instance cannot be null"));
}
MBeanMetaData metadata = createMBeanMetaData();
metadata.setMBean(mbean);
metadata.setClassLoader(mbean.getClass().getClassLoader());
metadata.setObjectName(secureObjectName(objectName));
registerImpl(metadata, privileged);
return metadata.getObjectInstance();
}
/**
* Returns a new instance of the metadata class used to store MBean information.
*/
private MBeanMetaData createMBeanMetaData()
{
return MBeanMetaData.Factory.create();
}
/**
* This method is called only to register implementation MBeans from the constructor.
* Since to create an instance of this class already requires a permission, here we hide the registration
* of implementation MBeans to the client that thus need no further permissions.
*/
private ObjectInstance privilegedRegisterMBean(final Object mbean, final ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
try
{
return (ObjectInstance)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception
{
return registerMBeanImpl(mbean, name, true);
}
});
}
catch (PrivilegedActionException x)
{
Exception xx = x.getException();
if (xx instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException)xx;
else if (xx instanceof MBeanRegistrationException)
throw (MBeanRegistrationException)xx;
else if (xx instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException)xx;
else
throw new MBeanRegistrationException(xx);
}
}
private void registerImpl(MBeanMetaData metadata, boolean privileged) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
introspector.introspect(metadata);
if (!introspector.isMBeanCompliant(metadata)) throw new NotCompliantMBeanException("MBean is not compliant");
MBeanServerInterceptor head = getHeadInterceptor();
head.registration(metadata, MBeanServerInterceptor.PRE_REGISTER);
// The MBean implementor could have replaced the ObjectName with a subclass that is not secure, secure it again
metadata.setObjectName(secureObjectName(metadata.getObjectName()));
int postRegisterFlag = MBeanServerInterceptor.POST_REGISTER_FALSE;
try
{
register(metadata, privileged);
postRegisterFlag = MBeanServerInterceptor.POST_REGISTER_TRUE;
}
finally
{
head.registration(metadata, postRegisterFlag);
}
Object mbean = metadata.getMBean();
if (mbean instanceof ClassLoader && !(mbean instanceof PrivateClassLoader))
{
ClassLoader cl = (ClassLoader)mbean;
getModifiableClassLoaderRepository().addClassLoader(cl);
}
}
private void register(MBeanMetaData metadata, boolean privileged) throws InstanceAlreadyExistsException
{
metadata.setObjectName(normalizeObjectName(metadata.getObjectName()));
ObjectName objectName = metadata.getObjectName();
if (objectName == null || objectName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName cannot be null or a pattern ObjectName"));
}
if (objectName.getDomain().equals("JMImplementation") && !privileged)
{
throw new JMRuntimeException("Domain 'JMImplementation' is reserved for the JMX Agent");
}
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
if (repository.get(objectName) != null) throw new InstanceAlreadyExistsException(objectName.toString());
repository.put(objectName, metadata);
}
addDomain(objectName.getDomain());
notify(objectName, MBeanServerNotification.REGISTRATION_NOTIFICATION);
}
private void notify(ObjectName objectName, String notificationType)
{
long sequenceNumber = 0;
synchronized (MX4JMBeanServer.class)
{
sequenceNumber = notifications;
++notifications;
}
delegate.sendNotification(new MBeanServerNotification(notificationType, delegateName, sequenceNumber, objectName));
}
private void addDomain(String domain)
{
synchronized (domains)
{
Integer count = (Integer)domains.get(domain);
if (count == null)
domains.put(domain, new Integer(1));
else
domains.put(domain, new Integer(count.intValue() + 1));
}
}
private void removeDomain(String domain)
{
synchronized (domains)
{
Integer count = (Integer)domains.get(domain);
if (count == null) throw new ImplementationException();
if (count.intValue() < 2)
domains.remove(domain);
else
domains.put(domain, new Integer(count.intValue() - 1));
}
}
public void unregisterMBean(ObjectName objectName)
throws InstanceNotFoundException, MBeanRegistrationException
{
objectName = secureObjectName(objectName);
if (objectName == null || objectName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName cannot be null or a pattern ObjectName"));
}
if (objectName.getDomain().equals("JMImplementation"))
{
throw new RuntimeOperationsException(new IllegalArgumentException("Domain 'JMImplementation' is reserved for the JMX Agent"));
}
MBeanMetaData metadata = findMBeanMetaData(objectName);
MBeanServerInterceptor head = getHeadInterceptor();
head.registration(metadata, MBeanServerInterceptor.PRE_DEREGISTER);
unregister(metadata);
getHeadInterceptor().registration(metadata, MBeanServerInterceptor.POST_DEREGISTER);
Object mbean = metadata.getMBean();
if (mbean instanceof ClassLoader && !(mbean instanceof PrivateClassLoader))
{
getModifiableClassLoaderRepository().removeClassLoader((ClassLoader)mbean);
}
}
private void unregister(MBeanMetaData metadata)
{
ObjectName objectName = metadata.getObjectName();
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
repository.remove(objectName);
}
removeDomain(objectName.getDomain());
notify(objectName, MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
}
public Object getAttribute(ObjectName objectName, String attribute)
throws InstanceNotFoundException, MBeanException, AttributeNotFoundException, ReflectionException
{
if (attribute == null || attribute.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
return getHeadInterceptor().getAttribute(metadata, attribute);
}
public void setAttribute(ObjectName objectName, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
if (attribute == null || attribute.getName().trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
getHeadInterceptor().setAttribute(metadata, attribute);
}
public AttributeList getAttributes(ObjectName objectName, String[] attributes)
throws InstanceNotFoundException, ReflectionException
{
if (attributes == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute list"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
// Must check if the user has the right to call this method, regardless of the attributes
sm.checkPermission(new MBeanPermission(metadata.getMBeanInfo().getClassName(), "-", objectName, "getAttribute"));
}
return getHeadInterceptor().getAttributes(metadata, attributes);
}
public AttributeList setAttributes(ObjectName objectName, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException
{
if (attributes == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute list"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
// Must check if the user has the right to call this method, regardless of the attributes
sm.checkPermission(new MBeanPermission(metadata.getMBeanInfo().getClassName(), "-", objectName, "setAttribute"));
}
return getHeadInterceptor().setAttributes(metadata, attributes);
}
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException
{
if (methodName == null || methodName.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid operation name '" + methodName + "'"));
}
if (args == null) args = EMPTY_ARGS;
if (parameters == null) parameters = EMPTY_PARAMS;
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
return getHeadInterceptor().invoke(metadata, methodName, parameters, args);
}
public String getDefaultDomain()
{
return defaultDomain;
}
public String[] getDomains()
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission(null, null, null, "getDomains"));
}
Set keys;
synchronized (domains)
{
keys = new HashSet(domains.keySet());
}
if (sm != null)
{
for (Iterator i = keys.iterator(); i.hasNext();)
{
String domain = (String)i.next();
try
{
ObjectName name = new ObjectName(domain, "x", "x");
sm.checkPermission(new MBeanPermission(null, null, name, "getDomains"));
}
catch (SecurityException e)
{
i.remove();
continue;
}
catch (MalformedObjectNameException e)
{
throw new ImplementationException("Unexpected MalformedObjectNameException for registered domain: " + domain);
}
}
}
return (String[])keys.toArray(new String[keys.size()]);
}
public Integer getMBeanCount()
{
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
return new Integer(repository.size());
}
}
public boolean isRegistered(ObjectName objectName)
{
try
{
return findMBeanMetaData(objectName) != null;
}
catch (InstanceNotFoundException x)
{
return false;
}
}
public MBeanInfo getMBeanInfo(ObjectName objectName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException
{
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
MBeanInfo info = getHeadInterceptor().getMBeanInfo(metadata);
if (info == null) throw new JMRuntimeException("MBeanInfo returned for MBean " + objectName + " is null");
return info;
}
public ObjectInstance getObjectInstance(ObjectName objectName)
throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
objectName = secureObjectName(objectName);
}
MBeanMetaData metadata = findMBeanMetaData(objectName);
if (sm != null)
{
sm.checkPermission(new MBeanPermission(metadata.getMBeanInfo().getClassName(), "-", objectName, "getObjectInstance"));
}
return metadata.getObjectInstance();
}
public boolean isInstanceOf(ObjectName objectName, String className)
throws InstanceNotFoundException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
String infoClassName = metadata.getMBeanInfo().getClassName();
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission(infoClassName, "-", objectName, "isInstanceOf"));
}
if (className.equals(infoClassName)) return true;
try
{
ClassLoader loader = metadata.getClassLoader();
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
Class cls = loader.loadClass(className);
Class infoClass = loader.loadClass(infoClassName);
return cls.isAssignableFrom(infoClass);
}
catch (ClassNotFoundException x)
{
return false;
}
}
public Set queryMBeans(ObjectName patternName, QueryExp filter)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
patternName = secureObjectName(patternName);
// Must check if the user has the right to call this method,
// no matter which ObjectName has been passed.
sm.checkPermission(new MBeanPermission("-#-[-]", "queryMBeans"));
}
Set match = queryObjectNames(patternName, filter, true);
Set set = new HashSet();
for (Iterator i = match.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
try
{
MBeanMetaData metadata = findMBeanMetaData(name);
set.add(metadata.getObjectInstance());
}
catch (InstanceNotFoundException ignored)
{
// A concurrent thread removed the MBean after queryNames, ignore
}
}
return set;
}
public Set queryNames(ObjectName patternName, QueryExp filter)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
patternName = secureObjectName(patternName);
// Must check if the user has the right to call this method,
// no matter which ObjectName has been passed.
sm.checkPermission(new MBeanPermission("-#-[-]", "queryNames"));
}
return queryObjectNames(patternName, filter, false);
}
/**
* Utility method for queryNames and queryMBeans that returns a set of ObjectNames.
* It does 3 things:
* 1) filter the MBeans following the given ObjectName pattern
* 2) filter the MBeans following the permissions that client code has
* 3) filter the MBeans following the given QueryExp
* It is important that these 3 operations are done in this order
*/
private Set queryObjectNames(ObjectName patternName, QueryExp filter, boolean instances)
{
// First, retrieve the scope of the query: all mbeans matching the patternName
Set scope = findMBeansByPattern(patternName);
// Second, filter the scope by checking the caller's permissions
Set secureScope = filterMBeansBySecurity(scope, instances);
// Third, filter the scope using the given QueryExp
Set match = filterMBeansByQuery(secureScope, filter);
return match;
}
/**
* Returns a set of ObjectNames of the registered MBeans that match the given ObjectName pattern
*/
private Set findMBeansByPattern(ObjectName pattern)
{
if (pattern == null)
{
try
{
pattern = new ObjectName("*:*");
}
catch (MalformedObjectNameException ignored)
{
}
}
pattern = normalizeObjectName(pattern);
String patternDomain = pattern.getDomain();
Hashtable patternProps = pattern.getKeyPropertyList();
Set set = new HashSet();
// Clone the repository, we are faster than holding the lock while iterating
MBeanRepository repository = null;
MBeanRepository original = getMBeanRepository();
synchronized (original)
{
repository = (MBeanRepository)original.clone();
}
for (Iterator i = repository.iterator(); i.hasNext();)
{
MBeanMetaData metadata = (MBeanMetaData)i.next();
ObjectName name = metadata.getObjectName();
Hashtable props = name.getKeyPropertyList();
String domain = name.getDomain();
if (Utils.wildcardMatch(patternDomain, domain))
{
// Domain matches, now check properties
if (pattern.isPropertyPattern())
{
// A property pattern with no entries, can only be '*'
if (patternProps.size() == 0)
{
// User wants all properties
set.add(name);
}
else
{
// Loop on the properties of the pattern.
// If one is not found then the current ObjectName does not match
boolean found = true;
for (Iterator j = patternProps.entrySet().iterator(); j.hasNext();)
{
Map.Entry entry = (Map.Entry)j.next();
Object patternKey = entry.getKey();
Object patternValue = entry.getValue();
if (patternKey.equals("*"))
{
continue;
}
// Try to see if the current ObjectName contains this entry
if (!props.containsKey(patternKey))
{
// Not even the key is present
found = false;
break;
}
else
{
// The key is present, let's check if the values are equal
Object value = props.get(patternKey);
if (value == null && patternValue == null)
{
// Values are equal, go on with next pattern entry
continue;
}
if (value != null && value.equals(patternValue))
{
// Values are equal, go on with next pattern entry
continue;
}
// Here values are different
found = false;
break;
}
}
if (found) set.add(name);
}
}
else
{
if (props.entrySet().equals(patternProps.entrySet())) set.add(name);
}
}
}
return set;
}
/**
* Filters the given set of ObjectNames following the permission that client code has granted.
* Returns a set containing the allowed ObjectNames.
*/
private Set filterMBeansBySecurity(Set mbeans, boolean instances)
{
SecurityManager sm = System.getSecurityManager();
if (sm == null) return mbeans;
HashSet set = new HashSet();
for (Iterator i = mbeans.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
try
{
MBeanMetaData metadata = findMBeanMetaData(name);
String className = metadata.getMBeanInfo().getClassName();
sm.checkPermission(new MBeanPermission(className, "-", name, instances ? "queryMBeans" : "queryNames"));
set.add(name);
}
catch (InstanceNotFoundException ignored)
{
// A concurrent thread removed this MBean, continue
continue;
}
catch (SecurityException ignored)
{
// Don't add the name to the list, and go on.
}
}
return set;
}
/**
* Filters the given set of ObjectNames following the given QueryExp.
* Returns a set of ObjectNames that match the given QueryExp.
*/
private Set filterMBeansByQuery(Set scope, QueryExp filter)
{
if (filter == null) return scope;
Set set = new HashSet();
for (Iterator i = scope.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
filter.setMBeanServer(this);
try
{
if (filter.apply(name)) set.add(name);
}
catch (BadStringOperationException ignored)
{
}
catch (BadBinaryOpValueExpException ignored)
{
}
catch (BadAttributeValueExpException x)
{
}
catch (InvalidApplicationException x)
{
}
catch (SecurityException x)
{
}
catch (Exception x)
{
// The 1.2 spec says Exceptions must not be propagated
}
}
return set;
}
/**
* Returns a normalized ObjectName from the given one.
* If an ObjectName is specified with the abbreviated notation for the default domain, that is ':key=value'
* this method returns an ObjectName whose domain is the default domain of this MBeanServer and with the same
* properties.
*/
private ObjectName normalizeObjectName(ObjectName name)
{
if (name == null) return null;
String defaultDomain = getDefaultDomain();
String domain = name.getDomain();
if (domain.length() == 0 && defaultDomain.length() > 0)
{
// The given object name specifies the abbreviated form to indicate the default domain,
// ie ':key=value', the empty string as domain. I must convert this abbreviated form
// to the full one, if the default domain of this mbeanserver is not the empty string as well
StringBuffer buffer = new StringBuffer(defaultDomain).append(":").append(name.getKeyPropertyListString());
if (name.isPropertyPattern())
{
if (name.getKeyPropertyList().size() > 0)
buffer.append(",*");
else
buffer.append("*");
}
try
{
name = new ObjectName(buffer.toString());
}
catch (MalformedObjectNameException ignored)
{
}
}
return name;
}
/**
* Returns an ObjectName instance even if the provided ObjectName is a subclass.
* This is done to avoid security holes: a nasty ObjectName subclass can bypass security checks.
*/
private ObjectName secureObjectName(ObjectName name)
{
// I cannot trust ObjectName, since a malicious user can send a subclass that overrides equals and hashcode
// to match another ObjectName for which it does not have permission, or returns different results from
// ObjectName.getCanonicalName() for different calls, so that passes the security checks but in fact will
// later refer to a different ObjectName for which it does not have permission.
if (name == null) return null;
return ObjectName.getInstance(name);
}
}
mx4j-3.0.2/src/core/mx4j/server/MX4JMBeanServerBuilder.java 100644 0 0 4066 10513545721 20433 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.MBeanServer;
import javax.management.MBeanServerBuilder;
import javax.management.MBeanServerDelegate;
/**
* This class is responsible for creating new instances of {@link MBeanServerDelegate}
* and {@link MBeanServer}. It creates instances from the implementation in the
* mx4j.server
package.
*
* The {@link javax.management.MBeanServerFactory} first creates the delegate, then it
* creates the MBeanServer and provides a reference to the created delegate to it.
* Note that the delegate passed to the MBeanServer might not be the instance returned
* by this builder; for example, it could be a wrapper around it.
*
* @version $Revision: 1.7 $
* @see MBeanServer
* @see javax.management.MBeanServerFactory
*/
public class MX4JMBeanServerBuilder extends MBeanServerBuilder
{
/**
* Returns a new {@link MX4JMBeanServerDelegate} instance for a new MBeanServer.
*
* @return a new {@link MX4JMBeanServerDelegate} instance for a new MBeanServer.
*/
public MBeanServerDelegate newMBeanServerDelegate()
{
return new MX4JMBeanServerDelegate();
}
/**
* Returns a new {@link MX4JMBeanServer} instance.
*
* @param defaultDomain the default domain name for the new server.
* @param outer the {@link MBeanServer} that is passed in calls to
* {@link javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)}.
* @param delegate the {@link MBeanServerDelegate} instance for the new server.
* @return a new {@link MX4JMBeanServer} instance.
*/
public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate)
{
return new MX4JMBeanServer(defaultDomain, outer, delegate);
}
}
mx4j-3.0.2/src/core/mx4j/server/MX4JMBeanServerDelegate.java 100644 0 0 1402 10513545721 20546 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.MBeanServerDelegate;
/**
* The MBeanServerDelegate subclass typical of the MX4J implementation.
*
* @version $Revision: 1.12 $
* @see javax.management.MBeanServerBuilder
*/
public class MX4JMBeanServerDelegate extends MBeanServerDelegate
{
public String getImplementationName()
{
return "MX4J";
}
public String getImplementationVendor()
{
return "The MX4J Team";
}
public String getImplementationVersion()
{
return "3.0.2";
}
}
mx4j-3.0.2/src/core/mx4j/server/ModifiableClassLoaderRepository.java 100644 0 0 2570 10513545721 22556 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import javax.management.loading.ClassLoaderRepository;
/**
* Base class to extend to create custom ClassLoaderRepositories.
* MX4J's MBeanServer can use a custom ClassLoaderRepository instead of the default one
* by simply specifying a suitable system property, see {@link mx4j.MX4JSystemKeys}.
* It must be a class, otherwise it opens up a security hole, as anyone can cast the MBeanServer's
* ClassLoaderRepository down to this class and call addClassLoader or removeClassLoader
* since, if this class is an interface, they must be public.
*
* @version $Revision: 1.4 $
*/
public abstract class ModifiableClassLoaderRepository implements ClassLoaderRepository
{
/**
* Adds, if does not already exist, the specified ClassLoader to this repository.
*
* @param cl The classloader to add
* @see #removeClassLoader
*/
protected abstract void addClassLoader(ClassLoader cl);
/**
* Removes, if exists, the specified ClassLoader from this repository.
*
* @param cl The classloader to remove
* @see #addClassLoader
*/
protected abstract void removeClassLoader(ClassLoader cl);
}
mx4j-3.0.2/src/core/mx4j/server/ReflectionMBeanInvoker.java 100644 0 0 21420 10513545721 20654 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeOperationsException;
import mx4j.ImplementationException;
import mx4j.util.Utils;
/**
* Stateless MBeanInvoker that uses reflection to invoke on MBean instances.
*
* @version $Revision: 1.6 $
*/
public class ReflectionMBeanInvoker implements MBeanInvoker
{
/**
* A zero-length String[] that indicates a parameterless signature of a method.
*/
protected static final String[] EMPTY_PARAMS = new String[0];
/**
* A zero-length Object[] that indicates a parameterless argument list of a method
*/
protected static final Object[] EMPTY_ARGS = new Object[0];
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException
{
MBeanOperationInfo oper = getStandardOperationInfo(metadata, method, params);
if (oper != null)
{
try
{
return doInvoke(metadata, method, params, args);
}
catch (BadArgumentException x)
{
throw new RuntimeOperationsException(x.nested);
}
}
else
{
throw new ReflectionException(new NoSuchMethodException("Operation " + method + " does not belong to the management interface"));
}
}
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException
{
MBeanAttributeInfo attr = getStandardAttributeInfo(metadata, attribute, false);
if (attr != null)
{
String methodName = getMethodForAttribute(attr, true);
try
{
return doInvoke(metadata, methodName, EMPTY_PARAMS, EMPTY_ARGS);
}
catch (BadArgumentException x)
{
// Never thrown, since there are no arguments
throw new ImplementationException();
}
}
else
{
throw new AttributeNotFoundException(attribute);
}
}
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException
{
String name = attribute.getName();
MBeanAttributeInfo attr = getStandardAttributeInfo(metadata, name, true);
if (attr != null)
{
String methodName = getMethodForAttribute(attr, false);
try
{
doInvoke(metadata, methodName, new String[]{attr.getType()}, new Object[]{attribute.getValue()});
}
catch (BadArgumentException x)
{
throw new InvalidAttributeValueException("Invalid value for attribute " + name + ": " + attribute.getValue());
}
}
else
{
throw new AttributeNotFoundException(name);
}
}
/**
* Centralizes exception handling necessary to convert exceptions thrown by MBean's methods to
* JMX exceptions. Delegates the actual invocation to {@link #invokeImpl}
*/
protected Object doInvoke(MBeanMetaData metadata, String method, String[] signature, Object[] args) throws ReflectionException, MBeanException, BadArgumentException
{
try
{
return invokeImpl(metadata, method, signature, args);
}
catch (ReflectionException x)
{
throw x;
}
catch (MBeanException x)
{
throw x;
}
catch (BadArgumentException x)
{
throw x;
}
catch (InvocationTargetException x)
{
Throwable t = x.getTargetException();
if (t instanceof RuntimeException) throw new RuntimeMBeanException((RuntimeException)t);
if (t instanceof Exception) throw new MBeanException((Exception)t);
throw new RuntimeErrorException((Error)t);
}
catch (Throwable t)
{
if (t instanceof RuntimeException) throw new RuntimeMBeanException((RuntimeException)t);
if (t instanceof Exception) throw new MBeanException((Exception)t);
throw new RuntimeErrorException((Error)t);
}
}
/**
* Performs the actual invocation of the MBean's method.
* Exceptions thrown by the MBean's methods should not be catched, since {@link #doInvoke}
* takes care of converting them to JMX exceptions.
*/
protected Object invokeImpl(MBeanMetaData metadata, String method, String[] signature, Object[] args) throws Throwable
{
Method m = getStandardManagementMethod(metadata, method, signature);
try
{
return m.invoke(metadata.getMBean(), args);
}
catch (IllegalAccessException x)
{
throw new ReflectionException(x);
}
catch (IllegalArgumentException x)
{
throw new BadArgumentException(x);
}
}
/**
* Returns the MBeanOperationInfo for the given operation, or null if the operation
* is not a management operation.
*/
protected MBeanOperationInfo getStandardOperationInfo(MBeanMetaData metadata, String method, String[] signature)
{
MBeanOperationInfo[] opers = metadata.getMBeanInfo().getOperations();
if (opers != null)
{
for (int i = 0; i < opers.length; ++i)
{
MBeanOperationInfo oper = opers[i];
String name = oper.getName();
if (method.equals(name))
{
// Same method name, check number of parameters
MBeanParameterInfo[] params = oper.getSignature();
if (signature.length == params.length)
{
boolean match = true;
for (int j = 0; j < params.length; ++j)
{
MBeanParameterInfo param = params[j];
if (!signature[j].equals(param.getType()))
{
match = false;
break;
}
}
if (match) return oper;
}
}
}
}
return null;
}
/**
* Returns the MBeanAttributeInfo for the given attribute, or null if the attribute
* is not a management attribute.
*/
protected MBeanAttributeInfo getStandardAttributeInfo(MBeanMetaData metadata, String attribute, boolean forWrite)
{
MBeanAttributeInfo[] attrs = metadata.getMBeanInfo().getAttributes();
if (attrs != null)
{
for (int i = 0; i < attrs.length; ++i)
{
MBeanAttributeInfo attr = attrs[i];
String name = attr.getName();
if (attribute.equals(name))
{
if (forWrite && attr.isWritable()) return attr;
if (!forWrite && attr.isReadable()) return attr;
}
}
}
return null;
}
/**
* Returns the method name for the given attribute.
*/
protected String getMethodForAttribute(MBeanAttributeInfo attribute, boolean forRead)
{
String name = attribute.getName();
String attributeName = null;
if (forRead)
{
String prefix = attribute.isIs() ? "is" : "get";
attributeName = prefix + name;
}
else
{
attributeName = "set" + name;
}
return attributeName;
}
/**
* Returns a java.lang.reflect.Method object for the given method name and signature.
*/
protected Method getStandardManagementMethod(MBeanMetaData metadata, String name, String[] signature) throws ReflectionException
{
try
{
Class[] params = Utils.loadClasses(metadata.getClassLoader(), signature);
Method method = metadata.getMBeanInterface().getMethod(name, params);
return method;
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
catch (NoSuchMethodException x)
{
throw new ReflectionException(x);
}
}
private static class BadArgumentException extends Exception
{
private final IllegalArgumentException nested;
private BadArgumentException(IllegalArgumentException nested)
{
this.nested = nested;
}
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/ContextClassLoaderMBeanServerInterceptor.java 100644 0 0 21462 10513545721 26737 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ReflectionException;
import mx4j.server.MBeanMetaData;
/**
* This interceptor sets the context class loader to the proper value for incoming calls.
* It saves the current context class loader, set the context class loader to be the MBean's class loader for
* the current call, and on return re-set the context class loader to the previous value
*
* @version $Revision: 1.11 $
*/
public class ContextClassLoaderMBeanServerInterceptor extends DefaultMBeanServerInterceptor
{
public ContextClassLoaderMBeanServerInterceptor()
{
// Disabled by default
setEnabled(false);
}
public String getType()
{
return "contextclassloader";
}
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.addNotificationListener(metadata, listener, filter, handback);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.addNotificationListener(metadata, listener, filter, handback);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.removeNotificationListener(metadata, listener);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.removeNotificationListener(metadata, listener);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.removeNotificationListener(metadata, listener, filter, handback);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.removeNotificationListener(metadata, listener, filter, handback);
}
public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.instantiate(metadata, className, params, args);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.instantiate(metadata, className, params, args);
}
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.registration(metadata, operation);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.registration(metadata, operation);
}
public MBeanInfo getMBeanInfo(MBeanMetaData metadata)
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
return super.getMBeanInfo(metadata);
}
finally
{
setContextClassLoader(context);
}
}
}
return super.getMBeanInfo(metadata);
}
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
return super.invoke(metadata, method, params, args);
}
finally
{
setContextClassLoader(context);
}
}
}
return super.invoke(metadata, method, params, args);
}
public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes)
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
return super.getAttributes(metadata, attributes);
}
finally
{
setContextClassLoader(context);
}
}
}
return super.getAttributes(metadata, attributes);
}
public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes)
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
return super.setAttributes(metadata, attributes);
}
finally
{
setContextClassLoader(context);
}
}
}
return super.setAttributes(metadata, attributes);
}
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
return super.getAttribute(metadata, attribute);
}
finally
{
setContextClassLoader(context);
}
}
}
return super.getAttribute(metadata, attribute);
}
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException
{
if (isEnabled())
{
ClassLoader context = getContextClassLoader();
if (metadata.getClassLoader() != context)
{
try
{
setContextClassLoader(metadata.getClassLoader());
super.setAttribute(metadata, attribute);
return;
}
finally
{
setContextClassLoader(context);
}
}
}
super.setAttribute(metadata, attribute);
}
private ClassLoader getContextClassLoader()
{
return Thread.currentThread().getContextClassLoader();
}
private void setContextClassLoader(final ClassLoader cl)
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
Thread.currentThread().setContextClassLoader(cl);
return null;
}
});
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/DefaultMBeanServerInterceptor.java 100644 0 0 10501 10513545721 24552 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.util.List;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ReflectionException;
import mx4j.log.Log;
import mx4j.log.Logger;
import mx4j.server.MBeanMetaData;
/**
* Base class for MBeanServer --> MBean interceptors.
*
* @version $Revision: 1.11 $
*/
public abstract class DefaultMBeanServerInterceptor implements MBeanServerInterceptor, DefaultMBeanServerInterceptorMBean
{
private boolean enabled = true;
private String logCategory;
private List chain;
protected DefaultMBeanServerInterceptor()
{
// It's amazing how setting up here this string dramatically reduces the times to get the Logger instance
logCategory = getClass().getName() + "." + getType();
}
/**
* Returns whether this interceptor is enabled
*
* @see #setEnabled
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Enables or disables this interceptor
*
* @see #isEnabled
*/
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
/**
* Returns the type of this interceptor
*/
public abstract String getType();
protected synchronized MBeanServerInterceptor getNext()
{
int index = chain.indexOf(this);
MBeanServerInterceptor next = (MBeanServerInterceptor)chain.get(index + 1);
next.setChain(chain);
return next;
}
public synchronized void setChain(List chain)
{
this.chain = chain;
}
protected Logger getLogger()
{
return Log.getLogger(logCategory);
}
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
getNext().addNotificationListener(metadata, listener, filter, handback);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException
{
getNext().removeNotificationListener(metadata, listener);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
getNext().removeNotificationListener(metadata, listener, filter, handback);
}
public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException
{
getNext().instantiate(metadata, className, params, args);
}
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException
{
getNext().registration(metadata, operation);
}
public MBeanInfo getMBeanInfo(MBeanMetaData metadata)
{
return getNext().getMBeanInfo(metadata);
}
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException
{
return getNext().invoke(metadata, method, params, args);
}
public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes)
{
return getNext().getAttributes(metadata, attributes);
}
public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes)
{
return getNext().setAttributes(metadata, attributes);
}
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException
{
return getNext().getAttribute(metadata, attribute);
}
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException
{
getNext().setAttribute(metadata, attribute);
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/DefaultMBeanServerInterceptorMBean.java 100644 0 0 1415 10513545721 25441 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
/**
* Management interface for the DefaultMBeanServerInterceptor MBean
*
* @version $Revision: 1.6 $
*/
public interface DefaultMBeanServerInterceptorMBean
{
/**
* Returns whether this interceptor is enabled
*
* @see #setEnabled
*/
public boolean isEnabled();
/**
* Enables or disables this interceptor
*
* @see #isEnabled
*/
public void setEnabled(boolean enabled);
/**
* Returns the type of this interceptor
*/
public String getType();
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/DefaultMBeanServerInterceptorMBeanDescription.java 100644 0 0 1674 10513545721 27654 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import mx4j.MBeanDescriptionAdapter;
/**
* Management interface description for the DefaultMBeanServerInterceptor MBean
*
* @version $Revision: 1.3 $
*/
public class DefaultMBeanServerInterceptorMBeanDescription extends MBeanDescriptionAdapter
{
public String getMBeanDescription()
{
return "MBeanServer interceptor";
}
public String getAttributeDescription(String attribute)
{
if (attribute.equals("Enabled"))
{
return "The enable status of this interceptor";
}
if (attribute.equals("Type"))
{
return "The type of this interceptor";
}
return super.getAttributeDescription(attribute);
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/InvokerMBeanServerInterceptor.java 100644 0 0 25736 10513545721 24623 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.JMRuntimeException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeMBeanException;
import mx4j.ImplementationException;
import mx4j.log.Logger;
import mx4j.server.MBeanMetaData;
import mx4j.util.Utils;
/**
* The last MBeanServer --$gt; MBean interceptor in the chain.
* It calls the MBean instance; if the MBean is a dynamic MBean, the call is direct, otherwise the call is delegated
* to an {@link mx4j.server.MBeanInvoker MBeanInvoker}.
*
* @version $Revision: 1.23 $
*/
public class InvokerMBeanServerInterceptor extends DefaultMBeanServerInterceptor implements InvokerMBeanServerInterceptorMBean
{
private MBeanServer outerServer;
/**
* Instantiates a new interceptor instance.
*
* @param outerServer the {@link MBeanServer} instance that is passed to
* {@link MBeanRegistration#preRegister(MBeanServer, ObjectName)}.
*/
public InvokerMBeanServerInterceptor(MBeanServer outerServer)
{
this.outerServer = outerServer;
}
/**
* Returns the type of this interceptor
*/
public String getType()
{
return "invoker";
}
/**
* This interceptor is always enabled
*/
public boolean isEnabled()
{
return true;
}
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
((NotificationBroadcaster)metadata.getMBean()).addNotificationListener(listener, filter, handback);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException
{
((NotificationBroadcaster)metadata.getMBean()).removeNotificationListener(listener);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException
{
((NotificationEmitter)metadata.getMBean()).removeNotificationListener(listener, filter, handback);
}
public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException
{
try
{
ClassLoader loader = metadata.getClassLoader();
if (loader == null) loader = Thread.currentThread().getContextClassLoader();
Class cls = loader.loadClass(className);
Class[] signature = Utils.loadClasses(loader, params);
Constructor ctor = cls.getConstructor(signature);
metadata.setMBean(ctor.newInstance(args));
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
catch (NoSuchMethodException x)
{
throw new ReflectionException(x);
}
catch (InstantiationException x)
{
throw new ReflectionException(x);
}
catch (IllegalAccessException x)
{
throw new ReflectionException(x);
}
catch (IllegalArgumentException x)
{
throw new ReflectionException(x);
}
catch (InvocationTargetException x)
{
Throwable t = x.getTargetException();
if (t instanceof Error)
{
throw new RuntimeErrorException((Error)t);
}
else if (t instanceof RuntimeException)
{
throw new RuntimeMBeanException((RuntimeException)t);
}
else
{
throw new MBeanException((Exception)t);
}
}
}
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException
{
Object mbean = metadata.getMBean();
if (!(mbean instanceof MBeanRegistration)) return;
MBeanRegistration registrable = (MBeanRegistration)mbean;
try
{
switch (operation)
{
case PRE_REGISTER:
ObjectName objName = registrable.preRegister(outerServer, metadata.getObjectName());
metadata.setObjectName(objName);
break;
case POST_REGISTER_TRUE:
registrable.postRegister(Boolean.TRUE);
break;
case POST_REGISTER_FALSE:
registrable.postRegister(Boolean.FALSE);
break;
case PRE_DEREGISTER:
registrable.preDeregister();
break;
case POST_DEREGISTER:
registrable.postDeregister();
break;
default:
throw new ImplementationException();
}
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Exception x)
{
if (x instanceof MBeanRegistrationException)
{
throw (MBeanRegistrationException)x;
}
throw new MBeanRegistrationException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
public MBeanInfo getMBeanInfo(MBeanMetaData metadata)
{
if (metadata.isMBeanDynamic())
{
// From JMX 1.1 the MBeanInfo may be dynamically changed at every time, let's refresh it
MBeanInfo info = null;
try
{
info = ((DynamicMBean)metadata.getMBean()).getMBeanInfo();
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
if (info == null) return null;
metadata.setMBeanInfo(info);
}
return (MBeanInfo)metadata.getMBeanInfo().clone();
}
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException
{
if (metadata.isMBeanDynamic())
{
try
{
return ((DynamicMBean)metadata.getMBean()).invoke(method, args, params);
}
catch (JMRuntimeException x)
{
throw x;
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
else
{
return metadata.getMBeanInvoker().invoke(metadata, method, params, args);
}
}
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException
{
if (metadata.isMBeanDynamic())
{
try
{
return ((DynamicMBean)metadata.getMBean()).getAttribute(attribute);
}
catch (JMRuntimeException x)
{
throw x;
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
else
{
return metadata.getMBeanInvoker().getAttribute(metadata, attribute);
}
}
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException
{
if (metadata.isMBeanDynamic())
{
try
{
((DynamicMBean)metadata.getMBean()).setAttribute(attribute);
}
catch (JMRuntimeException x)
{
throw x;
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
else
{
metadata.getMBeanInvoker().setAttribute(metadata, attribute);
}
}
public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes)
{
if (metadata.isMBeanDynamic())
{
try
{
return ((DynamicMBean)metadata.getMBean()).getAttributes(attributes);
}
catch (JMRuntimeException x)
{
throw x;
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
else
{
AttributeList list = new AttributeList();
for (int i = 0; i < attributes.length; ++i)
{
String name = attributes[i];
try
{
Object value = getAttribute(metadata, name);
Attribute attr = new Attribute(name, value);
list.add(attr);
}
catch (Exception ignored)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Exception caught from getAttributes(), ignoring attribute " + name);
}
}
return list;
}
}
public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes)
{
if (metadata.isMBeanDynamic())
{
try
{
return ((DynamicMBean)metadata.getMBean()).setAttributes(attributes);
}
catch (JMRuntimeException x)
{
throw x;
}
catch (RuntimeException x)
{
throw new RuntimeMBeanException(x);
}
catch (Error x)
{
throw new RuntimeErrorException(x);
}
}
else
{
AttributeList list = new AttributeList();
for (int i = 0; i < attributes.size(); ++i)
{
Attribute attr = (Attribute)attributes.get(i);
try
{
setAttribute(metadata, attr);
list.add(attr);
}
catch (Exception ignored)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Exception caught from setAttributes(), ignoring attribute " + attr, ignored);
}
}
return list;
}
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/InvokerMBeanServerInterceptorMBean.java 100644 0 0 1145 10513545721 25472 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
/**
* Management interface for the InvokerMBeanServerInterceptor MBean
*
* @version $Revision: 1.6 $
*/
public interface InvokerMBeanServerInterceptorMBean
{
/**
* Returns the type of this interceptor
*/
public String getType();
/**
* This interceptor is always enabled
*/
public boolean isEnabled();
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/InvokerMBeanServerInterceptorMBeanDescription.java 100644 0 0 1754 10513545721 27704 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import mx4j.MBeanDescriptionAdapter;
/**
* Management interface description for the InvokerMBeanServerInterceptor MBean.
*
* @version $Revision: 1.3 $
*/
public class InvokerMBeanServerInterceptorMBeanDescription extends MBeanDescriptionAdapter
{
public String getMBeanDescription()
{
return "The interceptor that invokes on the MBean instance";
}
public String getAttributeDescription(String attribute)
{
if (attribute.equals("Type"))
{
return "The type of this interceptor";
}
if (attribute.equals("Enabled"))
{
return "This interceptor is always enabled and cannot be disabled";
}
return super.getAttributeDescription(attribute);
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/MBeanServerInterceptor.java 100644 0 0 11137 10513545721 23253 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.util.List;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ReflectionException;
import mx4j.server.MBeanMetaData;
/**
* MBeanServer --> MBean interceptor.
* These interceptors are used internally to implement MBeanServer functionality prior to call
* MBeans, and can be used to customize MBeanServer implementation by users.
*
* @version $Revision: 1.6 $
*/
public interface MBeanServerInterceptor
{
/**
* Constant used to specify the status of the MBean registration in {@link #registration}
*/
public static final int PRE_REGISTER = 1;
/**
* Constant used to specify the status of the MBean registration in {@link #registration}
*/
public static final int POST_REGISTER_TRUE = 2;
/**
* Constant used to specify the status of the MBean registration in {@link #registration}
*/
public static final int POST_REGISTER_FALSE = 3;
/**
* Constant used to specify the status of the MBean registration in {@link #registration}
*/
public static final int PRE_DEREGISTER = 4;
/**
* Constant used to specify the status of the MBean registration in {@link #registration}
*/
public static final int POST_DEREGISTER = 5;
/**
* A concise string that tells the type of this interceptor
*/
public String getType();
/**
* Sets the chain of interceptors on this interceptor. This interceptor will use this list to
* find the interceptor in the chain after itself
*
* @param interceptors The list of interceptors
*/
public void setChain(List interceptors);
/**
* Adds the given notification listener to the MBean, along with the given filter and handback
*/
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback);
/**
* Removes the given notification listener from the MBean.
*/
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException;
/**
* Removes the given notification listener from the MBean, specified by the given filter and handback.
*/
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException;
/**
* Instantiate the given className passing the given arguments to the constructor with the given signature
*/
public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException;
/**
* Calls the specified {@link javax.management.MBeanRegistration} method on the MBean instance.
*/
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException;
/**
* Calls getMBeanInfo on the MBean instance (only on DynamicMBeans).
*/
public MBeanInfo getMBeanInfo(MBeanMetaData metadata);
/**
* Invokes the specified MBean operation on the MBean instance
*/
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException;
/**
* Gets the specified attributes values from the MBean instance.
*/
public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes);
/**
* Sets the specified attributes values on the MBean instance.
*/
public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes);
/**
* Gets the specified attribute value from the MBean instance.
*/
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException;
/**
* Sets the specified attribute value on the MBean instance.
*/
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException;
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/MBeanServerInterceptorConfigurator.java 100644 0 0 12062 10513545721 25634 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.util.ArrayList;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import mx4j.ImplementationException;
/**
* MBean that configures the MBeanServer --> MBean interceptor chain.
*
* @version $Revision: 1.9 $
*/
public class MBeanServerInterceptorConfigurator implements MBeanServerInterceptorConfiguratorMBean
{
public static final String OBJECT_NAME = "JMImplementation:type=MBeanServerInterceptorConfigurator";
private final MBeanServer server;
private final ArrayList preInterceptors = new ArrayList();
private final ArrayList postInterceptors = new ArrayList();
private final ArrayList clientInterceptors = new ArrayList();
private volatile boolean running;
private boolean chainModified;
private MBeanServerInterceptor head;
/**
* Creates an instance of this configurator, for the given MBeanServer
*/
public MBeanServerInterceptorConfigurator(MBeanServer server)
{
this.server = server;
chainModified = true;
}
/**
* Appends the given interceptor, provided by the client, to the existing interceptor chain.
*
* @see #registerInterceptor
*/
public void addInterceptor(MBeanServerInterceptor interceptor)
{
synchronized (clientInterceptors)
{
clientInterceptors.add(interceptor);
chainModified = true;
}
}
/**
* Appends the given interceptor, provided by the client, to the existing interceptor chain and registers it as MBean.
*
* @see #addInterceptor
*/
public void registerInterceptor(MBeanServerInterceptor interceptor, ObjectName name) throws MBeanException
{
// First, try register this interceptor. The call will use the old interceptor chain
try
{
server.registerMBean(interceptor, name);
addInterceptor(interceptor);
}
catch (Exception x)
{
throw new MBeanException(x, "Could not register interceptor with name " + name);
}
}
/**
* Removes all the interceptors added via {@link #addInterceptor(MBeanServerInterceptor interceptor)}.
*
* @see #addInterceptor
*/
public void clearInterceptors()
{
synchronized (clientInterceptors)
{
clientInterceptors.clear();
chainModified = true;
}
}
/**
* Adds the given interceptor at the beginning of the interceptor chain, before the custom interceptors that may be added
* via {@link #addInterceptor}.
* This method is called by the MBeanServer during initialization, to configure the interceptors needed to work properly.
*/
public void addPreInterceptor(MBeanServerInterceptor interceptor)
{
if (isRunning()) throw new ImplementationException();
preInterceptors.add(interceptor);
}
/**
* Adds the given interceptor at the end of the interceptor chain, after the custom interceptors that may be added
* via {@link #addInterceptor}.
* This method is called by the MBeanServer during initialization, to configure the interceptors needed to work properly.
*/
public void addPostInterceptor(MBeanServerInterceptor interceptor)
{
if (isRunning()) throw new ImplementationException();
postInterceptors.add(interceptor);
}
/**
* Returns the head interceptor of the interceptor chain.
* The head interceptor is always present.
*/
public MBeanServerInterceptor getHeadInterceptor()
{
if (!isRunning()) return null;
if (chainModified) setupChain();
return head;
}
private void setupChain()
{
chainModified = false;
int size = clientInterceptors.size();
ArrayList chain = new ArrayList(preInterceptors.size() + size + postInterceptors.size());
chain.addAll(preInterceptors);
if (size > 0)
{
synchronized (clientInterceptors)
{
chain.addAll(clientInterceptors);
}
}
chain.addAll(postInterceptors);
// Set the chain on the first interceptor
MBeanServerInterceptor first = (MBeanServerInterceptor)chain.get(0);
first.setChain(chain);
head = first;
}
/**
* Starts this configurator, so that the MBeanServer is now able to accept incoming calls.
*
* @see #stop
* @see #isRunning
*/
public void start()
{
if (!isRunning())
{
running = true;
}
}
/**
* Stops this configurator, so that the MBeanServer is not able to accept incoming calls.
*
* @see #start
*/
public void stop()
{
if (isRunning())
{
running = false;
}
}
/**
* Returns whether this configurator is running and thus if the MBeanServer can accept incoming calls
*
* @see #start
*/
public boolean isRunning()
{
return running;
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/MBeanServerInterceptorConfiguratorMBean.java 100644 0 0 3273 10513545721 26523 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import javax.management.MBeanException;
import javax.management.ObjectName;
/**
* Management interface for the MBeanServerInterceptorConfigurator MBean.
*
* @version $Revision: 1.6 $
*/
public interface MBeanServerInterceptorConfiguratorMBean
{
/**
* Appends the given interceptor, provided by the client, to the existing interceptor chain.
*
* @see #registerInterceptor
*/
public void addInterceptor(MBeanServerInterceptor interceptor);
/**
* Appends the given interceptor, provided by the client, to the existing interceptor chain and registers it as MBean.
*
* @see #addInterceptor
*/
public void registerInterceptor(MBeanServerInterceptor interceptor, ObjectName name) throws MBeanException;
/**
* Removes all the interceptors added via {@link #addInterceptor(MBeanServerInterceptor interceptor)}.
*
* @see #addInterceptor
*/
public void clearInterceptors();
/**
* Starts this configurator, so that the MBeanServer is now able to accept incoming calls.
*
* @see #stop
* @see #isRunning
*/
public void start();
/**
* Stops this configurator, so that the MBeanServer is not able to accept incoming calls.
*
* @see #start
*/
public void stop();
/**
* Returns whether this configurator is running and thus if the MBeanServer can accept incoming calls
*
* @see #start
*/
public boolean isRunning();
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/MBeanServerInterceptorConfiguratorMBeanDescription.java 100644 0 0 10337 10513545721 30746 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import mx4j.MBeanDescriptionAdapter;
/**
* Management interface description for the MBeanServerInterceptorConfigurator MBean.
*
* @version $Revision: 1.3 $
*/
public class MBeanServerInterceptorConfiguratorMBeanDescription extends MBeanDescriptionAdapter
{
public String getMBeanDescription()
{
return "Configurator for MBeanServer to MBean interceptors";
}
public String getConstructorDescription(Constructor ctor)
{
if (ctor.toString().equals("public mx4j.server.interceptor.MBeanServerInterceptorConfigurator(javax.management.MBeanServer)"))
{
return "Creates a new instance of MBeanServer to MBean interceptor configurator";
}
return super.getConstructorDescription(ctor);
}
public String getConstructorParameterName(Constructor ctor, int index)
{
if (ctor.toString().equals("public mx4j.server.interceptor.MBeanServerInterceptorConfigurator(javax.management.MBeanServer)"))
{
switch (index)
{
case 0:
return "server";
}
}
return super.getConstructorParameterName(ctor, index);
}
public String getConstructorParameterDescription(Constructor ctor, int index)
{
if (ctor.toString().equals("public mx4j.server.interceptor.MBeanServerInterceptorConfigurator(javax.management.MBeanServer)"))
{
switch (index)
{
case 0:
return "The MBeanServer that uses this configurator";
}
}
return super.getConstructorParameterDescription(ctor, index);
}
public String getAttributeDescription(String attribute)
{
if (attribute.equals("Running"))
{
return "The running status of the configurator";
}
return super.getAttributeDescription(attribute);
}
public String getOperationDescription(Method operation)
{
String name = operation.getName();
if (name.equals("addInterceptor"))
{
return "Appends an interceptor to the interceptor chain";
}
if (name.equals("registerInterceptor"))
{
return "Appends an MBean interceptor to the interceptor chain and registers it";
}
if (name.equals("clearInterceptors"))
{
return "Removes all the interceptors added via addInterceptor(MBeanServerInterceptor interceptor)";
}
if (name.equals("start"))
{
return "Starts the configurator so that the MBeanServer can accept incoming calls";
}
if (name.equals("stop"))
{
return "Stops the configurator so that the MBeanServer cannot accept incoming calls";
}
return super.getOperationDescription(operation);
}
public String getOperationParameterName(Method method, int index)
{
String name = method.getName();
if (name.equals("addInterceptor"))
{
switch (index)
{
case 0:
return "interceptor";
}
}
if (name.equals("registerInterceptor"))
{
switch (index)
{
case 0:
return "interceptor";
case 1:
return "name";
}
}
return super.getOperationParameterName(method, index);
}
public String getOperationParameterDescription(Method method, int index)
{
String name = method.getName();
if (name.equals("addInterceptor"))
{
switch (index)
{
case 0:
return "The interceptor to be appended to the interceptor chain";
}
}
if (name.equals("registerInterceptor"))
{
switch (index)
{
case 0:
return "The interceptor to be appended to the interceptor chain";
case 1:
return "The ObjectName under which register the interceptor";
}
}
return super.getOperationParameterDescription(method, index);
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/NotificationListenerMBeanServerInterceptor.java 100644 0 0 22602 10513545721 27327 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import mx4j.server.MBeanMetaData;
/**
* Interceptor that takes care of replacing the source of Notifications to the
* ObjectName of the NotificationBroadcaster that emitted it.
*
* @version $Revision: 1.14 $
*/
public class NotificationListenerMBeanServerInterceptor extends DefaultMBeanServerInterceptor
{
private final Map wrappers = new HashMap();
private final Map objectNames = new HashMap();
public String getType()
{
return "notificationlistener";
}
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
if (isEnabled())
{
ListenerWrapper wrapper = null;
synchronized (wrappers)
{
ListenerWrapperKey key = new ListenerWrapperKey(listener, metadata.getObjectName());
wrapper = (ListenerWrapper)wrappers.get(key);
if (wrapper == null)
{
wrapper = new ListenerWrapper(listener, metadata.getObjectName());
wrappers.put(key, wrapper);
wrapper.increaseReferenceCount();
}
else
{
// In case the listener is added twice to the same MBean,
// for example with different handbacks or filters
wrapper.increaseReferenceCount();
}
Set keys = (Set)objectNames.get(metadata.getObjectName());
if (keys == null)
{
// The MBean has no listeners
keys = new HashSet();
objectNames.put(metadata.getObjectName(), keys);
keys.add(key);
}
else
{
// The MBean has other listeners; in case the same listener
// is added twice to the same MBean, for example with different
// handback or filters, the Set semantic will retain the key only once.
keys.add(key);
}
}
super.addNotificationListener(metadata, wrapper, filter, handback);
}
else
{
super.addNotificationListener(metadata, listener, filter, handback);
}
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException
{
if (isEnabled())
{
ListenerWrapper wrapper = null;
synchronized (wrappers)
{
ListenerWrapperKey key = new ListenerWrapperKey(listener, metadata.getObjectName());
wrapper = (ListenerWrapper)wrappers.remove(key);
if (wrapper == null) throw new ListenerNotFoundException("Could not find listener " + listener);
wrapper.resetReferenceCount();
Set keys = (Set)objectNames.get(metadata.getObjectName());
keys.remove(key);
if (keys.isEmpty()) objectNames.remove(metadata.getObjectName());
}
super.removeNotificationListener(metadata, wrapper);
}
else
{
super.removeNotificationListener(metadata, listener);
}
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
if (isEnabled())
{
ListenerWrapper wrapper = null;
synchronized (wrappers)
{
ListenerWrapperKey key = new ListenerWrapperKey(listener, metadata.getObjectName());
wrapper = (ListenerWrapper)wrappers.get(key);
if (wrapper == null) throw new ListenerNotFoundException("Could not find listener " + listener);
wrapper.decreaseReferenceCount();
if (wrapper.getReferenceCount() == 0)
{
wrappers.remove(key);
Set keys = (Set)objectNames.get(metadata.getObjectName());
keys.remove(key);
if (keys.isEmpty()) objectNames.remove(metadata.getObjectName());
}
}
super.removeNotificationListener(metadata, wrapper, filter, handback);
}
else
{
super.removeNotificationListener(metadata, listener, filter, handback);
}
}
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException
{
if (isEnabled())
{
if (operation == POST_DEREGISTER)
{
// We must clean up in case the MBean is unregistered
// and the listeners are not removed
synchronized (wrappers)
{
Set keys = (Set)objectNames.remove(metadata.getObjectName());
if (keys != null)
{
for (Iterator iterator = keys.iterator(); iterator.hasNext();)
{
ListenerWrapperKey key = (ListenerWrapperKey)iterator.next();
ListenerWrapper wrapper = (ListenerWrapper)wrappers.remove(key);
wrapper.resetReferenceCount();
}
}
}
}
super.registration(metadata, operation);
}
else
{
super.registration(metadata, operation);
}
}
public Map getNotificationListenerWrappers()
{
return wrappers;
}
public int getNotificationListenerWrapperReferenceCount(Object wrapper)
{
ListenerWrapper listenerWrapper = (ListenerWrapper)wrapper;
return listenerWrapper.getReferenceCount();
}
public Map getObjectNames()
{
return objectNames;
}
private static class ListenerWrapper implements NotificationListener
{
private final NotificationListener listener;
private final ObjectName objectName;
private int referenceCount;
private ListenerWrapper(NotificationListener listener, ObjectName name)
{
this.listener = listener;
this.objectName = name;
}
public void handleNotification(Notification notification, Object handback)
{
// The JMX spec does not specify how to change the source to be the ObjectName
// of the broadcaster. If we serialize the calls to the listeners, then it's
// possible to change the source and restore it back to the old value before
// calling the next listener; but if we want to support concurrent calls
// to the listeners, this is not possible. Here I chose to support concurrent
// calls so I change the value once and I never restore it.
Object src = notification.getSource();
if (!(src instanceof ObjectName))
{
// Change the source to be the ObjectName of the notification broadcaster
// if we are not already an ObjectName (compliant with RI behaviour)
notification.setSource(objectName);
}
// Notify the real listener
NotificationListener listener = getTargetListener();
listener.handleNotification(notification, handback);
}
private NotificationListener getTargetListener()
{
return listener;
}
private int increaseReferenceCount()
{
return ++referenceCount;
}
private int decreaseReferenceCount()
{
return --referenceCount;
}
public void resetReferenceCount()
{
referenceCount = 0;
}
private int getReferenceCount()
{
return referenceCount;
}
public int hashCode()
{
return getTargetListener().hashCode();
}
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final ListenerWrapper wrapper = (ListenerWrapper)obj;
return getTargetListener().equals(wrapper.getTargetListener());
}
public String toString()
{
return getTargetListener().toString();
}
}
private static class ListenerWrapperKey
{
private final NotificationListener listener;
private final ObjectName objectName;
private ListenerWrapperKey(NotificationListener listener, ObjectName objectName)
{
this.listener = listener;
this.objectName = objectName;
}
public ObjectName getObjectName()
{
return objectName;
}
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final ListenerWrapperKey that = (ListenerWrapperKey)obj;
if (!listener.equals(that.listener)) return false;
return objectName.equals(that.objectName);
}
public int hashCode()
{
int result = listener.hashCode();
result = 29 * result + objectName.hashCode();
return result;
}
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/SecurityMBeanServerInterceptor.java 100644 0 0 16706 10513545721 25012 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanPermission;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanTrustPermission;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import mx4j.server.MBeanMetaData;
/**
* Interceptor that takes care of performing security checks (in case the SecurityManager is installed) for
* MBeanServer to MBean calls.
*
* @version $Revision: 1.14 $
*/
public class SecurityMBeanServerInterceptor extends DefaultMBeanServerInterceptor implements SecurityMBeanServerInterceptorMBean
{
public String getType()
{
return "security";
}
public boolean isEnabled()
{
return true;
}
public void addNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "addNotificationListener");
super.addNotificationListener(metadata, listener, filter, handback);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener) throws ListenerNotFoundException
{
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "removeNotificationListener");
super.removeNotificationListener(metadata, listener);
}
public void removeNotificationListener(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException
{
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "removeNotificationListener");
super.removeNotificationListener(metadata, listener, filter, handback);
}
public void instantiate(MBeanMetaData metadata, String className, String[] params, Object[] args) throws ReflectionException, MBeanException
{
checkPermission(className, null, metadata.getObjectName(), "instantiate");
super.instantiate(metadata, className, params, args);
}
public MBeanInfo getMBeanInfo(MBeanMetaData metadata)
{
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "getMBeanInfo");
return super.getMBeanInfo(metadata);
}
public Object invoke(MBeanMetaData metadata, String method, String[] params, Object[] args) throws MBeanException, ReflectionException
{
checkPermission(metadata.getMBeanInfo().getClassName(), method, metadata.getObjectName(), "invoke");
return super.invoke(metadata, method, params, args);
}
public AttributeList getAttributes(MBeanMetaData metadata, String[] attributes)
{
Object[] secured = filterAttributes(metadata.getMBeanInfo().getClassName(), metadata.getObjectName(), attributes, true);
String[] array = new String[secured.length];
for (int i = 0; i < array.length; ++i) array[i] = (String)secured[i];
return super.getAttributes(metadata, array);
}
public AttributeList setAttributes(MBeanMetaData metadata, AttributeList attributes)
{
Object[] secured = filterAttributes(metadata.getMBeanInfo().getClassName(), metadata.getObjectName(), attributes.toArray(), false);
AttributeList list = new AttributeList();
for (int i = 0; i < secured.length; ++i) list.add(secured[i]);
return super.setAttributes(metadata, list);
}
public Object getAttribute(MBeanMetaData metadata, String attribute) throws MBeanException, AttributeNotFoundException, ReflectionException
{
checkPermission(metadata.getMBeanInfo().getClassName(), attribute, metadata.getObjectName(), "getAttribute");
return super.getAttribute(metadata, attribute);
}
public void setAttribute(MBeanMetaData metadata, Attribute attribute) throws MBeanException, AttributeNotFoundException, InvalidAttributeValueException, ReflectionException
{
checkPermission(metadata.getMBeanInfo().getClassName(), attribute.getName(), metadata.getObjectName(), "setAttribute");
super.setAttribute(metadata, attribute);
}
public void registration(MBeanMetaData metadata, int operation) throws MBeanRegistrationException
{
switch (operation)
{
case PRE_REGISTER:
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "registerMBean");
checkTrustRegistration(metadata.getMBean().getClass());
break;
case POST_REGISTER_TRUE:
// The MBean can implement MBeanRegistration and change the ObjectName
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "registerMBean");
break;
case PRE_DEREGISTER:
checkPermission(metadata.getMBeanInfo().getClassName(), null, metadata.getObjectName(), "unregisterMBean");
break;
default:
break;
}
super.registration(metadata, operation);
}
private void checkPermission(String className, String methodName, ObjectName objectname, String action)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission(className, methodName, objectname, action));
}
}
private void checkTrustRegistration(final Class cls)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
ProtectionDomain domain = (ProtectionDomain)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return cls.getProtectionDomain();
}
});
MBeanTrustPermission permission = new MBeanTrustPermission("register");
if (!domain.implies(permission))
{
throw new AccessControlException("Access denied " + permission + ": MBean class " + cls.getName() + " is not trusted for registration");
}
}
}
private Object[] filterAttributes(String className, ObjectName objectName, Object[] attributes, boolean isGet)
{
SecurityManager sm = System.getSecurityManager();
if (sm == null) return attributes;
ArrayList list = new ArrayList();
for (int i = 0; i < attributes.length; ++i)
{
Object attribute = attributes[i];
String name = isGet ? (String)attribute : ((Attribute)attribute).getName();
try
{
checkPermission(className, name, objectName, isGet ? "getAttribute" : "setAttribute");
list.add(attribute);
}
catch (SecurityException ignore)
{
// This is ok. We just don't add this attribute to the list
}
}
return list.toArray();
}
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/SecurityMBeanServerInterceptorMBean.java 100644 0 0 1147 10513545721 25666 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
/**
* Management interface for the SecurityMBeanServerInterceptor MBean
*
* @version $Revision: 1.3 $
*/
public interface SecurityMBeanServerInterceptorMBean
{
/**
* Returns the type of this interceptor
*/
public String getType();
/**
* This interceptor is always enabled
*/
public boolean isEnabled();
}
mx4j-3.0.2/src/core/mx4j/server/interceptor/SecurityMBeanServerInterceptorMBeanDescription.java 100644 0 0 2010 10513545721 30060 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.server.interceptor;
import mx4j.MBeanDescriptionAdapter;
/**
* Management interface description for the SecurityMBeanServerInterceptor MBean.
*
* @version $Revision: 1.3 $
*/
public class SecurityMBeanServerInterceptorMBeanDescription extends MBeanDescriptionAdapter
{
public String getMBeanDescription()
{
return "The interceptor that performs security checks for MBeanServer to MBean calls";
}
public String getAttributeDescription(String attribute)
{
if (attribute.equals("Type"))
{
return "The type of this interceptor";
}
if (attribute.equals("Enabled"))
{
return "This interceptor is always enabled and cannot be disabled";
}
return super.getAttributeDescription(attribute);
}
}
mx4j-3.0.2/src/core/mx4j/timer/TimeQueue.java 100644 0 0 13165 10513545721 16045 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.timer;
import java.util.ArrayList;
import java.util.Collections;
/**
* A queue that executes {@link mx4j.timer.TimeTask}s when it is started.
* Every scheduled task is executed at the specified time; if this time is in the past,
* the task is executed immediately.
* Just before the task is executed, the task itself is updated so that its new
* execution time is set or it is marked as finished (if it is not forever periodic).
*
* @version $Revision: 1.5 $
* @see mx4j.timer.TimeTask
*/
public class TimeQueue
{
private Thread thread;
private volatile boolean running;
private final ArrayList tasks;
private final boolean daemon;
/**
* Creates a new TimeQueue
*/
public TimeQueue()
{
this(false);
}
/**
* Creates a new TimeQueue that will set the thread daemon or not depending on the given argument
*/
public TimeQueue(boolean daemon)
{
tasks = new ArrayList();
this.daemon = daemon;
}
/**
* Starts this TimeQueue.
* Tasks are executed only after the queue has been started.
*
* @see #stop
*/
public void start()
{
synchronized (this)
{
if (!running)
{
running = true;
thread = new Thread(new Loop(), "MBean Timer Notification Thread");
thread.setDaemon(daemon);
thread.start();
}
}
}
/**
* Stops this TimeQueue.
* No task is executed when the queue is stopped; however, already scheduled tasks
* are not removed; restarting the queue has the effect of executing the tasks remained
* if their time has come.
*
* @see #start
*/
public void stop()
{
synchronized (this)
{
if (running)
{
running = false;
thread.interrupt();
}
}
}
/**
* Returns the number of tasks present in this TimeQueue
*/
public int size()
{
synchronized (this)
{
return tasks.size();
}
}
/**
* Schedules the given task for execution.
*
* @see #unschedule
*/
public void schedule(TimeTask task)
{
synchronized (this)
{
tasks.add(task);
// Using tree sets or maps does not work, since they don't rely on equals for add, but on compareTo
Collections.sort(tasks);
notifyAll();
}
}
/**
* Removes the given task from this TimeQueue
*
* @see #schedule
*/
public void unschedule(TimeTask task)
{
synchronized (this)
{
tasks.remove(task);
}
}
/**
* Removes all the tasks from this TimeQueue.
*/
public void clear()
{
synchronized (this)
{
tasks.clear();
}
}
private TimeTask getTask() throws InterruptedException
{
synchronized (this)
{
while (tasks.isEmpty())
{
wait();
}
// Do not remove the task from the queue
TimeTask task = (TimeTask)tasks.get(0);
return task;
}
}
private class Loop implements Runnable
{
public void run()
{
while (running && !thread.isInterrupted())
{
try
{
TimeTask task = getTask();
long now = System.currentTimeMillis();
long executionTime = task.getNextExecutionTime();
if (executionTime == 0L) executionTime = now;
long timeToWait = executionTime - now;
boolean runTask = timeToWait <= 0;
if (!runTask)
{
// When a new job is scheduled, I wake up, but this job may not be the one to run
Object lock = TimeQueue.this;
synchronized (lock)
{
// timeToWait is always strictly > 0, so I don't wait forever
lock.wait(timeToWait);
}
}
else
{
// The task must be run, remove it from the list
unschedule(task);
if (task.isPeriodic())
{
// Compute the new execution time. This is different for
// fixed rate and fixed delay tasks
if (task.getFixedRate())
{
task.setNextExecutionTime(executionTime + task.getPeriod());
}
else
{
task.setNextExecutionTime(now + task.getPeriod());
}
// Reschedule on the new time
schedule(task);
}
else
{
// Mark the task as finished, it will be removed also by the Timer class
task.setFinished(true);
}
try
{
// Run it !
task.run();
}
catch (Throwable x)
{
// Problems, for now just print it
x.printStackTrace();
}
}
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
break;
}
}
}
}
}
mx4j-3.0.2/src/core/mx4j/timer/TimeTask.java 100644 0 0 5024 10513545721 15636 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.timer;
/**
* A task that is executed at a specified time.
* Subclasses implement the periodicity, if needed.
* Two TimeTasks are compared with their neext execution time.
*
* @version $Revision: 1.3 $
*/
public abstract class TimeTask implements Comparable, Runnable
{
private long executionTime;
private boolean finished;
/**
* Constructor for subclasses
*/
protected TimeTask()
{
}
/**
* The method to implement to have this TimeTask to do something.
*/
public abstract void run();
/**
* Returns whether this task is periodic. By default return false.
*
* @see #getPeriod
*/
protected boolean isPeriodic()
{
return false;
}
/**
* Returns the period of this task. By default returns 0.
*
* @see #isPeriodic
*/
protected long getPeriod()
{
return 0;
}
/**
* Returns whether this task is a fixed rate or fixed delay task. By default
* return false
*/
public boolean getFixedRate()
{
return false;
}
/**
* Returns the next time at which the task will be executed, ie the {@link #run} method is called.
*
* @see #setNextExecutionTime
*/
protected long getNextExecutionTime()
{
return executionTime;
}
/**
* Sets the next execution time.
*
* @see #getNextExecutionTime
*/
protected void setNextExecutionTime(long time)
{
executionTime = time;
}
/**
* Marks this task as finished or not. When a task is finished, its
* {@link #run} method will not be called anymore.
*
* @see #isFinished
*/
protected void setFinished(boolean value)
{
finished = value;
}
/**
* Returns whethere this task is finished.
*
* @see #setFinished
*/
protected boolean isFinished()
{
return finished;
}
/**
* Compares 2 TimeTasks by comparing their next execution times
*
* @see #getNextExecutionTime
*/
public int compareTo(Object obj)
{
if (obj == null) return 1;
if (obj == this) return 0;
TimeTask other = (TimeTask)obj;
long et = getNextExecutionTime();
long oet = other.getNextExecutionTime();
if (et > oet)
return 1;
else if (et < oet) return -1;
return 0;
}
}
mx4j-3.0.2/src/core/mx4j/timer/TimerTask.java 100644 0 0 5220 10513545721 16016 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.timer;
import java.util.Date;
import javax.management.timer.TimerNotification;
/**
* A subclass of TimeTask for the JMX Timer service.
*
* @version $Revision: 1.8 $
*/
public abstract class TimerTask extends TimeTask
{
private TimerNotification m_notification;
private long m_date;
private long m_period;
private long m_occurrences;
private long m_initialOccurrences;
private int m_hash;
private boolean m_fixedRate;
public TimerTask(TimerNotification n, Date date, long period, long occurrences, boolean fixedRate)
{
m_notification = n;
m_date = date.getTime();
m_period = period;
m_occurrences = occurrences;
m_initialOccurrences = occurrences;
m_fixedRate = fixedRate;
// Pre calculate hash code so that it does not reflect the fact that occurrences decrease
m_hash = new Long(getDate()).hashCode() ^ new Long(getPeriod()).hashCode() ^ new Long(getInitialOccurrences()).hashCode();
setNextExecutionTime(getDate());
}
public TimerNotification getNotification()
{
return m_notification;
}
public boolean isFinished()
{
return super.isFinished();
}
public void setFinished(boolean value)
{
super.setFinished(value);
}
public long getPeriod()
{
return m_period;
}
public boolean isPeriodic()
{
boolean periodic = getPeriod() > 0 && (getInitialOccurrences() == 0 || getOccurrences() > 0);
return periodic;
}
public long getNextExecutionTime()
{
return super.getNextExecutionTime();
}
public void setNextExecutionTime(long time)
{
super.setNextExecutionTime(time);
--m_occurrences;
}
public int hashCode()
{
return m_hash;
}
public boolean equals(Object obj)
{
if (obj == null) return false;
if (obj == this) return true;
try
{
TimerTask other = (TimerTask)obj;
return getDate() == other.getDate() && getPeriod() == other.getPeriod() && getInitialOccurrences() == other.getInitialOccurrences();
}
catch (ClassCastException x)
{
return false;
}
}
public long getOccurrences()
{
return m_occurrences;
}
private long getInitialOccurrences()
{
return m_initialOccurrences;
}
public long getDate()
{
return m_date;
}
public boolean getFixedRate()
{
return m_fixedRate;
}
}
mx4j-3.0.2/src/core/mx4j/util/Base64Codec.java 100644 0 0 25347 10513545721 15766 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.util;
/**
* This class is copy/paste of Jakarta's Commons-Codec v1.1 org.apache.commons.codec.binary.Base64
* implementation.
* It is reproduced here because we don't want to require a new jar just to perform Base64 code/decoding.
*
* @version $Revision: 1.3 $
*/
public class Base64Codec
{
static final int CHUNK_SIZE = 76;
static final byte[] CHUNK_SEPARATOR = "\n".getBytes();
static final int BASELENGTH = 255;
static final int LOOKUPLENGTH = 64;
static final int TWENTYFOURBITGROUP = 24;
static final int EIGHTBIT = 8;
static final int SIXTEENBIT = 16;
static final int SIXBIT = 6;
static final int FOURBYTE = 4;
static final int SIGN = -128;
static final byte PAD = (byte)'=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; i++)
{
base64Alphabet[i] = (byte)-1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
base64Alphabet[i] = (byte)(i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
base64Alphabet[i] = (byte)(i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
base64Alphabet[i] = (byte)(i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
lookUpBase64Alphabet[i] = (byte)('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
lookUpBase64Alphabet[i] = (byte)('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
lookUpBase64Alphabet[i] = (byte)('0' + j);
}
lookUpBase64Alphabet[62] = (byte)'+';
lookUpBase64Alphabet[63] = (byte)'/';
}
private Base64Codec()
{
}
public static boolean isArrayByteBase64(byte[] arrayOctect)
{
arrayOctect = discardWhitespace(arrayOctect);
int length = arrayOctect.length;
if (length == 0)
{
return true;
}
for (int i = 0; i < length; i++)
{
if (!isBase64(arrayOctect[i]))
{
return false;
}
}
return true;
}
public static byte[] encodeBase64(byte[] binaryData)
{
return (encodeBase64(binaryData, false));
}
public static byte[] decodeBase64(byte[] base64Data)
{
// RFC 2045 suggests line wrapping at (no more than) 76
// characters -- we may have embedded whitespace.
base64Data = discardWhitespace(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0)
{
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD)
{
if (--lastData == 0)
{
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++)
{
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD)
{
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte)(b3 << 6 | b4);
}
else if (marker0 == PAD)
{
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
}
else if (marker1 == PAD)
{
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
private static byte[] encodeBase64Chunked(byte[] binaryData)
{
return (encodeBase64(binaryData, true));
}
private static boolean isBase64(byte octect)
{
if (octect == PAD)
{
return true;
}
else if (base64Alphabet[octect] == -1)
{
return false;
}
else
{
return true;
}
}
private static byte[] encodeBase64(byte[] binaryData, boolean isChunked)
{
int lengthDataBits = binaryData.length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
byte encodedData[] = null;
int encodedDataLength = 0;
int nbrChunks = 0;
if (fewerThan24bits != 0)
{
//data not divisible by 24 bit
encodedDataLength = (numberTriplets + 1) * 4;
}
else
{
// 16 or 8 bit
encodedDataLength = numberTriplets * 4;
}
// If the output is to be "chunked" into 76 character sections,
// for compliance with RFC 2045 MIME, then it is important to
// allow for extra length to account for the separator(s)
if (isChunked)
{
nbrChunks =
(CHUNK_SEPARATOR.length == 0
? 0
: (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE));
encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
}
encodedData = new byte[encodedDataLength];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
int nextSeparatorIndex = CHUNK_SIZE;
int chunksSoFar = 0;
//log.debug("number of triplets = " + numberTriplets);
for (i = 0; i < numberTriplets; i++)
{
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
//log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
l = (byte)(b2 & 0x0f);
k = (byte)(b1 & 0x03);
byte val1 =
((b1 & SIGN) == 0)
? (byte)(b1 >> 2)
: (byte)((b1) >> 2 ^ 0xc0);
byte val2 =
((b2 & SIGN) == 0)
? (byte)(b2 >> 4)
: (byte)((b2) >> 4 ^ 0xf0);
byte val3 =
((b3 & SIGN) == 0)
? (byte)(b3 >> 6)
: (byte)((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
//log.debug( "val2 = " + val2 );
//log.debug( "k4 = " + (k<<4) );
//log.debug( "vak = " + (val2 | (k<<4)) );
encodedData[encodedIndex + 1] =
lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] =
lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
encodedIndex += 4;
// If we are chunking, let's put a chunk separator down.
if (isChunked)
{
// this assumes that CHUNK_SIZE % 4 == 0
if (encodedIndex == nextSeparatorIndex)
{
System.arraycopy(CHUNK_SEPARATOR,
0,
encodedData,
encodedIndex,
CHUNK_SEPARATOR.length);
chunksSoFar++;
nextSeparatorIndex =
(CHUNK_SIZE * (chunksSoFar + 1))
+ (chunksSoFar * CHUNK_SEPARATOR.length);
encodedIndex += CHUNK_SEPARATOR.length;
}
}
}
// form integral number of 6-bit groups
dataIndex = i * 3;
if (fewerThan24bits == EIGHTBIT)
{
b1 = binaryData[dataIndex];
k = (byte)(b1 & 0x03);
//log.debug("b1=" + b1);
//log.debug("b1<<2 = " + (b1>>2) );
byte val1 =
((b1 & SIGN) == 0)
? (byte)(b1 >> 2)
: (byte)((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte)(b2 & 0x0f);
k = (byte)(b1 & 0x03);
byte val1 =
((b1 & SIGN) == 0)
? (byte)(b1 >> 2)
: (byte)((b1) >> 2 ^ 0xc0);
byte val2 =
((b2 & SIGN) == 0)
? (byte)(b2 >> 4)
: (byte)((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] =
lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
if (isChunked)
{
// we also add a separator to the end of the final chunk.
if (chunksSoFar < nbrChunks)
{
System.arraycopy(CHUNK_SEPARATOR,
0,
encodedData,
encodedDataLength - CHUNK_SEPARATOR.length,
CHUNK_SEPARATOR.length);
}
}
return encodedData;
}
private static byte[] discardWhitespace(byte[] data)
{
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++)
{
switch (data[i])
{
case (byte)' ':
case (byte)'\n':
case (byte)'\r':
case (byte)'\t':
break;
default:
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
}
mx4j-3.0.2/src/core/mx4j/util/MethodTernaryTree.java 100644 0 0 13637 10513545721 17410 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.util;
/**
* Specialized ternary tree for method metadata information.
* In JMX methods are referred to with the method name and the String[] representing the signature.
* One can decide to cache method information using as key a concatenation of method name + signature,
* but the cost of concatenation is very high, while hashmap access is fast.
* Ternary trees avoid string concatenation, and result to be 10x faster than concatenation + hashmap.
* However, the signature of a standard TernaryTree would be Object get(Object[] key)
and
* void put(Object[] key, Object value)
. Unfortunately normalizing method name + signature
* into a single array is also very expensive.
* This version leaves method name and signature separated to have the fastest access possible to
* method information.
* See here for further information
* on TernaryTrees.
*
* @version $Revision: 1.3 $
*/
public class MethodTernaryTree
{
private Node m_root;
/**
* Returns the method information given the method name and its signature.
*
* @see #put
*/
public Object get(String methodName, String[] signature)
{
if (signature == null)
{
throw new IllegalArgumentException();
}
return search(methodName, signature);
}
/**
* Inserts in this TernaryTree the given method information, using as key the method name and its signature
*
* @see #get
*/
public void put(String methodName, String[] signature, Object information)
{
if (signature == null)
{
throw new IllegalArgumentException();
}
m_root = insert(m_root, methodName, signature, signature.length, information);
}
private Object search(String methodName, String[] signature)
{
Node node = m_root;
int index = 0;
while (node != null)
{
Object key = index == 0 ? methodName : signature[index - 1];
if (key == null)
{
throw new IllegalArgumentException();
}
int split = splitFunction(key);
if (split < node.splitValue)
{
node = node.left;
}
else if (split == node.splitValue)
{
if (index == signature.length)
{
// Two objects may return the same split, because the splitFunction is not perfect
// (ie does not always yield different values for different objects, eg hash functions)
if (node.keys == null)
{
return null;
}
for (int i = 0; i < node.keys.length; ++i)
{
if (node.keys[i].equals(key))
{
return node.values[i];
}
}
return null;
}
else
{
++index;
node = node.middle;
}
}
else
{
node = node.right;
}
}
return null;
}
private Node insert(Node node, String methodName, String[] signature, int length, Object value)
{
Object key = methodName;
if (key == null)
{
throw new IllegalArgumentException();
}
int split = splitFunction(key);
if (node == null)
{
node = new Node();
node.splitValue = split;
}
if (split < node.splitValue)
{
node.left = insert(node.left, methodName, signature, length, value);
}
else if (split == node.splitValue)
{
// Two objects may return the same split, because the splitFunction is not perfect
// (ie does not always yield different values for different objects, eg hash functions)
if (length == 0)
{
if (node.keys == null)
{
node.keys = new Object[1];
node.values = new Object[1];
node.keys[0] = key;
node.values[0] = value;
}
else
{
// Loop to see if the key already exists
boolean found = false;
for (int i = 0; i < node.keys.length; ++i)
{
if (node.keys[i].equals(key))
{
// Already present, replace the value
node.keys[i] = key;
node.values[i] = value;
found = true;
break;
}
}
// Not present, add it
if (!found)
{
int len = node.keys.length;
Object[] olds = node.keys;
node.keys = new Object[len + 1];
System.arraycopy(olds, 0, node.keys, 0, len);
node.keys[len] = key;
olds = node.values;
node.values = new Object[len + 1];
System.arraycopy(olds, 0, node.values, 0, len);
node.values[len] = value;
}
}
}
else
{
node.middle = insert(node.middle, signature[signature.length - length], signature, length - 1, value);
}
}
else
{
node.right = insert(node.right, methodName, signature, length, value);
}
return node;
}
protected int splitFunction(Object obj)
{
return obj.hashCode();
}
private class Node
{
private int splitValue;
private Node right;
private Node middle;
private Node left;
private Object[] keys;
private Object[] values;
}
}
mx4j-3.0.2/src/core/mx4j/util/Utils.java 100644 0 0 20031 10513545721 15065 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
package mx4j.util;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
/**
* Several utility functions for the JMX implementation
*
* @version $Revision: 1.18 $
*/
public class Utils
{
/**
* This methods load a class given the classloader and the name of the class, and work for
* extended names of primitive types.
* If you try to do ClassLoader.loadClass("boolean") it barfs it cannot find the class,
* so this method cope with this problem.
*/
public static Class loadClass(ClassLoader loader, String name) throws ClassNotFoundException
{
if (name == null) throw new ClassNotFoundException("null");
name = name.trim();
if (name.equals("boolean"))
return boolean.class;
else if (name.equals("byte"))
return byte.class;
else if (name.equals("char"))
return char.class;
else if (name.equals("short"))
return short.class;
else if (name.equals("int"))
return int.class;
else if (name.equals("long"))
return long.class;
else if (name.equals("float"))
return float.class;
else if (name.equals("double"))
return double.class;
else if (name.equals("java.lang.String"))
return String.class;
else if (name.equals("java.lang.Object"))
return Object.class;
else if (name.startsWith("["))
{
// It's an array, figure out how many dimensions
int dimension = 0;
while (name.charAt(dimension) == '[')
{
++dimension;
}
char type = name.charAt(dimension);
Class cls = null;
switch (type)
{
case 'Z':
cls = boolean.class;
break;
case 'B':
cls = byte.class;
break;
case 'C':
cls = char.class;
break;
case 'S':
cls = short.class;
break;
case 'I':
cls = int.class;
break;
case 'J':
cls = long.class;
break;
case 'F':
cls = float.class;
break;
case 'D':
cls = double.class;
break;
case 'L':
// Strip the semicolon at the end
String n = name.substring(dimension + 1, name.length() - 1);
cls = loadClass(loader, n);
break;
}
if (cls == null)
{
throw new ClassNotFoundException(name);
}
else
{
int[] dim = new int[dimension];
return Array.newInstance(cls, dim).getClass();
}
}
else
{
if (loader != null)
return loader.loadClass(name);
else
return Class.forName(name, false, null);
}
}
/**
* Returns the classes whose names are specified by the names
argument, loaded with the
* specified classloader.
*/
public static Class[] loadClasses(ClassLoader loader, String[] names) throws ClassNotFoundException
{
int n = names.length;
Class[] cls = new Class[n];
for (int i = 0; i < n; ++i)
{
String name = names[i];
cls[i] = loadClass(loader, name);
}
return cls;
}
/**
* Returns true is the given method is a JMX attribute getter method
*/
public static boolean isAttributeGetter(Method m)
{
if (m == null) return false;
String name = m.getName();
Class retType = m.getReturnType();
Class[] params = m.getParameterTypes();
if (retType != Void.TYPE && params.length == 0)
{
if (name.startsWith("get") && name.length() > 3)
return true;
else if (name.startsWith("is") && name.length() > 2 && retType == Boolean.TYPE) return true;
}
return false;
}
/**
* Returns true if the method is a JMX attribute setter method
*/
public static boolean isAttributeSetter(Method m)
{
if (m == null) return false;
String name = m.getName();
Class retType = m.getReturnType();
Class[] params = m.getParameterTypes();
if (retType == Void.TYPE && params.length == 1 && name.startsWith("set") && name.length() > 3)
{
return true;
}
return false;
}
public static boolean wildcardMatch(String pattern, String string)
{
int stringLength = string.length();
int stringIndex = 0;
for (int patternIndex = 0; patternIndex < pattern.length(); ++patternIndex)
{
char c = pattern.charAt(patternIndex);
if (c == '*')
{
// Recurse with the pattern without this '*' and the actual string, until
// match is found or we inspected the whole string
while (stringIndex < stringLength)
{
if (wildcardMatch(pattern.substring(patternIndex + 1), string.substring(stringIndex)))
{
return true;
}
// No match found, try a shorter string, since we are matching '*'
++stringIndex;
}
}
else if (c == '?')
{
// Increment the string index, since '?' match a single char in the string
++stringIndex;
if (stringIndex > stringLength)
{
return false;
}
}
else
{
// A normal character in the pattern, must match the one in the string
if (stringIndex >= stringLength || c != string.charAt(stringIndex))
{
return false;
}
++stringIndex;
}
}
// I've inspected the whole pattern, but not the whole string
return stringIndex == stringLength;
}
public static boolean arrayEquals(Object[] arr1, Object[] arr2)
{
if (arr1 == null && arr2 == null) return true;
if (arr1 == null ^ arr2 == null) return false;
if (!arr1.getClass().equals(arr2.getClass())) return false;
if (arr1.length != arr2.length) return false;
for (int i = 0; i < arr1.length; ++i)
{
Object obj1 = arr1[i];
Object obj2 = arr2[i];
if (obj1 == null ^ obj2 == null) return false;
if (obj1 != null && !obj1.equals(obj2)) return false;
}
return true;
}
public static boolean arrayEquals(byte[] arr1, byte[] arr2)
{
if (arr1 == null && arr2 == null) return true;
if (arr1 == null ^ arr2 == null) return false;
if (!arr1.getClass().equals(arr2.getClass())) return false;
if (arr1.length != arr2.length) return false;
for (int i = 0; i < arr1.length; ++i)
{
byte b1 = arr1[i];
byte b2 = arr2[i];
if (b1 != b2) return false;
}
return true;
}
public static int arrayHashCode(Object[] arr)
{
int hash = 0;
if (arr != null)
{
// Avoid that 2 arrays of length 0 but different classes return same hash
hash ^= arr.getClass().hashCode();
for (int i = 0; i < arr.length; ++i)
{
hash ^= arr[i] == null ? 0 : arr[i].hashCode();
}
}
return hash;
}
public static int arrayHashCode(byte[] arr)
{
int hash = 0;
if (arr != null)
{
// Avoid that 2 arrays of length 0 but different classes return same hash
hash ^= arr.getClass().hashCode();
for (int i = 0; i < arr.length; ++i)
{
hash ^= arr[i];
}
}
return hash;
}
public static char[] arrayCopy(char[] chars)
{
if (chars == null) return null;
char[] copy = new char[chars.length];
System.arraycopy(chars, 0, copy, 0, chars.length);
return copy;
}
}
mx4j-3.0.2/src/docs/english/dev-guide.xml 100644 0 0 33216 10513545721 15320 0 ustar 0 0
Introduction
This chapter aims to give some suggestion to developers of MX4J, in order to have some common base to start from.
It gives also some indication on how to create and distribute a new MX4J release, and the general architecture
of the MX4J implementation.
Coding conventions
The base to start from are the coding conventions for Java,
see here .
We require as additional convention the one-line one-brace style:
One-line one-brace style
Using logging
It is good practice to insert logging statements in the code, to help debugging and
to record information about what the program is doing.
MX4J has a built-in logging system based on the mx4j.log.Logger
class, whose usage is very similar to the Category class
of the Log4J project .
Class Logger has six methods that logs at a different priority;
from the lowest priority to the highest they are:
public void trace
public void debug
public void info
public void warn
public void error
public void fatal
They all have two overloaded version, one that takes one argument of type
Java.lang.Object , and one that takes two arguments
of type Java.lang.Object and
java.lang.Throwable .
Class Logger has another useful method that returns the
priority enabled for that instance of Logger :
public boolean isEnabledFor
Using correctly this method will save the run-time cost associated with the concatenation
of String objects:
Saving run-time cost of String concatenation
Saving the time associated with the creation of temporary objects used only for the logging
statement is mandatory when the priority is trace, debug or info, to avoid unnecessary drop of
performance.
Another useful way to avoid creation of temporary String objects is to use
the StringBuffer class, following this example:
Saving run-time cost of String concatenation with StringBuffer
This version, when the logging is performed because the priority is enabled for the logger instance,
is more efficient than the previous example that used String concatenation.
How do you obtain an instance of the Logger class ? You must use the
mx4j.log.Log class, this way:
Retrieving a Logger instance
Every logger instance is associated with a category , i.e. a string that
normally represent a correlated group of logging requests.
Choosing the right priority
Choosing the right priority is important, and here there are few guidelines:
Use Logger.trace to log execution flow.
Always surround a log with trace priority with a call
to Logger.isEnabledFor .
Use Logger.debug to log variables values.
Always surround a log with debug priority with a call
to Logger.isEnabledFor .
Use Logger.info to log information that
can be of interest for the user. For every public method there should
be at least one log with info priority.
Always surround a log with info priority with a call
to Logger.isEnabledFor .
Use Logger.warn to log recoverable errors that
in normal situations should not happen. The warn priority is the default priority
for MX4J.
Use Logger.error to log exceptions.
Typically, log with error priority are inside catch blocks, just before rethrowing:
Logs with error priority
Use Logger.fatal to log fatal errors that
will force the JVM to terminate.
Typically log with fatal priority are inside catch blocks, just before
calling System.exit :
Logs with fatal priority
However, it is mandatory that in the MX4J code
System.exit is never called.
Writing documentation
The documentation that comes with MX4J is written using DocBook .
It is very easy to use DocBook, and an on-line manual is available
here .
Generally, the layout is defined in the file index.xml. All other files are DocBook sections belonging to
a chapter, also defined in index.xml.
Releasing MX4J
The following steps are required for a new release of MX4J:
Fresh checkout from CVS. Do NOT update, checkout to a new directory the whole CVS
Add to lib directory all the optional libraries
Build the code and run the test suite. All tests must pass
Build the distribution kit
Check that the distribution kit contains all the jars, the sources and licensing information
(also for third party software used)
Tag CVS with the suitable release tag
Upload the new kit to SourceForge, creating a new release version
Update the Change Notes tracker in SourceForge
Submit a news in SourceForge
Submit a news in FreshMeat
Submit a news in JavaLobby
Submit a news in TheServerSide
Submit a news in jmx-forum@java.sun.com
Submit a news in comp.lang.java.announce
MX4J Implementation Architecture
The primary implementation class of the MX4J JMX Agent is mx4j.server.MX4JMBeanServer .
The MBeanServer implementation class accomplishes these roles:
Returns information about the Agent
It is a repository for MBeans
Introspect the MBeans to determine their type and compliance
It acts as invoker, on behalf of the user, of operations on the registered MBeans
The information about the JMX Agent are returned by several methods such as, for example,
getDefaultDomain() , and are implemented directly in the
mx4j.server.MX4JMBeanServer class.
The registered MBeans are stored into a repository.
The MBeanServer implementation delegates to implementations of the
mx4j.server.MBeanRepository interface the repository task; therefore the
MBeanServer implementation acts as a factory for MBeanRepository instances,
but the implementation is delegated to MBeanRepository instances.
It is possible to specify custom MBeanRepository implementations by specifying the full qualified name
of the implementation class as value of the system property "mx4j.mbeanserver.repository".
When an MBean is registered several checks must be made to determine the MBean's type, if it is a
compliant MBean or not and to retrieve its MBeanInfo information.
The MBeanServer implementation delegates this task to the mx4j.server.MBeanIntrospector
class.
Objects of this class are first asked to fully introspect the given MBean; after the MBeanIntrospector has
gathered all information about the MBean into an instance of mx4j.server.MBeanMetaData
class, the MBeanServer implementation asks the MBeanIntrospector to check the compliance of the MBean.
If the MBean is a standard one, the MBeanIntrospector must create the MBeanInfo information for it using
introspection on the MBean's management interface, and create the MBean invoker for it, see below.
The role of the MBeanIntrospector is thus to check the MBean compliance, to create the MBeanInfo information
for standard MBeans and to act as a factory for MBean invokers.
The MBeanServer implementation acts as an invoker, on behalf of the user, of operations on the registered
MBeans.
The architecture is interceptor-based, that is whenever you call
from a client an MBeanServer method that will end up to call the MBean instance, the call is dispatched to
the interceptor chain and eventually to the MBean instance.
The interceptors are configurable via the MBeanServer Interceptor Configurator MBean, that is an MBean
of class mx4j.server.MBeanServerInterceptorConfigurator registered under the
"JMImplementation" domain.
When the call is about to arrive to the MBean instance, the last interceptor dispatches the call depending on
the MBean type: if the MBean is a dynamic MBean, the call is dispatched directly using the methods of the
DynamicMBean interface; if the MBean is a standard
MBean, then an MBean invoker is delegated to invoke the operation on the MBean instance.
MBean invokers are implementations of the mx4j.server.MBeanInvoker interface.
There are 2 default MBean invoker implementations: the first is based on reflection to invoke the MBean instance,
the second is based on an on-the-fly generated class that invokes the MBean directly.
This on-the-fly generated class is created at registration time; its bytecode is built at runtime using the
Byte Code Engineering Library .
Both versions make use of TernaryTree as fast caches for MBean information, so that the invocations on
standard MBeans are really FAST .
Early performance benchmarks reveal that the on-the-fly generated version is 2 times faster than the one that use
reflection.
For further information, see the Javadocs of the cited classes.
mx4j-3.0.2/src/docs/english/examples.xml 100644 0 0 74506 10513545721 15274 0 ustar 0 0
Services
The Relation Service example
Introduction
A full description of the RelationService, what it does and why it does it can be found in the
JMX Specifications.
The example java source files can be found in the examples directory under services/relation, they include:
RelationServiceExample (the main class)
SimpleBooks
SimpleOwner
SimplePersonalLibrary (which extends the
javax.mangement.relation.RelationTypeSupport and provides the definitions of our roles)
Simple use-case for the example
1)Adding Books Use-Case: Main Success Scenario:
A user adds 1 book to his personal library, he already has 3, a check is done and it is determined that he is allowed 4 books, there are no problems and he can add the book.
2)Adding Books Use-Case: Alternate Scenarios:
Our user decides he would like to add another book, as he has defined the number of books to be minimum 1 and maximum 4, and he is now trying to add a fifth, he is not allowed to add the extra book..
3)Removing Books Use-Case: Main Success Scenario:
A User decides to remove 3 old books from his personal-library. As he has defined the number of books he is allowed as to being between 1 and 4 there are no problems, the books are removed and he can no longer read or write to them, from the RelationService..
4)Removing Books Use-Case: Alternate Scenario:
The book owner decides to remove all his books. The relation is invalidated and he can no longer access his records as they have been removed from the RelationService, including his role as Owner..
Code Usage
Before any relations can be defined the RelationService must be registered in the MBeanServer.
Creating the RelationService
Once we have the RelationService registered we can then create in the server our MBeans that will be playing the roles in our use-case scenarios. This being done we can proceed to adding our RelationType
SimplePersonalLibrary which must extend
javax.management.relation.RelationTypeSupport . This class is not registered in the MBeanServer, it is merely a simple way of providing the definitions of our Roles in the RelationService, an example of adding a RelationType in the RelationService follows:
Adding a RelationType
Our next step will be to start filling the roles we defined in our support class and adding the MBeans up to the maximum number we defined our SimplePersonalLibrary class. This means registering the MBeans first with MBeanServer. Once registered. we can add them within our Roles...
Building Roles
We are done a note about the alternate scenarios: Once Role cardinality has been invalidated the relation is removed from the RelationService and can no longer be accessed via the RelationService though any MBeans registered in the MBeanServer can still be accessed individually.
Using Examples from the JMX Reference Implementation
The RelationService examples which can be downloaded from the
JMX website will run in the MX4J implementation. The few changes required are due to the fact that
MX4J implements the accessors of MBeans as
server.getAttribute(..) and
server.setAttribute(...) whereas the JMX implements all as method calls using
server.invoke(..)
To be able to use the Examples from the JMX download. A list of the few changes required for the
RelationAgent follows:
Remove: import com.sun.jdmk.Trace;
Remove: Trace.parseTraceProperties();
Change all calls for
getAllRelationTypeNames
getRelationServiceName
getRelationId
getAllRelationIds
getReferencedMBeans Note: except where the call comes from an external relation(represented by a subclass of
javax.management.relation.RelationSupport or a type of
javax.management.relation.Relation
getRelationTypeName Note: same as above
getAllRoles Note: same as above
setRole Note: same as above
from
server.invoke(...) to
server.getAttribute(....) , server.setAttribute(...) depending on whether it sets or gets.
MBeans
RMI MBean example
Introduction
The purpose of this example is to give some guideline on how to expose RMI remote objects also as MBeans.
This will give to server administrators the possibility to manage RMI remote objects in the JMX sense. This
means that may be possible to start, stop and restart the service implemented by the remote object; and also
checking if it is running, or ask to reload configurations files.
The example classes
The example java source files can be found in the examples directory under mbeans/rmi, they include:
Server (the class that starts the remote service)
Client (the client class)
MyRemoteService (the remote interface)
MyRemoteServiceObjectMBean (the management interface)
MyRemoteServiceObject (the MBean that implements the remote interface)
Understanding the example
The remote object is, at the same time an MBean and an RMI remote object.
Clients can see it through 2 interfaces: users of the service see it through the
remote interface
(
MyRemoteService ), while management application (such as the HTTP adaptor)
see it through the
management interface (
MyRemoteServiceObjectMBean ).
The remote interface contains only one method:
public void
sayHello(String name)
that will execute client's requests.
The management interface, conversely, contains 3 methods:
public void
start()
public void
stop()
public boolean
isRunning()
that will be used by management application such as the HTTP adaptor.
Notice that users of the remote interface cannot invoke methods of the management interface, as well as management
application cannot invoke methods of the remote interface.
The implementation
The purpose of the
Server class is only to start a JMX Agent by instantiating the MBeanServer,
register the service we want to expose, and starting it.
The
Server class
The remote object, instance of
MyRemoteServiceObject class, is worth some more detail.
First notice that it extends
java.rmi.server.RemoteServer and not
java.rmi.server.UnicastRemoteObject . This is done to avoid that the object is automatically
exported to the RMI runtime when creating it, since we want to control the export and unexport via the
start() and
stop() methods of the management interface.
Second, notice the symmetry of the
start() and
stop() methods:
start() export the object to the RMI runtime and binds it in the naming, while
stop()
unbinds it from the naming and unexport it from the RMI runtime.
The
MyRemoteServiceObject class
Thus, will be possible to start the service via a management application and let it available to users;
and will be possible to stop it, maybe changing some configuration file (not in this simple example, but you
got the picture), and restarting it,
WITHOUT shutting down other services that may have
been started by the same JMX Agent.
The implementation of the
sayHello(String name) method is straightforward, as well as
the
isRunning() one that, accessible from management applications, returns if the
service is running or not.
Compiling the example files
The above classes must be compiled using
javac , and the
MyRemoteServiceObject class
must be compiled using
rmic .
Let's suppose you unpack the MX4J distribution in the mx4j-
ver directory; from this directory you issue these
commands:
C:\mx4j-
ver >javac -classpath lib\mx4j-jmx.jar examples\mbeans\rmi\*.java
C:\mx4j-
ver >rmic mx4j.examples.mbeans.rmi.MyRemoteServiceObject
Running the example
To run the example, three consoles are needed:
One for the
rmiregistry
One for the server
One for the client
For the rmiregistry, you need to have in the classpath the RMI stub of the
MyRemoteServiceObject
class you just compiled with
rmic . Then you can start it by typing the following command:
C:\mx4j-
ver >set classpath=.
C:\mx4j-
ver >rmiregistry
For the server, you need all the compiled classes (apart for the
Client class),
mx4j-jmx.jar (the JMX implementation), and a suitable
jndi.properties file (there is a default
one shipped with this example) in the classpath. Then you can start the server with the following command:
C:\mx4j-
ver >java -cp .;examples;lib\mx4j-jmx.jar mx4j.examples.mbeans.rmi.Server
For the client, you need the
Client class, the remote interface and the RMI stub, and a suitable
jndi.properties file (there is a default one shipped with this example).
Then you can start the client with the following command:
C:\mx4j-
ver >java -cp .;examples mx4j.examples.mbeans.rmi.Client
Tools
Using XDoclet
Introduction
MX4J provides a way to generate source code of MBean interfaces and descriptions using some custom javadoc comments in
source code. This source generation is done with the help of
XDoclet .
It is recommended to look at the example included in the distribution for getting started with this feature.
Preparing Ant
In order to generate the source code, XDoclet must be copied into the directory where all libraries are. This is usually
the lib subdirectory of the project which will be referred as the Ant variable
${lib} from now on.
A path must be defined for the Ant task. An example is given below:
Defining the xdoclet classpath and Ant task.
]]>
Let's suppose now that the Ant compilation target is called
compilation . The easiest way to generate
the source code of the MBean interface and description is to make the
compilation depending on the
target
generateJMX defined by:
]]>
Basic usage
A few javadoc tags can be used in order to specify how to generate the interface and the description of your MBean.
List of Javadoc tags
Javadoc Tag Name
Meaning
@jmx:mbean
Tag used in order to define the name of the MBean and its description. Must be defined at class level.
@jmx:managed-constructor
Tag used in order to define the name of the constructor and its description. Must be defined at constructor level.
@jmx:managed-constructor-parameter
Tag used in order to define the name of a constructor attribute, it's index, and its description. Must be defined at constructor level.
@jmx:managed-operation
Tag used in order to define the name of an operation and its description. Must be defined at method level.
@jmx:managed-operation-parameter
Tag used in order to define the name of an operation attribute, it's index, and its description. Must be defined at method level.
@jmx:managed-attribute
Tag used in order to define the description of an attribute. Must be defined at method level. Note: the getter description has
priority over the setter description.
@jmx:mlet-entry
Tag used in order to generate the mlets file. All classes having this tags will have the result merge in one file. Must be defined at class level.
FilePersister example
Introduction
This example will cover the usage of the FilePersister with MLets. It will give a good overview of how to use MLets into the bargain :-).
What we will do is create two MBeans the one extends FilePersister, so that it can load and store Objects. The other is a standard MBean which will ask the FilePersisterMBean to store it, The interesting thing about this example is that the two mbeans are loaded by two differnet MLets from two different jar files. One note of importance any object to be stored must implement the interface Serializable. Let us begin.
Writing the code
We are going to write an MBean which extends FilePersister and pass any calls made to it to its parent class.
MBeanOne implementation
Now to do the mbean that will ask the MBeanOne to store it.
MBeanTwo implementation
The Agent MLet implementation
The "main" class will now create and register two MLets, each MLet will load its own MBean from separate jar files
The FilePersisterAgent
Steps for Running the Example
Once you have the files and compiled them you will need to build the jars holding the mbeans start a command prompt (windows) cd to the examples/classes directory and type in the following commands:
Now delete the MBeanOne.class and MBeanTwo.class (we do not want them in the classpath :-). Once this is done add four application parameters
1) path to jar one.jar eg:file:C:/dev/mx4j/one.jar
2) path to jar two.jar eg: file:C:/dev/two.jar
3) path where to store the file eg: C:/temp
4) name of the file eg: test.ser
You are now ready to start the agent!
Have fun !!
mx4j-3.0.2/src/docs/english/extensions.xml 100644 0 0 40605 10513545721 15646 0 ustar 0 0
Extensions
MX4J provides some extension to the JMX specification, some transparent with respect to MBeans or applications portability
across JMX implementations, and some that instead ties your MBeans or applications to the MX4J implementation.
Standard MBean descriptions
This extension is totally transparent with respect to MBeans portability across JMX implementations.
When MBeans are coded as standard MBeans, the JMX Agent is responsible of the creation of the metadata
information for them. Conversely, when coded as dynamic MBeans, the programmer is responsible of the
creation of such metadata information exposed to the JMX Agent through the
public MBeanInfo
getMBeanInfo
method of the
DynamicMBean interface.
Although the JMX Agent can retrieve information about attributes, operations, constructors and notifications,
for standard MBeans it cannot retrieve user information such as attribute description, operation description
and parameter names and descriptions, and so on.
These information are important for the user of a management application, that can immediately understand
what an operation parameter is for just reading the description associated with that parameter. Same happens
with attributes.
MX4J offers the possibility of customize descriptions and parameter's names for attributes, operations,
constructors and notifications of standard MBeans. This customization is achieved by implementing a class
that follows some lexical patterns, in a way very similar to what happens to standard MBeans and the Java
interface that represent their management interface to the JMX Agent.
The MBean programmer should write a class that has the same full qualified name of the MBean class, ends
with "MBeanDescription" and implement the
mx4j.MBeanDescription interface
or extends the
mx4j.MBeanDescriptionAdapter class.
For example if you have an MBean whose class is
my.package.MyService , then you will
have a management interface defined by the
my.package.MyServiceMBean Java interface,
and you may add a class named
my.package.MyServiceMBeanDescription that implements
the
mx4j.MBeanDescription interface and that specifies descriptions and parameter's
names for the MBean (see example below).
The whole mechanism of generating the management interface and the description for standard MBean can be
automated using XDoclet (see the section about XDoclet for further details).
When the MyService MBean is used in another JMX implementation, that implementation will not care about the
MBeanDescription class, and thus will ignore the additional information you provided. Your MBean will
work normally, but the other implementation's MBeanServer will not be able to provide description information
to connectors and adaptors.
That's why this extension is transparent: it will not cause your MBeans to stop working in another JMX implementation.
Specifying description for standard MBeans
Interacting with the MX4J implementation
The MX4J implementation exposes some internal functionality via a public API that can be used by MBeans and applications.
However using these API ties the MBean or the application to the MX4J implementation, making them non-portable across
other JMX implementations.
Internal logging redirection
MX4J has a flexible logging system that allows you to tune the logging priority and
to redirect MX4J internal logging to other logging
systems such as
Commons Logging or
Log4J .
The MX4J logging system has six logging priorities;
from the lowest priority to the highest they are:
trace
debug
info
warn
error
fatal
The default level is
warn , and it can be set to a different value just by setting the system
property "mx4j.log.priority" to one of the values above.
For example, you can start the JVM with this command to have MX4J log at a
debug level:
java -Dmx4j.log.priority=debug MyMainClass
The fatal level is never used by MX4J.
MX4J default logging is done on the console via
System.out , but can be redirected to other
logging systems using the MX4J logging API, or through the broadcaster MBean (see below).
For example, let's assume you want to redirect MX4J logging to Log4J. Below is the code needed to do so:
Logging redirection to Log4J
It is also shown how to reset logging redirection to the standard one, that logs on the console.
The prototype for the new Logger, in the example above
Log4JLogger , can be specified
either in the code or by setting the system property "mx4j.log.prototype" to the full qualified name of the
Logger subclass, for example:
java -Dmx4j.log.prototype=mx4j.log.Log4JLogger MyMainClass
In this case, using system properties, your MBean or application remains portable across JMX implementations.
It is possible to redirect logging to the MX4J broadcaster MBean, that will send notifications
to registered listeners. The MBeanServer mechanism is used to emit these notifications, so that every listener
can register itself along with a filter, to exclude notifications in which it's not interested in.
The example below shows the code necessary to redirect the logging system to the broadcaster MBean:
Logging redirection to the broadcaster MBean
It is also shown how to reset logging redirection to the standard one, that logs on the console.
Log categories of the MX4J implementation
Various classes in the MX4J implementation log their activities.
Each class logs with a certain category, that organizes logging into a hierarchy of categories, following a
dotted scheme introduced by
Log4J .
The categories are simply the full qualified names of the classes that log their activities.
MBeanServerInterceptor configuration
The MX4J implementation allows client code to add custom interceptors for the MBeanServer calls that may end up in a
call to an MBean instance.
When the MX4J implementation of the MBeanServer is created, a configurator for the MBeanServer-to-MBean interceptor chain is
also created, along with a default set of interceptors (that cannot be removed by the client code).
Each one of the default interceptors is also an MBean, so it can be monitored/managed as a normal MBean, and also the
configurator is an MBean, registered with ObjectName "JMImplementation:type=MBeanServerInterceptorConfigurator".
The interceptor configurator exposes a management API that can be invoked as usual via the MBeanServer.
The API allows client code to add and remove custom interceptors, even at runtime, to perform additional tasks
such as logging, performance timing, redirection and so on.
Writing a custom interceptor is simple, and requires the client code to implement the interface
mx4j.server.interceptor.MBeanServerInterceptor or to extend the class
mx4j.server.interceptor.DefaultMBeanServerInterceptor .
Once you have written your custom interceptor, you can add it to the interceptor chain using the API provided
by the
MBeanServerInterceptorConfigurator , via these methods:
addInterceptor(MBeanServerInterceptor interceptor)
registerInterceptor(MBeanServerInterceptor interceptor, ObjectName name)
See the Javadoc API documentation relative to the class
mx4j.server.interceptor.MBeanServerInterceptorConfigurator and its management interface
for further details.
Below you can find a simple example of how to use the
MBeanServerInterceptorConfigurator API.
Using the interceptor configurator API
mx4j-3.0.2/src/docs/english/faq.xml 100644 0 0 4065 10513545721 14176 0 ustar 0 0
MX4J Frequently Asked Questions
How it is possible to change the default log level
of the MX4J implementation to understand what is going on ?
Just set the system property 'mx4j.log.priority' to one of these values (from less verbose to more verbose):
fatal
error
warn
info
debug
trace
like this example command line:
> java -Dmx4j.log.priority=debug -classpath . my.package.Application
See the MX4J documentation about logging for more information.
The MLet file format is not enough flexible for my needs.
Is there a more powerful configuration file format, maybe in XML, by means of which
will be possible to load and configure the MBeans of a system ?
MX4J, from version 2.0, supports a configuration file format in XML, by which it is
possible to specify constructor arguments to MBeans, call methods on object and MBeans,
register and unregister MBeans and so on.
Think of this configuration file format as an XML way to invoke Java methods and JMX
attributes or operations.
The class that allows this is mx4j.tools.config.ConfigurationLoader .
Refer to the MX4J tools documentation for details about usage of this class.
mx4j-3.0.2/src/docs/english/http-adaptor.xml 100644 0 0 100442 10513545721 16072 0 ustar 0 0
HttpAdaptor
Introduction
The HttpAdaptor offers a basic way to interface with an MX4J agent. It contains a simple HTTP 1.0 server,
able to translate HTTP requests to JMX requests. Obviously it has some limitations, like not being able to
manipulate data which cannot be obtained from Strings. As an advantage HTTP traffic is usually enabled through firewalls
and you can use your browser as a client.
The MX4J HttpAdaptor is built basically to serve XML data. Requests are made with normal http requests and they are
answered by constructing a XML tree containing the requested data. The request may also have variables which
may specify exactly the requested data. The XML tree can be later processed by defining a ProcessorMBean, which has the task to
take the XML tree and do something with it. The processor will also be responsible to serve requests not understood by
the server. In this way an appropriate processor can serve images and raw html. Currently there are two Processors defined:
DefaultProcessorMBean: It does not modify the XML tree limiting itself to publish the tree as text. Defining
the content-type as text/xml. This usually means that your browser will display the XML text. This processor won't server
any data besides the XML files.
XSLTProcessorMBean: This processor takes the XML tree and transforms it to HTML by means of XSLT. This requires that
you use some JAXP-compliant XSLT. It has been tested mainly with
Xalan XSLT processor .
The processor is also able to serve images and other files.
As the processor is an MBean it means you can deploy and modify it on runtime. The HttpAdaptorMBean defines three methods to set the Processor.
If no processor is defined or an error is found, the DefaultProcessor will be used.
Parameters and operations
The HttpAdaptor is an MBean defined by the interface HttpAdaptorMBean. It contains the following parameters.
Port: Defines the port in which the server will be listening to. By default is 8080.
Host: Defines the host name in which the server will be listening to. By default is localhost. This means that
you can't access the server from another computer. This is good for security reasons, forcing you to explicitly open the server to the outside.
You can also use 0.0.0.0 which will open the server to all local interfaces
Alive: Boolean property which tells whether the server is running or not.
AuthenticationMethod: Sets the authentication method. Valid values are none, basic, digest. Please refer to the security chapter
Processor: This sets the processor object to be used after the XML tree construction. If used the ProcessorName is set to null.
ProcessorName: This sets the MBean's ObjectName to be used as XML processor. If used then Processor is set to null. The MBean has to implement the
mx4j.tools.adaptor.http.ProcessorMBean interface
ProcessorNameString: The same as before but the object name is passed as a string
ProcessorClass: This will take a class name as string and instantiate a class object. The class has to implement the
mx4j.tools.adaptor.http.ProcessorMBean interface, and you have to set the ProcessorName or ProcessorNameString property
SocketFactory: Replaces the default socket factory with another, for example, the mx4j.tools.adaptor.http.ssl.SSLFactory
SocketFactoryName: Replaces the default socket factory with another using an ObjectName, the pointed mbean has to have an
public ServerSocket createServerSocket(int port, int backlog, String host) throws IOException method
SocketFactoryNameString: Same as previous but it takes a String object
StartDate: Date and Time when the Adaptor was started
RequestsCount: Total amount of requests served
Version: HttpAdaptor's version
The HttpAdaptor accept the following operations
start() : Starts the HttpAdaptor, notice that the server does not start by itself
stop() : Stops the server
addCommandProcessor(String path,HttpCommandProcessor processor) : It adds a command processor and assigns it to the path.
You can use this to create your own command processors which generate a customized XML tree. Notice that
if the path was assigned before this command will replace the previous definition
addCommandProcessor(String path,String classname) : Same as previous but the processor object is
indicated with a classname, the operation will try to instantiate an object of the given class, check that implements
the
mx4j.tools.adaptor.http.HttpCommandProcessor interface, and assign it to the indicated path
void removeCommandProcessor(String path) : Removes a command processor assigned to the give path
Security
The HttpAdaptor is in no way guaranteed to be secure. However basic authentication and SSL support are available.
Basic Authentication
The Basic Authentication method provides a weak form of protection. When it is set your browser should prompt you for a username
and password which are compared with the ones stored in the Adaptor. To add a username/password pair use the
addAuthorization method.
As mentioned before the basic authentication is weak since your username and password are sent with a weak encoding (Base64). However it can
be prefectly used in secured networks or via enabling SSL.
SSL support
The HttpAdaptor can use SSL instead of normal sockets. For that is necessary three steps:
Install JSSE: JSSE is necessary to run the Adaptor with SSL support. It is possible to use either JSSE version 1.0.2 available
here ,
or JDK 1.4. JSSE comes with 3 jar files which should be added to your classpath: jsse.jar, jcert.jar and jnet.jar. Another alternative
is to put those files at your JAVA_HOME/lib/ext dir. In case you are using JDK 1.4 you don't need to do this
Create server certificate:
Use the keytool command to create a server certificate. For example
keytool -genkey -keystore certs -keyalg RSA
where certs is the keystore file name.
You will be prompted for a password for the keystore and the certificate distinguished name.
Notice that your browser will probably
complain about the vailidty of the key since it was signed by yourself.
Note that if the key generation algorithm is not RSA but something else your browser may not accept it
Configure HttpAdaptor: Finally you should change the default socket factory for a SSL factory. To do that
you should use the SocketFactory attribute passing a
mx4j.tools.adaptor.http.ssl.SSLFactory object. The SSLFactory object should be previoulsy configured with
your keystore and key.
After this you can start the HttpAdaptor as usual and point to https://host:port instead of http://host:port
SSLFactory
The SSLFactory contains several parameters you need to configure to find the certificate keystore. They are in the SSLFactory Management interface
KeyStoreType: Sets the keystore type. If you used the keytool command this is JKS
KeyStoreFileName: Filename of the certificate file
KeyStorePassword: Keystore password
KeyManagerAlgorithm: Keymanagers's algorithm, by default is SunX509
KeyManagerPassword: Keymanagers's password
SSLProtocol: SSL's protocol, by default is SSLv3
Usage
To use the HttpAdaptor you should instantatiate the MBean and register it to the right server. Later you can set up the
desired parameters and invoke start to init the operation. Remember to add a JAXP-compliant parser such as xerces to the
CLASSPATH. If you want to use the XSLTAdaptor you should also add xalan.jar to the CLASSPATH. If you want to use SSL add
the JSSE jar files
Instantiating the HttpAdaptor
If you wan to use a non-default Processor. You may instantiate and install it as follow
Installing a non-default Processor
Available requests
The HttpAdaptor works by interpreting requests and executing some action. The Adaptor has a list of available requests
and they produce an XML ouput tree (Or an exception...). New request handlers can be added if necessary, creating
a
mx4j.tools.adaptor.http.HttpCommandProcessor implementation, and add it to the HttpAdaptor
using the addCommandProcessor and removeCommandProcessor.
The following is a list of the currently available requests, and the results and parameters required.
http://host:port/serverbydomain Returns a list of the MBeans available in the server grouped by domain. The result tree is as follows:
]]>
The request can accept the following parameters:
instanceof: Filters the MBeans whether they
are instance of the class. For instance
http://host:port/serverbydomain?instanceof=javax.management.timer.Timer
will produce a list of all timers
querynames: Filters the MBeans by objectname for instance
http://host:port/serverbydomain?querynames=*:*
will produce a list of all mbeans whether
http://host:port/serverbydomain?querynames=Test:* will only contain those MBeans in the Test domain
http://host:port/server Returns a list of the MBeans available in the server. The result tree is as follows:
]]>
The request can accept the following parameters:
instanceof: Filters the MBeans whether they
are instance of the class. For instance
http://host:port/serverbydomain?instanceof=javax.management.timer.Timer
will produce a list of all timers
http://host:port/mbean?objectname=XXX Returns the description of the referred MBean.
It requires that the target objectname is passed on the request. The result tree for the request is as follows
http://host:port/mbean?objectname=Test:name=test1
]]>
The Attribute element may have an aggregation attribute for composite types array, collection and map
The request can accept the following extra parameters:
attributes: if set to false as
http://host:port/mbean?objectname=Test:name=test1&attributes=false
no attributes are included in the result tree
operations: if set to false as
http://host:port/mbean?objectname=Test:name=test1&operations=false
no operations are included in the result tree
constructors: if set to false as
http://host:port/mbean?objectname=Test:name=test1&constructors=false
no constructors are included in the result tree
notifications: if set to false as
http://host:port/mbean?objectname=Test:name=test1¬ifications=false
no notifications are included in the result tree
http://host:port/getattribute?objectname=XXX&attribute=XXX&format=ZZZ
Gets the value of an attribute. This is an operation intended to get certain types
of attributes in a usable format, in particular arrays. If format is omited or not understood
the default value is returned like:
" +
"
]]>
However if format=array and the attribute is actually an array the result is like
]]>
If format=collection and the attribute is a collection the result is like
]]>
If format=map and the attribute is a map the result is like
]]>
The request requires the following parameters:
objectname: Target objectname
attribute: Attribute's name
format: Result format. The currently supported types are array, collection and map
http://host:port/setattribute?objectname=XXX&attribute=XXX&value=XXX Sets the value of one attribute. This is an operation request
rather that a data request. All operation requests are returned as a MBeanOperation tree, which looks as follow
]]>
or if there was an error it looks like
]]>
The request requires the following parameters:
objectname: Target objectname
attribute: Attribute's name
value: Attribute's value
setattribute is deprecated in 1.1.1 and setattributes should be used instead
http://host:port/setattributes?objectname=XXX&value_YYY=XXX&value_YYY2=XXX2&[set_XXX=Set | setall] Sets the value of many attributes.
This is an operation request. The result will be a list of the attributes set.
]]>
or if there was an error it looks like
]]>
The request requires the following parameters:
objectname: Target objectname
value_XXX: Value for the atribute name XXX. The request can pass many parameters, but it depends on
the set_XXX parameters which values will be set
[set_XXX=Set | setall]: Indicates which value is used. If setall is present it will set all attributes passed.
If only set_XXX is passed that will be set.
Notice that in case of one attribute failing the other will be set anyway
http://host:port/invoke?objectname=XXX&operation=XXX&type0=XXX&value0=XXX...
Invokes an operation on the target MBean
]]>
The following parameters are required:
objectname: Target objectname
operation: Name of the operation
If you want to invoke an operation which takes parameters, add the following parameters:
typeX: Type of the parameter number X. They are enumerated starting from 0
valueX: Value of the parameter number X. They are enumerated starting from 0
http://host:port/delete?objectname=XXX
Removed the target MBean
]]>
The following parameter is required:
objectname: Target objectname
http://host:port/create?class=XXX&objectname=XXX&type0=XXX&value0=XXX...
Creates a target MBean invoking the corresponding constructor
]]>
The following parameters are required:
classname: Target objectname
objectname: Target objectname
If you want to invoke create using a constructor which takes parameters, add the following parameters:
typeX: Type of the parameter number X. They are enumerated starting from 0
valueX: Value of the parameter number X. They are enumerated starting from 0
http://host:port/constructors?classname=mx4j.tools.adaptor.http.HttpAdaptor
Queries the MBean server of the available constructors for a class name resulting on
]]>
The following parameter is required:
classname: Target classname
In case the class is not found an exception will be sent as
]]>
http://host:port/empty
The empty request returns an empty xmltree. Is basically used to create 'static' requests
made on pure xsl. The result tree is as
]]>
mx4j-3.0.2/src/docs/english/index.xml 100644 0 0 1400 10513545721 14524 0 ustar 0 0
MX4J and JMX Overview
&introduction_en;
&license_en;
JMX 1.2 Explained
&jmx-explained_en;
JSR 160 (JMX Remoting) Explained
&jsr160-explained_en;
MX4J Extensions and utilities
&extensions_en;
MX4J HTTP Adaptor
&http-adaptor_en;
&xslt-processor_en;
MX4J Tools
&tools_en;
MX4J Examples
&examples_en;
FAQ
&faq_en;
MX4J Developer's guide
&dev-guide_en;
mx4j-3.0.2/src/docs/english/introduction.xml 100644 0 0 11067 10513545721 16170 0 ustar 0 0
Overview
MX4J
MX4J is an open source implementation of the JMX
TM technology.
JMX stands for
Java
TM Management Extensions
,
and it's an optional package for the J2SE
TM platform that is now
included in J2SE 5.0.
The Java Management Extension specification is a Java Specification Request (see
JSR 003 ) currently in maintenance release 1.2.
A new JSR has been issued to address connectivity to a remote JMX Agent,
JSR 160 , which has released version 1.0 on
October 2003.
MX4J implements both JSR 3 and JSR 160.
What is JMX ?
JMX defines the architecture, the patterns, the API and the services to build manageable Java applications.
But what do this really mean ?
For what can you use JMX ?
By means of JMX, components of an application have a standard way of exposing some of their functionality
for management. A JMX Agent enables manageability of these functionalities from local or remote, allowing
a system administrator to manage the components of the application.
Managing a component means having the possibility to stop and restart it, to remove it from the application or
to add it to an application, to change its configuration files,
to ask it to do some operation (such as downloading information from an URL the system administrator passes in),
and so on, depending on the management interface that this component expose.
Many application servers such as Tomcat, JBoss, IONA, BEA WebLogic have their architecture based on JMX.
Every JMX Agent comes with a set of predefined services, defined by the JMX specification.
A service is a manageable component that can be used by, embedded in or extended by an application.
Every JMX implementation can provide additional services, and normally each additional service can be used or
deployed in a different JMX implementation without requiring any additional operation, thus achieving
extreme portability of applications and application components.
MX4J's JMX implementation
MX4J's implementation of the JMX specification is stable and reliable, passing every night an extended
suite of tests
following the
XP principles.
The MX4J implementation runs in J2SE version 1.3 or superior.
It provides some non-standard but
useful extension that can be used at wish, or not used if maximum portability is a primary goal.
The MX4J implementation provides also useful services and tools, and several examples to guide users
in the use of JMX to build their applications.
Some example of tools, extensions and utilities are:
HTTP adaptor (also over SSL)
ConfigurationLoader to read MBean configuration from XML
AbstractDynamicMBean to ease DynamicMBean development
Utility MBeans for:
RMIRegistry
TNameServ
Statistics
EMail
Remote MBean Proxying
Automatic generation of management interfaces for standard MBean via
XDoclet
mx4j-3.0.2/src/docs/english/jmx-explained.xml 100644 0 0 70624 10513545721 16220 0 ustar 0 0
javax.management.ObjectName changes
The
getInstance() methods
JMX 1.2 introduced four overloaded static version of the
getInstance() method:
public static ObjectName getInstance(String name)
public static ObjectName getInstance(ObjectName name)
public static ObjectName getInstance(String name, Hashtable properties)
public static ObjectName getInstance(String domain, String key, String value)
The first version is the preferred way to create ObjectNames, and should be used instead of using the
new Java keyword.
Creating a new ObjectName from a string is expensive because require parsing of the string.
JMX implementations may use caching techniques to speed up creation of ObjectNames from strings.
MX4J does this optimization both in this method and in the ObjectName's constructor; it is likely that other
implementations perform the optimization in getInstance(), but not in the ObjectName's constructor, so choosing
to use getInstance() ensure coherent behaviors.
The second version is mostly used to convert ObjectName subclasses to plain ObjectName.
This is useful in a secure environment where evil ObjectName subclasses can try to bypass security checks
done when
javax.management.MBeanPermission s are checked to see if access to
the MBean with the given ObjectName is allowed or not.
The third and the fourth version are just a replacement for the usage of the
new Java keyword,
and offer mostly syntactic sugar to your code.
The
quote() and
unquote() methods
JMX 1.2 introduced a way to "quote" the value of ObjectName's properties that is, to allow special
characters to be present in the properties values of an ObjectName.
A simple example of this feature is to specify an LDAP name as an ObjectName property value.
Since the comma is a reserved character that separates ObjectName properties, it would have been
impossible to specify an LDAP name as an ObjectName property.
Let's suppose to have a distinguished name of 'uid=guest,ou=project,o=company', and to build an
ObjectName with a property called 'dname' whose value is the distinguished name.
Without quoting, the ObjectName is:
:dname=uid=guest,ou=project,o=company
which leads to an invalid ObjectName.
Using quoting, instead, it becomes:
:dname="uid=guest,ou=project,o=company"
which leads to a valid ObjectName.
It is possible also to "unquote" the property value to obtain the original string.
The ObjectName class has no knowledge if a value should be quoted or not, so it is responsibility
of the developer to quote and unquote property values.
It is a good practice to do so in those cases where the property value is chosen by users, for example
by inputting it in a web form or in a swing gui.
Refer to the javadoc of the ObjectName class for further information.
Support for remote API
Overview
JMX 1.2 defined all changes to the JMX specification needed to support remote API.
Imagine a situation where a client needs to contact a remote MBeanServer, to invoke operations on it and
to receive the result of such invocations.
In order for this situation to be possible, the JMX specification needed several changes such as
specifying the serialVersionUID of serializable classes that can be exchanged between the client and
the remote MBeanServer (for example
javax.management.MBeanInfo ), specifying
details of MBeanServer's classloading to support classloading from remote locations, and the possibility
for the client to invoke operations on an MBeanServer-like interface that supports remote invocation
(for example that throws IOException if the connection with the remote MBeanServer is broken).
The
javax.management.MBeanServer class inherits from
javax.management.MBeanServerConnection
The MBeanServer interface cannot be used directly by clients that need to contact a remote MBeanServer.
The reason is that this interface does not list, in its method's throws clause,
java.io.IOException as a possible exception being thrown.
Furthermore, the MBeanServer interface has some method (like registerMBean(), deserialize(),
getClassLoader(), etc.) that have no meaning in the remote case.
The
javax.management.MBeanServerConnection interface has been defined as the
portion of the MBeanServer interface that can be used by client to contact a remote MBeanServer, and
is MBeanServer's parent interface.
The
javax.management.MBeanServerBuilder class
Introduction
JMX 1.2 introduced the possibility to replace, at runtime, the MBeanServer implementation by specifying
a full qualified name of a
javax.management.MBeanServerBuilder subclass with the
system property "javax.management.builder.initial".
When creating a new
MBeanServer instance, the
MBeanServerFactory
checks (every time) for the value of that system property; if it is not null, loads (using the context classloader),
instantiates, and delegates the
MBeanServerBuilder subclass to create
MBeanServer instances.
Since now the creation of
MBeanServer instances can be delegated to a custom
MBeanServerBuilder , it is possible to achieve two things:
Use Sun's JMX reference implementation (JMXRI) but telling it to use MX4J's
MBeanServer implementation
"Wrap" the
MBeanServer implementation and "decorate" it with added functionality.
How to use MX4J's
MBeanServer implementation with Sun's JMX Reference Implementation.
This is very simple to achieve:
]]>
Note how the classpath specifies
first the JMXRI jar and
then the MX4J
implementation jar.
How to "decorate"
MBeanServer methods.
A custom
MBeanServerBuilder allows you to specify how to create an
MBeanServer .
Any JMX implementation has already in place a mechanism that uses a default
MBeanServerBuilder
to create instances of the default
MBeanServer implementation.
In order to be able to "decorate" an
MBeanServer it is sufficient to specify a custom
MBeanServerBuilder that "decorates" the default one; then the implementation of the custom
MBeanServerBuilder will "decorate" the default
MBeanServer .
However, implementing a "decorating"
MBeanServerBuilder requires a bit of precision.
We will explain how to do this in detail in the following, using as example the MX4J implementation.
Using the
MBeanServerBuilder to "decorate" an
MBeanServer
requires to write two classes:
a custom
MBeanServerBuilder
a decorating
MBeanServer
Although it's possible to start from scratch, the MX4J API gives you two base classes to start from:
mx4j.server.ChainedMBeanServerBuilder
mx4j.server.ChainedMBeanServer
Let's suppose we want to decorate the default
MBeanServer by adding logging statements
whenever a
MBeanServer method is called.
First, we write the "decorating"
MBeanServer :
A "decorating"
MBeanServer that logs method calls.
The class
ChainedMBeanServer simply forwards the calls to a nested
MBeanServer .
ChainedMBeanServer thus allows to create a "chain" of
MBeanServer s
that are called in succession, one after the other, from the outermost to the innermost.
Second, we write the "decorating"
MBeanServerBuilder :
A "decorating"
MBeanServerBuilder
As for the
ChainedMBeanServer class, also
ChainedMBeanServerBuilder
simply forwards the calls to a nested
MBeanServerBuilder .
Also here,
ChainedMBeanServerBuilder allows to create a "chain" of
MBeanServerBuilder s
that are called in succession, one after the other, from the outermost to the innermost.
The
MBeanServerBuilder chain works in parallel with the
MBeanServer
chain in this way:
The
MBeanServerBuilder and
MBeanServer chains
LoggingBuilder -- calls --> MX4JMBeanServerBuilder
| |
creates creates
| |
V V
Application -- calls --> LoggingMBeanServer -- calls --> MX4JMBeanServer
]]>
Note the
LoggingBuilder constructor: there is where the
MBeanServerBuilder chain is created.
The
LoggingBuilder specifies a chain of only two rings, the
LoggingBuilder
itself, and MX4J's default
MBeanServerBuilder ,
MX4JMBeanServerBuilder .
This chain is hardcoded in the builder, meaning that if you want to change it at runtime you cannot: either you
change and recompile the custom builder, or you use another custom builder.
Note also the usage of the ternary operator (condition ? this : that) in the nested
newMBeanServer()
call: checking for nullity of the "outer" argument is
of fundamental importance for the builder to be "chainable". If this check is not made, then
LoggingBuilder cannot be reused as a ring of a longer chain if, in future, we modify it
to accept as parameter to the constructor other builders (i.e. other "rings").
It is of course possible to use different builders from different vendors, simply by creating a custom builder
that "chains" all the other in the desired sequence:
A "decorating"
MBeanServerBuilder
Just remember that
MX4JMBeanServerBuilder is a "terminal" builder and must
always be the last in the chain.
Other vendors are expected to provide an API for their custom builders very similar to
ChainedMBeanServerBuilder (which is mostly being able to take a
javax.management.MBeanServerBuilder as argument to a constructor).
More complex
MBeanServer "decorations".
We saw above that is possible to "decorate"
MBeanServer s by decorating the
default mechanism of the
MBeanServerBuilder already in place in any JMX implementation.
We saw that to a chain of builders corresponded a chain of servers.
However, it's possible that a builder specifies more than one ring for the server chain, in the following way:
A More complex
MBeanServerBuilder and
MBeanServer chains
LoggingBuilder --calls--> PerformanceBuilder --calls--> MX4JMBeanServerBuilder
| | |
creates creates creates
| / \ |
V V V V
Application --calls--> LoggingMBeanServer --calls--> TimingServer --calls--> CountingServer --calls--> MX4JMBeanServer
]]>
An example of such chains is present in the MX4J testsuite, in the test class that tests the
MBeanServerBuilder functionality.
Possible usages of MBeanServer "decorators"
A (non complete) list of possible "decorators" for
MBeanServer
may include functionality such as:
Logging the invocation
Measuring the invocation time
Counting the number of invocations
Load-balancing the invocations among server nodes
Cascading the invocations to child servers
Notifying a message to someone for a particular invocation
...
The
javax.management.MBeanServerInvocationHandler class
Introduction
MX4J version 1.x provided a custom implementation of a JDK 1.3's dynamic proxy to ease invocation
of methods on a MBean via the MBeanServer, the
mx4j.util.StandardMBeanProxy class.
MX4J 1.x provided also a class for invocation of methods on remote MBeans, namely
mx4j.connector.RemoteStandardMBeanProxy
based on MX4J's custom remote implementation.
In MX4J 1.x these classes were separated since JMX 1.1 did not specify a super-interface for MBeanServer
that could be used also remotely.
In JMX 1.2, the
javax.management.MBeanServer interface inherits from the
javax.management.MBeanServerConnection interface.
The MBeanServerConnection interface has basically the same methods of MBeanServer except those that
does not have sense remotely (like deserialize() and registerMBean()), and adds
java.io.IOException in the throws clause
of each method, thus making it the "remote" view of a remote MBeanServer.
As of JMX 1.2, both
mx4j.util.StandardMBeanProxy and
mx4j.connector.RemoteStandardMBeanProxy are obsolete since they have been
replaced by one single class, the standard
javax.management.MBeanServerInvocationHandler class, that takes advantage of
the improved class hierarchy of the
javax.management.MBeanServer interface
to unify the functionalities that were provided before by the two MX4J classes.
In the following section will be explained how to port old MX4J 1.x code to the new JMX 1.2 code.
MBeanServerInvocationHandler usage
The JMX API to call an MBean via MBeanServer is very tedious: involves a reflection-like syntax and
a complex exception handling.
The reflection-like syntax is sometimes an advantage, but it suffers of lack of static type checkings
made by the compiler.
The exception handling is complex since it involves unwrapping of
javax.management.MBeanException s and rethrowing of the original exception thrown
by the MBean method, very much like
java.lang.reflect.InvocationTargetException
requires.
Fortunately, JDK 1.3 provides
dynamic proxies via the
java.lang.reflect.Proxy class.
By means of dynamic proxies, is it possible to write a proxy that hides the complexity of JMX
invocations and provides static type checking and trasparent exception handling.
Compare the two code examples below and note how the second example is cleaner.
Standard JMX invocation
JMX invocation with MBeanServerInvocationHandler
Usage of the
javax.management.MBeanServerInvocationHandler class is straightforward
for standard MBeans, since they already comply a management interface that is also a Java interface.
This interface can be used directly
as argument for the creation of the proxy (the third parameter of the
MBeanServerInvocationHandler.newProxyInstance() call).
However, usage of MBeanServerInvocationHandler is not limited to standard MBeans, but also to dynamic MBeans
can use it, provided that the management interface they comply to does not change during proxy's life.
It is not necessary that the dynamic MBean implements a Java interface: it is
enough that the Java interface provided to the MBeanServerInvocationHandler is a (sub)set of the
management interface exposed by the dynamic MBean.
The MBeanServerInvocationHandler class can also be used for remote MBeans, in conjuction with the
JSR 160 API, like shown in the following code snippet:
Remote JMX invocation with MBeanServerInvocationHandler
Refer to the javadocs of the
javax.management.MBeanServerInvocationHandler class
for further details.
Porting examples for
mx4j.util.StandardMBeanProxy
The MX4J 1.x API of
mx4j.util.StandardMBeanProxy is very similar to
javax.management.MBeanServerInvocationHandler 's.
Below are shown two code snippets that compare the old MX4J 1.x API with the new standard one.
Note how only the line marked with (*) changes from the old version to the new one.
Old MX4J 1.x proxy API
Standard JMX 1.2 proxy API
mx4j-3.0.2/src/docs/english/jsr160-explained.xml 100644 0 0 233224 10513545721 16464 0 ustar 0 0
What is JSR 160 ?
Introduction
The Java Management Extension (JMX) API is defined and under maintenance release of the Java Specification
Request (JSR) number 3.
JMX defines the API for management of Java applications, and those API are local to the application: remote
clients that would like to connect to a JMX-enabled remote application and manage or monitor it using JMX
could not do it in a standard way.
The MX4J project, the JMX reference implementation itself, and other JMX implementations provide custom
connectors, mostly RMI-based and HTTP-based, but those are not interoperable.
To fill this gap,
JSR 160 extends JSR 3 by providing a standard
API to connect to remote JMX-enabled applications.
Currently, JSR 160 has defined a mandatory connector based on RMI (that supports both RMI/JRMP and RMI/IIOP),
and an optional one based on sockets and Java serialization (JMXMP).
JSR 160 thus provides a standard way to connect to remote JMX-enabled applications using RMI; it is possible
to use MX4J JSR 160 implementation on client side, and have a JMX Remote Reference Implementation on server
side, or viceversa.
This allows the creation of Management Consoles based on Swing, for example, that will be able to interoperate
no matter which JMX implementation is used.
MX4J's JSR 160 implementation
MX4J implements JSR 160. This means that MX4J ships the standard JSR 160 API, located in package
javax.management.remote , and the mandatory providers defined by the specification,
namely the
rmi and
iiop providers, located in package
javax.management.remote.rmi .
MX4J does not implement yet the optional
jmxmp provider defined by the JSR 160 specification.
MX4J provides other four providers, not specified by the JSR 160 specification. This means that they will work
only if MX4J runs at both client and server side. These four providers are the
soap ,
local ,
hessian and
burlap providers.
To sum up, MX4J allows you to specify JMXServiceURLs (see next section) of the following kind:
service:jmx:rmi://host
service:jmx:iiop://host
service:jmx:soap://host
service:jmx:local://host
service:jmx:hessian://host
service:jmx:burlap://host
How to use JSR 160
Introduction
Using JSR 160 is very simple; the API is standard, so it does not matter if you use MX4J's JSR 160
implementation or Sun's JSR 160 reference implementation.
You can checkout the JSR 160 examples shipped with MX4J to understand how to use the JSR 160 API.
JMXServiceURLs
JSR 160 connector servers are identified by a JMXServiceURL, represented by the class
javax.management.remote.JMXServiceURL .
A JMXServiceURL is a string of the form:
service:jmx:
<protocol> ://[[[
<host> ]:
<port>] /
<path> ]
where
protocol is a short string that represent the protocol such as "rmi", "iiop", "jmxmp"
or "soap", while
host ,
port and
path are optional.
A JMXServiceURL can be seen as the "address" of a JMXConnectorServer, and it is the mean by which
a JMXConnector can connect to a JMXConnectorServer.
However, a JMXServiceURL is not sufficient to express the many possibile configurations of a
JMXConnectorServer (for example, it would be difficult to use a JMXServiceURL to specify - for the
RMIConnectorServer - the RMIClientSocketFactory and the RMIServerSocketFactory).
For this reason JMXConnectorServers and JMXConnector make use of
java.util.Map s to
specify environment properties that a JMXConnectorServer or a JMXConnector may use to setup properly.
Creating a JMXConnectorServer
A JMXConnectorServer is attached to an MBeanServer.
This can be achieved by explicitely passing the MBeanServer to the JMXConnectorServer at the moment of
creation, or by registering the JMXConnectorServer - an MBean itself - inside the target MBeanServer.
Once a JMXConnectorServer is attached to an MBeanServer, it is not yet ready to accept incoming calls
from clients: it must be
started .
After a JMXConnectorServer has been started successfully, it is ready to accept incoming calls from clients.
Symmetrically, a JMXConnectorServer must be
stopped in order to stop accepting incoming
calls from clients. After a JMXConnectorServer has been stopped, it cannot be restarted, and should be
tossed away.
The preferred way to create a JMXConnectorServer is by using the
javax.management.remote.JMXConnectorServerFactory class:
Creating and starting a standalone JMXConnectorServer
The example above creates a JMXConnectorServer attached to a freshly created MBeanServer.
The JMXConnectorServer - itself an MBean - is however not registered in the MBeanServer.
The following code creates a JMXConnectorServer and registers it in a MBeanServer.
Creating and starting an MBean JMXConnectorServer
Once a JMXConnectorServer is connected to an MBeanServer and once it has been started, it is possible to
create a JMXConnector on a client host and connect it to the JMXConnectorServer.
We already saw that the mean used by a JMXConnector to connect to a JMXConnectorServer is a JMXServiceURL.
Creating a JMXConnector
If a JMXConnectorServer is the server-side component that allows to interact with a MBeanServer,
a JMXConnector is the client-side component that allows client code to contact a remote MBeanServer.
A JMXConnector handles the details of registering notification listeners and receiving notifications from the
remote MBeanServer, as well as providing a way to authenticate to the JMXConnectorServer, and eventually
execute operations on behalf of a given
javax.security.auth.Subject .
Finally the JMXConnector allows client code to obtain an implementation of the
javax.management.MBeanServerConnection interface that allows to interact with the
remote MBeanServer as if it is local.
The preferred way to create a JMXConnector is to use the
javax.management.remote.JMXConnectorFactory class:
Connecting a JMXConnector
JMXConnectors can be instantiated, but connected at a later time.
Below is a code snippet that shows how to instantiate a JMXConnector and then connect it
to the JMXConnectorServer.
Note the use of two different environment Maps: one is used to specify creation parameters, the other
to specify connection parameters.
Creating and connecting a JMXConnector
Remote Notifications
JSR 160 connectors are able to receive notifications emitted by a remote MBean.
The details of the mechanism of how remote notifications are delivered depends on the protocol
used by the connector; however, few general principles are explained below.
To receive notifications, a client must register a listener by means of the
javax.management.MBeanServerConnection.addNotificationListener(...) method.
There are two overloaded versions of this method: one that takes an ObjectName as listener, and one that
takes a NotificationListener as listener.
In the first case, the listener is remote (an MBean in the remote MBeanServer) and thus both the filter
and the handback object are sent over the wire to the server (and of course both must be serializable).
The more interesting case is the second, where the listener is local to the client code.
In this case the listener that receives notifications emitted by a remote MBean always
remains local to the client code that registered it. The NotificationListener object is never sent across
the wire.
NotificationListener objects are usually implemented with anonymous inner classes
(that most of the times are not serializables), and client code should not make any particular attention
on how to implement NotificationListeners that receive remote Notifications: anonymous inner classes are
a good choice.
On the other end, if the remote MBean sends custom subclasses of the Notification class, it must ensure that
the custom Notification objects are
serializable .
The meaning of
serializable depends on the protocol used; in case of RMI, it is the
usual meaning of "Java serializable" (that is, it can be written to a
java.io.ObjectOutputStream ).
NotificationFilters may or may not be sent over the wire, depending on the protocol used by the JMXConnector.
It is a good choice to use the standard JMX NotificationFilters such as
javax.management.NotificationFilterSupport ,
javax.management.AttributeChangeNotificationFilter and
javax.management.relation.MBeanServerNotificationFilter to perform filtering of
Notifications: these classes are serializable, and known to the server side.
If you want to write your custom NotificationFilter, write it in such a way that will work no matter if it is
run on client side or on server side, and be sure its class is known to the server side (for more
details about server side classloading, refer to the JSR 160 specification).
The handback object always remains on client side.
In the MX4J implementation, notifications are requested by the client to the server, and use a notification
buffer as explained in the JSR 160 specification.
Since it's the client that initiates the notification request, the mechanism can be seen as a polling
mechanism. However, if the server does not have notifications to send to the client, it does not return
an empty result, but instead holds the call for a configurable timeout until a notification is emitted
or the timeout elapses.
This allows to reduce the network traffic (since there is no continuous polling from the client to the
server) and still have a fast reactivity to notification emitted by the server.
Refer to the javadocs of the
mx4j.remote.RemoteNotificationClientHandler
and of the
mx4j.remote.RemoteNotificationServerHandler
for further details.
Take also a look at the examples bundled with the MX4J distribution for code snippets on registering
listeners to remote MBeans.
Below, a quick example of how to register a listener to a remote MBean:
Registering a NotificationListener to a remote MBean
JSR 160 Security
Requiring user authentication to connect to a JMXConnectorServer
JSR 160 provides a pluggable authentication mechanism based on the
javax.management.remote.JMXAuthenticator interface.
The JMXAuthenticator interface has only one method that takes credentials from the client and returns a
javax.security.auth.Subject :
public Subject authenticate(Object credentials) throws SecurityException
An implementation of that interface may read username / password pairs from a file, and compare them
with the supplied credentials (for example a String[2] where String[0] contains the username and String[1]
contains the password).
MX4J provides a default implementation of the JMXAuthenticator interface, namely the
mx4j.tools.remote.PasswordAuthenticator class. Refer to the PasswordAuthenticator
javadoc for details.
It is possible to specify a file or a resource containing username/password pairs (where
passwords can be in clear text or obfuscated via a digest algorithm) to the PasswordAuthenticator, that
will then check correctness of the credentials passed by the client against this file or resource.
It is worth noting that JMXConnectorServers that offer a strong security (an example of a JMXConnectorServer
that offers strong security is the - optional -
javax.management.remote.jmxmp.JMXMPConnectorServer ,
whose security is based on
SASL ) may choose not to
base their security system on JMXAuthenticator.
The JMXAuthenticator implementation must be provided to the JMXConnectorServer via the environment map:
Using JMXAuthenticator in a JMXConnectorServer
Once the JMXConnectorServer is setup correctly, it is possible to connect only by providing correct credentials
from a JMXConnector.
The credentials must be serializable because they are provided by the JMXConnector and will be sent to the
JMXConnectorServer to authenticate a Subject.
If the credentials provided are not correct, a SecurityException is raised.
Passing credentials using a JMXConnector
Once correct credentials are provided the server side, the JMXAuthenticator can authenticate a Subject.
When you invoke operations on the MBeanServerConnection object obtained from the JMXConnector, the invocation
end up on the server side, and over there the operation will be executed on behalf of the authenticated Subject.
If a SecurityManager is in place, you can specify different permissions for different authenticated subjects,
fine tuning the security policy as you want.
You can for example grant all permissions to an "admin" principal, while granting only read access to MBean
attributes to a "guest" principal.
If a SecurityManager is not in place, then using a JMXAuthenticator only allows you to deny access to non
authenticated users: a simple way to restrict the access to the JMXConnectorServer.
Running under SecurityManager and Subject Delegation
Running a JMXConnectorServer under a SecurityManager allows to fine tune access to it from remote clients.
If you just want to restrict access to the JMXConnectorServer to authenticated users, but allow an
authenticated user to perform any operation on the JMXConnectorServer and its underlying MBeanServer,
then it is enough to provide a JMXAuthenticator while creating the JMXConnectorServer,
as explained in the section above.
If instead, you want to be able to grant different permissions to different users, then you have to
run the JMXConnectorServer under a SecurityManager and grant different permissions to different users.
For example, you may want the "admin" user to be able to perform any operation on the remote MBeanServer,
and the "guest" user to be able to perform only read operations, and not write operations.
To show how to achieve this fine tuning, we will refer to example classes bundled with the MX4J distribution,
namely
mx4j.examples.remote.security.Client and
mx4j.examples.remote.security.Server , and show how to setup the policy files in JDK 1.4
and JDK 1.3.
By default it will shown the sequence of operations for JDK 1.4, and differences with JDK 1.3 will be
highlighted.
We will assume that the JMX implementation (mx4j.jar), the JMX Remote implementation (mx4j-remote.jar)
and the MX4J examples (mx4j-examples.jar) are present in a directory called $WORK/lib, and that the
example is started from the $WORK directory.
For JDK 1.3 you will also need jaas.jar in the $WORK/lib directory.
As first step, let's take a look at
mx4j.examples.remote.security.Server .
It first creates a "users.properties" file with the "admin" and "guest" users under $WORK.
This step is of course omitted in a real environment, where the "users.properties" file is provided
externally.
Then it starts the NamingService and the JMXConnectorServer over RMI/JRMP, specifying a JMXAuthenticator
that reads user names and passwords from the "users.properties" file.
Let's create now a policy file under $WORK, server.policy:
The server.policy file
Notice how we grant AllPermission to the MX4J jars that implement JMX and JMX Remote,
and to the MX4J Tools jar (and to JAAS jar for JDK 1.3).
You can consider those jars as libraries, and you trust that the MX4J implementation, as well as the JAAS
implementation, won't harm your system.
Different is the motivation behind granting AllPermission to the MX4J Examples jar, which is the one that
containes
mx4j.examples.remote.security.Server .
For this example we grant AllPermission because we trust the Server class not to perform any security
sensitive operation beyond starting the JMXConnectorServer and reading the "users.properties" file,
but you may want to restrict the set of operations performed by the classes that start the
JMXConnectorServer.
With the above server.policy file, you can successfully start the
mx4j.examples.remote.security.Server class, in this way:
Starting the secured server
java -Djava.security.manager
-Djava.security.policy==server.policy
-Djava.security.auth.policy=jaas.server.policy --> Only for JDK 1.3
-classpath lib/mx4j-examples.jar; \
lib/mx4j.jar; \
lib/mx4j-remote.jar \
lib/jaas.jar --> Only for JDK 1.3
mx4j.examples.remote.security.Server
]]>
Note the double equals sign '=' after the property "java.security.policy": see the documentation guide
about policy files for the JDK for further information about the meaning of this double equals sign.
It is time now to grant permissions for the operations a remote client that is connecting
may want to do.
Since we specified a JMXAuthenticator, only authenticated users can connect to the JMXConnectorServer.
Furthermore, since we run under a SecurityManager, authenticated users may only perform the operations
granted to the corrispondent principal in the policy file.
For JDK 1.3, these permissions must be specified in a separate file, named here "jaas.policy.file",
referenced by the "java.security.auth.policy" system property at startup time (see above).
For JDK 1.4, these permissions can be added to the "server.policy" file.
The principal-specific permissions
First of all, note that there is no specification of the codebase.
It is not possible to specify the codebase for permissions you want to grant to a JSR 160 connector
server, you have to omit it.
Second, note that there are three grant blocks: one that specifies permissions common to all principals,
one that specifies permissions for the "admin" principal, and one that specifies permissions for the
"guest" principal.
The common block allows anyone to connect to the server side, as specified by the two SocketPermissions.
The "admin" principal has AllPermission, while the "guest" principal can only call the
javax.management.MBeanServerConnection.queryNames() method.
In the same exact way, you can specify many principal blocks, one per principal, with a different set
of permission for each one; this allows to fine tune the permissions granted to each principal
that connects to the server side.
Lastly, note the SubjectDelegationPermission. This permission is needed when you have, on client, a
JAAS Subject and you want to perform, on server side, operations on behalf of that Subject.
For example, it is possible that on a client there are many users that want to interact with the
server side, and that all users have been granted the same set of permissions.
In this case is more efficient to establish only one connection with the server side, with an
authenticated user (in the example above, "guest"), and then use that connection with many
delegate users, by using
javax.management.remote.JMXConnector.getMBeanServerConnection(Subject delegate) .
In the example above, the authenticated principal "guest" allows any delegate principal (of class
javax.management.remote.JMXPrincipal ) to perform
operations in its behalf, since it grants a SubjectDelegationPermission with a name of
"javax.management.remote.JMXPrincipal.*" (refer to the JMX Remote javadocs for explanation of the
syntax of SubjectDelegationPermission).
Advanced JSR 160
Intercepting calls between the JSR 160 JMXConnectorServer and the MBeanServer
JSR 160 offers a standard way of intercepting calls between the JMXConnectorServer
and the target MBeanServer.
Such interception can be useful for logging, for granting access in a dynamic way (for example
based on the value of the arguments for a certain call to an MBean - this cannot be
achieved via the standard security policy files), for caching of values, and whatever else
you may find useful.
In the examples bundled with the MX4J distribution, there is an example of how to setup
such an interception, and here we will show in brief how to do it. Refer to the example's
javadocs for further information.
First of all, you need to implement the interceptor. In the past, these interceptor were all
implementation-dependent, but JSR 160 standardized the interface to achieve this:
javax.management.remote.MBeanServerForwarder .
Below you can find a simple (incomplete) example of how to track the Subject of the current
invocation.
Simple subject interceptor skeleton
It is very simple to add this interceptors to a JMXConnectorServer, to intercept calls
directed to the target MBeanServer. It is important to do this before the JMXConnectorServer
is started, because if done afterwards it will have no effect (interception will not take place).
Setting up the interception on the JMXConnectorServer
Standard JSR 160 JMXConnectors and JMXConnectorServers
Overview of RMIConnector and RMIConnectorServer
JSR 160 compliance requires implementation of a JMXConnector and JMXConnectorServer that
use Java's Remote Method Invocation (RMI) to communicate.
The RMI connector and connector server are meant to work both over JRMP (Java Remote
Method Protocol, RMI's native protocol) and over IIOP (Internet Inter ORB Protocol, CORBA's
native protocol), and MX4J implements both fully.
Java's RMI works so that the RMI client needs to have a
stub object.
A normal java method call on the stub is routed to the network and ends up on the RMI server
making possible to perform remote calls as if they were standard local calls.
The stub takes care the details of invoking the server side such as arguments and return
value marshalling, exception throwing and so on.
The stub class is normally present in the client's
classpath (since the stub is part of the JSR 160 classes), but the stub object is normally
downloaded from a naming server such as the
rmiregistry .
The RMI client only needs to know the naming path under which the stub object has been bound to
by the RMI server.
Connecting to the RMIConnectorServer
A JSR 160 RMIConnector needs to be able to retrieve the stub object in order to contact
a remote JSR 160 RMIConnectorServer.
JSR 160 gives two possibilities to retrieve the RMI stub object to be able to contact the
RMIConnectorServer.
The first way to contact an RMIConnectorServer is make the stub object part of
the RMIConnectorServer's address, represented by a JMXServiceURL.
The JSR 160 specification refers to this possibility as the "encoded form".
In case of JRMP, the stub is serialized and its bytes are Base64 encoded and attached to
the JMXServiceURL, so that passing the JMXServiceURL to clients, they have all information
needed to contact the server side (no naming server is needed).
The JMXServiceURL path, in this case, starts with
/stub/ .
In case of IIOP, the IOR is attached to the JMXServiceURL (and again no naming server is
needed).
The JMXServiceURL path, in this case, starts with
/ior/ .
Simply passing an encoded form JMXServiceURL to a JMXConnector is enough to allow it
to contact the corrispondent JMXConnectorServer: the JMXConnector will take care of
decoding the stub.
Examples of encoded form JMXServiceURLs
The second way to contact an RMIConnectorServer is to specify a path in the JMXServiceURL
that indicates the location of a naming server and the JNDI path where the stub object
can be found.
The JSR 160 specification refers to this possibility as the "JNDI form".
In this case the JMXServiceURL path starts with
/jndi/ .
Working with JNDI requires to specify some information about the naming server and the configuration
of JNDI itself. These information can be passed to the RMIConnector in several ways; these ways are
very similar to the the ways JNDI requires to specify parameters and present no surprise to JNDI users.
For example, the URL 'rmi://namingHost:1099/jndiPath' (not to be confused with a JMXServiceURL) says that
a naming server on the host 'namingHost' is listening on port 1099, that the naming server is an
rmiregistry (indicated by the 'rmi' scheme) and that under the '/jndiPath' path something has been registered.
Similarly, the URL 'iiop://namingHost:900/jndiPath' says that
a naming server on the host 'namingHost' is listening on port 900, that the naming server is a
COS naming service (indicated by the 'iiop' scheme) and that under the '/jndiPath' path something
has been registered.
It is straightforward then to specify a JMXServiceURL that uses the JNDI URL form:
Examples of JNDI URL form JMXServiceURLs
Alternatively, JNDI properties can be specified in the usual ways they are specified for JNDI,
namely specifying system properties, a 'jndi.properties' file in the classpath or via an environment Map
passed to the
JMXConnector.connect(Map environment) method or to the
JMXConnectorFactory.connect(JMXServiceURL url, Map environment) method.
Since JNDI properties are specified separately, the JMXServiceURL path can be specified
using the JNDI short form, where only the JNDI path is specified in the JMXServiceURL:
Examples of JNDI short form JMXServiceURLs
ORB properties for JMXConnector and JMXConnectorServer over IIOP
When working with IIOP, there may be the need to pass some information in order to
correctly create the ORB.
In plain Java code, these properties are passed via system properties or via environment Map.
Similarly, when using the JSR 160 API, ORB properties can be specified as system properties
or via the environment Map
passed to the
JMXConnector.connect(Map environment) method or to the
JMXConnectorFactory.connect(JMXServiceURL url, Map environment) method.
RMI socket factories (over SSL) for the RMIConnectorServer over JRMP
JSR 160 specifies two constants to specify the
java.rmi.server.RMIClientSocketFactory
and
java.rmi.server.RMIServerSocketFactory instances that the
RMIConnectorServer should use to export itself to the RMI runtime.
These constants are
javax.management.remote.rmi.RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE and
javax.management.remote.rmi.RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE .
The MX4J implementation provides already an implementation of the
java.rmi.server.RMIClientSocketFactory
and
java.rmi.server.RMIServerSocketFactory interfaces that can be used to
encrypt the communication between the RMIConnector and the RMIConnectorServer using SSL, namely the
mx4j.tools.remote.rmi.SSLRMIClientSocketFactory and
mx4j.tools.remote.rmi.SSLRMIServerSocketFactory .
These classes only work with JDK 1.4 or superior.
How to specify the RMI socket factories
MX4J's JSR 160 JMXConnectors and JMXConnectorServers
The SOAP JSR 160 connector
Thanks to the fact that JSR 160 allows complete pluggability of the communication protocol between
JMXConnector and JMXConnectorServer, it is possible to add easily new protocol providers.
However, since these protocol providers are not defined by the JSR 160 specification, they are likely
to be not interoperable between different JSR 160 implementations.
This means that - for example - it is safe to have the JSR 160 Sun Reference Implementation on server side
and MX4J on client side, or viceversa, only when the the protocol used is RMI or IIOP.
MX4J implements a JSR 160 JMXConnector and JMXConnectorServer that use
SOAP to communicate. The SOAP toolkit used by MX4J is
Axis 1.1 .
When the SOAP protocol is used, other JSR 160 implementations will fail because
they don't implement the SOAP provider, or they don't implement it in a interoperable way with MX4J.
By placing MX4J on both client and server side, you can leverage the functionalities offered by MX4J:
in this case you can use SOAP to communicate from client to server and viceversa.
Refer to the examples shipped with the MX4J distribution,
mx4j.examples.tools.remote.soap.Server and
mx4j.examples.tools.remote.soap.Client to follow the instructions below.
Starting successfully a SOAPConnectorServer requires Axis 1.1 and a servlet 2.3 compliant web container.
In this example the web container will be the
Jetty web
container.
Starting a standalone SOAPConnectorServer will perform several operations:
Start a Jetty server on the port specified by the JMXServiceURL
Deploy to Jetty the Axis servlet, and mapping it to the path specified by the JMXServiceURL
Deploy to Axis the webservice that represent the remote MBeanServer
On server side, the SOAPConnectorServer ignores the host part of the JMXServiceURL, since
it starts the web container on the local host.
It is therefore recommended to start the SOAPConnectorServer passing null as host name,
to allow the real host name to be retrieved and used (as stated by the JMXServiceURL specification).
Also, it is recommended that URL path of the JMXServiceURL not be the empty string.
On client side, differently from the rmi, iiop and local providers, the host part of the JMXServiceURL
is not ignored; it is used to connect to the server side.
It is very important that the host name of the JMXServiceURL on the server and the host name
of the JMXServiceURL on the client be exactly the same. If they differ (for example one is the
IP address and the other is the host name), then a message saying that the SOAPConnectorServer
cannot be found will be displayed.
It is possible to start several SOAPConnectorServers in the same JVM, with the constraint that
they must all have different URL path in their JMXServiceURLs.
In this case only one instance of Jetty will be used (and multiple servlet-mappings mapped to
the same Axis servlet).
Starting the SOAPConnectorServer
Connecting to the SOAPConnectorServer
When you want to use a SOAPConnectorServer from within a running web application, it is possible
to tell to the SOAPConnectorServer not to start another web container, by passing the property
SOAPConnectorServer.USE_EXTERNAL_WEB_CONTAINER with the value
Boolean.TRUE to the environment map passed to
JMXConnectorServerFactory .
In this case, the external web container must already have Axis deployed and mapped to a certain path.
For example, the default installation of Axis maps the Axis servlet to the path /axis/services/*.
The JMXServiceURL to use in this case should be:
service:jmx:soap://host:8080/axis/services
As further example, you can take a look at the index.jsp page inside the mx4j-soap.war bundled
with the MX4J distribution to see how a SOAPConnectorServer can be started from within a web
application.
The HESSIAN and BURLAP JSR 160 connectors
MX4J implements other two JMXConnectors and JMXConnectorServers that use open source (Apache license)
Caucho protocols
Hessian and Burlap .
Similarly to the SOAP JMXConnector and JMXConnectorServer, Hessian's and Burlap's
JMXConnector and JMXConnectorServer use HTTP as transport protocol.
Starting successfully a [Hessian|Burlap]ConnectorServer requires the hessian/burlap library
(hessian-3.0.8.jar) and a servlet 2.3 compliant web container, like for example, the
Jetty web container.
Starting a standalone [Hessian|Burlap]ConnectorServer will perform several operations:
Start a Jetty server on the port specified by the JMXServiceURL
Deploy to Jetty an MX4J's customized [Hessian|Burlap] servlet, and mapping it to the path specified by the JMXServiceURL
Follow the advices given for the SOAPConnectorServer in choosing the JMXServiceURL on server side
and on client side.
Starting the HessianConnectorServer
Connecting to the HessianConnectorServer
To use the Burlap protocol instead of the Hessian protocol, just replace the protocol (and optionally
the path), from 'hessian' to 'burlap'.
Using HTTP-based connectors over HTTPS
The HTTP-based connectors, namely the soap, hessian and burlap connectors, can be run over the HTTPS
protocol.
The configuration of the MX4J connector is quite simple, but requires understanding of how certificates
and security in general work in the Java platform.
You can find more information on the security in the Java platform
here .
HTTP-based MX4J connectors can be run over HTTPS by adding the string "+ssl" (without quotes) to
the protocol of the JMXServiceURL normally used to start the connector over the plain HTTP protocol.
For example, the JMXServiceURL to start the SOAP connector server over plain HTTP would be something like
service:jmx:soap://host:8080/jmxconnector
while the JMXServiceURL to start the SOAP connector server over HTTPS would be something like
service:jmx:soap+ssl://host:8443/jmxconnector
However, this is not enough, since running a web container over HTTPS requires a detailed configuration
of the web container itself and of the keystore that contains the certificate with the public key for the
SSL protocol.
Configuration of the web container
The configuration of the web container usually requires to specify a file path for the keystore, the
keystore and the key passwords, and of course the HTTPS port the web container will listen to, that
must match the port provided in the JMXServiceURL.
This configuration is to be specified in the environment Map passed at the moment of the creation of the
JMXConnectorServer using the
mx4j.tools.remote.http.HTTPConnectorServer.WEB_CONTAINER_CONFIGURATION
constant as key, and a String that points to the file path of the configuration file as value.
Below there is a sample configuration file for the default web container used by MX4J,
Jetty .
Example Jetty configuration file to run JMXConnectorServers over HTTPS
8443
P1
30000
30
2000
/mx4j.ks
mx4jmx4j
mx4jmx4j
MSIE 5
]]>
Note that the configuration specifies the keystore file path, the keystore and the key passwords.
Jetty allows the passwords to be obfuscated; see the Jetty documentation for more details
here .
Configuration of the keystore
The keystore must contain a valid certificate issued for the server host where the
web container (started by the HTTP-based JMXConnectorServer) will run on.
This is normally specified in the common name part of the distinguished name of the certificate.
Furthermore, the certificate must be trusted by the client.
This means that the certificate must be signed by
a well-known certification authority, and that the root certification authority must be present
in the trusted certificates of the Java platform on client side, normally stored in the
$JAVA_HOME/jre/lib/security/cacerts file.
In the more common case of "experiments", or during development, you can create a self-signed
certificate using this command:
$JAVA_HOME/bin/keytool -genkey -keyalg "RSA" -keystore mx4j.ks -storepass mx4jmx4j -dname "cn=myhost"
Replace the keystore file path and password with your choices, and replace the common name value with
the host name the web container will run on.
To avoid to import this certificate in the trusted certificates of the Java platform on client side, you must
specify the following system property (using either the -D syntax in the command line that starts the JVM,
or calling
System.setProperty in your program):
javax.net.ssl.trustStore=mx4j.ks
Replace the keystore file path with your choice.
Needless to say we don't recommend to set these java properties in your programs, nor to share
the keystore between client and server. What should be done in real environments is to sign the
certificate with a trusted certification authority.
Code examples
Refer to the examples bundled with the MX4J distribution, specifically the
mx4j.examples.tools.remote.hessian.ssl.* files.
Starting and connecting to the Hessian connector server over HTTPS
Porting old MX4J remoting code to JSR 160
Introduction
MX4J version 1.x provided a custom implementation of a connector server and connector client based on
the RMI protocol.
That old code is now obsolete due to the fact that MX4J implements JSR 160. In the following sections will
be explained how to port old MX4J 1.x remoting code to the standard JSR 160 API.
Porting Examples
The following example will show old MX4J 1.x remoting code compared to JSR 160 code,
with respect to creating and starting a connector server over JRMP on server side.
Old MX4J 1.x remoting code, server side
JSR 160 remoting code, server side
Note the following differences:
How the JNDI name "jrmp" has been replaced by a JMXServiceURL with an URLPath of "/jndi/jrmp".
How the instantiation of the adaptor has been replaced by usage of a factory.
How the JNDI properties are passed via a Map.
Note that in both cases the adaptor (connector server) must be started in order to be able to accept
incoming connections (4).
Note also that both the JRMPAdaptor and the JMXConnectorServer are MBeans, and as such they can be
registered inside an MBeanServer (no differences here).
The following example will show old MX4J 1.x remoting code compared to JSR 160 code,
with respect to creating and connecting a connector over JRMP on client side.
Old MX4J 1.x remoting code, client side
JSR 160 remoting code, client side
Again, note the following differences:
How the JNDI name "jrmp" has been replaced by a JMXServiceURL with an URLPath of "/jndi/jrmp".
How the instantiation of the connector has been replaced by usage of a factory.
How the JNDI properties are passed via a Map.
The different number of arguments passed to the connect() method.
How the
mx4j.connector.RemoteMBeanServer class is replaced by the
javax.management.MBeanServerConnection class.
Very similar changes apply when the old MX4J 1.x remoting code is using the
mx4j.adaptor.rmi.iiop.IIOPAdaptor and the
mx4j.connector.rmi.iiop.IIOPConnector .
MX4J Remote Tools and Utilities
Remote MBean Proxying
Complex systems based on JMX are also, most of the times, distributed systems.
Such systems are often made of
nodes , and each node is made of
components .
When the underlying architecture is JMX, in each node there is one (possibly more) MBeanServer that manages
the components, and each component is an MBean.
Sometimes there is the need to have one MBeanServer gathering information from many remote
MBeanServers. However, the information needed is only part of the information exposed by each remote
MBeanServer: you may want to collect only some information from each remote MBeanServer.
For this purpose, it is useful to write an MBean that exposes this information, and register one instance
of this MBean per each remote MBeanServer.
A client application may want to connect to the gathering MBeanServer to see the gathered
information, without having the hassle to connect to each individual remote MBeanServer and choose the
information MBean among the others.
In short, the gathering MBeanServer acts as a proxy for certain MBeans hosted elsewhere: client applications
only need to contact the gathering MBeanServer to get the information they need.
For this purpose MX4J provides a remote MBean proxy: an MBean you can register in the
gathering MBeanServer that acts as a proxy for a remote MBean hosted in a remote MBeanServer.
Refer anyway to the javadocs of the
RemoteMBeanProxy class for further
information.
Below there is an example where remote MBeanServers publish information about the downloads of
products, and a gathering MBeanServer proxies these information for easier access via the HTTPAdaptor.
Remote MBean proxying
The
mx4j.remote.RemoteMBeanProxy MBean is a transparent proxy for the remote MBean:
invoking a method on the proxy results in the method being invoked on the remote MBean; registering a local
NotificationListener on the proxy results in registration on the remote MBean, and thus
the local listener will receive notifications emitted by the remote MBean.
For example, by proxying the remote MBeanServerDelegate MBean, you can receive locally notifications of
MBean registrations/unregistrations that happens in the remote MBeanServer.
mx4j-3.0.2/src/docs/english/license.xml 100644 0 0 6075 10513545721 15054 0 ustar 0 0
License
MX4J is released under an Apache-style license. In practice this means
that you can do almost anything you want with the code, including its
use in commercial software.
The actual text of the license is included below:
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 [at] users [dot] sourceforge [dot] 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
the MX4J website .
mx4j-3.0.2/src/docs/english/tools.xml 100644 0 0 110375 10513545721 14631 0 ustar 0 0
XML Configuration Loader
Loading and starting MBeans using XML files
The javax.management.loading.MLet class provides a way to load
and instantiate MBeans from a configuration file called MLet file .
The MLet file has however a limited syntax, since it can only instantiate and register
MBeans into an MBeanServer: no method invocation is possible, no MBean's unregistration,
no possibility to use factories to create objects and so on.
Furthermore, the MLet file format is not XML.
MX4J's mx4j.tools.config.ConfigurationLoader defines an XML configuration
file format where it is possible to specify creation of objects, their registration
into an MBeanServer, their unregistration, the invocation of methods, both via MBeanServer
(JMX invocations) and via normal Java invocation.
Let's see a simple example that registers MX4J's HTTP adaptor into an MBeanServer.
First, we need a small class that creates the MBeanServer and the ConfigurationLoader:
Main class for configuration loading
The class simply creates an MBeanServer, creates the ConfigurationLoader and tells
the configuration loader to read an XML file from the path passed as argument.
The XML file can be the following:
XML file for configuration of MX4J's HttpAdaptor
9090
localhost
connectors:type=http,processor=xslt
]]>
The first thing to notice is that the configuration file is splitted in 2 sections, namely
startup and shutdown .
We will see later how the shutdown section comes into play.
Let's examine the startup section.
It contains the creation of the mx4j.tools.adaptor.http.HttpAdaptor
MBean (passing 2 arguments to its constructor)
and of the mx4j.tools.adaptor.http.XSLTProcessor MBean via the
create element.
These MBeans are registered in the MBeanServer that also manages the ConfigurationLoader MBean.
Both these 2 operations are possible also with the MLet file.
What is different is the possibility to set JMX attributes and invoke JMX operations on the
MBeans just registered. This is achieved with the call element: first the
XSLT processor is set onto the HTTP adaptor, then the HTTP adaptor itself is started.
Let's see now a more complex example: how to register and start a JSR 160 connector server.
XML file for configuration of a JSR 160 connector server
1099
]]>
Note the usage of the object element. It is possible to assign an ID (in the example
is "rmi") to objects that gets created in the XML file, and refer to them afterwards using the
refobjectid attribute.
Note also the syntax to invoke the static call to the JMXConnectorServerFactory ,
and the syntax to invoke non-JMX operations when calling "start" on the "rmi" object.
Objects can be created by using the new element, and constructor arguments specified
with the arg element. Note how null arguments are passed to the
JMXConnectorServerFactory (the second and third argument of type Map and MBeanServer).
Let's now explain the meaning of the shutdown section.
If the startup section defines how the MBeans should be created, registered and
put into operation (for example by calling "start" operations on them), the shutdown section defines
how the MBeans should be stopped from operating and eventually unregistered.
It remains the problem of how to make the configuration loader invoke the shutdown section.
This is done by specifying a port as attribute of the configuration element;
the configuration loader will start a server socket on that port, so that from another JVM will be
possible to connect to that socket and invoke the shutdown command.
For security reasons, the server socket will listen on the loopback interface of the host, so that
only JVMs started on the same host can invoke the shutdown section.
Below, an example of a class that invokes the shutdown section and a sample XML file that specifies
the port for the server socket.
Simple XML file that specifies the command port
1099
]]>
Simple Java class that invokes "shutdown" to execute the shutdown section
The XML configuration DTD is the following:
XML configuration DTD
]]>
Dynamic MBeans
AbstractDynamicMBean base class for DynamicMBean implementation
Writing an MBean by implementing the
javax.management.DynamicMBean interface can be a heavy
and tedious task.
MX4J provides the class
mx4j.AbstractDynamicMBean as a base class to implement a
dynamic MBean.
This class handles most of the tedious work that must be done when implementing dynamic MBeans,
so that the MBean implementor has just to override few methods to provide the needed information required
to create the MBean.
The methods of the
AbstractDynamicMBean class can be divided in 2 groups: the methods of the
DynamicMBean interface and the methods added by
AbstractDynamicMBean itself.
AbstractDynamicMBean already implements all the methods of the
DynamicMBean
interface, and normally the MBean implementor does not have to override them.
The methods belonging to the second group are normally overridden by the MBean implementor to provide the MBean metadata information,
and are the following:
createMBeanAttributeInfo
, if the MBeans has manageable attributes
createMBeanOperationInfo
, if the MBeans has manageable operations
createMBeanNotificationInfo
, if the MBeans has manageable notifications
createMBeanConstructorInfo
, if the MBeans has manageable constructors
getMBeanDescription
A third group of methods belongs to the subclass of
AbstractDynamicMBean and are the implementation
methods, the ones that implement the functionality of the MBean itself (see below for an example).
Subclassing
AbstractDynamicMBean
As you can see above, no methods from the
DynamicMBean interface needs to be implemented.
It is sufficient to override some (or all) of the methods of the second group, and provide the relative methods
of the third group.
Normally the MBean implementor extends
AbstractDynamicMBean , but if the MBean already extends another
class it is sufficient to implement
DynamicMBean and delegate to a subclass of
AbstractDynamicMBean , having care of calling the
setResource
method (see example below).
Delegating to
AbstractDynamicMBean subclass
AbstractDynamicMBean can also be used for non-invasive management: if you already have a component
but you don't want to change it to implement a management interface, you can set it as target of a subclass of
AbstractDynamicMBean and provide the suitable metadata information.
Subclassing
AbstractDynamicMBean
The example above shows how simple can be to plug JMX into already existing architectures, and how it is possible,
in few lines of code, to make services manageable (and remotely manageable with JSR 160) without even impacting
already existing service's code.
Naming MBeans
MX4J ships with two naming MBeans, the NamingService and the CosNamingService, that wrap as MBeans respectively
the rmiregistry and the tnameserv tools provided with the JDK.
The NamingService MBean
The NamingService MBean allows you to start the
rmiregistry in the same JVM as other MBeans, such as the RMI MBean (see examples in the documentation), or the
RMI adaptor.
The MBean's class is
mx4j.tools.naming.NamingService .
The usage of the NamingService MBean does not require additional libraries, as all the needed classes are already
shipped with the JDK.
Deployment
The NamingService MBean is easily deployed into a JMX Agent. The following code snippet shows how to deploy it into
a JMX Agent.
Deploying the NamingService MBean
To use the NamingService MBean as rmiregistry, it must be started;
the NamingService MBean can be started and stopped at wish, simply by invoking the
start() and
stop() methods of the management interface.
Starting and stopping the NamingService MBean
It is also possible to specify the port on which the rmiregistry will run. Simply pass this parameter to
the constructor of the NamingService MBean. By default the rmiregistry runs on port 1099.
Changing the default port
]]>
It is also possible to change the rmiregistry port at runtime. Just start the NamingService MBean, stop it after a while,
change the port it runs on, and restarting it, so that it will accept requests on the new port.
Below you can see the steps needed to perform this change.
Changing the port at runtime
The CosNamingService MBean
The CosNamingService MBean is very similar to the NamingService MBean: it allows you to start
tnameserv in the same JVM as other MBeans.
The MBean's class is
mx4j.tools.naming.CosNamingService .
The usage of the CosNamingService MBean does not require additional libraries, as all the needed classes are already
shipped with the JDK.
Deployment
The CosNamingService MBean is easily deployed into a JMX Agent, in a way very similar to the NamingService MBean.
Exactly like the NamingService MBean, the CosNamingService MBean must be first registered in the MBeanServer and then
started using the management interface it exposes.
There is the possibility to set the port on which the service will listen for incoming connections, exactly like the
NamingService MBean.
One difference between the CosNamingService and the NamingService MBeans is that the latter provides and easy API
to be implemented, so that creating, starting and stopping it can be implemented easily by the MX4J team,
while the former does not.
A consequence of this is that tnameserv is started using
Runtime.exec()
and stopped by killing the process created when starting the MBean.
Since starting and stopping an external process may result in the
start
and
stop
returning
before the process is really started (or stopped),
it is recommended to sleep some time after start() and stop() in order to let
tnameserv to start and stop completely.
A suggested value for this delay may be few seconds (1000-5000 milliseconds), but the value strongly depends on the
hardware and operative system.
Mailer MBean
Introduction
The SMTP MBean is meant to be used to send emails from your JMX application.
The MBean's class is
mx4j.tools.mail.SMTP .
You can use it in basically two ways:
Directly by calling the sendMail method
By listening notifications, for instance from a Timer or Monitor
The usage of the MBean requires that you have JavaMail and the Java Activation Framework.
The MBean has been tested with JavaMail 1.2 and JAF 1.0.1.
Configuration
The MBean has quite many attributes to work but as a minimum you should set up the
serverHost
and
To . After that you can start sending emails.
If your server requires authentication, set the
LoginToServer attribute to true
and fill the
ServerUserName and
ServerPassword fields
You can also set the source address by setting the
FromAddress field as well
as the
FromName field. The destination attributes can be set setting a comma separated
list of addresses by using the
To ,
Cc and
Bcc attributes.
The addresses are not checked until a mail is actually sent, but in case some are not well formed, to those who are will be sent anyway
To make the MBean to listen for notifications set the
ObservedObject field. The SMTPMBean
will register iteself as listener of that MBean and when a notification is received it will send the mail.
If you set the
NotificationName field, only notification names with that type will be
valid to send a mail. For instance "javax.management.monitor.string.differ"
Keyword expanding
To make the content of the mail more customizable you can include keyword expansion
on the
Subject , and
Content field. The keywords
are special words set in between of $ signs. e.g. $date$. Those keywords will be replaced
before the mail is sent, so you can get text containing more information.
The recognized keywords are:
$date$ Expands to the current date formatted with locale format
$time$ Expands to the current time formatted with locale format
$datetime$ Expands to the current datetime formatted with locale format
$observed$ Expands to the observed MBean's ObjectName which triggered the mail
$notification$ Expands to the notification type which triggered the mail
$objectname$ Expands to the SMTPMBean's ObjectName
Jython MBean
Introduction
The JythonRunner MBean can be used to execute jython scripts. The main objective is
to use them for management tasks which are easiliy handled as scripts and that could be
modified and deployed at runtime.
The MBean's class is
mx4j.tools.jython.JythonRunner .
You can use it in two ways:
By calling the runScript method
By listening notifications, for instance from a Timer or Monitor
The usage of the MBean requires that you have jython installed. You can get a copy
at
http://www.jython.org . Jython is distributed
(as version 2.1) on a class file which is the installer and once execute will install the
jython distribution, e.g. at /usr/local/jython-2.1 or C:\Java\jython-2.1. Jython can be run in
two different ways depending on whether you want to use the jython standard library.
If you want to use the standard librarie, add the jython.jar as in the installation dir to the classpath. e.g.
java -cp /usr/local/jython-2.1/jython.jar:mx4j-jmx.jar:mx4j-tools.jar
In this way jython will be able to find the install dir and load the libraries from there. You can get the same effect by
passing a python.path variable as:
java -Dpython.path=/usr/local/jython-2.1 -cp jython.jar:mx4j-jmx.jar:mx4j-tools.jar
If you don't need the standard libraries (and that can be the case for many JMX tasks, it is enough to have the jython.jar
in your system classpath
Configuration
The MBean has a few parameters which can be used to configure the MBean. This includes the
ObservedObjectName and Notification Name used to configure the MBean to listen for notifications.
The Script and ScriptFile parameters point to the content of the script. For simple scripts
you could just use the Script parameter. For morke comple scripts you are better of pointing to a file.
The ScriptFile is actually a URL and therefore can point to http locations
Built-in functions
To ease the script constructions some variables, class and functions are readily
available to your script. The most important one is
server which point
to the current MBean server. The server variable IS a MBeanServer object and all methods
are valid. You can write scripts like:
# write all the "test:name=test" mbean operations
[print operation for operation in server.getMBeanInfo(ObjectName("test:name=test")).operations]
Aditionally all the javax.management.* class are imported making objects like ObjectName
or Attribute already available.
There are also some utility functions and classes:
proxy The proxy class wraps a objectname making it easier
to access (It is equivalent to the MBeanServerInvocationHandler class). You can directly retrieve and modify attributes and invoke mathods. For instance:
#
# Assume the MBean with ObjectName Test:name=jython has name and time attributes and a method start()
#
o = ObjectName("Test:name=jython")
p = proxy(o)
# you can access functions directly
print p.name
p.time = 12343
# also works with functions
p.start()
mbeans(query) Returns a list of the mbeans in the server which
are in the query. The query is of the form "*:*". It can be omited and the function will
return all the mbeans
instances(classname, query) Returns a list of the mbeans in the server which
are instances of classname. The server accepts also an optional query method.
mx4j-3.0.2/src/docs/english/xslt-processor.xml 100644 0 0 20567 10513545721 16463 0 ustar 0 0
XSLTProcessor
Introduction
The XSLTProcessor can be used to customize the output of the HttpAdaptor.
It basically takes the XML output of the HttpAdaptor and process it by using
XSL. This enables you to customize the look as you wish. Normally the processing
will produce HTML files you can display in a standard browser.
The actual files to be used are specified via the File property. This points to dir
where the template files are. Optionally you can package all your files in a .jar
or .zip file and deliver that instead.
The processor identifies which xsl template to use from the HTTP request. i.e.
if the request is mbean it will try to find a mbean.xsl file and use it to process
the resulting XML tree. You can modify this by passing a template variable. For instance.
http://host:port/mbean?objectname=Test:name=test1&template=testmbean
In that case the HttpAdaptor will build a mbean resulting tree but instead of being
processed using the mbean.xsl, it will use testmbean.xsl.
An identity transformation file is included in the distribution and you can use it to get the original XML message.
For instancehttp://host:port/mbean?objectname=Test:name=test1&template=identity
If you need to deliver extra files like images or raw HTML, you can add it to the
target filesystem. The processor knows a few MIME types which are classified according to
the extension. This includes:
GIF images: extension=".gif", MIME type: "image/gif"
PNG images: extension=".png", MIME type: "image/png"
JPG images: extension=".jpg", MIME type: "image/jpg"
HTML raw files: extension=".html,.html", MIME type: "text/html"
HTML raw files: extension=".css", MIME type: "text/css"
XML files: extension=".xml", MIME type: "text/xml"
XSL files: extension=".xsl", MIME type: "text/xsl"
etc...
You can add extra MIME type with the addMimeType method. If a MIME type is not found
for a given extension a text/plain type is assigned
Compatibility
For the XSLTProcessor to work you need a JAXP parser (Which you need for using the
raw HttpAdaptor too) and a TRaX (Transformation API for XML) library. In principle
anyone should work but there are differences between the different implementations
and versions. It follows some tested and working platforms:
Java SDK 1.4.0, using the bundled parser and transformation library
Java SDK 1.4.1, using the bundled parser and transformation library
Java SDK 1.4.0 + saxon 6.5.2, Working since MX4j version 1.1.1. Not
working with MX4J version 1.1
Java SDK 1.4.0 + saxon 7.2, Working since MX4j version 1.1.1.
Java SDK 1.4.0 + jd.xslt 1.2.8, Working since MX4j version 1.1.1.
Combinations reported not to work
Usage of xalan 2.0 and xerces 1.2.3 has been reported as not working
Attributes
The XSLTProcessor has the following attributes and operations that you can use to customize
the operation.
File: Determines where to look for xsl files. If the
target file is a dir, it assumes that xsl files are located on the dir. Otherwise
if it points to a .jar or .zip files, it assumes that the files are located inside.
Pointing it to a file system is especially useful for testing.
PathInJar: Sets the dir in the jar file where xsl files reside
UseJar: Read-only. It tells whether the processor is reading from a jar file
UsePath: Read-only. It tells whether the processor is reading from a dir
UseCache: Indicates whether to cache the transformation objects. This
speeds-up the process. It is usually set to true, but you can set it to false for easier testing
Locale: It's the locale used for i18n pruposes. By default it is "en"
LocaleString: Sets the locale by using a String
addMimeType: Adds a mime type in the form of a addMimeType(".pdf", "application/pdf"). The XSLTProcessor
will use th given MIME type for files with the given extension
For example you can set the attributes as follow:
XSL Development
If you want to develop your own GUI, please refer to the xsl sources of the
GUI delivered in the mx4j-tools.jar file
An important element to help you in the development are implicit params passed to
the template. This includes all the request variables in the form of request.variable
params. For instance with the follwing request
http://host.port/mbean?objectname=Test:name=test1&template=testmbean
There will be two paramaters request.objectname and request.template
Besides, there is alwyas a locale variable as request.locale. Notice that you can explicitly set the
locale in a request passing the locale varible like
http://host.port/mbean?objectname=Test:name=test1&template=testmbean&locale=de
Internationalization
Since MX4J version 1.1.1 the XSLTProcessor supports internationalization. This is done
replacing the previously hardcoded strings with a call to the 'str' template on the
common.xsl. The 'str' template takes an id which points to the string actually displayed on
screen. An xml file contains the strings indexed by id. With the current distribution a
strings_en.xml file is shipped containing the standard english translation.
If you want to create your own translation add or replace strings_XX.xml files by your
own translation on the jar file. The strings accept
a replacement of up to two parameters which are indicated wth brackets like {0} or {1}
mx4j-3.0.2/src/docs/images/logo.gif 100644 0 0 4127 10513545721 14147 0 ustar 0 0 GIF89aÊ Z ÷ iov00ƒ;;‰PP–[[£pp©{{°¼››Ã°°Ð»»ÖÐÐãÛÛéððöûûý !ù ÿ , Ê Z @ÿ ÿ H° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç
€)A ü‡²%•,[.Ð2%Æ(À$yòåΘ>kªÔˆòe͈8[êlH ¥Ç¦N
„
@$Ì“OVu ‚£\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/docs/index.xml 100644 0 0 1552 10513545721 13103 0 ustar 0 0
]>
MX4J English Documentation
&english;
mx4j-3.0.2/src/docs/styles.css 100644 0 0 3022 10513545721 13301 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms of the MX4J License version 1.0.
* See the terms of the MX4J License in the documentation provided with this software.
*/
/*
* MX4J stylesheet
* For colors definitions, see (among others)
* http://www.projectcool.com/developer/reference/color-chart.html
* $Revision: 1.3 $
*/
body
{
font-family: verdana,arial,helvetica,sans-serif;
font-size: 9pt;
color: black;
background: white;
}
tt
{
font-size: 9pt
}
td
{
font-size: 10pt
}
th
{
font-size: 10pt;
font-weight: bold
}
h1
{
font-size: 30pt;
color: dodgerblue;
text-align: center;
}
h2
{
font-size: 14pt;
color: dodgerblue;
font-weight: bold
}
h3
{
font-size: 12pt;
color: dodgerblue;
font-weight: bold
}
h4
{
font-size: 10pt;
color: dodgerblue;
font-weight: bold;
font-style: italic
}
a:link
{
color : forestgreen;
font-weight: bold;
}
a:visited
{
color : indianred;
font-weight: bold;
}
a:hover
{
color: indigo;
font-weight: bold;
}
.example
{
padding: 10;
border: thin solid;
background-color: whitesmoke
}
.programlisting
{
margin-left: 10;
margin-right: auto;
font-size: 8pt;
font-family: Courier;
border-style: solid;
border-width: 1;
white-space: pre;
background-color: lavender
}
.question
{
color: dodgerblue;
}
.abstract
{
padding: 5pt;
font-size: 8pt;
border-style: solid;
border-width: 1;
background-color: seashell
}
mx4j-3.0.2/src/docs/xsl/autotoc.xsl 100644 0 0 3462 10513545721 14270 0 ustar 0 0
mx4j-3.0.2/src/docs/xsl/mx4j-chunk.xsl 100644 0 0 447 10513545721 14562 0 ustar 0 0
styles.css
0
mx4j-3.0.2/src/etc/Apache-LICENSE.txt 100644 0 0 5156 10513545721 14103 0 ustar 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/src/etc/BUILD-HOWTO.txt 100644 0 0 7400 10513545721 13371 0 ustar 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/src/etc/JMXConnectorProvider-core.provider 100644 0 0 121 10513545721 17572 0 ustar 0 0 mx4j.remote.provider.iiop.ClientProvider
mx4j.remote.provider.rmi.ClientProvider
mx4j-3.0.2/src/etc/JMXConnectorProvider-tools.provider 100644 0 0 540 10513545721 20007 0 ustar 0 0 mx4j.tools.remote.provider.burlap.ClientProvider
mx4j.tools.remote.provider.burlap.ssl.ClientProvider
mx4j.tools.remote.provider.hessian.ClientProvider
mx4j.tools.remote.provider.hessian.ssl.ClientProvider
mx4j.tools.remote.provider.local.ClientProvider
mx4j.tools.remote.provider.soap.ClientProvider
mx4j.tools.remote.provider.soap.ssl.ClientProvider
mx4j-3.0.2/src/etc/JMXConnectorServerProvider-core.provider 100644 0 0 121 10513545721 20761 0 ustar 0 0 mx4j.remote.provider.iiop.ServerProvider
mx4j.remote.provider.rmi.ServerProvider
mx4j-3.0.2/src/etc/JMXConnectorServerProvider-tools.provider 100644 0 0 540 10513545721 21176 0 ustar 0 0 mx4j.tools.remote.provider.burlap.ServerProvider
mx4j.tools.remote.provider.burlap.ssl.ServerProvider
mx4j.tools.remote.provider.hessian.ServerProvider
mx4j.tools.remote.provider.hessian.ssl.ServerProvider
mx4j.tools.remote.provider.local.ServerProvider
mx4j.tools.remote.provider.soap.ServerProvider
mx4j.tools.remote.provider.soap.ssl.ServerProvider
mx4j-3.0.2/src/etc/Jetty-LICENSE.txt 100644 0 0 26136 10513545721 14042 0 ustar 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/src/etc/Jython-LICENSE.txt 100644 0 0 15520 10513545721 14211 0 ustar 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/src/etc/LICENSE.txt 100644 0 0 4713 10513545721 12722 0 ustar 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/src/etc/MANIFEST.MF 100644 0 0 265 10513545721 12507 0 ustar 0 0 Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.2
Created-By: 1.4.2_10-b03 (Sun Microsystems Inc.)
MX4J-Release: 3.0.2
MX4J-Release-Date: Friday 13 October 2006 01:11 CEST
mx4j-3.0.2/src/etc/README.txt 100644 0 0 14237 10513545721 12617 0 ustar 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/src/etc/RELEASE-NOTES-3.0.0.txt 100644 0 0 13512 10513545721 14257 0 ustar 0 0 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=461278
by choosing the "Closed" status. mx4j-3.0.2/src/etc/RELEASE-NOTES-3.0.1.txt 100644 0 0 14043 10513545721 14260 0 ustar 0 0 MX4J 3.0.1 is a bug fix release over 3.0.0, and restores JDK 1.3.x
compatibility, that was broken in 3.0.0.
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/src/etc/RELEASE-NOTES-3.0.2.txt 100644 0 0 14142 10513545721 14261 0 ustar 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/src/etc/index.jsp 100644 0 0 3665 10513545721 12731 0 ustar 0 0 <%--
Copyright (C) The MX4J Contributors.
All rights reserved.
This software is distributed under the terms of the MX4J License version 1.0.
See the terms of the MX4J License in the documentation provided with this software.
--%>
<%--
Purpose of this JSP is to provide an example of how to start a SOAPConnectorServer
from within a running servlet container.
The assumption is that Axis has already been deployed in the servlet container by
defining and mapping Axis' servlets in web.xml (see the sample web.xml bundled with
this WAR for details).
--%>
<%@ page import="java.util.*" %>
<%@ page import="javax.management.*" %>
<%@ page import="javax.management.remote.*" %>
<%@ page import="mx4j.tools.remote.http.HTTPConnectorServer" %>
<%
// The URLPath of this JMXServiceURL must match with the one in web.xml:
// Axis is mapped to /services/* and the 'jmxconnector' is the name of the
// remote MBeanServer web service.
String path = request.getContextPath() + "/services/jmxconnector";
JMXServiceURL address = new JMXServiceURL("soap", null, request.getServerPort(), path);
Map environment = new HashMap();
// Don't start a new web container, since it's already started
environment.put(HTTPConnectorServer.USE_EXTERNAL_WEB_CONTAINER, Boolean.TRUE);
JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, environment, null);
MBeanServer server = MBeanServerFactory.newMBeanServer();
ObjectName cntorServerName = ObjectName.getInstance("connectors:protocol=soap");
server.registerMBean(cntorServer, cntorServerName);
cntorServer.start();
// Register here another ton of MBeans you want to manage via the connector server
// For example:
ObjectName timerName = new ObjectName(":type=timer");
server.registerMBean(new javax.management.timer.Timer(), timerName);
// Now from a browser, you can view the WSDL:
// http://localhost:8080/mx4j-soap/services/jmxconnector?wsdl
%>
mx4j-3.0.2/src/etc/jndi.properties 100644 0 0 737 10513545721 14123 0 ustar 0 0 java.naming.factory.initial=com.sun.jndi.rmi.registry.RegistryContextFactory
java.naming.provider.url=rmi://localhost:1099
# Use the following properties for use with tnameserv, and remark the lines above
# Remember to start tnameserv with the -ORBInitialPort option if you want to change
# the ORB port (default port is 900), and change the value below accordingly
#java.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
#java.naming.provider.url=iiop://localhost:900
mx4j-3.0.2/src/etc/junit-frames.xsl 100644 0 0 63071 10513545721 14255 0 ustar 0 0
.
Unit Test Results.
Frame Alert
This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
a
{ color: #004E81; }
a:visited
{ color: #570084; }
body
{ font:normal 68% verdana,arial,helvetica;
color:#000000; }
table tr td, table tr th
{ font-size: 68%; }
table.details tr th
{ font-weight: bold;
text-align:left;
background:#CBD6DA; }
table.details tr td
{ background:#EBF1F3; }
p
{ line-height:1.5em;
margin-top:0.5em;
margin-bottom:1.0em; }
h1
{ margin: 0px 0px 5px;
font: 165% verdana,arial,helvetica;
color: #001523; }
h2
{ margin-top: 1em;
margin-bottom: 0.5em;
font: bold 125% verdana,arial,helvetica;
color: #001523; }
h3
{ margin-bottom: 0.5em;
font: bold 115% verdana,arial,helvetica;
color: #001523; }
h4
{ margin-bottom: 0.5em;
font: bold 100% verdana,arial,helvetica;
color: #001523; }
h5
{ margin-bottom: 0.5em;
font: bold 100% verdana,arial,helvetica;
color: #001523; }
h6
{ margin-bottom: 0.5em;
font: bold 100% verdana,arial,helvetica;
color: #001523; }
.Error
{ font-weight:bold;
color: #D9000A;}
.Failure
{font-weight:bold;
color:purple; }
.Properties
{ text-align:right;}
Class .
Tests
cur = TestCases[' . '] = new Array();
cur[' '] = ' ';
Classes
Classes
/
.html
Home
Packages
open('allclasses-frame.html','classListFrame')
Summary
Tests
Failures
Errors
Success rate
Time
Error
Failure
Pass
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.store 100644 0 0 2433 10513545721 12742 0 ustar 0 0 þíþí mykey ø»þÉY 0‚‹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‹2w—×Ïd
—õX¸#Š5³ñ>^áñà0¼ö$.=áĈ§[yf#–ÖnßWxÍJ¨U§g
Èû5À
¿¢ëzI“X @AÉò³# òì6sK X.509 F0‚B0‚ ?0*†HÎ8 0†10 UUS10 UNY10U
New York City10U
The MX4J Project10UMX4J Development Team10UAnonymous Geek0
031108153844Z
040206153844Z0†10 UUS10 UNY10U
New York City10U
The MX4J Project10UMX4J 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]-BSÄïÉ_iDpD mx4j-3.0.2/src/etc/log4j.xml 100644 0 0 1205 10513545721 12631 0 ustar 0 0
mx4j-3.0.2/src/etc/trust.store 100644 0 0 1604 10513545721 13332 0 ustar 0 0 þíþí mykey ø»ÿCÊ X.509 F0‚B0‚ ?0*†HÎ8 0†10 UUS10 UNY10U
New York City10U
The MX4J Project10UMX4J Development Team10UAnonymous Geek0
031108153844Z
040206153844Z0†10 UUS10 UNY10U
New York City10U
The MX4J Project10UMX4J 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^©õÆ*¿¦q mx4j-3.0.2/src/etc/web.xml 100644 0 0 1562 10513545721 12375 0 ustar 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.java 100644 0 0 5255 10513545721 24203 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 7536 10513545721 23311 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4057 10513545721 23201 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4106 10513545721 24510 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1023 10513545721 24072 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1157 10513545721 20754 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 3566 10513545721 21604 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2101 10513545721 22467 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1533 10513545721 21606 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2445 10513545721 21641 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 14300 10513545721 24261 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4266 10513545721 22741 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6074 10513545721 22745 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1150 10513545721 20747 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1143 10513545721 22615 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 3546 10513545721 23755 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1501 10513545721 24645 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2515 10513545721 21005 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2766 10513545721 22727 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 7362 10513545721 22754 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 25600 10513545721 26675 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4515 10513545721 22704 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4515 10513545721 22734 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 5117 10513545721 21744 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4647 10513545721 22003 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6327 10513545721 21611 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 11754 10513545721 21661 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6165 10513545721 22070 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6707 10513545721 22122 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.policy 100644 0 0 3371 10513545721 22532 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed 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.java 100644 0 0 5524 10513545721 21510 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 3530 10513545721 21533 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 11540 10513545721 21645 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.mlet 100644 0 0 464 10513545721 22211 0 ustar 0 0
CODEBASE="lib"
ARCHIVE="mx4j-tools.jar">
mx4j-3.0.2/src/examples/mx4j/examples/services/relation/RelationServiceExample.java 100644 0 0 33624 10513545721 25602 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1323 10513545721 23366 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1330 10513545721 23401 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 3440 10513545721 25423 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 21643 10513545721 23531 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 31116 10513545721 25704 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 13244 10513545721 24111 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2046 10513545721 26437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1302 10513545721 24157 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 1523 10513545721 24451 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 5313 10513545721 24301 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.xml 100644 0 0 1404 10513545721 21230 0 ustar 0 0
9090
localhost
connectors:type=http,processor=xslt
mx4j-3.0.2/src/examples/mx4j/examples/tools/jython/ScriptExample.java 100644 0 0 4152 10513545721 22735 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6711 10513545721 21765 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2321 10513545721 22302 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 2634 10513545721 22341 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 7050 10513545721 23502 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 5716 10513545721 23014 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 3502 10513545721 23033 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6333 10513545721 23611 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4541 10513545721 23640 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 6360 10513545721 22320 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 4422 10513545721 22345 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 5077 10513545721 22221 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the 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.java 100644 0 0 11015 10513545721 15314 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5105 10513545721 17375 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1054 10513545721 16011 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1042 10513545721 16024 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1040 10513545721 15324 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1110 10513545721 15631 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3761 10513545721 22411 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 12235 10513545721 22622 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13472 10513545721 24274 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 42331 10513545721 23305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 23674 10513545721 22216 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3207 10513545721 22752 0 ustar 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.java 100644 0 0 36262 10513545721 22613 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 22077 10513545721 22715 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 11706 10513545721 22733 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 43732 10513545721 24737 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 11000 10513545721 23437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 32046 10513545721 21403 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 15116 10513545721 21661 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 10527 10513545721 23546 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 16307 10513545721 23370 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 46034 10513545721 21243 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3761 10513545721 22140 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 63110 10513545721 20333 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 62231 10513545721 23127 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 15645 10513545721 21703 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5507 10513545721 24174 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 45554 10513545721 24601 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3445 10513545721 27376 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 66671 10513545721 27217 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 73022 10513545721 27553 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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;
}
}
}
././@LongLink 100644 0 0 146 10513545722 10260 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/SerializationVerifier.java mx4j-3.0.2/src/test/test/javax/management/compliance/serialization/support/SerializationVerifier.jav100644 0 0 13306 10513545721 31243 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2204 10513545721 27157 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4576 10513545721 25654 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1106 10513545721 26556 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2654 10513545721 26753 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 7436 10513545721 26767 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 722 10513545721 30443 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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);
}
}
././@LongLink 100644 0 0 151 10513545722 10254 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/NotCompliantWarningException.java mx4j-3.0.2/src/test/test/javax/management/compliance/signature/support/NotCompliantWarningException.100644 0 0 747 10513545721 31136 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5217 10513545721 26375 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3647 10513545721 26555 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 31065 10513545721 27656 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 7705 10513545721 25127 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 55276 10513545721 21522 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 42366 10513545721 25056 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 14321 10513545721 25774 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 7454 10513545721 26347 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 30732 10513545721 25511 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4543 10513545721 26444 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 10674 10513545721 26000 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 73336 10513545721 25010 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3665 10513545721 25310 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 26172 10513545721 23713 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 25327 10513545721 24713 0 ustar 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.java 100644 0 0 23446 10513545721 23325 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 10760 10513545721 23143 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 10732 10513545721 23535 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13431 10513545721 23113 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13202 10513545721 25320 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 23526 10513545721 24005 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 63350 10513545721 27101 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 22642 10513545721 27462 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 37765 10513545721 25230 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 26062 10513545721 27075 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 55646 10513545721 27067 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4764 10513545721 23257 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 25541 10513545721 24761 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 22523 10513545721 23431 0 ustar 0 0 /**
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 64422 10513545721 24150 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2240 10513545721 21721 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1570 10513545721 25351 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3225 10513545721 23755 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 600 10513545721 23050 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 552 10513545721 23761 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 7111 10513545721 24341 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 42351 10513545721 25664 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 6706 10513545721 25541 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 17746 10513545721 25033 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 32110 10513545721 23622 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 72226 10513545721 24515 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 14022 10513545721 23061 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 151013 10513545721 25613 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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;
}
}
}
././@LongLink 100644 0 0 145 10513545722 10257 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/OptionalRemoteJMXComplianceTestCase.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/OptionalRemoteJMXComplianceTestCase.java100644 0 0 7474 10513545721 30735 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 7740 10513545721 27223 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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");
}
}
././@LongLink 100644 0 0 162 10513545722 10256 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/OptionalRemoteJMXSerializationTest.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/OptionalRemoteJMXSerializa100644 0 0 3171 10513545721 31075 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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);
}
}
././@LongLink 100644 0 0 152 10513545722 10255 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/RemoteJMXSerializationTest.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/RemoteJMXSerializationTest100644 0 0 3071 10513545721 31120 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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);
}
}
././@LongLink 100644 0 0 160 10513545722 10254 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteComparator.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteComp100644 0 0 612 10513545721 31162 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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
{
}
././@LongLink 100644 0 0 162 10513545722 10256 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteInstantiator.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/OptionalRemoteInst100644 0 0 3670 10513545721 31230 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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;
}
}
././@LongLink 100644 0 0 150 10513545722 10253 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteComparator.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteComparator.j100644 0 0 11505 10513545721 31160 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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();
}
}
././@LongLink 100644 0 0 152 10513545722 10255 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteInstantiator.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/serialization/support/RemoteInstantiator100644 0 0 5503 10513545721 31261 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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;
}
}
././@LongLink 100644 0 0 152 10513545722 10255 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/OptionalRemoteJMXSignatureTest.java mx4j-3.0.2/src/test/test/javax/management/remote/compliance/signature/OptionalRemoteJMXSignatureTest100644 0 0 4240 10513545721 31075 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4143 10513545721 30311 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 10712 10513545721 25575 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 6142 10513545721 24370 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1622 10513545721 26305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5435 10513545721 25450 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4655 10513545721 24264 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2105 10513545721 25127 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 24160 10513545721 25207 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1621 10513545721 26314 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2652 10513545721 25456 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 6701 10513545721 24266 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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);
}
}
}
././@LongLink 100644 0 0 146 10513545722 10260 L ustar 0 0 mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPMultiThreadMBeanServerConnectionTest.java mx4j-3.0.2/src/test/test/javax/management/remote/rmi/RMIJRMPMultiThreadMBeanServerConnectionTest.jav100644 0 0 2725 10513545721 30531 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2120 10513545721 25134 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2542 10513545721 26611 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 20372 10513545721 24124 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 776 10513545721 22504 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4114 10513545721 23615 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1033 10513545721 24515 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1316 10513545721 23014 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1066 10513545721 23655 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 555 10513545721 24542 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 22657 10513545721 23564 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5600 10513545721 24347 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13371 10513545721 22375 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1071 10513545721 24626 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 746 10513545721 25521 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1062 10513545721 24103 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5123 10513545721 23036 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2406 10513545721 25000 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 562 10513545721 25664 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13543 10513545721 23731 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 15515 10513545721 22612 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 16453 10513545721 24161 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 12110 10513545721 24134 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 54255 10513545721 21440 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 26323 10513545721 20643 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 17051 10513545721 17471 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 17246 10513545721 20366 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 35615 10513545721 24426 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 23464 10513545721 24455 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 22130 10513545721 21134 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 34201 10513545721 21223 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 17507 10513545721 21016 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 4653 10513545721 22504 0 ustar 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.java 100644 0 0 43667 10513545721 26655 0 ustar 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.java 100644 0 0 3010 10513545721 17657 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 16744 10513545721 22701 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 142102 10513545721 23266 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 44001 10513545721 23224 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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 =
"" +
"" +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" ";
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 =
"" +
"" +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
"";
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)));
}
}
././@LongLink 100644 0 0 162 10513545722 10256 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationCompleteMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationCompleteMBeanResourc100644 0 0 121 10513545721 30324 0 ustar 0 0 #Default I18N
descr=The default direct implementation complete MBean description
././@LongLink 100644 0 0 162 10513545722 10256 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 122 10513545721 30277 0 ustar 0 0 #Default I18N
descr=The default direct implementation name only MBean description
././@LongLink 100644 0 0 165 10513545722 10261 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources_en.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 122 10513545721 30277 0 ustar 0 0 #English I18N
descr=The English direct implementation name only MBean description
././@LongLink 100644 0 0 165 10513545722 10261 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResources_fr.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$ImplementationNameOnlyMBeanResourc100644 0 0 120 10513545721 30275 0 ustar 0 0 #French I18N
descr=The French direct implementation name only MBean description
././@LongLink 100644 0 0 171 10513545722 10256 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousConstructorsMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousConstructorsMBean100644 0 0 1314 10513545721 30414 0 ustar 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
././@LongLink 100644 0 0 166 10513545722 10262 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousOperationMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassAmbiguousOperationMBeanRes100644 0 0 2075 10513545721 30323 0 ustar 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
././@LongLink 100644 0 0 154 10513545722 10257 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassCompleteMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassCompleteMBeanResources.pro100644 0 0 714 10513545721 30255 0 ustar 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
././@LongLink 100644 0 0 154 10513545722 10257 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources.pro100644 0 0 107 10513545721 30223 0 ustar 0 0 #Default I18N
descr=The default subclassed name only MBean description
././@LongLink 100644 0 0 157 10513545722 10262 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_en.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_en.100644 0 0 107 10513545721 30164 0 ustar 0 0 #English I18N
descr=The English subclassed name only MBean description
././@LongLink 100644 0 0 157 10513545722 10262 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_fr.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassNameOnlyMBeanResources_fr.100644 0 0 105 10513545721 30167 0 ustar 0 0 #French I18N
descr=The French subclassed name only MBean description
././@LongLink 100644 0 0 154 10513545722 10257 L ustar 0 0 mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassOverloadMBeanResources.properties mx4j-3.0.2/src/test/test/mx4j/tools/i18n/I18NStandardMBeanSupport$SubclassOverloadMBeanResources.pro100644 0 0 4072 10513545721 30301 0 ustar 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.java 100644 0 0 17622 10513545721 22411 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 45553 10513545721 21660 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 15236 10513545721 22011 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13640 10513545721 23736 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 13656 10513545721 23665 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1634 10513545721 25720 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1571 10513545721 25055 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2216 10513545721 23663 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2101 10513545721 24533 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1641 10513545721 26230 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1607 10513545721 25367 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2204 10513545721 24172 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2125 10513545721 25053 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1613 10513545721 25327 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1573 10513545721 24471 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1762 10513545721 23302 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 20175 10513545721 23703 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1622 10513545721 24707 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 5102 10513545721 24041 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 3660 10513545721 22661 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 2106 10513545721 23532 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 27000 10513545721 21343 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1640 10513545721 20326 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under 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.java 100644 0 0 1456 10513545721 23266 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1275 10513545721 24251 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 26370 10513545721 23121 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7235 10513545721 24673 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 11332 10513545721 24302 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 20300 10513545721 22254 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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("");
out.print(node.getNodeName());
String data = node.getNodeValue();
if (data != null && data.length() > 0)
{
out.print(' ');
out.print(data);
}
out.println("?>");
break;
}
}
// Close the element
if (type == Node.ELEMENT_NODE)
{
out.print("");
out.print(node.getNodeName());
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.java 100644 0 0 4725 10513545721 24271 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1664 10513545721 23261 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15247 10513545721 24610 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 70624 10513545721 21240 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 11444 10513545721 22136 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 16722 10513545721 24346 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2112 10513545721 23067 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2120 10513545721 24401 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3526 10513545721 21577 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3275 10513545721 21562 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 25666 10513545721 22127 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6621 10513545721 22276 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7333 10513545721 20540 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15072 10513545721 25315 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 22426 10513545721 23164 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4730 10513545721 21643 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2654 10513545721 24052 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 17244 10513545721 23761 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6703 10513545721 25053 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5306 10513545721 23426 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 10417 10513545721 24616 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15204 10513545721 25000 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 36054 10513545721 21477 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4371 10513545721 22357 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5541 10513545721 24563 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.xsl 100644 0 0 13140 10513545721 20601 0 ustar 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.xsl 100644 0 0 41436 10513545721 20770 0 ustar 0 0
en
common.title
common.subtitle
common.logo
common.logo.gif
common.site
common.logo.width
common.logo.height
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.xsl 100644 0 0 23721 10513545721 22245 0 ustar 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
constructors.error.exception
mbean
constructors.main.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/create.xsl 100644 0 0 5715 10513545721 20723 0 ustar 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.xsl 100644 0 0 5363 10513545721 20721 0 ustar 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.xsl 100644 0 0 5477 10513545721 21626 0 ustar 0 0
stylesheet.css
text/css
emptymbean.title
mbean
emptymbean.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/error.xsl 100644 0 0 4555 10513545721 20612 0 ustar 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.ico 100644 0 0 2576 10513545721 21053 0 ustar 0 0 h ( €€ €@ ûÇ û» û} ý »ý Ûý ëù qõ xè }_ }¿ }_ lï U÷ 9û }ÿ mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/identity.xsl 100644 0 0 1367 10513545721 21310 0 ustar 0 0
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/invoke.xsl 100644 0 0 10162 10513545721 20763 0 ustar 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.gif 100644 0 0 4127 10513545721 20353 0 ustar 0 0 GIF89aÊ Z ÷ iov00ƒ;;‰PP–[[£pp©{{°¼››Ã°°Ð»»ÖÐÐãÛÛéððöûûý !ù ÿ , Ê Z @ÿ ÿ H° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç
€)A ü‡²%•,[.Ð2%Æ(À$yòåΘ>kªÔˆòe͈8[êlH ¥Ç¦N
„
@$Ì“OVu ‚£\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.xsl 100644 0 0 44145 10513545721 20562 0 ustar 0 0
stylesheet.css
text/css
mbean.title
true
false
true
true
false
mbean.parameters.unknown
mbean.operations.title
mbean.operations.name
mbean.operations.returntype
mbean.operations.description
mbean.operations.invoke
clearline
darkline
true
false
mbean.constructors.class
mbean.constructors.description
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.xsl 100644 0 0 41147 10513545721 23027 0 ustar 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
mbean_attributes.attribute.name
mbean_attributes.attribute.description
mbean_attributes.attribute.type
mbean_attributes.attribute.value
mbean_attributes.attribute.newvalue
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/mlet.xsl 100644 0 0 6131 10513545721 20412 0 ustar 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.xsl 100644 0 0 15206 10513545721 21163 0 ustar 0 0
stylesheet.css
text/css
monitor.title
darkline
clearline
monitor.mbean.unregister
monitor
monitor.main.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/monitor_create.xsl 100644 0 0 11047 10513545721 22505 0 ustar 0 0
stylesheet.css
text/css
monitor_create.title
monitor_create.operation.stringmonitor
monitor_create.operation.gaguemonitor
monitor_create.operation.countermonitor
monitor_create.operation.title
monitor_create.operation.success
monitor_create.operation.error
monitor_create.operation.mbeanview
timer
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/relation.xsl 100644 0 0 17055 10513545721 21315 0 ustar 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.xsl 100644 0 0 7006 10513545721 20761 0 ustar 0 0
stylesheet.css
text/css
server.title
darkline
clearline
server.unregister
server
server.mbeans.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/serverbydomain.xsl 100644 0 0 13626 10513545721 22531 0 ustar 0 0
stylesheet.css
text/css
serverbydomain.title
serverbydomain.error.query
serverbydomain.domain.label
darkline
clearline
server
serverbydomain.server.query
serverbydomain.server.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/setattribute.xsl 100644 0 0 7125 10513545721 22174 0 ustar 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.xsl 100644 0 0 7641 10513545721 22362 0 ustar 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.xml 100644 0 0 26560 10513545721 21646 0 ustar 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
MX4J logo
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.css 100644 0 0 7136 10513545721 21632 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed 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.xsl 100644 0 0 11523 10513545721 20612 0 ustar 0 0
stylesheet.css
text/css
timer.title
timer.domain.title
timer.domain.objectname
darkline
clearline
timer.mbean.unregister
timer
timer.main.title
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/timer_create.xsl 100644 0 0 6472 10513545721 22124 0 ustar 0 0
stylesheet.css
text/css
timer_create.title
timer_create.operation.title
timer_create.operation.success
timer_create.operation.error
timer_create.operation.mbeanview
timer
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewarray.xsl 100644 0 0 13041 10513545721 21500 0 ustar 0 0
stylesheet.css
text/css
viewarray.title
30
0
mbean
viewarray.main.title
viewarray.main.arraytitle
viewarray.main.index
viewarray.main.value
clearline
darkline
getattribute?objectname=
&attribute=
&format=array&template=viewarray&locale=
viewarray.main
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewcollection.xsl 100644 0 0 14304 10513545721 22520 0 ustar 0 0
stylesheet.css
text/css
viewcollection.title
30
0
mbean
viewcollection.main.title
viewcollection.main.viewcollectiontitle
viewcollection.main.index
viewcollection.main.value
viewcollection.main.valueclass
clearline
darkline
getattribute?objectname=
&attribute=
&format=collection&template=viewcollection&locale=
viewcollection.main
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/viewmap.xsl 100644 0 0 15447 10513545721 21153 0 ustar 0 0
stylesheet.css
text/css
viewmap.title
30
0
mbean
viewmap.main.title
viewmap.main.viewmaptitle
viewmap.main.key
viewmap.main.keyclass
viewmap.main.value
viewmap.main.valueclass
clearline
darkline
getattribute?objectname=
&attribute=
&format=map&template=viewmap&locale=
viewmap.main
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/http/xsl/xalan-ext.xsl 100644 0 0 2311 10513545721 21346 0 ustar 0 0
No encode function available
mx4j-3.0.2/src/tools/mx4j/tools/adaptor/ssl/SSLAdaptorServerSocketFactory.java 100644 0 0 22336 10513545721 24471 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4516 10513545721 25354 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6435 10513545721 27562 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2223 10513545721 21726 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3337 10513545721 22305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 10432 10513545721 21567 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 771 10513545721 22437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 60135 10513545721 23261 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 72227 10513545721 20220 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 21070 10513545721 20344 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4645 10513545721 21240 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3276 10513545721 23443 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.py 100644 0 0 12353 10513545721 17231 0 ustar 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.py 100644 0 0 3557 10513545721 16262 0 ustar 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.java 100644 0 0 31134 10513545721 16073 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 12161 10513545721 16775 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15617 10513545721 21046 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2162 10513545721 21720 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5261 10513545721 24127 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4310 10513545721 20345 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3353 10513545721 21256 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5066 10513545721 23465 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1644 10513545721 21427 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 16626 10513545721 22750 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 12742 10513545721 21662 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7730 10513545721 23032 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 14645 10513545721 22161 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1466 10513545721 17745 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3705 10513545721 21236 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 12122 10513545721 20333 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 20365 10513545721 21641 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 16503 10513545721 24454 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 21755 10513545721 22226 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5520 10513545721 20576 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7442 10513545721 23007 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2035 10513545721 21323 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1463 10513545721 21530 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3336 10513545721 21631 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 11013 10513545721 21664 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3165 10513545721 23763 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3147 10513545721 24164 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1616 10513545721 24314 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2345 10513545721 23164 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1015 10513545721 23537 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3132 10513545721 24267 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4331 10513545721 24472 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1604 10513545721 24623 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2371 10513545721 23475 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1021 10513545721 24046 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2221 10513545721 24754 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1640 10513545721 24447 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2137 10513545721 26001 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15535 10513545721 22123 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4026 10513545721 21417 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4147 10513545721 22721 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7634 10513545721 25541 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4122 10513545721 22707 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6464 10513545721 21262 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 11270 10513545721 22460 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1510 10513545721 21152 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2167 10513545721 25563 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 17274 10513545721 21152 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6366 10513545721 22135 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 27040 10513545721 20741 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2772 10513545721 22263 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2161 10513545721 21176 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 11707 10513545721 23403 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2516 10513545721 22007 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4066 10513545721 23307 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 17353 10513545721 26146 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2654 10513545721 23305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3724 10513545721 21644 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7464 10513545721 23040 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6053 10513545721 22514 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2671 10513545721 22647 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1741 10513545721 23712 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2114 10513545721 23735 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1751 10513545721 24514 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2124 10513545721 24537 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1743 10513545721 24061 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2116 10513545721 24104 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1753 10513545721 24663 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2126 10513545721 24706 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1742 10513545721 23520 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2115 10513545721 23543 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2002 10513545721 23356 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2155 10513545721 23417 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1745 10513545721 24174 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2120 10513545721 24210 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 15771 10513545721 22253 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1645 10513545721 24105 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1633 10513545721 22571 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1243 10513545721 23367 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1642 10513545721 22736 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1250 10513545721 23532 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7164 10513545721 22403 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7565 10513545721 22260 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.wsdd 100644 0 0 26717 10513545721 21775 0 ustar 0 0
mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/server-deploy.wsdd 100644 0 0 27652 10513545721 23316 0 ustar 0 0
http://mx4j.sourceforge.net/remote/soap/1.0
mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/server-undeploy.wsdd 100644 0 0 152 10513545721 23603 0 ustar 0 0
mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/Resolver.java 100644 0 0 1001 10513545721 23034 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.wsdd 100644 0 0 27100 10513545721 22561 0 ustar 0 0
mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/server-deploy.wsdd 100644 0 0 27655 10513545721 24122 0 ustar 0 0
http://mx4j.sourceforge.net/remote/soap/1.0
mx4j-3.0.2/src/tools/mx4j/tools/remote/resolver/soap/ssl/server-undeploy.wsdd 100644 0 0 152 10513545721 24404 0 ustar 0 0
mx4j-3.0.2/src/tools/mx4j/tools/remote/rmi/SSLRMIClientSocketFactory.java 100644 0 0 1653 10513545721 23304 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2120 10513545721 23322 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 12004 10513545721 23205 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3122 10513545721 23762 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 44511 10513545721 22065 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2160 10513545721 21215 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1021 10513545721 21232 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2204 10513545721 20662 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1015 10513545721 21243 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1575 10513545721 23274 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1151 10513545721 24612 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1465 10513545721 24126 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1157 10513545721 25454 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3650 10513545721 23613 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1153 10513545721 25137 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4070 10513545721 22754 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1137 10513545721 24305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6476 10513545721 23622 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1711 10513545721 23274 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2740 10513545721 25006 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1204 10513545721 26330 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7577 10513545721 24512 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1172 10513545721 26023 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2150 10513545721 25363 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1212 10513545721 26711 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5111 10513545721 25052 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1200 10513545721 26375 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3306 10513545721 23121 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1151 10513545721 24445 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 7727 10513545721 22623 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1137 10513545721 24140 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2113 10513545721 25463 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1215 10513545721 27015 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5164 10513545721 25163 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1203 10513545721 26501 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2556 10513545721 25010 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1204 10513545721 26325 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6621 10513545721 24474 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1172 10513545721 26020 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2025 10513545721 24757 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1204 10513545721 26305 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5044 10513545721 24452 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1172 10513545721 26000 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2102 10513545721 26034 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1223 10513545721 27367 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2705 10513545721 27213 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1245 10513545721 30541 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6140 10513545721 26677 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1233 10513545721 30225 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2507 10513545721 25534 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1211 10513545721 27053 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4730 10513545721 25323 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1207 10513545721 26647 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6032 10513545721 25007 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1175 10513545721 26342 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3573 10513545721 23757 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1162 10513545721 25277 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1514 10513545721 26513 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1231 10513545721 30037 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4465 10513545721 26212 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1217 10513545721 27532 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2402 10513545721 25144 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1204 10513545721 26473 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5471 10513545721 24644 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1172 10513545721 26166 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 10141 10513545721 23453 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1150 10513545721 24763 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1670 10513545721 24220 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1170 10513545721 25543 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4264 10513545721 23711 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1156 10513545721 25236 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1651 10513545721 23333 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1154 10513545721 24661 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3251 10513545721 23020 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1142 10513545721 24345 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2206 10513545721 23242 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1151 10513545721 24570 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4152 10513545721 22733 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1137 10513545721 24263 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2353 10513545721 25340 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1210 10513545721 26657 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5107 10513545721 25027 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1175 10513545721 26360 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1663 10513545721 22230 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1133 10513545721 23550 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3212 10513545721 23034 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1146 10513545721 24370 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 10775 10513545721 22557 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1134 10513545721 24054 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1434 10513545721 23060 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1146 10513545721 24410 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3616 10513545721 22553 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1134 10513545721 24074 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2037 10513545721 23423 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1155 10513545721 24753 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4162 10513545721 23113 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1142 10513545721 24436 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 5014 10513545721 21711 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1120 10513545721 23233 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1524 10513545721 24273 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1170 10513545721 25620 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1504 10513545721 25125 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1204 10513545721 26452 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3750 10513545721 24621 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1172 10513545721 26145 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3746 10513545721 23772 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1156 10513545721 25313 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1417 10513545721 22057 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1127 10513545721 23405 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3522 10513545721 21545 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1115 10513545721 23071 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2275 10513545721 22726 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1143 10513545721 24247 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6244 10513545721 22415 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1131 10513545721 23733 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1755 10513545721 25437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1212 10513545721 26753 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 4352 10513545721 25122 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1200 10513545721 26437 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1723 10513545721 24753 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1202 10513545721 26273 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3021 10513545721 24433 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1170 10513545721 25766 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 12233 10513545721 23027 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3164 10513545721 23675 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 6257 10513545721 23044 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1605 10513545721 23737 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1511 10513545721 26137 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2675 10513545721 17424 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3302 10513545721 22223 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3325 10513545721 24434 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 3435 10513545721 22312 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1266 10513545721 23215 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1345 10513545721 25417 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2345 10513545721 22323 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1155 10513545721 23224 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1245 10513545721 25430 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1266 10513545721 23215 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1345 10513545721 25417 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 2345 10513545721 22323 0 ustar 0 0 /*
* Copyright (C) The MX4J Contributors.
* All rights reserved.
*
* This software is distributed under the terms 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.java 100644 0 0 1155 10513545721 23224 0 ustar 0 0