Changeset 1273 for MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java
- Timestamp:
- 05/08/11 01:04:30 (13 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/WorkspaceAction.java
r911 r1273 8 8 import java.io.FileInputStream; 9 9 import java.io.FileNotFoundException; 10 import java.io.FileWriter; 10 11 import java.io.IOException; 11 12 import java.io.InputStream; 12 13 import java.io.InputStreamReader; 13 14 import java.io.Reader; 15 import java.io.UnsupportedEncodingException; 14 16 import java.io.Writer; 15 17 import java.net.MalformedURLException; 16 18 import java.net.URL; 19 import java.text.DateFormat; 20 import java.text.SimpleDateFormat; 21 import java.util.Date; 17 22 import java.util.Enumeration; 18 23 … … 27 32 import javax.xml.parsers.ParserConfigurationException; 28 33 import javax.xml.transform.OutputKeys; 34 import javax.xml.transform.Result; 35 import javax.xml.transform.Source; 29 36 import javax.xml.transform.Transformer; 30 37 import javax.xml.transform.TransformerConfigurationException; … … 34 41 import javax.xml.transform.dom.DOMSource; 35 42 import javax.xml.transform.stream.StreamResult; 43 import javax.xml.transform.stream.StreamSource; 44 import javax.xml.xpath.XPath; 45 import javax.xml.xpath.XPathConstants; 46 import javax.xml.xpath.XPathExpression; 47 import javax.xml.xpath.XPathExpressionException; 48 import javax.xml.xpath.XPathFactory; 36 49 37 50 … … 49 62 50 63 import org.apache.struts2.interceptor.ServletRequestAware; 64 import org.w3c.dom.Attr; 65 import org.w3c.dom.DOMException; 51 66 import org.w3c.dom.Document; 67 import org.w3c.dom.Element; 52 68 import org.w3c.dom.Node; 53 69 import org.w3c.dom.NodeList; … … 69 85 private static final long serialVersionUID = 1L; 70 86 87 // workspaceprofiles 71 88 public static String USER = "user"; 72 89 public static String SERVER = "server"; 90 // administration query identification 91 public static String ADMIN = "admin"; 92 public static String FILENAME = "filename"; 73 93 74 94 public static String PROFILENAME_BASE = "WorkspaceProfile_"; 75 95 public static String PROFILENAME_SERVER = "WorkspaceProfileServer.xml"; 76 96 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"; 77 100 /** 78 101 * Properties to be filled by Struts with according request-parameters … … 81 104 private String data; 82 105 private String type; 106 private String qid; 83 107 //private String format; 84 108 //private String userMsg; 85 109 private String base_path; 86 110 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 87 120 //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 } 88 129 89 130 public String getData(){ … … 102 143 this.type = type; 103 144 } 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 } 121 185 /** 122 186 * primitive identification of the target-proxy … … 209 273 } 210 274 */ 275 } else if (type.toLowerCase().equals(ADMIN)){ 276 profilename = ADMINISTRATION_FILENAME; 277 } else if (type.toLowerCase().equals(FILENAME)){ 278 profilename = this.workspace_filename; 211 279 } 212 280 … … 239 307 240 308 public String getPath() { 241 String targetPath = getBasePath() + getWorkspaceProfile();309 String targetPath = getBasePath() + this.workspace_filename;//getWorkspaceProfile(); 242 310 Admin.notifyUser("WorkspaceAction TARGETPATH: " + targetPath); 243 311 return targetPath; … … 261 329 } 262 330 263 331 /* 264 332 @Override 265 333 public void prepare() throws Exception { … … 293 361 } 294 362 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 { 296 391 297 392 String jsonData = getData(); 298 393 299 394 Admin.notifyUser("JSON data:"+jsonData); 395 if ((!this.getType().equals(ADMIN)) && this.getQid() != null) { 396 administrateQid(); 397 } 300 398 301 399 XMLSerializer serializer = new XMLSerializer(); 302 400 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 } 304 406 serializer.setElementName("item"); 305 407 serializer.setTypeHintsEnabled(false); … … 317 419 return SUCCESS; 318 420 } 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 674 public 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 320 790 321 791 }
Note: See TracChangeset
for help on using the changeset viewer.