source: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java @ 1310

Last change on this file since 1310 was 1310, checked in by gaba, 13 years ago

virtualcollection publish

File size: 24.2 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.BufferedInputStream;
4import java.io.BufferedReader;
5import java.io.ByteArrayInputStream;
6import java.io.ByteArrayOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileNotFoundException;
10import java.io.FileWriter;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.InputStreamReader;
14import java.io.Reader;
15import java.io.UnsupportedEncodingException;
16import java.io.Writer;
17import java.net.MalformedURLException;
18import java.net.URL;
19import java.text.DateFormat;
20import java.text.SimpleDateFormat;
21import java.util.Date;
22import java.util.Enumeration;
23
24import java.io.StringReader;
25import java.io.StringWriter;
26
27import javax.servlet.ServletInputStream;
28import javax.servlet.http.HttpServletRequest;
29import javax.servlet.http.HttpSession;
30import javax.xml.parsers.DocumentBuilder;
31import javax.xml.parsers.DocumentBuilderFactory;
32import javax.xml.parsers.ParserConfigurationException;
33import javax.xml.transform.OutputKeys;
34import javax.xml.transform.Result;
35import javax.xml.transform.Source;
36import javax.xml.transform.Transformer;
37import javax.xml.transform.TransformerConfigurationException;
38import javax.xml.transform.TransformerException;
39import javax.xml.transform.TransformerFactory;
40import javax.xml.transform.TransformerFactoryConfigurationError;
41import javax.xml.transform.dom.DOMSource;
42import javax.xml.transform.stream.StreamResult;
43import javax.xml.transform.stream.StreamSource;
44import javax.xml.xpath.XPath;
45import javax.xml.xpath.XPathConstants;
46import javax.xml.xpath.XPathExpression;
47import javax.xml.xpath.XPathExpressionException;
48import javax.xml.xpath.XPathFactory;
49
50
51import net.sf.json.JSON;
52import net.sf.json.JSONArray;
53import net.sf.json.JSONObject;
54import net.sf.json.JSONSerializer;
55import net.sf.json.xml.XMLSerializer;
56
57import java.security.AccessController;
58import java.security.PrivilegedActionException;
59import java.security.PrivilegedExceptionAction;
60//import javax.servlet.ServletInputStream;
61
62
63import org.apache.struts2.interceptor.ServletRequestAware;
64import org.w3c.dom.Attr;
65import org.w3c.dom.DOMException;
66import org.w3c.dom.Document;
67import org.w3c.dom.Element;
68import org.w3c.dom.Node;
69import org.w3c.dom.NodeList;
70import org.xml.sax.InputSource;
71import org.xml.sax.SAXException;
72
73import com.opensymphony.xwork2.ActionSupport;
74
75
76/**
77 *
78 * @author
79 *
80 */
81public class WorkspaceAction extends GenericProxyAction
82//implements ServletRequestAware
83{
84
85        private static final long serialVersionUID = 1L;
86       
87        // workspaceprofiles
88        public static String USER = "user";
89        public static String SERVER = "server";
90        // administration query identification
91        public static String ADMIN = "admin";
92        public static String FILENAME = "filename";
93       
94        public static String PROFILENAME_BASE = "WorkspaceProfile_";
95        public static String PROFILENAME_SERVER = "WorkspaceProfileServer.xml";
96        public static String PROFILENAME_DEFAULT = PROFILENAME_BASE + "default.xml";
97        public static String ADMINISTRATION_FILENAME = "Administration.xml";
98       
99        private String workspace_filename = "WorkspaceProfile.xml";
100        /**
101         * Properties to be filled by Struts with according request-parameters
102         */     
103        //private String actionkey;
104        private String data;
105        private String type;
106        private String qid;
107        //private String format;
108        //private String userMsg;
109        private String base_path;
110       
111       
112        private static WorkspaceAction singleton;
113        private static String workspacefilename;
114        private static Document workspace_doc;
115       
116        //private String workspaceindex_path;
117        //private static Integer querycounter;
118        private static final Integer start_query = 1;
119       
120       
121       
122        //private HttpServletRequest request;
123       
124        public String Workspace_filename(){
125                return workspace_filename;
126        }
127
128        public void setWorkspace_filename(String workspace_filename) {
129                this.workspace_filename = workspace_filename;
130        }
131       
132        public String getData(){
133                return data;
134        }
135
136        public void setData(String data) {
137                this.data = data;
138        }
139
140        public String getType() {
141                return type;
142        }
143
144        public void setType(String type) {
145                this.type = type;
146        }
147       
148        public String getQid() {
149                return qid;
150        }
151
152        public void setQid(String qid) {
153                this.qid = qid;
154        }
155
156        public WorkspaceAction () {             
157                workspacefilename = Admin.getConfig().getProperty("workspaceprofile.path") + Admin.getConfig().getProperty("workspace.file");
158                if (workspace_doc == null){
159                        //workspacefilename = Admin.getConfig().getProperty("workspace.path") + Admin.getConfig().getProperty("workspace.file");
160                        initDocument();
161                }
162        }
163       
164        public static WorkspaceAction getWorkspaceAction() {
165                if (singleton == null) {
166                        singleton = new WorkspaceAction();
167                } 
168                return singleton;
169        }
170
171        protected void finalize() throws Throwable {       
172            try {               
173                //updateQuerycounter();
174                //saveDocument();
175            } catch(Exception e) {
176            }       
177            finally {           
178                super.finalize();
179                //more code can be written here as per need of application             
180            }
181        }
182        /**
183         * primitive identification of the target-proxy
184         * base for finding the right base_url in the props
185         * subclass has to override with its specific proxykey
186         * @return
187         */
188        public String getProxyKey() {
189                return "workspaceprofile";
190        }
191
192        /*
193        @Override
194        public void setServletRequest(HttpServletRequest arg0) {
195                request = arg0;
196               
197        }
198
199        @Override
200        public HttpServletRequest getServletRequest() {
201                return request;         
202        }
203*/
204        /*
205        public String getUserMsg() {
206                return userMsg;
207        }
208
209        public void setUserMsg(String userMsg) {
210                this.userMsg = this.userMsg + "\n" + userMsg;
211        }
212
213
214        private InputStream resultStream;
215        private InputStream sourceStream;
216*/
217        /**
218         * The stream holding the resulting data to be sent back to the user as response
219         * @return
220         */
221        /*
222        public InputStream getResultStream() {
223                return resultStream;
224    }
225        public void setResultStream(InputStream _resultStream){
226                resultStream = _resultStream;
227        }
228        public void setSourceStream(InputStream _sourceStream){
229                sourceStream = _sourceStream;
230        }
231        */
232        @Override
233        public URL getBaseURL() {
234                File file=new File(getPath());
235            URL url=null;
236            try{
237                    url=file.toURL(); 
238                    Admin.notifyUser("DEBUG: WorkspaceAction.getBaseURL(): "  + url);
239            } catch (MalformedURLException e){
240                Admin.notifyUser("JSON exception has been caught" + e);
241            }
242           
243            return url;
244        }
245       
246        public String getBasePath() {           
247                if (base_path == null) {
248                        base_path = Admin.getConfig().getProperty(getProxyKey() + ".path");
249                }
250                return base_path;
251        }
252       
253       
254        public String getWorkspaceProfile() {
255                String profilename = null;
256               
257                if (type.toLowerCase().equals(USER)) {
258                        if (getServletRequest().getRemoteUser() != null) {
259                                profilename =  PROFILENAME_BASE + getServletRequest().getRemoteUser() + ".xml";
260                        } else {
261                                profilename = PROFILENAME_DEFAULT;
262                        }
263                } else if (type.toLowerCase().equals(SERVER)) {
264                        profilename =  PROFILENAME_SERVER;
265                        /*
266                        File f = new File(getBasePath() + profilename);
267                        if (! f.exists()){
268                                //Admin.notifyUser(" not exists");
269                                profilename = "WorkspaceProfile_default.xml";
270                        }
271                        */
272                } else if (type.toLowerCase().equals(ADMIN)){
273                        profilename =  ADMINISTRATION_FILENAME;
274                } else if (type.toLowerCase().equals(FILENAME)){
275                        profilename = this.workspace_filename;
276                }
277               
278                if (profilename == null){
279                        profilename = PROFILENAME_DEFAULT;
280                        Admin.notifyUser("WorkspaceProfilePath not specified (USER, SERVER)!");
281                }
282               
283                Admin.notifyUser("WorkspaceProfilename : " + profilename);
284                return profilename;
285        }
286       
287        @Override
288        public String getFullFormat() {
289                return "xml2json";
290        }
291       
292        public URL getURL() {
293                File file=new File(getPath());
294            URL url=null;
295            try{
296                    url=file.toURL(); 
297                    //Admin.notifyUser("url "  + url);
298            } catch (MalformedURLException e){
299                //Admin.notifyUser("" + e);
300            }
301                return url;
302        }
303       
304       
305        public String getPath() {
306                String targetPath = getBasePath() + this.workspace_filename;//getWorkspaceProfile();       
307        Admin.notifyUser("WorkspaceAction TARGETPATH: " + targetPath);             
308        return targetPath;
309        }
310
311        @Override
312        public InputStream getSourceStream() throws IOException {       
313                InputStream stream = new BufferedInputStream( new FileInputStream(getPath()));
314       
315               
316                return   stream;
317        }
318       
319        // set the server - session data =  repositories, termsets
320        public void setSessionData(InputStream source) throws IOException {
321                if (source == null) return;
322                if (this.getWorkspaceProfile() != PROFILENAME_SERVER) return;
323               
324               
325                       
326        }
327       
328        /*
329        @Override
330        public void prepare() throws Exception {               
331               
332                //Admin.notifyUser("execute:");
333                InputStream in = getSourceStream();
334                this.setSourceStream(in);
335                if (getFormat().equals("xml")) {                       
336                        setResultStream(in);   
337                }else { //JSON
338                        // set srcFile (for MDTransformer to pass to xsl-scripts)
339                        MDTransformer transformer = new MDTransformer();
340                        transformer.setSrcFile(getURL());
341                        transformer.setParams(MDTransformer.createParamsMap(getFullFormat()));
342                        setResultStream(transformer.transformXML(in));//, getFullFormat()));
343                        //setSessionData(getResultStream());
344                }
345                       
346                Admin.notifyUser(getProxyKey() + " success:" + (getResultStream()!=null));
347        }
348
349        public void changeNodeName(Document doc, Node node, String new_name){
350                // Create an element with the new name
351                Node node2 = (Node ) doc.createElement(new_name);
352                // Copy the attributes to the new element NamedNodeMap attrs = element.getAttributes(); for (int i=0; i<attrs.getLength(); i++) { Attr attr2 = (Attr)doc.importNode(attrs.item(i), true); element2.getAttributes().setNamedItem(attr2); }
353                // Move all the children
354                while (node.hasChildNodes()) { node2.appendChild(node.getFirstChild()); }
355                // Replace the old node with the new node
356                Admin.notifyUser("replace:" + node2.getNodeName() + "," + node.getNodeName());
357                node.getParentNode().replaceChild(node2, node);
358        }
359
360        public void administrateQid() throws IOException, SAXException, ParserConfigurationException, TransformerException{
361                WorkspaceAction wa = new WorkspaceAction();
362                wa.setType("Admin");
363               
364                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
365        DocumentBuilder builder;
366
367                builder = factory.newDocumentBuilder();
368                Document  document = builder.parse(wa.getSourceStream());
369                // find user-filename-id or create one
370                //add qid
371                //NodeList list = document.getElementsByTagName("e");
372                //Admin.notifyUser("list:" + list.getLength());
373
374                // save the changes
375                Transformer transformer;
376                transformer = TransformerFactory.newInstance().newTransformer();
377                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
378                StreamResult result = new StreamResult(new StringWriter());
379                DOMSource source = new DOMSource(document);
380                transformer.transform(source, result);
381                String xmlString = result.getWriter().toString();
382                InputStream is_xml = new ByteArrayInputStream( xmlString.getBytes( ) );
383                Admin.writeToFile(wa.getPath(), is_xml);
384                //wa.save();
385        }
386       
387        public String save() throws IOException, SAXException, ParserConfigurationException, TransformerException {
388               
389        String jsonData = getData();
390             
391        Admin.notifyUser("JSON data:"+jsonData);
392        if ((!this.getType().equals(ADMIN)) && this.getQid() != null) {
393                        administrateQid();
394                }
395       
396        XMLSerializer serializer = new XMLSerializer();
397                JSON json = JSONSerializer.toJSON( jsonData );
398                if (this.getType().equals(ADMIN)){
399                        serializer.setRootName("Admin");
400                } else {
401                        serializer.setRootName("WorkspaceProfile");     
402                }
403                serializer.setElementName("item");
404        serializer.setTypeHintsEnabled(false);
405        String xml = serializer.write( json );
406        Admin.notifyUser("XML:" + xml);
407       
408        InputStream is_xml = new ByteArrayInputStream( xml.getBytes( ) );
409       
410        Admin.writeToFile(getPath(), is_xml);
411   
412        String ret = "1";
413                this.setResultStream( new ByteArrayInputStream(ret.getBytes()));
414                               
415
416                return SUCCESS;
417        }
418*/
419        public void changeQueryId(Document doc, String from_id, String to_id) throws XPathExpressionException{
420                InputStream is = null;
421                XPathFactory factory = XPathFactory.newInstance(); 
422            XPath xpath = factory.newXPath(); 
423            XPathExpression expr;
424            String xpath_expr = "";
425                xpath_expr = "//WorkspaceProfile/Querysets/item/Queries/item/id[.='" + from_id + "']";
426                expr = xpath.compile(xpath_expr);
427                Object result = null;
428                result = expr.evaluate(doc, XPathConstants.NODESET);
429               
430            NodeList nodelist = (NodeList) result;
431            nodelist.item(0).setTextContent(to_id);
432        }
433        public String createNewQid(){
434                String id = workspace_doc.getElementsByTagName("maxqid").item(0).getTextContent();
435                Integer i = Integer.parseInt(id) + 1;
436                id = i.toString();
437                workspace_doc.getElementsByTagName("maxqid").item(0).setTextContent(id);
438                return id.toString();
439        }
440        public InputStream createStream(String value) throws TransformerException, TransformerFactoryConfigurationError, ParserConfigurationException, UnsupportedEncodingException{
441        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
442        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
443        Document doc = docBuilder.newDocument();
444
445        ////////////////////////
446        //Creating the XML tree
447        Element root = doc.createElement("root");
448        root.setTextContent(value);
449        doc.appendChild(root);
450        //set up a transformer
451        TransformerFactory transfac = TransformerFactory.newInstance();
452        Transformer trans = transfac.newTransformer();
453        //trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
454        //trans.setOutputProperty(OutputKeys.INDENT, "yes");
455
456        //create string from xml tree
457        //StringWriter sw = new StringWriter();
458        //StreamResult result = new StreamResult(sw);
459        //DOMSource source = new DOMSource(doc);
460        //trans.transform(source, result);
461       
462
463        DOMSource source = new DOMSource(doc);   
464        StringWriter xmlAsWriter = new StringWriter();   
465        StreamResult result = new StreamResult(xmlAsWriter);     
466        TransformerFactory.newInstance().newTransformer().transform(source, result);   
467         
468        // write changes   
469        ByteArrayInputStream is = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
470           
471
472       return is;
473
474
475        }
476        public String save() throws ParserConfigurationException, SAXException, IOException, DOMException, XPathExpressionException, TransformerException, TransformerFactoryConfigurationError{
477               
478                // user data
479                String jsonData = getData();
480        XMLSerializer serializer = new XMLSerializer();
481                JSON json = JSONSerializer.toJSON( jsonData );
482                serializer.setRootName("WorkspaceProfile");     
483                serializer.setElementName("item");
484        serializer.setTypeHintsEnabled(false); 
485        String xml = serializer.write( json );
486        //Admin.notifyUser("XML:" + xml);
487        InputStream is_xml = new ByteArrayInputStream( xml.getBytes( ) );
488        // add to document
489        //Admin.writeToFile(getPath(), is_xml);
490        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
491        DocumentBuilder builder = factory.newDocumentBuilder();
492        Document d = builder.parse( is_xml );
493        // set user
494        //((Element)d.getFirstChild()).setAttribute("user", getServletRequest().getRemoteUser());
495        NodeList wsnodelist = (NodeList) getWorkspace();
496        // remove
497        //childeNode
498        if (wsnodelist.getLength() > 0){
499                ((Node)wsnodelist.item(0)).getParentNode().removeChild(wsnodelist.item(0));
500        }
501        String qidstring = "";
502        if (qid.equals("0")) {
503            qidstring = createNewQid();
504            changeQueryId(d,qid,qidstring);
505        }
506       
507        Node node = d.getFirstChild();
508        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
509        ((Element)node2).setAttribute("user", getUserName());
510        workspace_doc.getElementsByTagName("WorkspaceProfiles").item(0).appendChild(node2);
511
512      //TODO
513        saveDocument();
514        // return new qid
515        //String src = "<body>" + qidstring + "</body>";
516        //javax.xml.transform.stream.StreamSource s = new StreamSource(src);
517        //InputStream in = s.getInputStream();
518                this.setResultStream(createStream(qidstring));//(InputStream)(new ByteArrayInputStream(qidstring.getBytes())));
519               
520               
521                return SUCCESS;
522               
523        }
524        public InputStream DocumentToStream(Node node) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{
525               
526                InputStream is = null;
527                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
528                Source xmlSource;
529               
530                if (node == null) {
531                        xmlSource = new DOMSource(workspace_doc); 
532                } else {
533                        xmlSource = new DOMSource(node);
534                }
535                Result outputTarget = new StreamResult(outputStream); 
536                TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); 
537                is = new ByteArrayInputStream(outputStream.toByteArray()); 
538                return is;
539        }
540
541        public String DocumentToXMLString(){
542                Transformer transformer;
543                String xmlString = "";
544                try {
545                                transformer = TransformerFactory.newInstance().newTransformer();
546                                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
547
548                                //initialize StreamResult with File object to save to file
549                                StreamResult result = new StreamResult(new StringWriter());
550                                DOMSource source = new DOMSource(workspace_doc);
551                                try {
552                                        transformer.transform(source, result);
553                                } catch (TransformerException e1) {
554                                        // TODO Auto-generated catch block
555                                        e1.printStackTrace();
556                                }
557
558                                xmlString = result.getWriter().toString();
559                        } catch (TransformerConfigurationException e) {
560                                // TODO Auto-generated catch block
561                                e.printStackTrace();
562                        } catch (TransformerFactoryConfigurationError e) {
563                                // TODO Auto-generated catch block
564                                e.printStackTrace();
565                        }
566                       
567                return xmlString;
568        }
569       
570        public void addWorkspaceToDocument(){
571                //{'WorkspaceProfile':{'CustomTermsets':'null',
572                //                     'Termsets':'null',
573                //                     'Repositories':'null',
574                //                     'Querysets':'null','created':'null','lastchanged':'null','profilename':'null'}};
575                Element we = workspace_doc.createElement("WorkspaceProfile");
576                we.setAttribute("user", getType().toLowerCase());
577                workspace_doc.getFirstChild().appendChild(we);
578               
579                Element e = workspace_doc.createElement("CustomTermsets");
580                e.setNodeValue("null");
581                we.appendChild(e);
582               
583                e = workspace_doc.createElement("Termsets");
584                e.setNodeValue("null");
585                we.appendChild(e);
586               
587                e = workspace_doc.createElement("Repositories");
588                e.setNodeValue("null");
589                we.appendChild(e);
590               
591                e = workspace_doc.createElement("Querysets");
592                e.setNodeValue("null");
593                we.appendChild(e);
594               
595                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
596                String strdate = dateFormat.format(new Date()).toString();
597                e = workspace_doc.createElement("created");
598                e.setNodeValue(strdate);
599                we.appendChild(e);
600               
601                e = workspace_doc.createElement("lastchanged");
602                e.setNodeValue(strdate);
603                we.appendChild(e);
604               
605                e = workspace_doc.createElement("profilename");
606                e.setNodeValue(getType().toLowerCase());
607                we.appendChild(e);
608        }
609       
610        public String getUserName(){
611                String userstring;
612                if (getType().toLowerCase().equals(SERVER)){
613                        userstring = SERVER;
614                }else {
615                        userstring = getServletRequest().getRemoteUser();
616                        if (userstring == null){
617                                userstring = "default";
618                        }
619                }
620                return userstring;
621        }
622        public String getWorkspaceXPathExpression(){
623                String xpath_expr = "";
624
625                xpath_expr = "//Profiles/WorkspaceProfiles/WorkspaceProfile[@user='" + getUserName() + "']";
626
627                return xpath_expr;
628        }
629       
630        public Object getWorkspace() throws XPathExpressionException{
631                InputStream is = null;
632                XPathFactory factory = XPathFactory.newInstance(); 
633            XPath xpath = factory.newXPath(); 
634            XPathExpression expr;
635                        expr = xpath.compile(getWorkspaceXPathExpression());
636                        //expression is evaluated with respect to a certain context node which is doc.
637                        Object result = null;
638                        try{
639                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
640                        } catch(Exception e){
641                               
642                        }
643
644             return result;
645        }
646       
647           
648        @Override
649        public void prepare() throws Exception {               
650               
651                NodeList list = (NodeList) getWorkspace();//result;
652                if (list.getLength() < 1) {
653                        addWorkspaceToDocument();
654                        list = (NodeList) getWorkspace();
655                }
656                if (list.getLength() > 1){
657                        // error
658                }
659                // nodelistto stream
660                InputStream is = this.DocumentToStream(list.item(0));
661                this.setSourceStream(is);     
662               
663                if (getFormat().equals("xml")) {                       
664                        setResultStream(is);   
665                }else { //JSON
666                        // set srcFile (for MDTransformer to pass to xsl-scripts)
667                        MDTransformer transformer = new MDTransformer();
668                        transformer.setSrcFile(getURL());
669                        transformer.setParams(MDTransformer.createParamsMap(getFullFormat()));
670                        setResultStream(transformer.transformXML(is));//, getFullFormat()));
671                        //setSessionData(getResultStream());
672                }
673                       
674                Admin.notifyUser(getProxyKey() + " success:" + (getResultStream()!=null));
675        }
676
677       
678       
679public void initDocument() {
680       
681        boolean init=false;
682        Integer counter = start_query;
683        //String fname = getPath();//workspacefile;
684        File f = new File (workspacefilename);
685               
686        if (!f.exists()) {
687                                // create new  counter document
688                                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
689                        DocumentBuilder docBuilder;
690                                try {
691                                        docBuilder = docFactory.newDocumentBuilder();
692                                        workspace_doc = docBuilder.newDocument();
693                                        // append root tag <index >
694                                        Element root = (Element) workspace_doc.createElement("Profiles");
695                                        //root.setAttribute("idcounter", "1");
696                                        workspace_doc.appendChild(root);
697                                        Element e = workspace_doc.createElement("Querycounter");
698                                        root.appendChild(e);
699                                        e = workspace_doc.createElement("maxqid");
700                                        e.setNodeValue(counter.toString());
701                                        e = workspace_doc.createElement("WorkspaceProfiles");
702                                        root.appendChild(e);
703
704                                        //updateQuerycounter();
705                                        this.saveDocument();
706                                       
707                                        //Admin.notifyUser("new document");
708                                } catch (ParserConfigurationException e) {
709                                        // TODO Auto-generated catch block
710                                        e.printStackTrace();
711                                }
712            }
713                else {
714                        try {
715                               
716                        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
717                        DocumentBuilder docBuilder;
718                                try {
719                                        docBuilder = docFactory.newDocumentBuilder();               
720                                        try {
721                                                        workspace_doc = docBuilder.parse(workspacefilename);
722                                        } catch (SAXException e) {
723                                                        // TODO Auto-generated catch block
724                                                       
725                                                        e.printStackTrace();
726                                        }
727                                } catch (ParserConfigurationException e) {
728                                                // TODO Auto-generated catch block
729                                                e.printStackTrace();
730                                }
731                               
732                         //read counter
733                         //counter = new Integer(workspace_doc.getFirstChild().getFirstChild().getFirstChild().getNodeValue());
734                         init = true;
735                    }  catch (IOException ex){
736                        //Admin.notifyUser("initCacheCounter:" + ex.toString());
737                        ex.printStackTrace();
738                    }
739                }
740               
741            //return counter;
742        }
743/*
744        public void updateQuerycounter () {
745                workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(querycounter.toString());
746            saveDocument();
747        }
748        */
749        public void saveDocument() {
750        //public void writeQuerycounter (Integer i) {           
751               
752                // first update <index idcounter>
753                //workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(i.toString());
754               
755                //Admin.notifyUser("writeCacheCounter:" + i.toString());
756                // write xml
757                Transformer transformer;
758                try {
759                        transformer = TransformerFactory.newInstance().newTransformer();
760                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
761
762                        //initialize StreamResult with File object to save to file
763                        StreamResult result = new StreamResult(new StringWriter());
764                        DOMSource source = new DOMSource(workspace_doc);
765                        try {
766                                transformer.transform(source, result);
767                        } catch (TransformerException e1) {
768                                // TODO Auto-generated catch block
769                                e1.printStackTrace();
770                        }
771
772                        String xmlString = result.getWriter().toString();
773
774                        File f = new File (workspacefilename);
775                        FileWriter fw;
776                        try {
777                                fw = new FileWriter(f);
778                                try {
779                                        fw.write(xmlString);
780                                        fw.close();
781                                } catch (IOException e) {
782                                        // TODO Auto-generated catch block
783                                        e.printStackTrace();
784                                }       
785                        } catch (IOException e) {
786                                // TODO Auto-generated catch block
787                                e.printStackTrace();
788                        }
789                } catch (TransformerConfigurationException e2) {
790                        // TODO Auto-generated catch block
791                        e2.printStackTrace();
792                } catch (TransformerFactoryConfigurationError e2) {
793                        // TODO Auto-generated catch block
794                        e2.printStackTrace();
795                }
796        }
797       
798
799}
Note: See TracBrowser for help on using the repository browser.