package gov.nih.nci.cbiit.cmts.transform;

import java.util.Stack;
import java.util.StringTokenizer;

public class QueryBuilderUtil {

	/**
	 * Retrieve the relative path of an xpath based on current home path
	 * @param referencePath
	 * @param absolutePath
	 * @return
	 */
	public static String  retrieveRelativePath(String referencePath, String absolutePath)
	{
		if (referencePath==null)
			return absolutePath; //the root element
		if (absolutePath.startsWith(referencePath))
		{
			String pathEnd=absolutePath.substring(referencePath.length());
			if (pathEnd.startsWith("/")||pathEnd.equals(""))
				return pathEnd;
		}
		
		StringBuilder ancestorPath = new StringBuilder();
		StringTokenizer stCur = new StringTokenizer(referencePath, "/");
		StringTokenizer stNew = new StringTokenizer(absolutePath, "/");
 
		//find the common shared ancestor
		while(stCur.hasMoreTokens() && stNew.hasMoreTokens()) 
		{
			String t = stCur.nextToken(); 
			if (t.equals(stNew.nextToken()))
 				ancestorPath.append("/").append(t);
			else 
				break;
		}
		String ret = "";
		if (ancestorPath.length()==0)//there not any shared ancestor
			ret=null;
		else
		{
			
			//There are shared ancestor
			ret += "/..";
			while(stCur.hasMoreTokens()) {
				ret += "/..";
				stCur.nextToken();
			}
			
			ret += absolutePath.substring(ancestorPath.toString().length());
		}
		System.out.println("QueryBuilderUtil.retrieveRelativePath()...return...home="+referencePath+"...path="+absolutePath+"..relative="+ret);
		return ret;	
	}
	
	public static String buildXPath(Stack<String>  pathStack) 
	{
		StringBuilder sb = new StringBuilder();
		for (String s:pathStack) {
			sb.append("/").append(s);
		}
		return sb.toString();
	}
}

@@ -1089,17 +1089,17 @@
 length()
-=
+!
 =0)//the
@@ -1131,32 +1131,9 @@
 r%0A%09%09
-%09ret=null;%0A%09%09else%0A%09%09%7B%0A%09%09
+%7B
 %09%0A%09%09

return empty string as relative path if not shared ancestor by two paths