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

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

new lib hierarchy

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