From 6e7c782f26ac3958dddd0024e65a106dd314ea91 Mon Sep 17 00:00:00 2001
From: "Eduardo L. Buratti" <elb09@c3sl.ufpr.br>
Date: Thu, 21 Feb 2013 00:12:24 -0300
Subject: [PATCH] webservice: Add inventory database insert query

Signed-off-by: Eduardo L. Buratti <elb09@c3sl.ufpr.br>
---
 webservice/Main.jws | 177 ++++++++++++++++++++++++++++++++++----------
 1 file changed, 139 insertions(+), 38 deletions(-)

diff --git a/webservice/Main.jws b/webservice/Main.jws
index a44e7d7..e000a45 100644
--- a/webservice/Main.jws
+++ b/webservice/Main.jws
@@ -20,28 +20,32 @@
  * USA.
  */
 
-/* General libs */
 import java.io.*;
 import java.util.*;
-import java.text.*;
+import java.util.regex.*;
 
-/* File libs */
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.StringWriter;
+import java.sql.Timestamp;
+import java.sql.SQLException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.Types;
 
-/* DOM */
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import org.w3c.dom.*;
+import javax.naming.InitialContext;
+import javax.sql.DataSource;
+import javax.xml.bind.*;
+import javax.xml.bind.util.ValidationEventCollector;
+import javax.xml.bind.helpers.DefaultValidationEventHandler;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
 
