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

SAP Sybase SQL Anywhere 16.0 » MobiLink - Getting Started » MobiLink tutorials » Tutorial: Synchronizing with XML


Lesson 5: Creating a Java class for MobiLink direct row handling

In this lesson, you use direct row handling to process rows in the OrderComments table in your client database. You add the GetUpload methods for direct row handling for the handle_UploadData event. GetUpload writes uploaded comments to the XML file.


This lesson assumes you have completed all preceding lessons. See Lesson 1: Setting up an XML data source.

This lesson assumes that you have the roles and privileges listed in the Privileges section at the start of this tutorial: Tutorial: Synchronizing with XML.

Contexte et remarques

The following procedure shows you how to create a Java class including your methods for processing. For a complete listing, see MobiLinkOrders Java code listing.

  1. Create a class named MobiLinkOrders.

    Write the following code:

    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;  
    public class MobiLinkOrders {
  2. Declare a class-level DBConnectionContext instance and Document instance. Document is a class that represents an XML document as an object.

    Write the following code:

        // Class level DBConnectionContext
        DBConnectionContext _cc;
        Document _doc;

    The MobiLink server passes a DBConnectionContext instance to your class constructor. DBConnectionContext encapsulates information about the current connection with the MobiLink consolidated database.

  3. Create your class constructor.

    Your class constructor sets your class-level DBConnectionContext instance.

    Write the following code:

        public MobiLinkOrders( DBConnectionContext cc ) throws IOException, FileNotFoundException {
            // Declare a class-level DBConnectionContext
            _cc = cc;
  4. Write the GetUpload method.

    The GetUpload method obtains an UploadedTableData class instance representing the OrderComments table. The OrderComments table contains special comments made by remote sales employees. You create this table in a later lesson.

    The UploadedTableData getInserts method returns a result set for new order comments.

    1. Write the method declaration.

      Write the following code:

          //  Method for the handle_UploadData synchronization event
          public void GetUpload( UploadData ut ) throws SQLException, IOException {
    2. Write code that retrieves any uploaded inserts from the MobiLink client.

      Write the following code:

              // 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. Write code that reads the existing XML file, order_comments.xml.

      Write the following code:

              try {
    4. Write code that adds all uploaded inserts to the XML file.

      Write the following code:

         // Write out each insert in the XML file
         while( ) {  
    5. Write code that outputs to the XML file.

      Write the following code:

    6. Write code that closes the ResultSet.

      Write the following code:

              finally {
          // Close the result set of uploaded inserts
  5. Write the buildXML method.

    Write the following code:

         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));
            // 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) {
                        // The comment has been added to the file, so exit
                        // the function.
            // 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
  6. Write the writeXML method.

    Write the following code:

        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();
            } 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();
  7. Write the readDom method.

    Write the following code:

        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();
            } catch (ParserConfigurationException pce) {
                // Parser with specified options can't be built
            } catch (IOException ioe) {
                // I/O error
  8. Save your Java code as in your working directory, c:\MLobjxml.

    To verify the code in, see MobiLinkOrders Java code listing.

  9. Compile your class file.

    1. Navigate to the directory containing your Java source files.

    2. Compile MobiLinkOrders that refer to the MobiLink server API library for Java.

      You need to reference mlscript.jar located in %SQLANY16%\Java and make sure that you have the XML DOM library installed correctly.

      Run the following command, replacing C:\Program Files\SQL Anywhere 16\ with your SQL Anywhere 16 directory:

      javac -classpath "C:\Program Files\SQL Anywhere 16\java\mlscript.jar"


The Java class for MobiLink direct row handling is created.

 See also

MobiLinkOrders Java code listing