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

import java.util.StringTokenizer;

public class QueryBuilderUtil {

	/**
	 * Retrieve the relative path of an xpath based on current home path
	 * @param currentHome
	 * @param path
	 * @return
	 */
	public static String  retrieveRelativePath(String currentHome, String path)
	{
		System.out.println("QueryBuilderUtil.retrieveRelativePath()..currentHome="+currentHome+"...path="+path);
		if (path.startsWith(currentHome))
			return path.substring(currentHome.length());
		
		StringBuilder ancestorPath = new StringBuilder();
		StringTokenizer stCur = new StringTokenizer(currentHome, "/");
		StringTokenizer stNew = new StringTokenizer(path, "/");
 
		//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;
		}
		if (ancestorPath.length()==0)//there not any shared ancestor
			return null;
		
		//There are shared ancestor
		String ret = "";
		ret += "/..";
		while(stCur.hasMoreTokens()) {
			ret += "/..";
		}
		
		ret += path.substring(ancestorPath.toString().length());	
		return ret;	
	}
}

@@ -36,16 +36,40 @@
 sform;%0A%0A
+import java.util.Stack;%0A
 import j
@@ -1224,10 +1224,209 @@
 et;%09%0A%09%7D%0A
+%09%0A%09public static String buildXPath(Stack%3CString%3E  pathStack) %0A%09%7B%0A%09%09StringBuilder sb = new StringBuilder();%0A%09%09for (String s:pathStack) %7B%0A%09%09%09sb.append(%22/%22).append(s);%0A%09%09%7D%0A%09%09%0A%09%09return sb.toString();%0A%09%7D%0A
 %7D%0A

add function: build xpath