Ignore:
Timestamp:
04/01/12 20:33:03 (12 years ago)
Author:
gaba
Message:

workspace actions - new version

File:
1 edited

Legend:

Unmodified
Added
Removed
  • MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java

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