source: MDService2/branches/MDService_simple2/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java @ 1511

Last change on this file since 1511 was 1511, checked in by vronk, 13 years ago

brutal refactoring,
added new packages: proxies, internal,
very much restructured Action hierarchy.
Introduced division Action/Proxy?.
This is a first compiling version.
it's total mess.

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