source: MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java @ 1530

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

repository action

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