001 /** 002 * QuerySerializer.java 003 * jCOLIBRI2 framework. 004 * @author Juan A. Recio-García. 005 * GAIA - Group for Artificial Intelligence Applications 006 * http://gaia.fdi.ucm.es 007 * 04/11/2007 008 */ 009 package jcolibri.connector.xmlutils; 010 011 import java.io.FileWriter; 012 013 import javax.xml.parsers.DocumentBuilder; 014 import javax.xml.parsers.DocumentBuilderFactory; 015 import javax.xml.transform.Transformer; 016 import javax.xml.transform.TransformerFactory; 017 import javax.xml.transform.dom.DOMSource; 018 import javax.xml.transform.stream.StreamResult; 019 020 import jcolibri.cbrcore.CBRQuery; 021 import jcolibri.util.FileIO; 022 023 import org.w3c.dom.Document; 024 import org.w3c.dom.Element; 025 import org.w3c.dom.Node; 026 027 /** 028 * Utility class to serialize queries into xml files. 029 * @author Juan A. Recio-Garcia 030 * @version 1.0 031 * 032 */ 033 public class QuerySerializer 034 { 035 public static void serializeQuery(CBRQuery query, String filename) 036 { 037 try 038 { 039 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 040 DocumentBuilder db = dbf.newDocumentBuilder(); 041 Document doc = db.newDocument(); 042 043 Element root = doc.createElement("CBRQuery"); 044 String id = "null"; 045 Object idObject = query.getID(); 046 if(idObject != null) 047 id = idObject.toString(); 048 root.setAttribute("Id", id); 049 root.appendChild(CaseComponentSerializer.serializeCaseComponent(query.getDescription(),"Description",doc)); 050 051 TransformerFactory tf = TransformerFactory.newInstance(); 052 Transformer trans = tf.newTransformer(); 053 FileWriter fw = new FileWriter(filename); 054 trans.transform(new DOMSource(root), new StreamResult(fw)); 055 } catch (Exception e) 056 { 057 org.apache.commons.logging.LogFactory.getLog(CaseComponentSerializer.class).error(e); 058 059 } 060 } 061 062 public static CBRQuery deserializeQuery(String filename) 063 { 064 CBRQuery query = new CBRQuery(); 065 066 try 067 { 068 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 069 DocumentBuilder db = dbf.newDocumentBuilder(); 070 Document doc = db.parse(FileIO.openFile(filename)); 071 072 Node node = doc.getElementsByTagName("CaseComponent").item(0); 073 query.setDescription(CaseComponentSerializer.deserializeCaseComponent(node)); 074 075 } catch (Exception e) 076 { 077 org.apache.commons.logging.LogFactory.getLog(CaseComponentSerializer.class).error(e); 078 079 } 080 081 return query; 082 } 083 }