-/* Regular Expressions */
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
+import br.ufpr.c3sl.datasid.*;
 
 public class Main {
 
+    private static final String SA_INVENTORY = "sidtb00_sa_inventory";
+
+    private static final File XML_SCHEMA = new File("/home/datasid/collected-data.xsd");
+
     private static final String AGENT_VERSION = "1.0.0";
     private static final String AGENT_UPDATE_LINK = "http://localhost:8280/webservice/datasid-1.0.0-update.run";
 
@@ -104,7 +108,7 @@ public class Main {
      */
     private static String getTimestamp() {
         // gets the current time
-        Date date = new Date();
+        java.util.Date date = new java.util.Date();
         long milisecs = date.getTime();
 
         // generates timestamp string
@@ -112,27 +116,6 @@ public class Main {
         return timestamp.toString();
     }
 
-
-    /**
-     * Parse a XML and returns the root DOM Element
-     *
-     * @author                 Eduardo Luis Buratti
-     * @param     xml          The xml string to be parsed
-     * @return                 Element
-     */
-    private static Element parseXML(String xml) throws Exception {
-        // transform the xml string into a InputStream
-        InputStream is = new ByteArrayInputStream(xml.getBytes());
-
-        // creates a builder
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        DocumentBuilder builder = dbf.newDocumentBuilder();
-
-        Document dom = builder.parse(is);
-
-        return dom.getDocumentElement();
-    }
-
     /**
      * Receive an XML string which has the inventory data to be parsed and
      * inserted into database. Return "Success" string if insertion operation
@@ -144,11 +127,41 @@ public class Main {
      */
     public static String setInventory(String xmlData) {
         try {
-            Element root = parseXML(xmlData);
-            System.out.println("RECEIVED: " + root.getTagName());
+            InitialContext cxt = new InitialContext();
+            DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/datasid");
+            if (ds == null)
+                throw new Exception("Data source not found!");
+
+            Connection con = ds.getConnection();
+            if (con == null)
+                throw new Exception("Failed to get a database connection!");
+
+            SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
+            Schema schema = factory.newSchema(XML_SCHEMA);
+
+            JAXBContext context = JAXBContext.newInstance("br.ufpr.c3sl.datasid");
+            Unmarshaller unmarshaller = context.createUnmarshaller();
+            unmarshaller.setSchema(schema);
+
+            // Strip spaces in the beginning of the xml
+            xmlData = xmlData.replaceAll("^\\s+", "");
+
+            // transform the xml string into a InputStream
+            InputStream is = new ByteArrayInputStream(xmlData.getBytes());
+
+            // Decode the XML into a Java Object
+            JAXBElement<CollectedData> element = (JAXBElement<CollectedData>) unmarshaller.unmarshal(is);
+            CollectedData collected = element.getValue();
+
+            PreparedStatement st = createInventoryStatement(con, collected);
+            st.executeUpdate();
+
+            con.close();
+
             return "Success";
         } catch (Exception e) {
             log(ERROR, e.getMessage() + " " + xmlData);
+            e.printStackTrace();
             return "ERROR: " + e.getMessage();
         }
     }
@@ -175,4 +188,92 @@ public class Main {
         return AGENT_UPDATE_LINK;
     }
 
+
+    private static PreparedStatement createInventoryStatement(Connection con, CollectedData collectedData) throws SQLException {
+        final String query = "INSERT INTO " + SA_INVENTORY + " " +
+            "(sa_contact_date, sa_gesacid, sa_machine, sa_versao, " +
+            "sa_hd_model, sa_hd_size, sa_hd_used, " +
+            "sa_hd2_model, sa_hd2_size, sa_hd2_used, " +
+            "sa_extra_hds, sa_memory_size, sa_processor, " +
+            "sa_os_type, sa_os_distro, sa_kernel) VALUES " +
+            "(?, ?, ?, ?, " +
+            "?, ?, ?, " +
+            "?, ?, ?, " +
+            "?, ?, ?, " +
+            "?, ?, ?);";
+
+        PreparedStatement st = con.prepareStatement(query);
+
+        List<Interface> interfaces = collectedData.getInterfaces().getInterface();
+
+        Inventory inventory = collectedData.getInventory();
+        int diskCount = inventory.getDisks().getQuantity().intValue();
+        List<Disk> disks = inventory.getDisks().getDisk();
+
+        // sa_contact_date = current date
+        Calendar cal = Calendar.getInstance();
+        st.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
+
+        // sa_gesacid
+        st.setInt(2, collectedData.getGesacid().intValue());
+
+        // sa_machine
+        org.postgresql.util.PGobject macaddr = new org.postgresql.util.PGobject();
+        macaddr.setType("macaddr");
+        macaddr.setValue(interfaces.get(0).getMacAddress());
+        st.setObject(3, macaddr);
+
+        // sa_versao
+        st.setString(4, collectedData.getAgentVersion());
+
+        // sa_hd_model
+        st.setString(5, disks.get(0).getModel());
+
+        // sa_hd_size
+        st.setInt(6, disks.get(0).getSize().intValue());
+
+        // sa_hd_used
+        st.setInt(7, disks.get(0).getUsed().intValue());
+
+        if (diskCount > 1) {
+            // sa_hd2_model
+            st.setString(8, disks.get(1).getModel());
+
+            // sa_hd2_size
+            st.setInt(9, disks.get(1).getSize().intValue());
+
+            // sa_hd2_used
+            st.setInt(10, disks.get(1).getUsed().intValue());
+        }
+        else {
+            // sa_hd2_model
+            st.setNull(8, Types.VARCHAR);
+
+            // sa_hd2_size
+            st.setNull(9, Types.INTEGER);
+
+            // sa_hd2_used
+            st.setNull(10, Types.INTEGER);
+        }
+
+        // sa_extra_hds
+        st.setInt(11, (diskCount > 2) ? (diskCount - 2) : 0);
+
+        // sa_memory_size
+        st.setInt(12, inventory.getMemory().intValue());
+
+        // sa_processor
+        st.setString(13, inventory.getProcessor());
+
+        // sa_os_type
+        st.setString(14, inventory.getOs());
+
+        // sa_os_distro
+        st.setString(15, inventory.getDistro());
+
+        // sa_kernel
+        st.setString(16, inventory.getKernel());
+
+        return st;
+    }
 }
-- 
GitLab