Lesson 4: Create 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 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 Java code listing.

 To create a Java class for download-only direct row handling
  1. Create a class named MobiLinkOrders.

    Write the following code:



    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. 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 Lesson 6: Set up your MobiLink client database. 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:

              readDom("order_comments.xml");
    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( insertResultSet.next() ) {  
                  buildXML(insertResultSet);
              }
    5. Write code that outputs to the XML file.

      Write the following code:

              writeXML();
    6. Write code that closes the ResultSet.

      Write the following code:

              // Close the result set of uploaded inserts
              insertResultSet.close();
          }
  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));
            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.

    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();
                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.

    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();
                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.

    See Complete MobiLinkOrders Java code listing to verify the code in MobiLinkOrders.java.

  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 install-dir\Java and make sure that you have the XML DOM library installed correctly.

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

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

Complete MobiLinkOrders Java code listing