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

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

querysetid,
bookmarksets structure

File size: 34.9 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       
91        // save element type
92        public static String SE_WORKSPACE = "workspace";
93        public static String SE_QUERYSET = "queryset";
94        public static String SE_QUERY = "query";
95        public static String SE_BOOKMARKSET = "bookmarkset";
96        public static String SE_BOOKMARK = "bookmark";
97       
98        // administration query identification
99        public static String ADMIN = "admin";
100        public static String FILENAME = "filename";
101       
102        public static String PROFILENAME_BASE = "WorkspaceProfile_";
103        public static String PROFILENAME_SERVER = "WorkspaceProfileServer.xml";
104        public static String PROFILENAME_DEFAULT = PROFILENAME_BASE + "default.xml";
105        public static String ADMINISTRATION_FILENAME = "Administration.xml";
106       
107        private String workspace_filename = "WorkspaceProfile.xml";
108        /**
109         * Properties to be filled by Struts with according request-parameters
110         */     
111        //private String actionkey;
112        private String data;
113        private String type;  //workspacetype
114        private String elementtype;
115        private String qid;
116        private String qsid;
117        //private String format;
118        //private String userMsg;
119        private String base_path;
120       
121       
122        private static WorkspaceAction singleton;
123        private static String workspacefilename;
124        private static Document workspace_doc;
125       
126        //private String workspaceindex_path;
127        //private static Integer querycounter;
128        private static final Integer start_query = 1;
129       
130       
131       
132        //private HttpServletRequest request;
133       
134        public String Workspace_filename(){
135                return workspace_filename;
136        }
137
138        public void setWorkspace_filename(String workspace_filename) {
139                this.workspace_filename = workspace_filename;
140        }
141       
142        public String getData(){
143                return data;
144        }
145
146        public void setData(String data) {
147                this.data = data;
148        }
149
150        public String getEelemnttype(){
151                return elementtype;
152        }
153
154        public void setElementtype(String elementtype) {
155                this.elementtype = elementtype;
156        }
157
158        public String getType() {
159                return type;
160        }
161
162        public void setType(String type) {
163                this.type = type;
164        }
165       
166        public String getQid() {
167                return qid;
168        }
169       
170        public void setQid(String qid) {
171                this.qid = qid;
172        }
173
174        public void setQsid(String qsid) {
175                this.qsid = qsid;
176        }
177       
178        public String getQsid() {
179                return qsid;
180        }
181
182        public WorkspaceAction () {     
183                this.elementtype = WorkspaceAction.SE_WORKSPACE;
184                workspacefilename = Admin.getConfig().getProperty("workspaceprofile.path") + Admin.getConfig().getProperty("workspace.file");
185                if (workspace_doc == null){
186                        //workspacefilename = Admin.getConfig().getProperty("workspace.path") + Admin.getConfig().getProperty("workspace.file");
187                        initDocument();
188                }
189        }
190       
191        public static WorkspaceAction getWorkspaceAction() {
192                if (singleton == null) {
193                        singleton = new WorkspaceAction();
194                } 
195                return singleton;
196        }
197
198        protected void finalize() throws Throwable {       
199            try {               
200                //updateQuerycounter();
201                //saveDocument();
202            } catch(Exception e) {
203            }       
204            finally {           
205                super.finalize();
206                //more code can be written here as per need of application             
207            }
208        }
209        /**
210         * primitive identification of the target-proxy
211         * base for finding the right base_url in the props
212         * subclass has to override with its specific proxykey
213         * @return
214         */
215        public String getProxyKey() {
216                return "workspaceprofile";
217        }
218
219        /*
220        @Override
221        public void setServletRequest(HttpServletRequest arg0) {
222                request = arg0;
223               
224        }
225
226        @Override
227        public HttpServletRequest getServletRequest() {
228                return request;         
229        }
230*/
231        /*
232        public String getUserMsg() {
233                return userMsg;
234        }
235
236        public void setUserMsg(String userMsg) {
237                this.userMsg = this.userMsg + "\n" + userMsg;
238        }
239
240
241        private InputStream resultStream;
242        private InputStream sourceStream;
243*/
244        /**
245         * The stream holding the resulting data to be sent back to the user as response
246         * @return
247         */
248        /*
249        public InputStream getResultStream() {
250                return resultStream;
251    }
252        public void setResultStream(InputStream _resultStream){
253                resultStream = _resultStream;
254        }
255        public void setSourceStream(InputStream _sourceStream){
256                sourceStream = _sourceStream;
257        }
258        */
259        @Override
260        public URL getBaseURL() {
261                File file=new File(getPath());
262            URL url=null;
263            try{
264                    url=file.toURL(); 
265                    Admin.notifyUser("DEBUG: WorkspaceAction.getBaseURL(): "  + url);
266            } catch (MalformedURLException e){
267                Admin.notifyUser("JSON exception has been caught" + e);
268            }
269           
270            return url;
271        }
272       
273        public String getBasePath() {           
274                if (base_path == null) {
275                        base_path = Admin.getConfig().getProperty(getProxyKey() + ".path");
276                }
277                return base_path;
278        }
279       
280       
281        public String getWorkspaceProfile() {
282                String profilename = null;
283               
284                if (type.toLowerCase().equals(USER)) {
285                        if (getServletRequest().getRemoteUser() != null) {
286                                profilename =  PROFILENAME_BASE + getServletRequest().getRemoteUser() + ".xml";
287                        } else {
288                                profilename = PROFILENAME_DEFAULT;
289                        }
290                } else if (type.toLowerCase().equals(SERVER)) {
291                        profilename =  PROFILENAME_SERVER;
292                        /*
293                        File f = new File(getBasePath() + profilename);
294                        if (! f.exists()){
295                                //Admin.notifyUser(" not exists");
296                                profilename = "WorkspaceProfile_default.xml";
297                        }
298                        */
299                } else if (type.toLowerCase().equals(ADMIN)){
300                        profilename =  ADMINISTRATION_FILENAME;
301                } else if (type.toLowerCase().equals(FILENAME)){
302                        profilename = this.workspace_filename;
303                }
304               
305                if (profilename == null){
306                        profilename = PROFILENAME_DEFAULT;
307                        Admin.notifyUser("WorkspaceProfilePath not specified (USER, SERVER)!");
308                }
309               
310                Admin.notifyUser("WorkspaceProfilename : " + profilename);
311                return profilename;
312        }
313       
314        @Override
315        public String getFullFormat() {
316                return "xml2json";
317        }
318       
319        public URL getURL() {
320                File file=new File(getPath());
321            URL url=null;
322            try{
323                    url=file.toURL(); 
324                    //Admin.notifyUser("url "  + url);
325            } catch (MalformedURLException e){
326                //Admin.notifyUser("" + e);
327            }
328                return url;
329        }
330       
331       
332        public String getPath() {
333                String targetPath = getBasePath() + this.workspace_filename;//getWorkspaceProfile();       
334        Admin.notifyUser("WorkspaceAction TARGETPATH: " + targetPath);             
335        return targetPath;
336        }
337
338        @Override
339        public InputStream getSourceStream() throws IOException {       
340                InputStream stream = new BufferedInputStream( new FileInputStream(getPath()));
341       
342               
343                return   stream;
344        }
345       
346        // set the server - session data =  repositories, termsets
347        public void setSessionData(InputStream source) throws IOException {
348                if (source == null) return;
349                if (this.getWorkspaceProfile() != PROFILENAME_SERVER) return;
350               
351               
352                       
353        }
354       
355        /*
356        @Override
357        public void prepare() throws Exception {               
358               
359                //Admin.notifyUser("execute:");
360                InputStream in = getSourceStream();
361                this.setSourceStream(in);
362                if (getFormat().equals("xml")) {                       
363                        setResultStream(in);   
364                }else { //JSON
365                        // set srcFile (for MDTransformer to pass to xsl-scripts)
366                        MDTransformer transformer = new MDTransformer();
367                        transformer.setSrcFile(getURL());
368                        transformer.setParams(MDTransformer.createParamsMap(getFullFormat()));
369                        setResultStream(transformer.transformXML(in));//, getFullFormat()));
370                        //setSessionData(getResultStream());
371                }
372                       
373                Admin.notifyUser(getProxyKey() + " success:" + (getResultStream()!=null));
374        }
375
376        public void changeNodeName(Document doc, Node node, String new_name){
377                // Create an element with the new name
378                Node node2 = (Node ) doc.createElement(new_name);
379                // 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); }
380                // Move all the children
381                while (node.hasChildNodes()) { node2.appendChild(node.getFirstChild()); }
382                // Replace the old node with the new node
383                Admin.notifyUser("replace:" + node2.getNodeName() + "," + node.getNodeName());
384                node.getParentNode().replaceChild(node2, node);
385        }
386
387        public void administrateQid() throws IOException, SAXException, ParserConfigurationException, TransformerException{
388                WorkspaceAction wa = new WorkspaceAction();
389                wa.setType("Admin");
390               
391                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
392        DocumentBuilder builder;
393
394                builder = factory.newDocumentBuilder();
395                Document  document = builder.parse(wa.getSourceStream());
396                // find user-filename-id or create one
397                //add qid
398                //NodeList list = document.getElementsByTagName("e");
399                //Admin.notifyUser("list:" + list.getLength());
400
401                // save the changes
402                Transformer transformer;
403                transformer = TransformerFactory.newInstance().newTransformer();
404                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
405                StreamResult result = new StreamResult(new StringWriter());
406                DOMSource source = new DOMSource(document);
407                transformer.transform(source, result);
408                String xmlString = result.getWriter().toString();
409                InputStream is_xml = new ByteArrayInputStream( xmlString.getBytes( ) );
410                Admin.writeToFile(wa.getPath(), is_xml);
411                //wa.save();
412        }
413       
414        public String save() throws IOException, SAXException, ParserConfigurationException, TransformerException {
415               
416        String jsonData = getData();
417             
418        Admin.notifyUser("JSON data:"+jsonData);
419        if ((!this.getType().equals(ADMIN)) && this.getQid() != null) {
420                        administrateQid();
421                }
422       
423        XMLSerializer serializer = new XMLSerializer();
424                JSON json = JSONSerializer.toJSON( jsonData );
425                if (this.getType().equals(ADMIN)){
426                        serializer.setRootName("Admin");
427                } else {
428                        serializer.setRootName("WorkspaceProfile");     
429                }
430                serializer.setElementName("item");
431        serializer.setTypeHintsEnabled(false);
432        String xml = serializer.write( json );
433        Admin.notifyUser("XML:" + xml);
434       
435        InputStream is_xml = new ByteArrayInputStream( xml.getBytes( ) );
436       
437        Admin.writeToFile(getPath(), is_xml);
438   
439        String ret = "1";
440                this.setResultStream( new ByteArrayInputStream(ret.getBytes()));
441                               
442
443                return SUCCESS;
444        }
445*/
446        public void changeQueryId(Document doc, String from_id, String to_id) throws XPathExpressionException{
447                InputStream is = null;
448                XPathFactory factory = XPathFactory.newInstance(); 
449            XPath xpath = factory.newXPath(); 
450            XPathExpression expr;
451            String xpath_expr = "";
452                //xpath_expr = "//WorkspaceProfile/Querysets/item/Queries/item/id[.='" + from_id + "']";
453            xpath_expr = "//item/id[.='" + from_id + "']";
454                expr = xpath.compile(xpath_expr);
455                Object result = null;
456                result = expr.evaluate(doc, XPathConstants.NODESET);
457               
458            NodeList nodelist = (NodeList) result;
459            nodelist.item(0).setTextContent(to_id);
460        }
461        public String createNewId(String name){
462                String id = workspace_doc.getElementsByTagName(name).item(0).getTextContent();
463                Integer i = Integer.parseInt(id) + 1;
464                id = i.toString();
465                workspace_doc.getElementsByTagName(name).item(0).setTextContent(id);
466                return id.toString();
467        }
468        /*
469        public String createNewQsid(){
470                String id = workspace_doc.getElementsByTagName("maxqsid").item(0).getTextContent();
471                Integer i = Integer.parseInt(id) + 1;
472                id = i.toString();
473                workspace_doc.getElementsByTagName("maxqsid").item(0).setTextContent(id);
474                return id.toString();
475        }
476        */
477        public InputStream createStream(String value) throws TransformerException, TransformerFactoryConfigurationError, ParserConfigurationException, UnsupportedEncodingException{
478        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
479        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
480        Document doc = docBuilder.newDocument();
481
482        ////////////////////////
483        //Creating the XML tree
484        Element root = doc.createElement("root");
485        root.setTextContent(value);
486        doc.appendChild(root);
487        //set up a transformer
488        TransformerFactory transfac = TransformerFactory.newInstance();
489        Transformer trans = transfac.newTransformer();
490        //trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
491        //trans.setOutputProperty(OutputKeys.INDENT, "yes");
492
493        //create string from xml tree
494        //StringWriter sw = new StringWriter();
495        //StreamResult result = new StreamResult(sw);
496        //DOMSource source = new DOMSource(doc);
497        //trans.transform(source, result);
498       
499
500        DOMSource source = new DOMSource(doc);   
501        StringWriter xmlAsWriter = new StringWriter();   
502        StreamResult result = new StreamResult(xmlAsWriter);     
503        TransformerFactory.newInstance().newTransformer().transform(source, result);   
504         
505        // write changes   
506        ByteArrayInputStream is = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
507           
508
509       return is;
510
511
512        }
513        public String getXMLRootName(){
514                String rootname = "WorkspaceProfile";
515                if (this.elementtype.equals(WorkspaceAction.SE_QUERY)){
516                        rootname = "item";
517                }
518                if (this.elementtype.equals(WorkspaceAction.SE_QUERYSET)){
519                        rootname = "item";
520                }
521                return rootname;
522        }
523        public  String  DocumentReplaceNewElement(Document new_doc) throws XPathExpressionException{
524                String newid = "";
525                if (this.elementtype.equals(WorkspaceAction.SE_WORKSPACE)){
526                        NodeList wsnodelist = (NodeList) getWorkspace();
527                // remove
528                //childeNode
529                if (wsnodelist.getLength() > 0){
530                        ((Node)wsnodelist.item(0)).getParentNode().removeChild(wsnodelist.item(0));
531                }
532                //String qidstring = "";
533                //if (qid.equals("0")) {
534                //    newid = createNewQid();
535                //    changeQueryId(new_doc,qid,newid);
536                //}
537               
538                Node node = new_doc.getFirstChild();
539                Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
540                ((Element)node2).setAttribute("user", getUserName());
541                workspace_doc.getElementsByTagName("WorkspaceProfiles").item(0).appendChild(node2);
542                }
543                if (this.elementtype.equals(WorkspaceAction.SE_QUERY)){
544// new query
545                        Node node = new_doc.getFirstChild();
546                        if (this.qid.equals("0")){
547                                newid = createNewId("maxqid");   
548                                new_doc.getElementsByTagName("id").item(0).setTextContent(newid);
549                        Element root = workspace_doc.getDocumentElement();
550                        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
551                        node2 = workspace_doc.renameNode(node2, "", "item");
552                   // apend to specific queryset
553                                NodeList wsnodelist = (NodeList) getQueryParent();
554                        wsnodelist.item(0).appendChild(node2);
555                        } 
556                       
557                        else {
558                                // edit existing query
559                                NodeList wsnodelist = (NodeList) getQuery();
560                        // remove
561                        //childeNode
562                        if (wsnodelist.getLength() > 0){
563                                //Element root = workspace_doc.getDocumentElement();
564                                Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
565                                node2 = workspace_doc.renameNode(node2, "", "item");
566                                Node qnode  = (Node)wsnodelist.item(0);
567                                //root.replaceChild(node2,(Node)wsnodelist.item(0));   
568                               
569                                Element parentElement = (Element)qnode.getParentNode();
570                                        parentElement.insertBefore(node2, qnode);
571                                        qnode.getParentNode().removeChild(qnode);
572                                        parentElement.normalize();
573                        }
574                        }
575                }
576                if (this.elementtype.equals(WorkspaceAction.SE_BOOKMARK)){
577                        // new bookmark
578                                                Node node = new_doc.getFirstChild();
579                                                if (this.qid.equals("0")){
580                                                        newid = createNewId("maxbid");   
581                                                        new_doc.getElementsByTagName("id").item(0).setTextContent(newid);
582                                                Element root = workspace_doc.getDocumentElement();
583                                                Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
584                                                node2 = workspace_doc.renameNode(node2, "", "item");
585                                           // apend to specific bookmarkset
586                                                        NodeList wsnodelist = (NodeList) getBookmarkParent();
587                                                wsnodelist.item(0).appendChild(node2);
588                                                } 
589                                               
590                                                else {
591                                                        // edit existing query
592                                                        NodeList wsnodelist = (NodeList) getQuery();
593                                                // remove
594                                                //childeNode
595                                                if (wsnodelist.getLength() > 0){
596                                                        //Element root = workspace_doc.getDocumentElement();
597                                                        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
598                                                        node2 = workspace_doc.renameNode(node2, "", "item");
599                                                        Node qnode  = (Node)wsnodelist.item(0);
600                                                        //root.replaceChild(node2,(Node)wsnodelist.item(0));   
601                                                       
602                                                        Element parentElement = (Element)qnode.getParentNode();
603                                                                parentElement.insertBefore(node2, qnode);
604                                                                qnode.getParentNode().removeChild(qnode);
605                                                                parentElement.normalize();
606                                                }
607                                                }
608                                        }
609                //new queryset
610                if (this.elementtype.equals(WorkspaceAction.SE_QUERYSET)){
611                        // new queryset
612                                                Node node = new_doc.getFirstChild();
613                                                if (this.qsid.equals("0")){
614                                                        newid = createNewId("maxqsid"); 
615                                                        new_doc.getElementsByTagName("id").item(0).setTextContent(newid);
616                                                Element root = workspace_doc.getDocumentElement();
617                                                Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
618                                                node2 = workspace_doc.renameNode(node2, "", "item");
619                                           // apend to specific querysets
620                                                NodeList wsnodelist = (NodeList) this.getWorkspace();
621                                                Element welem = (Element)wsnodelist.item(0);
622                                                        welem.getElementsByTagName("Querysets").item(0).appendChild(node2);
623                                                } 
624                                               
625                                                else {
626                                                        // edit existing queryset
627                                                        NodeList wsnodelist = (NodeList) getQueryset();
628                                                // remove
629                                                //childeNode
630                                                if (wsnodelist.getLength() > 0){
631                                                        //Element root = workspace_doc.getDocumentElement();
632                                                        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
633                                                        node2 = workspace_doc.renameNode(node2, "", "item");
634                                                        Node qset  = (Node)wsnodelist.item(0);
635                                                       
636                                                        Element parentElement = (Element)qset.getParentNode();
637                                                                parentElement.insertBefore(node2, qset);
638                                                                qset.getParentNode().removeChild(qset);
639                                                                parentElement.normalize();
640                                                }
641                                                }
642                                        }
643               
644                //new bookmarkset
645                if (this.elementtype.equals(WorkspaceAction.SE_BOOKMARKSET)){
646                        // new queryset
647                                                Node node = new_doc.getFirstChild();
648                                                if (this.qsid.equals("0")){
649                                                        newid = createNewId("maxbsid"); 
650                                                        new_doc.getElementsByTagName("id").item(0).setTextContent(newid);
651                                                Element root = workspace_doc.getDocumentElement();
652                                                Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
653                                                node2 = workspace_doc.renameNode(node2, "", "item");
654                                           // apend to specific querysets
655                                                NodeList wsnodelist = (NodeList) this.getWorkspace();
656                                                Element welem = (Element)wsnodelist.item(0);
657                                                        welem.getElementsByTagName("Bookmarksets").item(0).appendChild(node2);
658                                                } 
659                                               
660                                                else {
661                                                        // edit existing bookmarkset
662                                                        NodeList wsnodelist = (NodeList) getBookmarkset();
663                                                // remove
664                                                //childeNode
665                                                if (wsnodelist.getLength() > 0){
666                                                        //Element root = workspace_doc.getDocumentElement();
667                                                        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
668                                                        node2 = workspace_doc.renameNode(node2, "", "item");
669                                                        Node qset  = (Node)wsnodelist.item(0);
670                                                       
671                                                        Element parentElement = (Element)qset.getParentNode();
672                                                                parentElement.insertBefore(node2, qset);
673                                                                qset.getParentNode().removeChild(qset);
674                                                                parentElement.normalize();
675                                                }
676                                                }
677                                        }
678                return newid;
679        }
680       
681        //todo .has("Queries")
682        public void parseDataInit(JSONObject json){
683                // workspaceelement
684                if (json.has("Querysets")) {
685                        this.setQid("0");
686                        this.setElementtype(WorkspaceAction.SE_WORKSPACE);
687                } else {
688                        // Querysetelement
689                        if (json.has("Queries")) {
690                                this.setElementtype(WorkspaceAction.SE_QUERYSET);
691                                this.setQsid(json.getString("id"));
692                        } else {
693                                if (json.has("Bookmarks")) {
694                                        this.setElementtype(WorkspaceAction.SE_BOOKMARKSET);
695                                        this.setQsid(json.getString("id"));
696                                } else {
697                                        // Query-Bookmark-element
698                                        if (json.getString("bookmark").equals("1")) {
699                                                this.setElementtype(WorkspaceAction.SE_BOOKMARK);
700                                        } else {
701                                                // Queryelement
702                                                this.setElementtype(WorkspaceAction.SE_QUERY);
703                                        }
704                                        this.setQid(json.getString("id"));
705                                }
706                        }
707                }
708
709        }
710        public String save() throws ParserConfigurationException, SAXException, IOException, DOMException, XPathExpressionException, TransformerException, TransformerFactoryConfigurationError{
711               
712                // user data
713                String jsonData = getData();
714        XMLSerializer serializer = new XMLSerializer();
715                JSON json = JSONSerializer.toJSON( jsonData );
716                // init qid, elementtype
717                parseDataInit((JSONObject)json);
718                serializer.setRootName(getXMLRootName()); //"WorkspaceProfile");       
719                serializer.setElementName("item");
720        serializer.setTypeHintsEnabled(false); 
721        String xml = serializer.write( json );
722        //Admin.notifyUser("XML:" + xml);
723        InputStream is_xml = new ByteArrayInputStream( xml.getBytes( ) );
724        // add to document
725        //Admin.writeToFile(getPath(), is_xml);
726        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
727        DocumentBuilder builder = factory.newDocumentBuilder();
728        Document new_doc = builder.parse( is_xml );
729        // set user
730        //((Element)d.getFirstChild()).setAttribute("user", getServletRequest().getRemoteUser());
731        String newid = DocumentReplaceNewElement(new_doc);
732       
733
734      //TODO
735        saveDocument();
736        // return new qid
737        //String src = "<body>" + qidstring + "</body>";
738        //javax.xml.transform.stream.StreamSource s = new StreamSource(src);
739        //InputStream in = s.getInputStream();
740                this.setResultStream(createStream(newid));//(InputStream)(new ByteArrayInputStream(qidstring.getBytes())));
741               
742               
743                return SUCCESS;
744               
745        }
746        public InputStream DocumentToStream(Node node) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{
747               
748                InputStream is = null;
749                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
750                Source xmlSource;
751               
752                if (node == null) {
753                        xmlSource = new DOMSource(workspace_doc); 
754                } else {
755                        xmlSource = new DOMSource(node);
756                }
757                Result outputTarget = new StreamResult(outputStream); 
758                TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); 
759                is = new ByteArrayInputStream(outputStream.toByteArray()); 
760                return is;
761        }
762
763        public String DocumentToXMLString(){
764                Transformer transformer;
765                String xmlString = "";
766                try {
767                                transformer = TransformerFactory.newInstance().newTransformer();
768                                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
769
770                                //initialize StreamResult with File object to save to file
771                                StreamResult result = new StreamResult(new StringWriter());
772                                DOMSource source = new DOMSource(workspace_doc);
773                                try {
774                                        transformer.transform(source, result);
775                                } catch (TransformerException e1) {
776                                        // TODO Auto-generated catch block
777                                        e1.printStackTrace();
778                                }
779
780                                xmlString = result.getWriter().toString();
781                        } catch (TransformerConfigurationException e) {
782                                // TODO Auto-generated catch block
783                                e.printStackTrace();
784                        } catch (TransformerFactoryConfigurationError e) {
785                                // TODO Auto-generated catch block
786                                e.printStackTrace();
787                        }
788                       
789                return xmlString;
790        }
791       
792        public void addWorkspaceToDocument(){
793                //{'WorkspaceProfile':{'CustomTermsets':'null',
794                //                     'Termsets':'null',
795                //                     'Repositories':'null',
796                //                     'Querysets':'null','created':'null','lastchanged':'null','profilename':'null'}};
797                Element we = workspace_doc.createElement("WorkspaceProfile");
798                we.setAttribute("user", getType().toLowerCase());
799                workspace_doc.getFirstChild().appendChild(we);
800               
801                Element e = workspace_doc.createElement("CustomTermsets");
802                e.setNodeValue("null");
803                we.appendChild(e);
804               
805                e = workspace_doc.createElement("Termsets");
806                e.setNodeValue("null");
807                we.appendChild(e);
808               
809                e = workspace_doc.createElement("Repositories");
810                e.setNodeValue("null");
811                we.appendChild(e);
812               
813                e = workspace_doc.createElement("Querysets");
814                e.setNodeValue("null");
815                we.appendChild(e);
816               
817                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
818                String strdate = dateFormat.format(new Date()).toString();
819                e = workspace_doc.createElement("created");
820                e.setNodeValue(strdate);
821                we.appendChild(e);
822               
823                e = workspace_doc.createElement("lastchanged");
824                e.setNodeValue(strdate);
825                we.appendChild(e);
826               
827                e = workspace_doc.createElement("profilename");
828                e.setNodeValue(getType().toLowerCase());
829                we.appendChild(e);
830        }
831       
832        public String getUserName(){
833                String userstring;
834                if (getType().toLowerCase().equals(SERVER)){
835                        userstring = SERVER;
836                }else {
837                        userstring = getServletRequest().getRemoteUser();
838                        if (userstring == null){
839                                userstring = "default";
840                        }
841                }
842                return userstring;
843        }
844        public String getWorkspaceXPathExpression(){
845                String xpath_expr = "";
846
847                xpath_expr = "//Profiles/WorkspaceProfiles/WorkspaceProfile[@user='" + getUserName() + "']";
848
849                return xpath_expr;
850        }
851       
852        public Object getWorkspace() throws XPathExpressionException{
853                InputStream is = null;
854                XPathFactory factory = XPathFactory.newInstance(); 
855            XPath xpath = factory.newXPath(); 
856            XPathExpression expr;
857                        expr = xpath.compile(getWorkspaceXPathExpression());
858                        //expression is evaluated with respect to a certain context node which is doc.
859                        Object result = null;
860                        try{
861                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
862                        } catch(Exception e){
863                               
864                        }
865
866             return result;
867        }
868       
869        public Object getQuery() throws XPathExpressionException{
870               
871                XPathFactory factory = XPathFactory.newInstance(); 
872            XPath xpath = factory.newXPath(); 
873            XPathExpression expr;
874                        expr = xpath.compile("//Profiles/WorkspaceProfiles/WorkspaceProfile/Querysets/item/Queries/item[id='" + this.qid + "']");
875                                //expr = xpath.compile("//item[@id='" + this.qid + "']");
876                        //expression is evaluated with respect to a certain context node which is doc.
877                        Object result = null;
878                        try{
879                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
880                        } catch(Exception e){
881                               
882                        }
883
884             return result;
885        }
886
887public Object getQueryParent() throws XPathExpressionException{
888               
889                XPathFactory factory = XPathFactory.newInstance(); 
890            XPath xpath = factory.newXPath(); 
891            XPathExpression expr;
892                        expr = xpath.compile("//Profiles/WorkspaceProfiles/WorkspaceProfile/Querysets/item[id='" + this.qsid + "']/Queries");
893                        //expression is evaluated with respect to a certain context node which is doc.
894                        Object result = null;
895                        try{
896                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
897                        } catch(Exception e){
898                               
899                        }
900
901             return result;
902        }
903        public Object getQueryset() throws XPathExpressionException{
904               
905                XPathFactory factory = XPathFactory.newInstance(); 
906            XPath xpath = factory.newXPath(); 
907            XPathExpression expr;
908                        expr = xpath.compile("//Profiles/WorkspaceProfiles/WorkspaceProfile/Querysets/item[id='" + this.qsid + "']");
909                        //expression is evaluated with respect to a certain context node which is doc.
910                        Object result = null;
911                        try{
912                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
913                        } catch(Exception e){
914                               
915                        }
916
917             return result;
918        }
919
920        public Object getBookmarkParent() throws XPathExpressionException{
921               
922                XPathFactory factory = XPathFactory.newInstance(); 
923            XPath xpath = factory.newXPath(); 
924            XPathExpression expr;
925                        expr = xpath.compile("//Profiles/WorkspaceProfiles/WorkspaceProfile/Bookmarksets/item[id='" + this.qsid + "']/Bookmarks");
926                        //expression is evaluated with respect to a certain context node which is doc.
927                        Object result = null;
928                        try{
929                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
930                        } catch(Exception e){
931                               
932                        }
933
934             return result;
935        }
936       
937        public Object getBookmarkset() throws XPathExpressionException{
938               
939                XPathFactory factory = XPathFactory.newInstance(); 
940            XPath xpath = factory.newXPath(); 
941            XPathExpression expr;
942                        expr = xpath.compile("//Profiles/WorkspaceProfiles/WorkspaceProfile/Bookmarksets/item[id='" + this.qsid + "']");
943                        //expression is evaluated with respect to a certain context node which is doc.
944                        Object result = null;
945                        try{
946                        result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
947                        } catch(Exception e){
948                               
949                        }
950
951             return result;
952        }
953
954       
955        @Override
956        public void prepare() throws Exception {               
957               
958                NodeList list = (NodeList) getWorkspace();//result;
959                if (list.getLength() < 1) {
960                        addWorkspaceToDocument();
961                        list = (NodeList) getWorkspace();
962                }
963                if (list.getLength() > 1){
964                        // error
965                }
966                // nodelistto stream
967                InputStream is = this.DocumentToStream(list.item(0));
968                this.setSourceStream(is);     
969               
970                if (getFormat().equals("xml")) {                       
971                        setResultStream(is);   
972                }else { //JSON
973                        // set srcFile (for MDTransformer to pass to xsl-scripts)
974                        MDTransformer transformer = new MDTransformer();
975                        transformer.setSrcFile(getURL());
976                        transformer.setParams(MDTransformer.createParamsMap(getFullFormat()));
977                        setResultStream(transformer.transformXML(is));//, getFullFormat()));
978                        //setSessionData(getResultStream());
979                }
980                       
981                Admin.notifyUser(getProxyKey() + " success:" + (getResultStream()!=null));
982        }
983
984       
985       
986public void initDocument() {
987       
988        boolean init=false;
989        Integer counter = start_query;
990        //String fname = getPath();//workspacefile;
991        File f = new File (workspacefilename);
992               
993        if (!f.exists()) {
994                                // create new  counter document
995                                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
996                        DocumentBuilder docBuilder;
997                                try {
998                                        docBuilder = docFactory.newDocumentBuilder();
999                                        workspace_doc = docBuilder.newDocument();
1000                                        // append root tag <index >
1001                                        Element root = (Element) workspace_doc.createElement("Profiles");
1002                                        //root.setAttribute("idcounter", "1");
1003                                        workspace_doc.appendChild(root);
1004                                        Element e = workspace_doc.createElement("Querycounter");
1005                                        root.appendChild(e);
1006                                        e = workspace_doc.createElement("maxqid");
1007                                        e.setNodeValue(counter.toString());
1008                                        e = workspace_doc.createElement("WorkspaceProfiles");
1009                                        root.appendChild(e);
1010
1011                                        //updateQuerycounter();
1012                                        this.saveDocument();
1013                                       
1014                                        //Admin.notifyUser("new document");
1015                                } catch (ParserConfigurationException e) {
1016                                        // TODO Auto-generated catch block
1017                                        e.printStackTrace();
1018                                }
1019            }
1020                else {
1021                        try {
1022                               
1023                        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1024                        DocumentBuilder docBuilder;
1025                                try {
1026                                        docBuilder = docFactory.newDocumentBuilder();               
1027                                        try {
1028                                                        workspace_doc = docBuilder.parse(workspacefilename);
1029                                        } catch (SAXException e) {
1030                                                        // TODO Auto-generated catch block
1031                                                       
1032                                                        e.printStackTrace();
1033                                        }
1034                                } catch (ParserConfigurationException e) {
1035                                                // TODO Auto-generated catch block
1036                                                e.printStackTrace();
1037                                }
1038                               
1039                         //read counter
1040                         //counter = new Integer(workspace_doc.getFirstChild().getFirstChild().getFirstChild().getNodeValue());
1041                         init = true;
1042                    }  catch (IOException ex){
1043                        //Admin.notifyUser("initCacheCounter:" + ex.toString());
1044                        ex.printStackTrace();
1045                    }
1046                }
1047               
1048            //return counter;
1049        }
1050/*
1051        public void updateQuerycounter () {
1052                workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(querycounter.toString());
1053            saveDocument();
1054        }
1055        */
1056        public void saveDocument() {
1057        //public void writeQuerycounter (Integer i) {           
1058               
1059                // first update <index idcounter>
1060                //workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(i.toString());
1061               
1062                //Admin.notifyUser("writeCacheCounter:" + i.toString());
1063                // write xml
1064                Transformer transformer;
1065                try {
1066                        transformer = TransformerFactory.newInstance().newTransformer();
1067                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
1068
1069                        //initialize StreamResult with File object to save to file
1070                        StreamResult result = new StreamResult(new StringWriter());
1071                        DOMSource source = new DOMSource(workspace_doc);
1072                        try {
1073                                transformer.transform(source, result);
1074                        } catch (TransformerException e1) {
1075                                // TODO Auto-generated catch block
1076                                e1.printStackTrace();
1077                        }
1078
1079                        String xmlString = result.getWriter().toString();
1080
1081                        File f = new File (workspacefilename);
1082                        FileWriter fw;
1083                        try {
1084                                fw = new FileWriter(f);
1085                                try {
1086                                        fw.write(xmlString);
1087                                        fw.close();
1088                                } catch (IOException e) {
1089                                        // TODO Auto-generated catch block
1090                                        e.printStackTrace();
1091                                }       
1092                        } catch (IOException e) {
1093                                // TODO Auto-generated catch block
1094                                e.printStackTrace();
1095                        }
1096                } catch (TransformerConfigurationException e2) {
1097                        // TODO Auto-generated catch block
1098                        e2.printStackTrace();
1099                } catch (TransformerFactoryConfigurationError e2) {
1100                        // TODO Auto-generated catch block
1101                        e2.printStackTrace();
1102                }
1103        }
1104       
1105
1106}
Note: See TracBrowser for help on using the repository browser.