Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 12.0.0 (中文) » MobiLink - 入门 » MobiLink 教程 » 教程:与 XML 同步

 

第 4 课:创建 Java 类进行 MobiLink 直接行处理

在本课中,您将使用直接行处理来处理客户端数据库的 OrderComments 表中的行。为直接行处理添加以下方法:

  • GetUpload   将此方法用于 handle_UploadData 事件。GetUpload 将上载的注释写入 XML 文件中。

以下过程介绍如何创建 Java 类,其中包括用于处理的方法。有关完整列表,请参见完整的 MobiLinkOrders Java 代码列表

 ♦  为仅下载直接行处理创建 Java 类
  1. 创建名为 MobiLinkOrders 的类。

    编写以下代码:



    import ianywhere.ml.script.*;
    import java.io.*;
    import java.sql.*;
    
    import javax.xml.parsers.DocumentBuilder; 
    import javax.xml.parsers.DocumentBuilderFactory;  
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.xml.sax.SAXException;  
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    // For write operation
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.dom.DOMSource;  
    import javax.xml.transform.stream.StreamResult; 
    
    public class MobiLinkOrders {
    
  2. 声明一个类级别 DBConnectionContext 实例和文档实例。文档是将 XML 文档作为对象表示的类。

    编写以下代码:

        // Class level DBConnectionContext
        DBConnectionContext _cc;
        Document _doc;

    MobiLink 服务器会将 DBConnectionContext 实例传递到类构造函数。DBConnectionContext 封装有关与 MobiLink 统一数据库的当前连接的信息。

  3. 创建类构造函数。

    类构造函数设置类级别 DBConnectionContext 实例。

    编写以下代码:

        public MobiLinkOrders( DBConnectionContext cc ) throws IOException, FileNotFoundException {
            // Declare a class-level DBConnectionContext
            _cc = cc;
        }
    
  4. 编写 GetUpload 方法。

    GetUpload 方法获得表示 OrderComments 表的 UploadedTableData 类实例。OrderComments 表包含由远程销售雇员进行的特殊注释。您将在第 6 课:建立 MobiLink 客户端数据库中创建该表。UploadedTableData getInserts 方法返回新订单注释的结果集。

    1. 编写方法声明。

      编写以下代码:

          // Method for the handle_UploadData synchronization event
          public void GetUpload( UploadData ut ) throws SQLException, IOException {
    2. 编写可从 MobiLink 客户端中检索任何上载的插入项的代码。

      编写以下代码:

              // Get an UploadedTableData for the remote table
              UploadedTableData remoteOrdersTable = ut.getUploadedTableByName("OrderComments");
      
              // Get inserts uploaded by the MobiLink client 
              // as a java.sql.ResultSet    
              ResultSet insertResultSet = remoteOrdersTable.getInserts();
    3. 编写可读取现有 XML 文件 order_comments.xml 的代码。

      编写以下代码:

              readDom("order_comments.xml");
    4. 编写可在 XML 文件中添加所有上载的插入项的代码。

      编写以下代码:

              // Write out each insert in the XML file
              while( insertResultSet.next() ) {  
                  buildXML(insertResultSet);
              }
    5. 编写可输出到 XML 文件的代码。

      编写以下代码:

              writeXML();
    6. 编写可关闭结果集的代码。

      编写以下代码:

              // Close the result set of uploaded inserts
              insertResultSet.close();
          }
  5. 编写 buildXML 方法。

    编写以下代码:



        private void buildXML( ResultSet rs ) throws SQLException {  
            int order_id = rs.getInt(1);
            int comment_id = rs.getInt(2);
            String order_comment = rs.getString(3);    
    
            // Create the comment object to be added to the XML file
            Element comment = _doc.createElement("comment");
            comment.setAttribute("id", Integer.toString(comment_id));
            comment.appendChild(_doc.createTextNode(order_comment));
    
            // Get the root element (orders)
            Element root = _doc.getDocumentElement();
        
            // Get each individual order
            NodeList rootChildren = root.getChildNodes();
            for(int i = 0; i < rootChildren.getLength(); i++) {
                // If the order exists, add the comment to the order      
                Node n = rootChildren.item(i);
                if(n.getNodeType() == Node.ELEMENT_NODE) {
                    Element e = (Element) n;
                    int idIntVal = Integer.parseInt(e.getAttribute("id"));
                    if(idIntVal == order_id) {
                        e.appendChild(comment);
                        // The comment has been added to the file, so exit the function
                        return;
                    }
                }
            }
    
            // If the order did not exist already, create it
            Element order = _doc.createElement("order");
            order.setAttribute("id", Integer.toString(order_id));
            // Add the comment to the new order
            order.appendChild(comment);    
            root.appendChild(order);
        }
  6. 编写 writeXML 方法。

    编写以下代码:



        private void writeXML() {
            try {
                // Use a Transformer for output
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
     
                // The XML source is _doc
                DOMSource source = new DOMSource(_doc);
                // Write the xml data to order_comments.xml
                StreamResult result = new StreamResult(new File("order_comments.xml"));
                transformer.transform(source, result);   
            } catch (TransformerConfigurationException tce) {
                // Error generated by the parser
                System.out.println ("\n** Transformer Factory error");
                System.out.println("   " + tce.getMessage() );
    
                // Use the contained exception, if any
                Throwable x = tce;
                if (tce.getException() != null) x = tce.getException();
                x.printStackTrace();
          
            } catch (TransformerException te) {
                // Error generated by the parser
                System.out.println ("\n** Transformation error");
                System.out.println("   " + te.getMessage() );
    
                // Use the contained exception, if any
                Throwable x = te;
                if (te.getException() != null) x = te.getException();
                x.printStackTrace();      
            }
        }
  7. 编写 readDOM 方法。

    编写以下代码:



        private void readDom(String filename) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
            try {
                // Parse the Document data into _doc
                DocumentBuilder builder = factory.newDocumentBuilder();
                _doc = builder.parse( new File(filename) );
     
            } catch (SAXException sxe) {
                // Error generated during parsing)
                Exception x = sxe;
                if (sxe.getException() != null) x = sxe.getException();
                x.printStackTrace();
    
            } catch (ParserConfigurationException pce) {
                // Parser with specified options can't be built
                pce.printStackTrace();
    
            } catch (IOException ioe) {
                // I/O error
                ioe.printStackTrace();
            }
        }
    }
  8. 将 Java 代码在工作目录 c:\MLobjxml 中保存为 MobiLinkOrders.java

    请参见完整的 MobiLinkOrders Java 代码列表,以此验证 MobiLinkOrders.java 中的代码。

  9. 编译您的类文件。

    1. 浏览到包含 Java 源文件的目录。

    2. 编译 MobiLinkOrders,它将引用面向 Java 的 MobiLink 服务器 API 库。

      需要引用位于 install-dir\Java 中的 mlscript.jar,并确保正确安装了 XML DOM 库。

      运行以下命令,将 C:\Program Files\SQL Anywhere 12\ 替换为 SQL Anywhere 12 目录:

      javac -classpath "C:\Program Files\SQL Anywhere 12\java\mlscript.jar" MobiLinkOrders.java
 进一步阅读

完整的 MobiLinkOrders Java 代码列表