1 package com.thoughtworks.xstream.io.path; 2 3 import com.thoughtworks.xstream.core.util.StringStack; 4 5 import java.util.ArrayList ; 6 import java.util.List ; 7 8 public class RelativePathCalculator { 9 10 public String relativePath(String from, String to) { 11 String [] fromBits = split(from); 12 String [] toBits = split(to); 13 StringBuffer result = new StringBuffer (); 14 boolean nothingWrittenYet = true; 15 16 int depthOfPathDivergence = depthOfPathDivergence(fromBits, toBits); 17 18 for (int i = depthOfPathDivergence; i < fromBits.length; i++) { 19 if (nothingWrittenYet) { 20 nothingWrittenYet = false; 21 } else { 22 result.append('/'); 23 } 24 result.append(".."); 25 } 26 27 for (int j = depthOfPathDivergence; j < toBits.length; j++) { 28 if (nothingWrittenYet) { 29 nothingWrittenYet = false; 30 } else { 31 result.append('/'); 32 } 33 result.append(toBits[j]); 34 } 35 36 if (nothingWrittenYet) { 37 return "."; 38 } else { 39 return result.toString(); 40 } 41 } 42 43 private String [] split(String str) { 44 List result = new ArrayList (); 46 int currentIndex = 0; 47 int nextSeperator; 48 while ((nextSeperator = str.indexOf('/', currentIndex)) != -1) { 49 result.add(str.substring(currentIndex, nextSeperator)); 50 currentIndex = nextSeperator + 1; 51 } 52 result.add(str.substring(currentIndex)); 53 String [] arr = new String [result.size()]; 54 result.toArray(arr); 55 return arr; 56 } 57 58 private int depthOfPathDivergence(String [] path1, String [] path2) { 59 int minLength = Math.min(path1.length, path2.length); 60 for (int i = 0; i < minLength; i++) { 61 if (!path1[i].equals(path2[i])) { 62 return i; 63 } 64 } 65 return minLength; 66 } 67 68 public String absolutePath(String currentPath, String relativePathOfReference) { 69 StringStack absoluteStack = new StringStack(16); 70 71 String [] currentPathChunks = split(currentPath); 72 for (int i = 0; i < currentPathChunks.length; i++) { 73 absoluteStack.push(currentPathChunks[i]); 74 } 75 76 String [] relativeChunks = split(relativePathOfReference); 77 for (int i = 0; i < relativeChunks.length; i++) { 78 String relativeChunk = relativeChunks[i]; 79 if (relativeChunk.equals("..")) { 80 absoluteStack.pop(); 81 } else if (!relativeChunk.equals(".")) { 82 absoluteStack.push(relativeChunk); 83 } 84 } 85 86 StringBuffer result = new StringBuffer (); 87 int size = absoluteStack.size(); 88 for (int i = 0; i < size; i++) { 89 if (i > 0) { 90 result.append('/'); 91 } 92 result.append(absoluteStack.get(i)); 93 } 94 95 return result.toString(); 96 } 97 98 } 99 | Popular Tags |