Index: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/Cache.java
===================================================================
--- MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/Cache.java	(revision 582)
+++ MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/Cache.java	(revision 635)
@@ -1,6 +1,8 @@
 package eu.clarin.cmdi.mdservice.action;
 
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
+import java.io.*;
+import java.net.MalformedURLException;
+import java.net.URL;
+/*import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileInputStream;
@@ -11,4 +13,25 @@
 import java.io.InputStream;
 import java.io.Writer;
+*/
+import java.util.Date;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+ 
+import javax.xml.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.sax.*;
+import javax.xml.transform.stream.*;
+import javax.xml.transform.dom.*;
+import javax.xml.xpath.*;
+
+import org.w3c.dom.*;
+import org.xml.sax.SAXException;
+import org.xml.sax.InputSource;
+
+
+import eu.clarin.cmdi.mdservice.action.Admin;
+import eu.clarin.cmdi.mdservice.model.Query;
 
 /**
@@ -25,5 +48,5 @@
 
 public class Cache {
-	public static String PREFIX = "_xc";
+	public static String PREFIX = "xc_";
 	
 	private static Cache singleton;
@@ -32,4 +55,5 @@
 	private static final Integer start_cache = 1;
 	
+	private static Document document_counter;
 	
 	public Cache () {		
@@ -65,16 +89,56 @@
 	 * @return
 	 */
