1 package com.thoughtworks.xstream.io.path; 2 3 import java.util.HashMap ; 4 import java.util.Map ; 5 6 public class PathTracker { 7 8 private int pointer; 9 private int capacity; 10 private String [] pathStack; 11 private Map [] indexMapStack; 12 13 private String currentPath; 14 15 public PathTracker() { 16 this(16); 17 } 18 19 public PathTracker(int initialCapacity) { 20 this.capacity = initialCapacity; 21 pathStack = new String [capacity]; 22 indexMapStack = new Map [capacity]; 23 } 24 25 public void pushElement(String name) { 26 if (pointer + 1 >= capacity) { 27 resizeStacks(capacity * 2); 28 } 29 pathStack[pointer] = name; 30 Map indexMap = indexMapStack[pointer]; 31 if (indexMap == null) { 32 indexMap = new HashMap (); 33 indexMapStack[pointer] = indexMap; 34 } 35 if (indexMap.containsKey(name)) { 36 indexMap.put(name, new Integer (((Integer ) indexMap.get(name)).intValue() + 1)); 37 } else { 38 indexMap.put(name, new Integer (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 getCurrentPath() { 51 if (currentPath == null) { 52 StringBuffer result = new StringBuffer (); 53 for (int i = 0; i < pointer; i++) { 54 result.append('/'); 55 result.append(pathStack[i]); 56 Integer integer = ((Integer ) 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 [] newPathStack = new String [newCapacity]; 69 Map [] newIndexMapStack = new Map [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 |