1 10 11 package org.mule.util.counters.impl; 12 13 import org.mule.util.counters.CounterFactory.Type; 14 15 import java.security.InvalidParameterException ; 16 import java.util.Iterator ; 17 import java.util.LinkedList ; 18 19 23 public class RatePerUnit extends AggregateCounter 24 { 25 26 private static class Sample 27 { 28 public Sample(double value, long time) 29 { 30 this.value = value; 31 this.time = time; 32 } 33 34 private double value; 35 private long time; 36 37 40 public long getTime() 41 { 42 return time; 43 } 44 45 48 public double getValue() 49 { 50 return value; 51 } 52 53 } 54 55 private LinkedList samples; 56 private long unit; 57 private long length; 58 private long baseTime; 59 60 public RatePerUnit(String name, String p, Type type, AbstractCounter base) 61 { 62 super(name, type, base); 63 if (type == Type.RATE_PER_SECOND) 64 { 65 unit = 1000; 66 } 67 else if (type == Type.RATE_PER_MINUTE) 68 { 69 unit = 60 * 1000; 70 } 71 else if (type == Type.RATE_PER_HOUR) 72 { 73 unit = 60 * 60 * 1000; 74 } 75 else 76 { 77 throw new InvalidParameterException (); 78 } 79 try 80 { 81 length = Long.parseLong(p); 82 } 83 catch (Exception e) 84 { 85 length = 0; 86 } 87 if (length <= 0) 88 { 89 length = 128; 90 } 91 samples = new LinkedList (); 92 this.baseTime = System.currentTimeMillis(); 93 } 94 95 public double nextValue() 96 { 97 if (samples.isEmpty()) 98 { 99 return 0.0; 100 } 101 else 102 { 103 double total = 0.0; 104 long current = getTime(); 105 Iterator it = samples.iterator(); 106 Sample sample = null; 107 while (it.hasNext()) 108 { 109 sample = (Sample)it.next(); 110 if (current - sample.time > length) 111 { 112 break; 113 } 114 total += sample.value; 115 } 116 return total / (1 + current - (sample != null ? sample.time : 0)); 117 } 118 } 119 120 public void doCompute() 121 { 122 Sample l = samples.isEmpty() ? null : (Sample)samples.getFirst(); 123 long t = getTime(); 124 if (l == null || t > l.time) 125 { 126 Sample s = new Sample(getBase().nextValue(), t); 127 samples.addFirst(s); 128 } 129 else 130 { 131 l.value += getBase().nextValue(); 132 } 133 while (samples.size() > length) 134 { 135 samples.removeLast(); 136 } 137 } 138 139 protected long getTime() 140 { 141 return (System.currentTimeMillis() - baseTime) / unit; 142 } 143 144 } 145 | Popular Tags |