在java中修改birt報表模板的數據源

 // 修改rptdesign內的數據源信息
 public void setDataSource(String rptdesignPath) {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = null;
  InputStream is = null;
  String datasource = null;
  Document doc = null;
  String EncodePsd = null;

  try {
   db = dbf.newDocumentBuilder();
   try {
    is = new FileInputStream(rptdesignPath);
    try {
     doc = db.parse(is);
     is.close();
    } catch (SAXException e) {
     toPrint("SAXException");
     return;
    } catch (IOException e) {
     toPrint("Can't read file [" + rptdesignPath + "]");
     return;
    }
   } catch (FileNotFoundException e) {
    toPrint("Can't found file [" + rptdesignPath + "]");
    return;
   }

  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   toPrint("ParserConfigurationException");
   return;
  }

  // 查找data-sources信息
  NodeList nodeList = doc.getElementsByTagName("data-sources");
  for (int i = 0; i < nodeList.getLength(); i++) {
   Element e = (Element) nodeList.item(i);
   NodeList properties = e.getChildNodes();
   if (properties != null) {
    // 得到oda-data-source部分信息
    Node property = properties.item(1);
    for (Node node = property.getFirstChild(); node != null; node = node
      .getNextSibling()) {
     // 得到driver、url、username、password四項的值,並重新設置
     if (node.getNodeName().equals("property")
       || node.getNodeName().equals("encrypted-property")) {
      String name = node.getAttributes().getNamedItem("name")
        .getNodeValue();
      if (name.equals("odaDriverClass")) {
       node.getFirstChild().setNodeValue(driver);
      } else if (name.equals("odaURL")) {
       node.getFirstChild().setNodeValue(url);
      } else if (name.equals("odaUser")) {
       node.getFirstChild().setNodeValue(username);
      } else if (name.equals("odaPassword")) {
       // 對密碼進行base64編碼
       EncodePsd = (new sun.misc.BASE64Encoder())
         .encode(password.getBytes());
       // System.out.println("********EncodePsd:
       // "+EncodePsd);
       node.getFirstChild().setNodeValue(EncodePsd);

      }
     }

    }
   }
  }
  // 寫入指定的文件中
  writeToXml(doc, rptdesignPath);
 }

 // write to xml
 public void writeToXml(Document doc, String rptdesign) {
  try {
   OutputStream fileoutputStream = new FileOutputStream(rptdesign);
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer = tFactory.newTransformer();
   DOMSource source = new DOMSource(doc);
   StreamResult result = new StreamResult(fileoutputStream);
   transformer.transform(source, result);
   fileoutputStream.close();

  } catch (Exception e) {
   toPrint("Can't write to file: " + rptdesign);
   return;

  }
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章