Lesson 4: Creating a Java class using 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 following methods for direct row handling:

  • GetUpload   You use this method for the handle_UploadData event. GetUpload writes uploaded comments to the XML file.

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

To create a Java class for download-only direct row handling

  1. Create a class called MobilinkOrders using Java.

    Type the following code in a text editor or development environment:

    //Mobilink imports
    import ianywhere.ml.script.*;
    import java.io.*;
    import java.sql.*;
    
    //XML parser
    import javax.xml.parsers.DocumentBuilder; 
    import javax.xml.parsers.DocumentBuilderFactory;  
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.xml.sax.SAXException;  
    
    //DOM Objects
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    //For writing XML objects
    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. Declare a class-level DBConnectionContext instance and Document instance. Document is a class that represents an XML document as an object.

    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.

    Type the following code in a text editor or development environment:

    public MobiLinkOrders( DBConnectionContext cc ) {
      _cc = cc;
    }
  4. Write the GetUpload() method.

    1. Write the method declaration.

      Type the following code in a text editor or development environment:

      // method for the handle_UploadData synchronization event
      public void GetUpload( UploadData ut ) throws SQLException, IOException {
    2. Get any uploaded insert from the Mobilink client.

      Type the following code in a text editor or development environment:

      //  get an UploadedTableData for OrderComments
        UploadedTableData orderCommentsTbl = 
          ut.getUploadedTableByName("OrderComments");
       
        // get inserts uploaded by the MobiLink client
        ResultSet insertResultSet = orderCommentsTbl.getInserts();
    3. Read in the existing XML file, order_comments.xml.

      Type the following code in a text editor or development environment:

          readDom("order_comments.xml");
    4. For each inserted row, add it to the XML file.

      Type the following code in a text editor or development environment:

          // Write out each insert in the XML file
          while( insertResultSet.next() ) {  
            buildXML(insertResultSet);
          }
    5. Write the XML file.

      Type the following code in a text editor or development environment:

      writeXML();
    6. Close the ResultSet.

      Type the following code in a text editor or development environment:

          // Close the result set of uploaded inserts
          insertResultSet.close(); 
  5. Write the buildXML method.

    Type the following code in a text editor or development environment:

      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. Write the writeXML method.

    Type the following code in a text editor or development environment:

      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. Write the readDOM method.

    Type the following code in a text editor or development environment:

      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. Save your Java code as MobiLinkOrders.java in your working directory c:\MLobjxml.

  9. Compile your class file.

    • Navigate to the directory containing your Java source files.
    • Compile MobiLinkOrders with references to the MobiLink server API library for Java.

      For Java, you need to reference mlscript.jar in the java subdirectory of your SQL Anywhere installation. You also need to make sure that you have the XML DOM library installed correctly. Run the following command to compile your Java class, replacing c:\Program Files\SQL Anywhere 11\ with your SQL Anywhere 11 directory:

      javac -classpath "c:\Program Files\SQL Anywhere 11\java\mlscript.jar" MobiLinkOrders.java
Further reading

For more information about synchronization logic, see Writing synchronization scripts in Java.

For more information about direct row handling, see Direct row handling.


Complete MobiLinkOrders code listing (Java)