Changeset 1273 for MDService2/trunk


Ignore:
Timestamp:
05/08/11 01:04:30 (13 years ago)
Author:
gaba
Message:

query indices
VCR first version

Location:
MDService2/trunk/MDService2
Files:
1 added
8 edited

Legend:

Unmodified
Added
Removed
  • MDService2/trunk/MDService2/WebContent/scripts/mdservice_model.js

    r1252 r1273  
    99var page_record_count = 10;
    1010var formatquerystring_len = 25;
    11 var workspace;
     11//var workspace;
    1212
    1313function Workspace(){
    1414
    1515};
    16 Workspace.save = function(type){
    17         var JSONText = JSON.stringify(jsonw["WorkspaceProfile"]);
     16Workspace.save = function(type, query, id, iq){
     17        var JSONText;
     18        var qdata = "/";
     19        /*
     20        if (type == "ADMIN"){
     21                JSONText = JSON.stringify(json_admin["WorkspaceProfile"]);
     22        } else {
     23                JSONText = JSON.stringify(jsonw["WorkspaceProfile"]);
     24        }
     25        */
    1826        //var JSONText = JSON.stringify({"aa.a":"r"});
    1927        //notifyUser(JSONText,'debug');
    20         $.post("/MDService2/workspaceprofilesave/" + type,{"data":JSONText});
    21 };
    22 Workspace.saveQuery = function(query){
    23         //queryset id
    24         var id = parseInt($("#qts_select option:selected").val());
    25         var iq = 0;
    26         var queries = jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"];
    27        
    28         //var iq = $('#userqueries').children().size();
    29         if (queries == "null"){
    30                 jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"] = [{}];
    31         } else {
    32                 iq = queries.length;
    33         }
    34         var jsonq = query.toJSON();
    35         jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq] = jsonq;
    36         Workspace.save("USER");
    37         appendQueryUI(jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq],iq, $('#userqueries'));
    38        
    39 };
     28       
     29        JSONText = JSON.stringify(jsonw["WorkspaceProfile"]);
     30        if (query != undefined){
     31                qdata = "/" + query.id;
     32        }
     33        $.post("/MDService2/workspaceprofilesave/" + type + qdata,{"data":JSONText},  function(data) {
     34                query.id = $(data).text();
     35                jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq]["id"] = query.id;
     36                appendQueryUI(jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq],iq, $('#userqueries'));
     37//            alert("success");
     38        });
     39        //.success(function() { alert("second success"); })
     40    //.error(function(e) { alert("error"); })
     41    //.complete(function() { alert("complete"); });
     42
     43
     44};
     45/*
     46Workspace.newQueryID = function(){
     47        var new_id;
     48       
     49        loadAdminFile();
     50        json_admin["Admin"]["maxqid"]  = parseInt(json_admin["Admin"]["maxqid"]) + 1;
     51        new_id = json_admin["Admin"]["maxqid"];
     52        Workspace.save("ADMIN");
     53        return new_id;
     54};
     55*/
    4056function Collection(index, name){
    4157        this.index = index;
     
    4965*/
    5066function Query(collection, columns, query , squery) {
     67        this.id = 0;
    5168        this.collection = collection;   // []
    5269        this.columns = columns;         // string
     
    125142};
    126143
     144Query.prototype.save = function(){
     145        //queryset id
     146        var id = parseInt($("#qts_select option:selected").val());
     147        var iq = 0;
     148        var queries = jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"];
     149       
     150        //var iq = $('#userqueries').children().size();
     151        if (queries == "null"){
     152                jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"] = [{}];
     153        } else {
     154                iq = queries.length;
     155        }
     156        // create queryID
     157        this.id = 0;//Workspace.newQueryID();//id + "_" + iq;
     158        var jsonq = this.toJSON();
     159        jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq] = jsonq;
     160        Workspace.save("USER", this, id, iq);
     161        //appendQueryUI(jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq],iq, $('#userqueries'));
     162       
     163};
     164
     165
    127166Query.prototype.getcolumnstext = function (){
    128167       
     
    195234        str = Query.queryliststring(this.squery, this.query) + coll + " @" + this.repository.toString();
    196235        return str;
     236};
     237
     238Query.prototype.publish = function() {
     239        $.post("/MDService2/virtualcollection/USER/" + this.id,"");
    197240};
    198241
     
    245288        }
    246289
    247         var jsonq = {"name":"",
     290        var jsonq = {"id":this.id,
     291                                 "name":"",
    248292                             "squerystring":this.squery,
    249293                                 "querystring":this.query,     
     
    253297                                 "startItem" : this.startItem,
    254298                                 "maximumItems" : this.maximumItems,
    255                                  "options" : json_options, "bookmark" : "0", "time" : str_time};
     299                                 "options" : json_options,
     300                                 "bookmark" : "0",
     301                                 "time" : str_time};
    256302       
    257303        jsonq.name = Query.fullformatstring(jsonq);
  • MDService2/trunk/MDService2/WebContent/scripts/mdservice_ui.js

    r1266 r1273  
    228228        });
    229229       
     230        $('.cmd_publish').live('click', function(event){
     231                var query = $(this).parent().data('query');
     232                query.publish();
     233        });
    230234       
    231235        //////////////////////////////////////////////
     
    351355                qid = $(this).data('query').listid;
    352356                notifyUser("here I would save query: " + qid, "debug");
    353                 Workspace.saveQuery($(this).data('query'));
     357                $(this).data('query').save();
     358                //Workspace.saveQuery($(this).data('query'));
    354359        });
    355360
  • MDService2/trunk/MDService2/WebContent/scripts/mdservice_ui_load.js

    r1266 r1273  
    3434
    3535};
     36/*
     37function loadAdminFile(){
     38        json_admin = {'Admin':{'maxqid':'0','QueryIndices':'null'}};
     39       
     40        jQuery.getJSON("/MDService2/workspaceprofile/admin",function(data){
     41                        json_admin = preprocessJSON(data);
     42        });
     43}
     44*/
    3645function loadWorkspaceProfiles(){
    3746        //empty json
     
    3948        $('#qts_input').val("");
    4049       
    41         jQuery.getJSON("/MDService2/workspaceprofile/server",function(data){
    42                 notifyUser(data['WorkspaceProfile'],'debug');
    43                                 var json = preprocessJSON(data);
    44                                 $("#serverqs").attr("data",JSON.stringify(json));
    45                                 loadQuerysets(json["WorkspaceProfile"]["Querysets"],"server");
    46                                 loadRepositories(json["WorkspaceProfile"]["Repositories"]);
    47                                 loadCollections(true);                         
    48                                 loadTerms();
    49                                 loadTermsAutocomplete();
    50                                 createTooltip(null);
    51                 });
    52 
    5350        // USER WORKSPACEPROFILE
    5451        jQuery.getJSON("/MDService2/workspaceprofile/user",function(data){
    5552                notifyUser(data['WorkspaceProfile'],'debug');
    5653                                jsonw = preprocessJSON(data);
     54                               
     55                                jQuery.getJSON("/MDService2/workspaceprofile/server",function(data){
     56                                        notifyUser(data['WorkspaceProfile'],'debug');
     57                                                        var json = preprocessJSON(data);
     58                                                        $("#serverqs").attr("data",JSON.stringify(json));
     59                                                        loadQuerysets(json["WorkspaceProfile"]["Querysets"],"server");
     60                                                        loadRepositories(json["WorkspaceProfile"]["Repositories"]);
     61                                                        loadCollections(true);                         
     62                                                        loadTerms();
     63                                                        loadTermsAutocomplete();
     64                                                        createTooltip(null);
     65                                                       
     66                                                       
     67                                        });
     68
    5769                                loadQuerysets(jsonw["WorkspaceProfile"]["Querysets"],"user");
    5870                                //loadTermsets(jsonw["WorkspaceProfile"]["CustomTermsets"]);
    5971                                createTooltip(this);
    6072        });
     73       
     74       
    6175
    6276}
     
    259273        json.name + '</a></span>' +
    260274        del +
    261         '<div class="detail" >' +
     275        '<span class="cmd cmd_publish"></span><div class="detail" >' +
    262276        name +
    263277        '<div class="cmds-elem-prop"><span class="label">squery:</span><span class="value">' + squery + '</span></div>' +
     
    276290        $(qs).append(x);
    277291       
     292        var query = new Query([],"","","");
     293        query.load(json);
     294        $(qs).find("[href='"+ id + "_" + i + "']").closest('.cmds-elem-plus').data('query',query);
    278295        $(qs).find('.detail').css({'z-index' : '1000'});
    279296       
     
    366383
    367384function  preprocessJSON(json){
     385        if (json["Admin"] != undefined) {
     386                if (json["Admin"]["QueryIndices"] != undefined){
     387                        if (String(json["Admin"]["QueryIndices"]) != "null") {
     388                                if (json["Admin"].QueryIndices[0] == undefined){
     389                                        var jj = json["Admin"]["QueryIndices"]["item"];
     390                                        delete json["Admin"]["QueryIndices"]["item"];
     391                                        json["Admin"]["QueryIndices"] = [{}];
     392                                        json["Admin"]["QueryIndices"][0] = jj;
     393                                }
     394                        }
     395                }
     396        }
     397       
     398       
    368399        if (json["WorkspaceProfile"]["CustomTermsets"] != undefined){
    369400       
  • MDService2/trunk/MDService2/WebContent/scripts/mdservice_ui_settings.js

    r1234 r1273  
    1212
    1313//VARIABLES
    14 var jsonw;
     14var jsonw, json_admin;
    1515var url_params;
    1616var local_collections = false;
  • MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/AdminAction.java

    r1269 r1273  
    1212import net.sf.json.JSONObject;
    1313import net.sf.json.xml.XMLSerializer;
     14
     15import org.jzkit.service.*;
     16import org.jzkit.search.provider.iface.Searchable;
     17import org.jzkit.search.provider.iface.SearchableFactory;
    1418
    1519
     
    7377        public String del() throws Exception {
    7478               
     79                //String connection_descriptor_string = "";
     80                //SearchableFactory sf = app_ctx.getBean("SearchableFactory");
     81            //Searchable z3950_target = sf.create(connection_descriptor_string);//create(new IRServiceDescriptor("proto=z3950,addr=www.lcweb.gov:210,code=LC,shortname=\"Library of congress\",longname="\"Library of congress\""));
     82
    7583                //getServletRequest().getRemoteUser()
    7684                if (getServletRequest().getRemoteUser() != null){
  • MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java

    r911 r1273  
    88import java.io.FileInputStream;
    99import java.io.FileNotFoundException;
     10import java.io.FileWriter;
    1011import java.io.IOException;
    1112import java.io.InputStream;
    1213import java.io.InputStreamReader;
    1314import java.io.Reader;
     15import java.io.UnsupportedEncodingException;
    1416import java.io.Writer;
    1517import java.net.MalformedURLException;
    1618import java.net.URL;
     19import java.text.DateFormat;
     20import java.text.SimpleDateFormat;
     21import java.util.Date;
    1722import java.util.Enumeration;
    1823
     
    2732import javax.xml.parsers.ParserConfigurationException;
    2833import javax.xml.transform.OutputKeys;
     34import javax.xml.transform.Result;
     35import javax.xml.transform.Source;
    2936import javax.xml.transform.Transformer;
    3037import javax.xml.transform.TransformerConfigurationException;
     
    3441import javax.xml.transform.dom.DOMSource;
    3542import javax.xml.transform.stream.StreamResult;
     43import javax.xml.transform.stream.StreamSource;
     44import javax.xml.xpath.XPath;
     45import javax.xml.xpath.XPathConstants;
     46import javax.xml.xpath.XPathExpression;
     47import javax.xml.xpath.XPathExpressionException;
     48import javax.xml.xpath.XPathFactory;
    3649
    3750
     
    4962
    5063import org.apache.struts2.interceptor.ServletRequestAware;
     64import org.w3c.dom.Attr;
     65import org.w3c.dom.DOMException;
    5166import org.w3c.dom.Document;
     67import org.w3c.dom.Element;
    5268import org.w3c.dom.Node;
    5369import org.w3c.dom.NodeList;
     
    6985        private static final long serialVersionUID = 1L;
    7086       
     87        // workspaceprofiles
    7188        public static String USER = "user";
    7289        public static String SERVER = "server";
     90        // administration query identification
     91        public static String ADMIN = "admin";
     92        public static String FILENAME = "filename";
    7393       
    7494        public static String PROFILENAME_BASE = "WorkspaceProfile_";
    7595        public static String PROFILENAME_SERVER = "WorkspaceProfileServer.xml";
    7696        public static String PROFILENAME_DEFAULT = PROFILENAME_BASE + "default.xml";
     97        public static String ADMINISTRATION_FILENAME = "Administration.xml";
     98       
     99        private String workspace_filename = "WorkspaceProfile.xml";
    77100        /**
    78101         * Properties to be filled by Struts with according request-parameters
     
    81104        private String data;
    82105        private String type;
     106        private String qid;
    83107        //private String format;
    84108        //private String userMsg;
    85109        private String base_path;
    86110       
     111       
     112        private static WorkspaceAction singleton;
     113        private String workspacefile;
     114        //private String workspaceindex_path;
     115        //private static Integer querycounter;
     116        private static final Integer start_query = 1;
     117       
     118        private static Document workspace_doc;
     119       
    87120        //private HttpServletRequest request;
     121       
     122        public String Workspace_filename(){
     123                return workspace_filename;
     124        }
     125
     126        public void setWorkspace_filename(String workspace_filename) {
     127                this.workspace_filename = workspace_filename;
     128        }
    88129       
    89130        public String getData(){
     
    102143                this.type = type;
    103144        }
    104         /*
    105         public String getFormat() {
    106                 return format;
    107         }
    108 
    109         public void setFormat(String format) {
    110                 this.format = format;
    111         }
    112        
    113         public String getActionkey() {
    114                 return actionkey;
    115         }
    116 
    117         public void setActionkey(String actionKey) {
    118                 actionkey = actionKey;
    119         }
    120 */
     145       
     146        public String getQid() {
     147                return qid;
     148        }
     149
     150        public void setQid(String qid) {
     151                this.qid = qid;
     152        }
     153
     154       
     155       
     156        public WorkspaceAction () {             
     157                workspacefile = Admin.getConfig().getProperty("workspace.path") + Admin.getConfig().getProperty("workspace.file");
     158                //querycounter =
     159                if (singleton == null){
     160                        initDocument();
     161                        singleton = this;
     162                }
     163
     164               
     165        }
     166       
     167        public static WorkspaceAction getWorkspaceAction() {
     168                if (singleton == null) {
     169                        singleton = new WorkspaceAction();
     170                }
     171                return singleton;
     172        }
     173
     174        protected void finalize() throws Throwable {       
     175            try {               
     176                //updateQuerycounter();
     177                //saveDocument();
     178            } catch(Exception e) {
     179            }       
     180            finally {           
     181                super.finalize();
     182                //more code can be written here as per need of application             
     183            }
     184        }
    121185        /**
    122186         * primitive identification of the target-proxy
     
    209273                        }
    210274                        */
     275                } else if (type.toLowerCase().equals(ADMIN)){
     276                        profilename =  ADMINISTRATION_FILENAME;
     277                } else if (type.toLowerCase().equals(FILENAME)){
     278                        profilename = this.workspace_filename;
    211279                }
    212280               
     
    239307       
    240308        public String getPath() {
    241                 String targetPath = getBasePath() + getWorkspaceProfile();         
     309                String targetPath = getBasePath() + this.workspace_filename;//getWorkspaceProfile();       
    242310        Admin.notifyUser("WorkspaceAction TARGETPATH: " + targetPath);             
    243311        return targetPath;
     
    261329        }
    262330       
    263        
     331        /*
    264332        @Override
    265333        public void prepare() throws Exception {               
     
    293361        }
    294362
    295         public String save() throws IOException {
     363        public void administrateQid() throws IOException, SAXException, ParserConfigurationException, TransformerException{
     364                WorkspaceAction wa = new WorkspaceAction();
     365                wa.setType("Admin");
     366               
     367                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     368        DocumentBuilder builder;
     369
     370                builder = factory.newDocumentBuilder();
     371                Document  document = builder.parse(wa.getSourceStream());
     372                // find user-filename-id or create one
     373                //add qid
     374                //NodeList list = document.getElementsByTagName("e");
     375                //Admin.notifyUser("list:" + list.getLength());
     376
     377                // save the changes
     378                Transformer transformer;
     379                transformer = TransformerFactory.newInstance().newTransformer();
     380                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     381                StreamResult result = new StreamResult(new StringWriter());
     382                DOMSource source = new DOMSource(document);
     383                transformer.transform(source, result);
     384                String xmlString = result.getWriter().toString();
     385                InputStream is_xml = new ByteArrayInputStream( xmlString.getBytes( ) );
     386                Admin.writeToFile(wa.getPath(), is_xml);
     387                //wa.save();
     388        }
     389       
     390        public String save() throws IOException, SAXException, ParserConfigurationException, TransformerException {
    296391               
    297392        String jsonData = getData();
    298393             
    299394        Admin.notifyUser("JSON data:"+jsonData);
     395        if ((!this.getType().equals(ADMIN)) && this.getQid() != null) {
     396                        administrateQid();
     397                }
    300398       
    301399        XMLSerializer serializer = new XMLSerializer();
    302400                JSON json = JSONSerializer.toJSON( jsonData );
    303                 serializer.setRootName("WorkspaceProfile");
     401                if (this.getType().equals(ADMIN)){
     402                        serializer.setRootName("Admin");
     403                } else {
     404                        serializer.setRootName("WorkspaceProfile");     
     405                }
    304406                serializer.setElementName("item");
    305407        serializer.setTypeHintsEnabled(false);
     
    317419                return SUCCESS;
    318420        }
    319 
     421*/
     422        public void changeQueryId(Document doc, String from_id, String to_id) throws XPathExpressionException{
     423                InputStream is = null;
     424                XPathFactory factory = XPathFactory.newInstance();
     425            XPath xpath = factory.newXPath();
     426            XPathExpression expr;
     427            String xpath_expr = "";
     428                xpath_expr = "//WorkspaceProfile/Querysets/item/Queries/item/id[.='" + from_id + "']";
     429                expr = xpath.compile(xpath_expr);
     430                Object result = null;
     431                result = expr.evaluate(doc, XPathConstants.NODESET);
     432               
     433            NodeList nodelist = (NodeList) result;
     434            nodelist.item(0).setTextContent(to_id);
     435        }
     436        public String createNewQid(){
     437                String id = workspace_doc.getElementsByTagName("maxqid").item(0).getTextContent();
     438                Integer i = Integer.parseInt(id) + 1;
     439                id = i.toString();
     440                workspace_doc.getElementsByTagName("maxqid").item(0).setTextContent(id);
     441                return id.toString();
     442        }
     443        public InputStream createStream(String value) throws TransformerException, TransformerFactoryConfigurationError, ParserConfigurationException, UnsupportedEncodingException{
     444        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
     445        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
     446        Document doc = docBuilder.newDocument();
     447
     448        ////////////////////////
     449        //Creating the XML tree
     450        Element root = doc.createElement("root");
     451        root.setTextContent(value);
     452        doc.appendChild(root);
     453        //set up a transformer
     454        TransformerFactory transfac = TransformerFactory.newInstance();
     455        Transformer trans = transfac.newTransformer();
     456        //trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     457        //trans.setOutputProperty(OutputKeys.INDENT, "yes");
     458
     459        //create string from xml tree
     460        //StringWriter sw = new StringWriter();
     461        //StreamResult result = new StreamResult(sw);
     462        //DOMSource source = new DOMSource(doc);
     463        //trans.transform(source, result);
     464       
     465
     466        DOMSource source = new DOMSource(doc);   
     467        StringWriter xmlAsWriter = new StringWriter();   
     468        StreamResult result = new StreamResult(xmlAsWriter);     
     469        TransformerFactory.newInstance().newTransformer().transform(source, result);   
     470         
     471        // write changes   
     472        ByteArrayInputStream is = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); 
     473           
     474
     475       return is;
     476
     477
     478        }
     479        public String save() throws ParserConfigurationException, SAXException, IOException, DOMException, XPathExpressionException, TransformerException, TransformerFactoryConfigurationError{
     480               
     481                // user data
     482                String jsonData = getData();
     483        XMLSerializer serializer = new XMLSerializer();
     484                JSON json = JSONSerializer.toJSON( jsonData );
     485                serializer.setRootName("WorkspaceProfile");     
     486                serializer.setElementName("item");
     487        serializer.setTypeHintsEnabled(false);
     488        String xml = serializer.write( json );
     489        //Admin.notifyUser("XML:" + xml);
     490        InputStream is_xml = new ByteArrayInputStream( xml.getBytes( ) );
     491        // add to document
     492        //Admin.writeToFile(getPath(), is_xml);
     493        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     494        DocumentBuilder builder = factory.newDocumentBuilder();
     495        Document d = builder.parse( is_xml );
     496        // set user
     497        //((Element)d.getFirstChild()).setAttribute("user", getServletRequest().getRemoteUser());
     498        NodeList wsnodelist = (NodeList) getWorkspace();
     499        // remove
     500        //childeNode
     501        if (wsnodelist.getLength() > 0){
     502                ((Node)wsnodelist.item(0)).getParentNode().removeChild(wsnodelist.item(0));
     503        }
     504        String qidstring = "";
     505        if (qid.equals("0")) {
     506            qidstring = createNewQid();
     507            changeQueryId(d,qid,qidstring);
     508        }
     509       
     510        Node node = d.getFirstChild();
     511        Node node2 = workspace_doc.adoptNode(node.cloneNode(true));
     512        ((Element)node2).setAttribute("user", getUserName());
     513        workspace_doc.getElementsByTagName("WorkspaceProfiles").item(0).appendChild(node2);
     514
     515      //TODO
     516        saveDocument();
     517        // return new qid
     518        //String src = "<body>" + qidstring + "</body>";
     519        //javax.xml.transform.stream.StreamSource s = new StreamSource(src);
     520        //InputStream in = s.getInputStream();
     521                this.setResultStream(createStream(qidstring));//(InputStream)(new ByteArrayInputStream(qidstring.getBytes())));
     522               
     523               
     524                return SUCCESS;
     525               
     526        }
     527        public InputStream DocumentToStream(Node node) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{
     528               
     529                InputStream is = null;
     530                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     531                Source xmlSource;
     532               
     533                if (node == null) {
     534                        xmlSource = new DOMSource(workspace_doc);
     535                } else {
     536                        xmlSource = new DOMSource(node);
     537                }
     538                Result outputTarget = new StreamResult(outputStream);
     539                TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
     540                is = new ByteArrayInputStream(outputStream.toByteArray());
     541                return is;
     542        }
     543
     544        public String DocumentToXMLString(){
     545                Transformer transformer;
     546                String xmlString = "";
     547                try {
     548                                transformer = TransformerFactory.newInstance().newTransformer();
     549                                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     550
     551                                //initialize StreamResult with File object to save to file
     552                                StreamResult result = new StreamResult(new StringWriter());
     553                                DOMSource source = new DOMSource(workspace_doc);
     554                                try {
     555                                        transformer.transform(source, result);
     556                                } catch (TransformerException e1) {
     557                                        // TODO Auto-generated catch block
     558                                        e1.printStackTrace();
     559                                }
     560
     561                                xmlString = result.getWriter().toString();
     562                        } catch (TransformerConfigurationException e) {
     563                                // TODO Auto-generated catch block
     564                                e.printStackTrace();
     565                        } catch (TransformerFactoryConfigurationError e) {
     566                                // TODO Auto-generated catch block
     567                                e.printStackTrace();
     568                        }
     569                       
     570                return xmlString;
     571        }
     572       
     573        public void addWorkspaceToDocument(){
     574                //{'WorkspaceProfile':{'CustomTermsets':'null',
     575                //                     'Termsets':'null',
     576                //                     'Repositories':'null',
     577                //                     'Querysets':'null','created':'null','lastchanged':'null','profilename':'null'}};
     578                Element we = workspace_doc.createElement("WorkspaceProfile");
     579                we.setAttribute("user", getType().toLowerCase());
     580                workspace_doc.getFirstChild().appendChild(we);
     581               
     582                Element e = workspace_doc.createElement("CustomTermsets");
     583                e.setNodeValue("null");
     584                we.appendChild(e);
     585               
     586                e = workspace_doc.createElement("Termsets");
     587                e.setNodeValue("null");
     588                we.appendChild(e);
     589               
     590                e = workspace_doc.createElement("Repositories");
     591                e.setNodeValue("null");
     592                we.appendChild(e);
     593               
     594                e = workspace_doc.createElement("Querysets");
     595                e.setNodeValue("null");
     596                we.appendChild(e);
     597               
     598                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     599                String strdate = dateFormat.format(new Date()).toString();
     600                e = workspace_doc.createElement("created");
     601                e.setNodeValue(strdate);
     602                we.appendChild(e);
     603               
     604                e = workspace_doc.createElement("lastchanged");
     605                e.setNodeValue(strdate);
     606                we.appendChild(e);
     607               
     608                e = workspace_doc.createElement("profilename");
     609                e.setNodeValue(getType().toLowerCase());
     610                we.appendChild(e);
     611        }
     612       
     613        public String getUserName(){
     614                String userstring;
     615                if (getType().toLowerCase().equals(SERVER)){
     616                        userstring = SERVER;
     617                }else {
     618                        userstring = getServletRequest().getRemoteUser();
     619                        if (userstring == null){
     620                                userstring = "default";
     621                        }
     622                }
     623                return userstring;
     624        }
     625        public String getWorkspaceXPathExpression(){
     626                String xpath_expr = "";
     627
     628                xpath_expr = "//Profiles/WorkspaceProfiles/WorkspaceProfile[@user='" + getUserName() + "']";
     629
     630                return xpath_expr;
     631        }
     632       
     633        public Object getWorkspace() throws XPathExpressionException{
     634                InputStream is = null;
     635                XPathFactory factory = XPathFactory.newInstance();
     636            XPath xpath = factory.newXPath();
     637            XPathExpression expr;
     638                        expr = xpath.compile(getWorkspaceXPathExpression());
     639                        //expression is evaluated with respect to a certain context node which is doc.
     640                Object result = expr.evaluate(workspace_doc, XPathConstants.NODESET);
     641             return result;
     642        }
     643       
     644           
     645        @Override
     646        public void prepare() throws Exception {               
     647               
     648                NodeList list = (NodeList) getWorkspace();//result;
     649                if (list.getLength() < 1) {
     650                        addWorkspaceToDocument();
     651                        list = (NodeList) getWorkspace();
     652                }
     653                if (list.getLength() > 1){
     654                        // error
     655                }
     656                // nodelistto stream
     657                InputStream is = this.DocumentToStream(list.item(0));
     658                this.setSourceStream(is);     
     659               
     660                if (getFormat().equals("xml")) {                       
     661                        setResultStream(is);   
     662                }else { //JSON
     663                        // set srcFile (for MDTransformer to pass to xsl-scripts)
     664                        MDTransformer transformer = new MDTransformer();
     665                        transformer.setSrcFile(getURL());
     666                        transformer.setParams(MDTransformer.createParamsMap(getFullFormat()));
     667                        setResultStream(transformer.transformXML(is));//, getFullFormat()));
     668                        //setSessionData(getResultStream());
     669                }
     670                       
     671                Admin.notifyUser(getProxyKey() + " success:" + (getResultStream()!=null));
     672        }
     673
     674public void initDocument() {
     675               
     676                Integer counter = start_query;
     677                boolean init=false;
     678                String fname = getPath();//workspacefile;
     679                File f = new File (fname);
     680               
     681                if (!f.exists()) {
     682                                // create new  counter document
     683                                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     684                        DocumentBuilder docBuilder;
     685                                try {
     686                                        docBuilder = docFactory.newDocumentBuilder();
     687                                        workspace_doc = docBuilder.newDocument();
     688                                        // append root tag <index >
     689                                        Element root = (Element) workspace_doc.createElement("Profiles");
     690                                        //root.setAttribute("idcounter", "1");
     691                                        workspace_doc.appendChild(root);
     692                                        Element e = workspace_doc.createElement("Querycounter");
     693                                        root.appendChild(e);
     694                                        e = workspace_doc.createElement("maxqid");
     695                                        e.setNodeValue(counter.toString());//setAttribute("id", c.toString());
     696                                        //updateQuerycounter();
     697                                        this.saveDocument();
     698                                       
     699                                        //Admin.notifyUser("new document");
     700                                } catch (ParserConfigurationException e) {
     701                                        // TODO Auto-generated catch block
     702                                        e.printStackTrace();
     703                                }
     704            }
     705                else {
     706                        try {
     707                               
     708                        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     709                        DocumentBuilder docBuilder;
     710                                try {
     711                                        docBuilder = docFactory.newDocumentBuilder();               
     712                                        try {
     713                                                        workspace_doc = docBuilder.parse(fname);
     714                                        } catch (SAXException e) {
     715                                                        // TODO Auto-generated catch block
     716                                                       
     717                                                        e.printStackTrace();
     718                                        }
     719                                } catch (ParserConfigurationException e) {
     720                                                // TODO Auto-generated catch block
     721                                                e.printStackTrace();
     722                                }
     723                               
     724                         //read counter
     725                         //counter = new Integer(workspace_doc.getFirstChild().getFirstChild().getFirstChild().getNodeValue());
     726                         init = true;
     727                    }  catch (IOException ex){
     728                        //Admin.notifyUser("initCacheCounter:" + ex.toString());
     729                        ex.printStackTrace();
     730                    }
     731                }
     732               
     733            //return counter;
     734        }
     735/*
     736        public void updateQuerycounter () {
     737                workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(querycounter.toString());
     738            saveDocument();
     739        }
     740        */
     741        public void saveDocument() {
     742        //public void writeQuerycounter (Integer i) {           
     743               
     744                // first update <index idcounter>
     745                //workspace_doc.getFirstChild().getAttributes().getNamedItem("idcounter").setNodeValue(i.toString());
     746               
     747                //Admin.notifyUser("writeCacheCounter:" + i.toString());
     748                // write xml
     749                Transformer transformer;
     750                try {
     751                        transformer = TransformerFactory.newInstance().newTransformer();
     752                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     753
     754                        //initialize StreamResult with File object to save to file
     755                        StreamResult result = new StreamResult(new StringWriter());
     756                        DOMSource source = new DOMSource(workspace_doc);
     757                        try {
     758                                transformer.transform(source, result);
     759                        } catch (TransformerException e1) {
     760                                // TODO Auto-generated catch block
     761                                e1.printStackTrace();
     762                        }
     763
     764                        String xmlString = result.getWriter().toString();
     765
     766                        File f = new File (getPath());//workspacefile);
     767                        FileWriter fw;
     768                        try {
     769                                fw = new FileWriter(f);
     770                                try {
     771                                        fw.write(xmlString);
     772                                        fw.close();
     773                                } catch (IOException e) {
     774                                        // TODO Auto-generated catch block
     775                                        e.printStackTrace();
     776                                }       
     777                        } catch (IOException e) {
     778                                // TODO Auto-generated catch block
     779                                e.printStackTrace();
     780                        }
     781                } catch (TransformerConfigurationException e2) {
     782                        // TODO Auto-generated catch block
     783                        e2.printStackTrace();
     784                } catch (TransformerFactoryConfigurationError e2) {
     785                        // TODO Auto-generated catch block
     786                        e2.printStackTrace();
     787                }
     788        }
     789       
    320790
    321791}
  • MDService2/trunk/MDService2/src/mdservice.properties

    r1236 r1273  
    1616//cache.path = /srv/tomcat6/webapps/MDService2_cache/
    1717//workspaceprofile.path = /srv/tomcat6/webapps/MDService2_profiles/
    18 cache.path = C:/apps/apache-tomcat/webapps/MDService2_cache/
    19 workspaceprofile.path = C:/apps/apache-tomcat/webapps/MDService2_profiles/
    20 //cache.path = C:/apache-tomcat-6.0.26/webapps/MDService2_cache/
    21 //workspaceprofile.path = C:/apache-tomcat-6.0.26/webapps/MDService2_profiles/
     18//cache.path = C:/apps/apache-tomcat/webapps/MDService2_cache/
     19//workspaceprofile.path = C:/apps/apache-tomcat/webapps/MDService2_profiles/
     20cache.path = C:/apache-tomcat-6.0.26/webapps/MDService2_cache/
     21workspaceprofile.path = C:/apache-tomcat-6.0.26/webapps/MDService2_profiles/
    2222
    2323
    2424cacheindex.file = cache_index.xml
    2525xml.comp =
     26xsl.profile2VC = profile2VC.xsl
    2627xsl.XCQL2XPATH = XCQL2Xpath.xsl
    2728xsl.recordset2htmltable = mdset2view.xsl
  • MDService2/trunk/MDService2/src/struts.xml

    r1187 r1273  
    187187                </action>
    188188               
    189                 <action name="workspaceprofilesave/*" class="eu.clarin.cmdi.mdservice.action.WorkspaceAction" method="save">           
     189                <action name="workspaceprofilesave/*/*" class="eu.clarin.cmdi.mdservice.action.WorkspaceAction" method="save">         
    190190                           <param name="format">JSON</param>
    191191                           <param name="type">{1}</param>
     192                           <param name="qid">{2}</param>
    192193                           <!-- <param name="data">{1}</param> 
    193194                           <param name="actionkey"></param>     
     
    201202                           
    202203                           
     204                </action>
     205               
     206                <action name="virtualcollection/*/*" class="eu.clarin.cmdi.mdservice.action.VirtualCollectionProxyAction" method="publish">             
     207                           <param name="type">{1}</param>
     208                           <param name="qid">{2}</param>
     209                           <result type="stream">                         
     210                                <param name="contentType">text/xml</param>
     211                                <param name="inputName">resultStream</param>                   
     212                            </result>   
    203213                </action>
    204214               
Note: See TracChangeset for help on using the changeset viewer.