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

query indices
VCR first version

Location:
MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action
Files:
1 added
2 edited

Legend:

Unmodified
Added
Removed
  • 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}
Note: See TracChangeset for help on using the changeset viewer.