1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.monitoring.listeners;
19
20 import org.apache.commons.monitoring.Composite;
21 import org.apache.commons.monitoring.Monitor;
22 import org.apache.commons.monitoring.StatValue;
23 import org.apache.commons.monitoring.impl.monitors.AbstractMonitor;
24
25 /**
26 * A Monitor implementation that maintains a set of secondary StatValues in sync
27 * with the primary monitor. Register itself as a monitor listener to get notified
28 * on new StatValues and automatically create the required secondary.
29 * <p>
30 * When detached, deregister itself as Monitor.Listener and detaches all secondary
31 * from the primary StatValues.
32 *
33 * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
34 */
35 public class SecondaryMonitor
36 extends AbstractMonitor
37 implements Monitor.Listener, Detachable
38 {
39 /** The primary monitor */
40 private Monitor.Observable monitor;
41
42 private boolean detached;
43
44 private long attachedAt;
45
46 private long detachedAt;
47
48 public SecondaryMonitor( Monitor.Observable monitor )
49 {
50 super( monitor.getKey() );
51 this.monitor = monitor;
52 this.attachedAt = System.currentTimeMillis();
53 this.detached = false;
54 for ( StatValue value : monitor.getValues() )
55 {
56 onStatValueRegistered( value );
57 }
58 monitor.addListener( this );
59 }
60
61 @SuppressWarnings("unchecked")
62 public void detach()
63 {
64 this.detached = true;
65 for ( StatValue value : monitor.getValues() )
66 {
67 if ( value instanceof Composite )
68 {
69 ( (Composite<StatValue>) value ).removeSecondary( getValue( value.getRole() ) );
70 }
71 }
72 this.detachedAt = System.currentTimeMillis();
73 }
74
75 @SuppressWarnings("unchecked")
76 public void onStatValueRegistered( StatValue value )
77 {
78 if ( !detached && value instanceof Composite )
79 {
80 register( ( (Composite<StatValue>) value ).createSecondary() );
81 }
82 }
83
84 public boolean isDetached()
85 {
86 return detached;
87 }
88
89 public long getAttachedAt()
90 {
91 return attachedAt;
92 }
93
94 public long getDetachedAt()
95 {
96 return detachedAt;
97 }
98
99 }