-	public String putInCache(String id, InputStream instream) {
-
+	public String putInCache(String key_info, InputStream instream) {
+
+		Admin.notifyUser("CACHE.putInCache:"+key_info);
 		Integer c = getCounter();
-		String xc = PREFIX + c.toString();
+		String xc;
+		
+		
+		//update xml_structure
+		Element e = document_counter.createElement("f");
+		//Attr attr = document_counter.createAttribute("id");
+		//attr.setValue(c.toString());
+		//e.setNamedItem(attr);
+		e.setAttribute("id", c.toString());
+		String[] key_array = key_info.split("-");
+		
+		e.setAttribute("type", key_array[0]);
+		if (key_array.length > 1){
+			String query_str;
+			if (key_array[0].equals("recordset")){
+				query_str = transformQuery(key_array[1]);
+			} else {
+				query_str = key_array[1];
+			}
+			e.setAttribute("query", query_str);
+		}else{
+			e.setAttribute("query", "");
+		}
+		if (key_array.length > 2){
+			e.setAttribute("collection", key_array[2]);
+		}else{
+			e.setAttribute("collection", "");
+		}
+
+		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:hh-mm-ss");
+		e.setAttribute("date", dateFormat.format(new Date()).toString());
+		document_counter.getFirstChild().appendChild(e);
+		
+		// update XML-counter
 	    //Admin.writeToFile(formPath(id + xc),instream);
-		Admin.writeToFile(formPath(id),instream);
+		updateCachecounter();
+		
+		xc = PREFIX + key_array[0] + "_" + c.toString();
+		Admin.writeToFile(cachepath + xc + ".xml",instream);
+		
 	    return xc;
 	}
 	
 	
-	public InputStream getFromCache(String id) {
-		   File f = new File (formPath(id));
+	public InputStream getFromCache(String key_info) {
+		   Admin.notifyUser("CACHE.getFromCache:"+key_info);
+		
+		   File f = new File (formPath(key_info));
 		    
 		    if (f.exists()) { // read from file to InputStream;
@@ -86,5 +150,4 @@
 				} catch (FileNotFoundException e) {
 					// TODO Auto-generated catch block
-					Admin.notifyUser("Cache: file not found" + f.getPath());
 					e.printStackTrace();
 					return null;
@@ -96,7 +159,81 @@
 	}
  
+	private String transformQuery (String str) {
+		String transformed;
+		Query query;
+		
+		query = new Query(str,"recordset","");
+		if (query.isStatus(Query.PARSEERROR)) {
+			Admin.notifyUser("Cache.transformQuery.PARSEERROR:" + query.getMsg());
+			// pass this bad news to the client
+			//setUserMsg(query.getMsg());
+			transformed = "";
+		} else {
+			try {
+				transformed =  query.toURLParam();
+				transformed = transformed.replace("'", "__qqqqq__");
+				//Admin.notifyUser("CACHE.transformQuery:"+transformed);
+			} catch (MalformedURLException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+				transformed = "";
+			}
+		}
+		return transformed;
+	}
+	
 	 //TODO: sanitize-key
-	public String formPath (String id) {
-	    String path = cachepath + id + ".xml";
+	public String formPath (String key_info) {
+		String id="";
+		String path="";
+		String xpath_expr="";
+		
+		String[] key_array = key_info.split("-");
+		String query_str;
+		
+		if(key_array.length > 1){
+			if (key_array[0].equals("recordset")){
+				query_str = transformQuery(key_array[1]);	
+			}
+			else {
+				query_str = key_array[1];
+			}
+		} else {
+			query_str = "";
+		}
+		xpath_expr = "//index/f[@type='" + key_array[0] + "'";
+		xpath_expr = xpath_expr + " and @query='"+query_str+"'";
+		
+		if (key_array.length > 2){
+			xpath_expr = xpath_expr + "and @collection='"+key_array[2]+"']";
+		}else{
+			xpath_expr = xpath_expr + " and @collection='']";
+		}
+		
+		//Admin.notifyUser("formPath:xpath:"+xpath_expr);
+		//creating an XPathFactory:
+        XPathFactory factory = XPathFactory.newInstance();
+        //using this factory to create an XPath object: 
+        XPath xpath = factory.newXPath();
+        //XPath object created compiles the XPath expression: 
+        XPathExpression expr;
+		try {
+			expr = xpath.compile(xpath_expr);
+			//expression is evaluated with respect to a certain context node which is doc.
+	        Object result = expr.evaluate(document_counter, XPathConstants.NODESET);
+	        NodeList list = (NodeList) result;
+	        if (list.getLength() > 0) {
+		        id = list.item(0).getAttributes().getNamedItem("id").getNodeValue();
+		        path = cachepath + PREFIX + key_array[0] + "_"+id + ".xml";
+	        }  else if (list.getLength() > 1){
+	        	//Admin.notifyUser("formPath:!!!:multiple paths:"+key_info);
+	        	
+	        }
+	        
+		} catch (XPathExpressionException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
 	    return path;
 	}
@@ -113,18 +250,65 @@
 	 */
 	public Integer initCachecounter() {
-	Integer counter = start_cache;
+		
+		Integer counter = start_cache;
 		boolean init=false;
-		File f = new File (Admin.getConfig().getProperty("cache.path") + "counter.txt");
-		FileInputStream fis ;
-	    if (!f.exists()) {
+		String fname = cachepath + "cache_counter.xml";
+		File f = new File (fname);
+		
+		//Admin.notifyUser("initCacheCounter");
+		if (!f.exists()) {
+				// create new  counter document
+				DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+	         	DocumentBuilder docBuilder;
+				try {
+					docBuilder = docFactory.newDocumentBuilder();
+					document_counter = docBuilder.newDocument();
+					// append root tag <index >
+					Element root = (Element) document_counter.createElement("index");
+					root.setAttribute("idcounter", "1");
+					document_counter.appendChild(root);
+					writeCachecounter(counter);
+					
+					//Admin.notifyUser("new document");
+				} catch (ParserConfigurationException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+				
+			//} catch (IOException e2) {
+			//	Admin.notifyUser("ERROR creating cache counter");
+			//	e2.printStackTrace();
+			//}
+	    }
+		else {
 			try {
-				f.createNewFile();
-			} catch (IOException e2) {
-				Admin.notifyUser("ERROR creating cache counter");
-				e2.printStackTrace();
-			}
-	    }
-	    
-	    try {
+				
+	         	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+	         	DocumentBuilder docBuilder;
+				try {
+					docBuilder = docFactory.newDocumentBuilder();		    
+					try {
+							document_counter = docBuilder.parse(fname);
+					} catch (SAXException e) {
+							// TODO Auto-generated catch block
+							
+							e.printStackTrace();
+					}
+				} catch (ParserConfigurationException e) {
+						// TODO Auto-generated catch block
+						e.printStackTrace();
+				}
+		         	
+		         //read counter
+		         counter = new Integer(document_counter.getFirstChild().getAttributes().getNamedItem("idcounter").getNodeValue());
+		         init = true;
+		    }  catch (IOException ex){
+		    	//Admin.notifyUser("initCacheCounter:" + ex.toString());
+		        ex.printStackTrace();
+		    }
+		}
+		
+	    return counter;
+	    /*
     	      //use buffering, reading one line at a time
     	      //FileReader always assumes default encoding is OK!
@@ -137,5 +321,5 @@
 		        * it returns null only for the END of the stream.
 		        * it returns an empty String if two newlines appear in a row.
-		        */
+		        *
 	    		try {
 					if (( line = input.readLine()) != null){
@@ -159,9 +343,6 @@
     		} finally {
     	        input.close();
-    	     }	    	
-	    }  catch (IOException ex){
-	        ex.printStackTrace();
-	    }
-	    return counter;
+    	     }	 
+    	     */   	
 	}
 
@@ -170,4 +351,57 @@
 	}
 	public void writeCachecounter (Integer i) {
+		
+		
+		// first update <index idcounter>
+		document_counter.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(i.toString());
+		
+		//Admin.notifyUser("writeCacheCounter:" + i.toString());
+		// write xml
+		Transformer transformer;
+		try {
+			transformer = TransformerFactory.newInstance().newTransformer();
+			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+
+			//initialize StreamResult with File object to save to file
+			StreamResult result = new StreamResult(new StringWriter());
+			DOMSource source = new DOMSource(document_counter);
+			try {
+				transformer.transform(source, result);
+			} catch (TransformerException e1) {
+				// TODO Auto-generated catch block
+				e1.printStackTrace();
+			}
+
+			String xmlString = result.getWriter().toString();
+			//Admin.notifyUser("writeCacheCounter:" + xmlString);
+			//Admin.writeToFile("", result);
+
+
+			File f = new File (cachepath + "counter.xml");
+			FileWriter fw;
+			try {
+				fw = new FileWriter(f);
+				try {
+					fw.write(xmlString);
+					fw.close();
+				} catch (IOException e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}	
+			} catch (IOException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		} catch (TransformerConfigurationException e2) {
+			// TODO Auto-generated catch block
+			e2.printStackTrace();
+		} catch (TransformerFactoryConfigurationError e2) {
+			// TODO Auto-generated catch block
+			e2.printStackTrace();
+		}
+		
+			
+
+		/*
 		File f = new File (Admin.getConfig().getProperty("cache.path") + "counter.txt");
  	    
@@ -184,4 +418,5 @@
 			e.printStackTrace();
 		}
+		*/
 	}
 }
