1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2008, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.core.sift.tracker;
11  
12  import java.util.ArrayList;
13  import java.util.Collections;
14  import java.util.LinkedList;
15  import java.util.List;
16  
17  import ch.qos.logback.core.Appender;
18  import ch.qos.logback.core.sift.AppenderTracker;
19  
20  /**
21   * This is an alternative (slower) implementation of AppenderTracker for testing
22   * purposes.
23   * 
24   * @author Ceki Gulcu
25   */
26  public class AppenderTrackerTImpl implements AppenderTracker<Object> {
27  
28    List<TEntry> entryList = new LinkedList<TEntry>();
29    long lastCheck = 0;
30  
31    public AppenderTrackerTImpl() {
32    }
33  
34    @SuppressWarnings("unchecked")
35    synchronized public void put(String k, Appender<Object> appender,
36        long timestamp) {
37      TEntry te = getEntry(k);
38      if (te != null) {
39        te.timestamp = timestamp;
40      } else {
41        te = new TEntry(k, appender, timestamp);
42        entryList.add(te);
43      }
44      Collections.sort(entryList);
45    }
46  
47    @SuppressWarnings("unchecked")
48    synchronized public Appender<Object> get(String k, long timestamp) {
49      TEntry te = getEntry(k);
50      if (te == null) {
51        return null;
52      } else {
53        te.timestamp = timestamp;
54        Collections.sort(entryList);
55        return te.appender;
56      }
57    }
58  
59    synchronized public void stopStaleAppenders(long timestamp) {
60      if (lastCheck + MILLIS_IN_ONE_SECOND > timestamp) {
61        return;
62      }
63      lastCheck = timestamp;
64      while (entryList.size() != 0 && isEntryStale(entryList.get(0), timestamp)) {
65        entryList.remove(0);
66      }
67    }
68  
69    final private boolean isEntryStale(TEntry entry, long now) {
70      return ((entry.timestamp + THRESHOLD) < now);
71    }
72  
73    synchronized public List<String> keyList() {
74      List<String> keyList = new ArrayList<String>();
75      for (TEntry e : entryList) {
76        keyList.add(e.key);
77      }
78      return keyList;
79    }
80  
81    synchronized public List<Appender<Object>> valueList() {
82      List<Appender<Object>> appenderList = new ArrayList<Appender<Object>>();
83      for (TEntry e : entryList) {
84        appenderList.add(e.appender);
85      }
86      return appenderList;
87    }
88  
89    private TEntry getEntry(String k) {
90      for (int i = 0; i < entryList.size(); i++) {
91        TEntry te = entryList.get(i);
92        if (te.key.equals(k)) {
93          return te;
94        }
95      }
96      return null;
97    }
98  }