Ignore:
Timestamp:
08/18/10 20:26:15 (14 years ago)
Author:
gaba
Message:
 
File:
1 edited

Legend:

Unmodified
Added
Removed
  • MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/Cache.java

    r582 r635  
    11package eu.clarin.cmdi.mdservice.action;
    22
    3 import java.io.BufferedReader;
    4 import java.io.BufferedWriter;
     3import java.io.*;
     4import java.net.MalformedURLException;
     5import java.net.URL;
     6/*import java.io.BufferedWriter;
    57import java.io.File;
    68import java.io.FileInputStream;
     
    1113import java.io.InputStream;
    1214import java.io.Writer;
     15*/
     16import java.util.Date;
     17import java.text.DateFormat;
     18import java.text.SimpleDateFormat;
     19import java.util.Calendar;
     20 
     21import javax.xml.*;
     22import javax.xml.parsers.*;
     23import javax.xml.transform.*;
     24import javax.xml.transform.sax.*;
     25import javax.xml.transform.stream.*;
     26import javax.xml.transform.dom.*;
     27import javax.xml.xpath.*;
     28
     29import org.w3c.dom.*;
     30import org.xml.sax.SAXException;
     31import org.xml.sax.InputSource;
     32
     33
     34import eu.clarin.cmdi.mdservice.action.Admin;
     35import eu.clarin.cmdi.mdservice.model.Query;
    1336
    1437/**
     
    2548
    2649public class Cache {
    27         public static String PREFIX = "_xc";
     50        public static String PREFIX = "xc_";
    2851       
    2952        private static Cache singleton;
     
    3255        private static final Integer start_cache = 1;
    3356       
     57        private static Document document_counter;
    3458       
    3559        public Cache () {               
     
    6589         * @return
    6690         */
    67         public String putInCache(String id, InputStream instream) {
    68 
     91        public String putInCache(String key_info, InputStream instream) {
     92
     93                Admin.notifyUser("CACHE.putInCache:"+key_info);
    6994                Integer c = getCounter();
    70                 String xc = PREFIX + c.toString();
     95                String xc;
     96               
     97               
     98                //update xml_structure
     99                Element e = document_counter.createElement("f");
     100                //Attr attr = document_counter.createAttribute("id");
     101                //attr.setValue(c.toString());
     102                //e.setNamedItem(attr);
     103                e.setAttribute("id", c.toString());
     104                String[] key_array = key_info.split("-");
     105               
     106                e.setAttribute("type", key_array[0]);
     107                if (key_array.length > 1){
     108                        String query_str;
     109                        if (key_array[0].equals("recordset")){
     110                                query_str = transformQuery(key_array[1]);
     111                        } else {
     112                                query_str = key_array[1];
     113                        }
     114                        e.setAttribute("query", query_str);
     115                }else{
     116                        e.setAttribute("query", "");
     117                }
     118                if (key_array.length > 2){
     119                        e.setAttribute("collection", key_array[2]);
     120                }else{
     121                        e.setAttribute("collection", "");
     122                }
     123
     124                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:hh-mm-ss");
     125                e.setAttribute("date", dateFormat.format(new Date()).toString());
     126                document_counter.getFirstChild().appendChild(e);
     127               
     128                // update XML-counter
    71129            //Admin.writeToFile(formPath(id + xc),instream);
    72                 Admin.writeToFile(formPath(id),instream);
     130                updateCachecounter();
     131               
     132                xc = PREFIX + key_array[0] + "_" + c.toString();
     133                Admin.writeToFile(cachepath + xc + ".xml",instream);
     134               
    73135            return xc;
    74136        }
    75137       
    76138       
    77         public InputStream getFromCache(String id) {
    78                    File f = new File (formPath(id));
     139        public InputStream getFromCache(String key_info) {
     140                   Admin.notifyUser("CACHE.getFromCache:"+key_info);
     141               
     142                   File f = new File (formPath(key_info));
    79143                   
    80144                    if (f.exists()) { // read from file to InputStream;
     
    86150                                } catch (FileNotFoundException e) {
    87151                                        // TODO Auto-generated catch block
    88                                         Admin.notifyUser("Cache: file not found" + f.getPath());
    89152                                        e.printStackTrace();
    90153                                        return null;
     
    96159        }
    97160 
     161        private String transformQuery (String str) {
     162                String transformed;
     163                Query query;
     164               
     165                query = new Query(str,"recordset","");
     166                if (query.isStatus(Query.PARSEERROR)) {
     167                        Admin.notifyUser("Cache.transformQuery.PARSEERROR:" + query.getMsg());
     168                        // pass this bad news to the client
     169                        //setUserMsg(query.getMsg());
     170                        transformed = "";
     171                } else {
     172                        try {
     173                                transformed =  query.toURLParam();
     174                                transformed = transformed.replace("'", "__qqqqq__");
     175                                //Admin.notifyUser("CACHE.transformQuery:"+transformed);
     176                        } catch (MalformedURLException e) {
     177                                // TODO Auto-generated catch block
     178                                e.printStackTrace();
     179                                transformed = "";
     180                        }
     181                }
     182                return transformed;
     183        }
     184       
    98185         //TODO: sanitize-key
    99         public String formPath (String id) {
    100             String path = cachepath + id + ".xml";
     186        public String formPath (String key_info) {
     187                String id="";
     188                String path="";
     189                String xpath_expr="";
     190               
     191                String[] key_array = key_info.split("-");
     192                String query_str;
     193               
     194                if(key_array.length > 1){
     195                        if (key_array[0].equals("recordset")){
     196                                query_str = transformQuery(key_array[1]);       
     197                        }
     198                        else {
     199                                query_str = key_array[1];
     200                        }
     201                } else {
     202                        query_str = "";
     203                }
     204                xpath_expr = "//index/f[@type='" + key_array[0] + "'";
     205                xpath_expr = xpath_expr + " and @query='"+query_str+"'";
     206               
     207                if (key_array.length > 2){
     208                        xpath_expr = xpath_expr + "and @collection='"+key_array[2]+"']";
     209                }else{
     210                        xpath_expr = xpath_expr + " and @collection='']";
     211                }
     212               
     213                //Admin.notifyUser("formPath:xpath:"+xpath_expr);
     214                //creating an XPathFactory:
     215        XPathFactory factory = XPathFactory.newInstance();
     216        //using this factory to create an XPath object:
     217        XPath xpath = factory.newXPath();
     218        //XPath object created compiles the XPath expression:
     219        XPathExpression expr;
     220                try {
     221                        expr = xpath.compile(xpath_expr);
     222                        //expression is evaluated with respect to a certain context node which is doc.
     223                Object result = expr.evaluate(document_counter, XPathConstants.NODESET);
     224                NodeList list = (NodeList) result;
     225                if (list.getLength() > 0) {
     226                        id = list.item(0).getAttributes().getNamedItem("id").getNodeValue();
     227                        path = cachepath + PREFIX + key_array[0] + "_"+id + ".xml";
     228                }  else if (list.getLength() > 1){
     229                        //Admin.notifyUser("formPath:!!!:multiple paths:"+key_info);
     230                       
     231                }
     232               
     233                } catch (XPathExpressionException e) {
     234                        // TODO Auto-generated catch block
     235                        e.printStackTrace();
     236                }
     237               
    101238            return path;
    102239        }
     
    113250         */
    114251        public Integer initCachecounter() {
    115         Integer counter = start_cache;
     252               
     253                Integer counter = start_cache;
    116254                boolean init=false;
    117                 File f = new File (Admin.getConfig().getProperty("cache.path") + "counter.txt");
    118                 FileInputStream fis ;
    119             if (!f.exists()) {
     255                String fname = cachepath + "cache_counter.xml";
     256                File f = new File (fname);
     257               
     258                //Admin.notifyUser("initCacheCounter");
     259                if (!f.exists()) {
     260                                // create new  counter document
     261                                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     262                        DocumentBuilder docBuilder;
     263                                try {
     264                                        docBuilder = docFactory.newDocumentBuilder();
     265                                        document_counter = docBuilder.newDocument();
     266                                        // append root tag <index >
     267                                        Element root = (Element) document_counter.createElement("index");
     268                                        root.setAttribute("idcounter", "1");
     269                                        document_counter.appendChild(root);
     270                                        writeCachecounter(counter);
     271                                       
     272                                        //Admin.notifyUser("new document");
     273                                } catch (ParserConfigurationException e) {
     274                                        // TODO Auto-generated catch block
     275                                        e.printStackTrace();
     276                                }
     277                               
     278                        //} catch (IOException e2) {
     279                        //      Admin.notifyUser("ERROR creating cache counter");
     280                        //      e2.printStackTrace();
     281                        //}
     282            }
     283                else {
    120284                        try {
    121                                 f.createNewFile();
    122                         } catch (IOException e2) {
    123                                 Admin.notifyUser("ERROR creating cache counter");
    124                                 e2.printStackTrace();
    125                         }
    126             }
    127            
    128             try {
     285                               
     286                        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     287                        DocumentBuilder docBuilder;
     288                                try {
     289                                        docBuilder = docFactory.newDocumentBuilder();               
     290                                        try {
     291                                                        document_counter = docBuilder.parse(fname);
     292                                        } catch (SAXException e) {
     293                                                        // TODO Auto-generated catch block
     294                                                       
     295                                                        e.printStackTrace();
     296                                        }
     297                                } catch (ParserConfigurationException e) {
     298                                                // TODO Auto-generated catch block
     299                                                e.printStackTrace();
     300                                }
     301                               
     302                         //read counter
     303                         counter = new Integer(document_counter.getFirstChild().getAttributes().getNamedItem("idcounter").getNodeValue());
     304                         init = true;
     305                    }  catch (IOException ex){
     306                        //Admin.notifyUser("initCacheCounter:" + ex.toString());
     307                        ex.printStackTrace();
     308                    }
     309                }
     310               
     311            return counter;
     312            /*
    129313              //use buffering, reading one line at a time
    130314              //FileReader always assumes default encoding is OK!
     
    137321                        * it returns null only for the END of the stream.
    138322                        * it returns an empty String if two newlines appear in a row.
    139                         */
     323                        *
    140324                        try {
    141325                                        if (( line = input.readLine()) != null){
     
    159343                } finally {
    160344                input.close();
    161              }         
    162             }  catch (IOException ex){
    163                 ex.printStackTrace();
    164             }
    165             return counter;
     345             }   
     346             */         
    166347        }
    167348
     
    170351        }
    171352        public void writeCachecounter (Integer i) {
     353               
     354               
     355                // first update <index idcounter>
     356                document_counter.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(i.toString());
     357               
     358                //Admin.notifyUser("writeCacheCounter:" + i.toString());
     359                // write xml
     360                Transformer transformer;
     361                try {
     362                        transformer = TransformerFactory.newInstance().newTransformer();
     363                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     364
     365                        //initialize StreamResult with File object to save to file
     366                        StreamResult result = new StreamResult(new StringWriter());
     367                        DOMSource source = new DOMSource(document_counter);
     368                        try {
     369                                transformer.transform(source, result);
     370                        } catch (TransformerException e1) {
     371                                // TODO Auto-generated catch block
     372                                e1.printStackTrace();
     373                        }
     374
     375                        String xmlString = result.getWriter().toString();
     376                        //Admin.notifyUser("writeCacheCounter:" + xmlString);
     377                        //Admin.writeToFile("", result);
     378
     379
     380                        File f = new File (cachepath + "counter.xml");
     381                        FileWriter fw;
     382                        try {
     383                                fw = new FileWriter(f);
     384                                try {
     385                                        fw.write(xmlString);
     386                                        fw.close();
     387                                } catch (IOException e) {
     388                                        // TODO Auto-generated catch block
     389                                        e.printStackTrace();
     390                                }       
     391                        } catch (IOException e) {
     392                                // TODO Auto-generated catch block
     393                                e.printStackTrace();
     394                        }
     395                } catch (TransformerConfigurationException e2) {
     396                        // TODO Auto-generated catch block
     397                        e2.printStackTrace();
     398                } catch (TransformerFactoryConfigurationError e2) {
     399                        // TODO Auto-generated catch block
     400                        e2.printStackTrace();
     401                }
     402               
     403                       
     404
     405                /*
    172406                File f = new File (Admin.getConfig().getProperty("cache.path") + "counter.txt");
    173407           
     
    184418                        e.printStackTrace();
    185419                }
     420                */
    186421        }
    187422}
Note: See TracChangeset for help on using the changeset viewer.