pax_global_header00006660000000000000000000000064130715146520014516gustar00rootroot0000000000000052 comment=2ea65e008a48c54482f176ccfd1a6a3a972c55a6 java.jmx-java.jmx-0.3.4/000077500000000000000000000000001307151465200147545ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/.gitignore000066400000000000000000000000111307151465200167340ustar00rootroot00000000000000target/* java.jmx-java.jmx-0.3.4/CONTRIBUTING.md000066400000000000000000000012171307151465200172060ustar00rootroot00000000000000This is a [Clojure contrib] project. Under the Clojure contrib [guidelines], this project cannot accept pull requests. All patches must be submitted via [JIRA]. See [Contributing] and the [FAQ] on the Clojure development [wiki] for more information on how to contribute. [Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib [Contributing]: http://dev.clojure.org/display/community/Contributing [FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ [JIRA]: http://dev.clojure.org/jira/browse/JMX [guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers [wiki]: http://dev.clojure.org/ java.jmx-java.jmx-0.3.4/README.md000066400000000000000000000057731307151465200162470ustar00rootroot00000000000000clojure.java.jmx ======================================== Produce and consume JMX beans from Clojure. Releases and Dependency Information ======================================== Latest stable release: 0.3.3 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22java.jmx%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav%7Eorg.clojure%7Ejava.jmx%7E%7E%7E) [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/java.jmx "0.3.3"] [Maven](http://maven.apache.org/) dependency information: org.clojure java.jmx 0.3.3 Usage ======================================== [Full Documentation](http://clojure.github.com/java.jmx/) ```clojure (require '[clojure.java.jmx :as jmx]) ``` What beans do I have? ```clojure (jmx/mbean-names "*:*") -> # (:Verbose :ObjectPendingFinalizationCount :HeapMemoryUsage :NonHeapMemoryUsage) ``` What is the value of an attribute? ```clojure (jmx/read "java.lang:type=Memory" :ObjectPendingFinalizationCount) -> 0 ``` Give me all the attributes: ```clojure (jmx/mbean "java.lang:type=Memory") -> {:NonHeapMemoryUsage {:used 16674024, :max 138412032, :init 24317952, :committed 24317952}, :HeapMemoryUsage {:used 18619064, :max 85393408, :init 0, :committed 83230720}, :ObjectPendingFinalizationCount 0, :Verbose false} ``` Find an invoke an operation: ```clojure (jmx/operation-names "java.lang:type=Memory") -> (:gc) (jmx/invoke "java.lang:type=Memory" :gc) -> nil ``` Conneting to another process? Just run *any* of the above code inside a with-connection: ```clojure (jmx/with-connection {:host "localhost", :port 3000} (jmx/mbean "java.lang:type=Memory")) -> {:ObjectPendingFinalizationCount 0, :HeapMemoryUsage ... etc.} ``` Serve your own beans. Drop a Clojure ref into create-bean to expose read-only attributes for every key/value pair in the ref: ```clojure (jmx/register-mbean (jmx/create-bean (ref {:string-attribute "a-string"})) "my.namespace:name=Value")} ``` Developer Information ======================================== * [GitHub project](https://github.com/clojure/java.jmx) * [Bug Tracker](http://dev.clojure.org/jira/browse/JMX) * [Continuous Integration](http://build.clojure.org/job/java.jmx/) * [Compatibility Test Matrix](http://build.clojure.org/job/java.jmx-test-matrix/) Building ==================== 0. Clone the repo 1. Make sure you have maven installed 2. Run the maven build: `mvn install` will produce a JAR file in the target directory, and run all tests with the most recently-released build of Clojure. ## License Copyright © Stuart Halloway Licensed under the EPL. (See the file epl.html.) java.jmx-java.jmx-0.3.4/epl.html000066400000000000000000000305361307151465200164310ustar00rootroot00000000000000 Eclipse Public License - Version 1.0

Eclipse Public License - v 1.0

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS

"Contribution" means:

a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and

b) in the case of each subsequent Contributor:

i) changes to the Program, and

ii) additions to the Program;

where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.

"Contributor" means any person or entity that distributes the Program.

"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.

2. GRANT OF RIGHTS

a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.

b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.

c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.

d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.

3. REQUIREMENTS

A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;

ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and

iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the Program.

Contributors may not remove or alter any copyright notices contained within the Program.

Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.

4. COMMERCIAL DISTRIBUTION

Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL

If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.

This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

java.jmx-java.jmx-0.3.4/pom.xml000066400000000000000000000016001307151465200162660ustar00rootroot00000000000000 4.0.0 java.jmx 0.3.4 java.jmx org.clojure pom.contrib 0.2.2 Stuart Halloway Nick Bailey scm:git:git@github.com:clojure/java.jmx.git scm:git:git@github.com:clojure/java.jmx.git git@github.com:clojure/java.jmx.git java.jmx-0.3.4 java.jmx-java.jmx-0.3.4/src/000077500000000000000000000000001307151465200155435ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/main/000077500000000000000000000000001307151465200164675ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/main/clojure/000077500000000000000000000000001307151465200201325ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/main/clojure/clojure/000077500000000000000000000000001307151465200215755ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/main/clojure/clojure/java/000077500000000000000000000000001307151465200225165ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/main/clojure/clojure/java/jmx.clj000066400000000000000000000322601307151465200240110ustar00rootroot00000000000000;; Copyright (c) Stuart Halloway. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns ^{:author "Stuart Halloway" :doc "JMX support for Clojure Usage (require '[clojure.java.jmx :as jmx]) What beans do I have? (jmx/mbean-names \"*:*\") -> # (:Verbose :ObjectPendingFinalizationCount :HeapMemoryUsage :NonHeapMemoryUsage) What is the value of an attribute? (jmx/read \"java.lang:type=Memory\" :ObjectPendingFinalizationCount) -> 0 (jmx/read \"java.lang:type=Memory\" [:HeapMemoryUsage :NonHeapMemoryUsage]) -> {:NonHeapMemoryUsage {:used 16674024, :max 138412032, :init 24317952, :committed 24317952}, :HeapMemoryUsage {:used 18619064, :max 85393408, :init 0, :committed 83230720}} Can't I just have *all* the attributes in a Clojure map? (jmx/mbean \"java.lang:type=Memory\") -> {:NonHeapMemoryUsage {:used 16674024, :max 138412032, :init 24317952, :committed 24317952}, :HeapMemoryUsage {:used 18619064, :max 85393408, :init 0, :committed 83230720}, :ObjectPendingFinalizationCount 0, :Verbose false} Can I find and invoke an operation? (jmx/operation-names \"java.lang:type=Memory\") -> (:gc) (jmx/invoke \"java.lang:type=Memory\" :gc) -> nil What about some other process? Just run *any* of the above code inside a with-connection: (jmx/with-connection {:host \"localhost\", :port 3000} (jmx/mbean \"java.lang:type=Memory\")) -> {:ObjectPendingFinalizationCount 0, :HeapMemoryUsage ... etc.} Can I serve my own beans? Sure, just drop a Clojure ref into an instance of clojure.java.jmx.Bean, and the bean will expose read-only attributes for every key/value pair in the ref: (jmx/register-mbean (create-bean (ref {:string-attribute \"a-string\"})) \"my.namespace:name=Value\")"} clojure.java.jmx (:refer-clojure :exclude [read]) (:use [clojure.walk :only [postwalk]]) (:import [clojure.lang Associative] java.lang.management.ManagementFactory [javax.management Attribute AttributeList DynamicMBean MBeanInfo MBeanServer ObjectName RuntimeMBeanException MBeanAttributeInfo MBeanOperationInfo MBeanParameterInfo MBeanServerConnection] [javax.management.remote JMXConnectorFactory JMXServiceURL])) (set! *warn-on-reflection* true) (def ^{:dynamic true :doc "The connection to be used for JMX ops. Defaults to the local process." :skip-wiki true :tag MBeanServerConnection} *connection* (ManagementFactory/getPlatformMBeanServer)) (declare jmx->clj) (defn ^{:skip-wiki true} jmx-url "Build a JMX URL from options." ([] (jmx-url {})) ([overrides] (let [opts (merge {:protocol "rmi:///jndi/rmi", :host "localhost", :port "3000", :jndi-path "jmxrmi"} overrides)] (format "service:jmx:%s://%s:%s/%s" (opts :protocol) (opts :host) (opts :port) (opts :jndi-path))))) (defprotocol CoercionImpl (as-object-name [_])) (extend-protocol CoercionImpl String (as-object-name [_] (ObjectName. _)) ObjectName (as-object-name [_] _)) (defn- maybe-keywordize "Convert a string key to a keyword, leaving other types alone. Used to simplify keys in the tabular data API." [s] (if (string? s) (keyword s) s)) (defn- maybe-atomize "Convert a list of length 1 into its contents, leaving other things alone. Used to simplify keys in the tabular data API." [k] (if (and (instance? java.util.List k) (= 1 (count k))) (first k) k)) (def ^{:private true} simplify-tabular-data-key (comp maybe-keywordize maybe-atomize)) (defprotocol ^{:skip-wiki true} Destract (objects->data [_] "Convert JMX object model into data. Handles CompositeData, TabularData, maps, and atoms.")) (extend-protocol Destract javax.management.openmbean.CompositeData (objects->data [cd] (into {} (map (fn [attr] [(keyword attr) (objects->data (.get cd attr))]) (.. cd getCompositeType keySet)))) javax.management.openmbean.TabularData (objects->data [td] (into {} (map (fn [k] [(simplify-tabular-data-key k) (objects->data (.get td (into-array k)))]) (.keySet td)))) clojure.lang.Associative (objects->data [m] (into {} (zipmap (keys m) (map objects->data (vals m))))) java.lang.Boolean (objects->data [b] (boolean b)) Object (objects->data [obj] obj) nil (objects->data [_] nil)) (def ^{:private true} guess-attribute-map {"java.lang.Integer" "int" "java.lang.Boolean" "boolean" "java.lang.Long" "long" }) (defn- guess-attribute-typename "Guess the attribute typename for MBeanAttributeInfo based on the attribute value." [value] (let [classname (.getName (class value))] (get guess-attribute-map classname classname))) (defn- build-attribute-info "Construct an MBeanAttributeInfo. Normally called with a key/value pair from a Clojure map." ([attr-name attr-value] (build-attribute-info (name attr-name) (guess-attribute-typename attr-value) (name attr-name) true false false)) ([name type desc readable? writable? is?] (MBeanAttributeInfo. name type desc readable? writable? is? ))) (defn- map->attribute-infos "Construct an MBeanAttributeInfo[] from a Clojure associative." [attr-map] (into-array MBeanAttributeInfo (map (fn [[attr-name value]] (build-attribute-info attr-name value)) attr-map))) (defmacro with-connection "Execute body with a JMX connection created based on opts. opts can include [default]: :protocol The protocol to use [rmi:///jndi/rmi] :host The host to connect to [localhost] :port The port to connect to [3000] :jndi-path The jndi-path to use [jmxuri] :url The full url (as a String) to use instead of generating a rmi url from the above options [nil] :environment A map representing the environment used for the connection. See JMXConnectorFactory/connect for details [{}]" [opts & body] `(let [opts# ~opts env# (get opts# :environment {}) opts# (dissoc opts# :environment)] (with-open [connector# (javax.management.remote.JMXConnectorFactory/connect (JMXServiceURL. (:url opts# (jmx-url opts#))) env#)] (binding [*connection* (.getMBeanServerConnection connector#)] ~@body)))) (defn ^{:skip-wiki true} mbean-info ^MBeanInfo [n] (.getMBeanInfo *connection* (as-object-name n))) (defn ^{:skip-wiki true} raw-read "Read a list of mbean properties. Returns low-level Java object models for composites, tabulars, etc. Most callers should use read." [n attrs] (if (sequential? attrs) (into {} (map (fn [^Attribute attr] [(keyword (.getName attr)) (.getValue attr)]) (.getAttributes *connection* (as-object-name n) (into-array (map name attrs))))) (.getAttribute *connection* (as-object-name n) (name attrs)))) (def ^{:doc "Read one or more mbean properties."} read (comp objects->data raw-read)) (defn- read-supported "Calls read to read an mbean property, *returning* unsupported operation exceptions instead of throwing them. Used to keep mbean from blowing up. Note: There is no good exception that aggregates unsupported operations, hence the overly-general catch block." [n attr] (try (read n attr) (catch Exception e e))) (defn write! "Write an attribute value." [n attr value] (.setAttribute ^MBeanServerConnection *connection* ^ObjectName (as-object-name n) (Attribute. ^String (name attr) ^String value))) (defn ^{:skip-wiki true} attribute-info "Get the MBeanAttributeInfo for an attribute." ^MBeanAttributeInfo [object-name attr-name] (first (filter #(= (name attr-name) (.getName ^MBeanAttributeInfo %)) (.getAttributes (mbean-info object-name))))) (defn readable? "Is attribute readable?" [n attr] (.isReadable (attribute-info n attr))) (defn ^{:skip-wiki true} operations "All operations available on an MBean." [n] (.getOperations (mbean-info n))) (defn- operation "The MBeanOperationInfo for operation op on mbean n. Used by invoke." ^MBeanOperationInfo [n op] (first (filter (fn [^MBeanOperationInfo info] (= (-> info .getName keyword) op)) (operations n)))) (defn- op-param-types "The parameter types (as class name strings) for operation op on n. Used for invoke." [n op] (map #(.getType ^MBeanParameterInfo %) (.getSignature (operation n op)))) (defn register-mbean "Register an mbean with the current *connection*." [mbean mbean-name] (.registerMBean ^MBeanServer *connection* mbean (as-object-name mbean-name))) (defn unregister-mbean "Unregister mbean named mbean-name with the current *connection*." [mbean-name] (.unregisterMBean *connection* (as-object-name mbean-name))) (defn mbean-names "Finds all MBeans matching a name on the current *connection*." [n] (.queryNames *connection* (as-object-name n) nil)) (defn attribute-names "All attribute names available on an MBean." [n] (doall (map (fn [^MBeanAttributeInfo info] (-> info .getName keyword)) (.getAttributes (mbean-info n))))) (defn operation-names "All operation names available on an MBean." [n] (doall (map (fn [^MBeanOperationInfo info] (-> info .getName keyword)) (operations n)))) (defn invoke-signature "Invoke an operation an an MBean. You must also supply the signature of the operation. This is useful in cases where the operation is overloaded. Otherwise you should use the 'invoke' operation which will determine the signature for you. The signature parameter is a sequence of strings that describes the method parameter types in order." [n op signature & args] (if ( seq args) (.invoke *connection* (as-object-name n) (name op) (into-array Object args) (into-array String signature)) (.invoke *connection* (as-object-name n) (name op) nil nil))) (defn invoke "Invoke an operation an an MBean. See also: invoke-signature" [n op & args] (apply invoke-signature n op (op-param-types n op) args)) (defn mbean "Like clojure.core/bean, but for JMX beans. Returns a read-only map of a JMX bean's attributes. If an attribute it not supported, value is set to the exception thrown." [n] (into {} (map (fn [attr-name] [(keyword attr-name) (read-supported n attr-name)]) (attribute-names n)))) (deftype Bean [state-ref] DynamicMBean (getMBeanInfo [_] (MBeanInfo. (.. _ getClass getName) ; class name "Clojure Dynamic MBean" ; description (map->attribute-infos @state-ref) ; attributes nil ; constructors nil ; operations nil)) (getAttribute [_ attr] (@state-ref (keyword attr))) (getAttributes [_ attrs] (let [result (AttributeList.)] (doseq [attr attrs] (.add result (Attribute. attr (.getAttribute _ attr)))) result)) (setAttribute [_ attr] (let [attr-name (.getName attr) attr-value (.getValue attr) state-update {(keyword attr-name) attr-value}] (condp = (type state-ref) clojure.lang.Agent (await (send state-ref (fn [state state-update] (merge state state-update)) state-update)) clojure.lang.Atom (swap! state-ref merge state-update) clojure.lang.Ref (dosync (ref-set state-ref (merge @state-ref state-update)))))) (setAttributes [_ attrs] (let [attr-names (map (fn [^Attribute attr] (.setAttribute _ attr) (.getName attr)) attrs)] (.getAttributes _ (into-array attr-names))))) (defn create-bean "Expose a reference as a JMX bean. state-ref should be a Clojure reference (ref, atom, agent) containing a map. Using an agent for the state-ref is not recommended when the bean may be modified with the setAttribute(s) methods. The setAttribute(s) methods will block on the agent to complete all submitted actions (via await)." [state-ref] (Bean. state-ref)) java.jmx-java.jmx-0.3.4/src/test/000077500000000000000000000000001307151465200165225ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/test/clojure/000077500000000000000000000000001307151465200201655ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/test/clojure/clojure/000077500000000000000000000000001307151465200216305ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/test/clojure/clojure/java/000077500000000000000000000000001307151465200225515ustar00rootroot00000000000000java.jmx-java.jmx-0.3.4/src/test/clojure/clojure/java/test_jmx.clj000066400000000000000000000243761307151465200251140ustar00rootroot00000000000000;; Tests for JMX support for Clojure ;; by Stuart Halloway ;; Copyright (c) Stuart Halloway. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns clojure.java.test-jmx (:import javax.management.openmbean.CompositeDataSupport [javax.management MBeanAttributeInfo Attribute AttributeList InstanceNotFoundException] [java.util.logging LogManager Logger]) (:use clojure.test) (:require [clojure.java [jmx :as jmx]])) (defn =set [a b] (= (set a) (set b))) (defn seq-contains-all? "Does container contain every item in containee? Not fast. Testing use only" [container containee] (let [container (set container)] (every? #(contains? container %) containee))) (deftest finding-mbeans (testing "as-object-name" (are [cname object-name] (= cname (.getCanonicalName object-name)) "java.lang:type=Memory" (jmx/as-object-name "java.lang:type=Memory"))) (testing "mbean-names" (are [cnames object-name] (= cnames (map #(.getCanonicalName %) object-name)) ["java.lang:type=Memory"] (jmx/mbean-names "java.lang:type=Memory")))) ; These actual beans may differ on different JVM platforms. ; Tested April 2010 to work on Sun and IBM JDKs. (deftest testing-actual-beans (testing "reflecting on capabilities" (are [attr-list mbean-name] (seq-contains-all? (jmx/attribute-names mbean-name) attr-list) [:Verbose :ObjectPendingFinalizationCount :HeapMemoryUsage :NonHeapMemoryUsage] "java.lang:type=Memory") (are [op-list mbean-name] (seq-contains-all? (jmx/operation-names mbean-name) op-list) [:gc] "java.lang:type=Memory")) (testing "mbean-from-oname" (are [key-names oname] (seq-contains-all? (keys (jmx/mbean oname)) key-names) [:Verbose :ObjectPendingFinalizationCount :HeapMemoryUsage :NonHeapMemoryUsage] "java.lang:type=Memory"))) (deftest raw-reading-attributes (let [mem "java.lang:type=Memory" log "java.util.logging:type=Logging"] (testing "simple scalar attributes" (are [a b] (= a b) false (jmx/raw-read mem :Verbose)) (are [type attr] (instance? type attr) Number (jmx/raw-read mem :ObjectPendingFinalizationCount))) (testing "reading multiple attributes" (are [a b] (= a b) false ((jmx/raw-read mem [:Verbose]) :Verbose)) (are [type attr] (instance? type attr) Number ((jmx/raw-read mem [:ObjectPendingFinalizationCount]) :ObjectPendingFinalizationCount))))) (deftest reading-attributes (testing "simple scalar attributes" (is (jmx/readable? "java.lang:type=Memory" :ObjectPendingFinalizationCount)) (are [type attr] (instance? type attr) Number (jmx/read "java.lang:type=Memory" :ObjectPendingFinalizationCount))) (testing "composite attributes" (is (jmx/readable? "java.lang:type=Memory" :HeapMemoryUsage)) (are [ks attr] (=set ks (keys attr)) [:used :max :init :committed] (jmx/read "java.lang:type=Memory" :HeapMemoryUsage))) (testing "tabular attributes" (is (jmx/readable? "java.lang:type=Runtime" :SystemProperties)) (is (map? (jmx/read "java.lang:type=Runtime" :SystemProperties))))) (deftest reading-multiple-attributes (testing "simple scalar attributes" (are [type attr] (instance? type attr) Number ((jmx/read "java.lang:type=Memory" [:ObjectPendingFinalizationCount]) :ObjectPendingFinalizationCount))) (testing "composite attributes" (are [ks attr] (=set ks (keys attr)) [:used :max :init :committed] ((jmx/read "java.lang:type=Memory" [:HeapMemoryUsage :NonHeapMemoryUsage]) :HeapMemoryUsage))) (testing "tabular attributes" (is (map? ((jmx/read "java.lang:type=Runtime" [:SystemProperties]) :SystemProperties))))) (deftest writing-attributes (let [mem "java.lang:type=Memory"] (jmx/write! mem :Verbose true) (is (true? (jmx/read mem :Verbose))) (jmx/write! mem :Verbose false) (is (false? (jmx/read mem :Verbose))))) (deftest test-invoke-operations (testing "without arguments" (jmx/invoke "java.lang:type=Memory" :gc)) (testing "with arguments" (.addLogger (LogManager/getLogManager) (Logger/getLogger "clojure.java.test_jmx")) (jmx/invoke "java.util.logging:type=Logging" :setLoggerLevel "clojure.java.test_jmx" "WARNING")) (testing "with signature" (jmx/invoke-signature "java.lang:type=Threading" :getThreadInfo ["long"] 1) (jmx/invoke-signature "java.lang:type=Threading" :getThreadInfo ["long" "int"] 1 (new java.lang.Integer 1)))) (deftest test-objects->data (let [objects (jmx/raw-read "java.lang:type=Memory" :HeapMemoryUsage) prox (jmx/objects->data objects)] (testing "returns a map with keyword keys" (is (= (set [:committed :init :max :used]) (set (keys prox)))))) (let [raw-props (jmx/raw-read "java.lang:type=Runtime" :SystemProperties) props (jmx/objects->data raw-props)] (are [k] (contains? props k) :java.class.path :path.separator)) (testing "it works recursively on maps" (let [some-map {:foo (jmx/raw-read "java.lang:type=Memory" :HeapMemoryUsage)}] (is (map? (:foo (jmx/objects->data some-map)))))) (testing "it handles null references" (is (nil? (jmx/objects->data nil)))) (testing "it leaves everything else untouched" (is (= "foo" (jmx/objects->data "foo"))))) (deftest test-creating-attribute-infos (let [infos (@#'jmx/map->attribute-infos [[:a 1] [:b 2]]) info (first infos)] (testing "generates the right class" (is (= (class (into-array MBeanAttributeInfo [])) (class infos)))) (testing "generates the right instance data" (are [result expr] (= result expr) "a" (.getName info) "a" (.getDescription info))))) (deftest various-beans-are-readable (testing "that all java.lang beans can be read without error" (doseq [mb (jmx/mbean-names "*:*")] (is (map? (jmx/mbean mb)) mb)))) (deftest test-jmx-url (testing "creates default url" (is (= "service:jmx:rmi:///jndi/rmi://localhost:3000/jmxrmi" (jmx/jmx-url)))) (testing "creates custom url" (is (= "service:jmx:rmi:///jndi/rmi://example.com:4000/jmxrmi" (jmx/jmx-url {:host "example.com" :port 4000})))) (testing "creates custom jndi path" (is (= "service:jmx:rmi:///jndi/rmi://example.com:4000/jmxconnector" (jmx/jmx-url {:host "example.com" :port 4000 :jndi-path "jmxconnector"}))))) ;; ---------------------------------------------------------------------- ;; tests for clojure.java.jmx.Bean. (deftest dynamic-mbean-from-compiled-class (let [mbean-name "clojure.java.test_jmx:name=Foo"] (jmx/register-mbean (jmx/create-bean (ref {:string-attribute "a-string"})) mbean-name) (are [result expr] (= result expr) "a-string" (jmx/read mbean-name :string-attribute) {:string-attribute "a-string"} (jmx/mbean mbean-name) ))) (deftest test-getAttribute (doseq [reftype [ref atom agent]] (let [state (reftype {:a 1 :b 2}) bean (jmx/create-bean state)] (testing (str "accessing values from a " (class state)) (are [result expr] (= result expr) 1 (.getAttribute bean "a") 2 (.getAttribute bean "b")))))) (deftest test-setAttribute (doseq [reftype [ref atom agent]] (let [state (reftype {:a 1 :b 2}) bean (jmx/create-bean state)] (testing (str "setting values on a " (class state)) (.setAttribute bean (Attribute. "a" 3)) (are [result expr] (= result expr) 3 (.getAttribute bean "a") 2 (.getAttribute bean "b")))))) (deftest test-setAttributes (doseq [reftype [ref atom agent]] (let [state (reftype {:r 5 :d 4}) bean (jmx/create-bean state) atts (.setAttributes bean (AttributeList. [(Attribute. "r" 6) (Attribute. "d" 5)]))] (are [x y] (= x y) AttributeList (class atts) ["r" "d"] (map (memfn getName) (seq atts)) [6 5] (map (memfn getValue) (seq atts)))))) (deftest test-bean-info (let [state (ref {:a 1 :b 2}) bean (jmx/create-bean state) info (.getMBeanInfo bean)] (testing "accessing info" (are [result expr] (= result expr) "clojure.java.jmx.Bean" (.getClassName info))))) (deftest test-getAttributes (let [bean (jmx/create-bean (ref {:r 5 :d 4})) atts (.getAttributes bean (into-array ["r" "d"]))] (are [x y] (= x y) AttributeList (class atts) ["r" "d"] (map (memfn getName) (seq atts)) [5 4] (map (memfn getValue) (seq atts))))) (def primitive-int? (< (.compareTo (clojure-version) "1.3.0") 0)) (deftest test-guess-attribute-typename (are [x y] (= x (@#'jmx/guess-attribute-typename y)) "boolean" false "java.lang.String" "foo" "long" (Long/valueOf (long 10))) (if primitive-int? (is (= "int" (@#'jmx/guess-attribute-typename 10))) (is (= "long" (@#'jmx/guess-attribute-typename 10))))) (deftest test-unregister-mbean (let [mbean (jmx/create-bean (ref {:a-property 123})) mbean-name "clojure.java.test_jmx:name=UnregisterTest"] (jmx/register-mbean mbean mbean-name) (is (= 123 (jmx/read mbean-name :a-property))) (jmx/unregister-mbean mbean-name) (if (= [1 3] [(*clojure-version* :major) (*clojure-version* :minor)]) ; clojure 1.3 throws RuntimeException directly for some reason so catch that and ; verify that the underlying exception is right (try (jmx/read mbean-name :a-property) (catch RuntimeException e (is (instance? InstanceNotFoundException (.getCause e))))) (is (thrown? InstanceNotFoundException (jmx/read mbean-name :a-property))))))