KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > io > path > PathTracker


1 package com.thoughtworks.xstream.io.path;
2
3 import java.util.HashMap JavaDoc;
4 import java.util.Map JavaDoc;
5
6 public class PathTracker {
7
8     private int pointer;
9     private int capacity;
10     private String JavaDoc[] pathStack;
11     private Map JavaDoc[] indexMapStack;
12
13     private String JavaDoc currentPath;
14
15     public PathTracker() {
16         this(16);
17     }
18
19     public PathTracker(int initialCapacity) {
20         this.capacity = initialCapacity;
21         pathStack = new String JavaDoc[capacity];
22         indexMapStack = new Map JavaDoc[capacity];
23     }
24
25     public void pushElement(String JavaDoc name) {
26         if (pointer + 1 >= capacity) {
27             resizeStacks(capacity * 2);
28         }
29         pathStack[pointer] = name;
30         Map JavaDoc indexMap = indexMapStack[pointer];
31         if (indexMap == null) {
32             indexMap = new HashMap JavaDoc();
33             indexMapStack[pointer] = indexMap;
34         }
35         if (indexMap.containsKey(name)) {
36             indexMap.put(name, new Integer JavaDoc(((Integer JavaDoc) indexMap.get(name)).intValue() + 1));
37         } else {
38             indexMap.put(name, new Integer JavaDoc(1));
39         }
40         pointer++;
41         currentPath = null;
42     }
43
44     public void popElement() {
45         indexMapStack[pointer] = null;
46         currentPath = null;
47         pointer--;
48     }
49
50     public String JavaDoc getCurrentPath() {
51         if (currentPath == null) {
52             StringBuffer JavaDoc result = new StringBuffer JavaDoc();
53             for (int i = 0; i < pointer; i++) {
54                 result.append('/');
55                 result.append(pathStack[i]);
56                 Integer JavaDoc integer = ((Integer JavaDoc) indexMapStack[i].get(pathStack[i]));
57                 int index = integer.intValue();
58                 if (index > 1) {
59                     result.append('[').append(index).append(']');
60                 }
61             }
62             currentPath = result.toString();
63         }
64         return currentPath;
65     }
66
67     private void resizeStacks(int newCapacity) {
68         String JavaDoc[] newPathStack = new String JavaDoc[newCapacity];
69         Map JavaDoc[] newIndexMapStack = new Map JavaDoc[newCapacity];
70         int min = Math.min(capacity, newCapacity);
71         System.arraycopy(pathStack, 0, newPathStack, 0, min);
72         System.arraycopy(indexMapStack, 0, newIndexMapStack, 0, min);
73         pathStack = newPathStack;
74         indexMapStack = newIndexMapStack;
75         capacity = newCapacity;
76     }
77
78 }
79
Popular Tags