BUG-865: remove YangInstanceIdentifier.toInstance()
[controller.git] / opendaylight / md-sal / sal-dom-xsql / src / main / java / org / opendaylight / controller / md / sal / dom / xsql / XSQLAdapter.java
index 4571baf2e467d3c8e86079b89720d88a3584c874..91b34b85e51301b876165b8372c0d1903ea58537 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.md.sal.dom.xsql;
 
 import java.io.File;
@@ -20,16 +27,20 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
 import org.opendaylight.controller.md.sal.dom.xsql.jdbc.JDBCResultSet;
 import org.opendaylight.controller.md.sal.dom.xsql.jdbc.JDBCServer;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-
+/**
+ * @author Sharon Aicler(saichler@gmail.com)
+ **/
 public class XSQLAdapter extends Thread implements SchemaContextListener {
 
     private static final int SLEEP = 10000;
     private static XSQLAdapter a = new XSQLAdapter();
     private static PrintStream l = null;
+    private static String tmpDir = null;
+    private static File xqlLog = null;
     public boolean stopped = false;
     private List<String> elementHosts = new ArrayList<String>();
     private String username;
@@ -49,6 +60,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
     private String pinningFile;
     private ServerSocket serverSocket = null;
     private DOMDataBroker domDataBroker = null;
+    private static final String REFERENCE_FIELD_NAME = "reference";
 
     private XSQLAdapter() {
         XSQLAdapter.log("Starting Adapter");
@@ -63,10 +75,28 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
 
     }
 
+    public void loadBluePrint(){
+        try{
+            InputStream in = this.getClass().getClassLoader().getResourceAsStream("BluePrintCache.dat");
+            if(in!=null){
+                this.bluePrint =  XSQLBluePrint.load(in);
+            }
+            in.close();
+        }catch(Exception err){
+            err.printStackTrace();
+        }
+    }
+
     public static XSQLAdapter getInstance() {
         return a;
     }
 
+    public static File getXQLLogfile() {
+        tmpDir = System.getProperty("java.io.tmpdir");
+        xqlLog = new File(tmpDir + "/xql.log");
+        return xqlLog;
+    }
+
     public static void main(String args[]) {
         XSQLAdapter adapter = new XSQLAdapter();
         adapter.start();
@@ -78,7 +108,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                 synchronized (XSQLAdapter.class) {
                     if (l == null) {
                         l = new PrintStream(
-                            new FileOutputStream("/tmp/xql.log"));
+                                new FileOutputStream(getXQLLogfile()));
                     }
                 }
             }
@@ -96,7 +126,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                 synchronized (XSQLAdapter.class) {
                     if (l == null) {
                         l = new PrintStream(
-                            new FileOutputStream("/tmp/xql.log"));
+                                new FileOutputStream(getXQLLogfile()));
                     }
                 }
             }
@@ -126,50 +156,50 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         return this.bluePrint;
     }
 
-    public List<Object> collectModuleRoots(XSQLBluePrintNode table) {
+    public List<Object> collectModuleRoots(XSQLBluePrintNode table,LogicalDatastoreType type) {
         if (table.getParent().isModule()) {
             try {
                 List<Object> result = new LinkedList<Object>();
-                InstanceIdentifier instanceIdentifier =
-                    InstanceIdentifier.builder()
-                        .node(XSQLODLUtils.getPath(table.getODLNode()).get(0))
-                        .toInstance();
-                DOMDataReadTransaction t = this.domDataBroker.newReadOnlyTransaction();
-                Object node =
-                    t.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier)
-                        .get();
-                node = XSQLODLUtils.get(node, "reference");
+                YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier
+                        .builder()
+                        .node(XSQLODLUtils.getPath(table.getFirstFromSchemaNodes()).get(0))
+                        .build();
+                DOMDataReadTransaction t = this.domDataBroker
+                        .newReadOnlyTransaction();
+                Object node = t.read(type,
+                        instanceIdentifier).get();
+
+                node = XSQLODLUtils.get(node, REFERENCE_FIELD_NAME);
                 if (node == null) {
                     return result;
                 }
-
-                //XSQLAdapter.log(""+node);
-                Map<?, ?> children = XSQLODLUtils.getChildren(node);
-                for (Object c : children.values()) {
-                    Map<?, ?> sons = XSQLODLUtils.getChildren(c);
-                    for (Object child : sons.values()) {
-                        result.add(child);
-                    }
-                }
-
+                result.add(node);
                 return result;
             } catch (Exception err) {
                 XSQLAdapter.log(err);
             }
         } else {
-            return collectModuleRoots(table.getParent());
+            return collectModuleRoots(table.getParent(),type);
         }
         return null;
     }
 
     public void execute(JDBCResultSet rs) {
+        if(this.domDataBroker==null){
+            rs.setFinished(true);
+            return;
+        }
         List<XSQLBluePrintNode> tables = rs.getTables();
-        List<Object> roots = collectModuleRoots(tables.get(0));
+        List<Object> roots = collectModuleRoots(tables.get(0),LogicalDatastoreType.OPERATIONAL);
+        roots.addAll(collectModuleRoots(tables.get(0),LogicalDatastoreType.CONFIGURATION));
+        if(roots.isEmpty()){
+            rs.setFinished(true);
+        }
         XSQLBluePrintNode main = rs.getMainTable();
         List<NETask> tasks = new LinkedList<XSQLAdapter.NETask>();
 
         for (Object entry : roots) {
-            NETask task = new NETask(rs, entry, main,bluePrint);
+            NETask task = new NETask(rs, entry, main, bluePrint);
             rs.numberOfTasks++;
             tasks.add(task);
         }
@@ -200,8 +230,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
 
     }
 
-    protected void processCommand(StringBuffer inputString, PrintStream sout,
-        TelnetConnection tc) {
+    public void processCommand(StringBuffer inputString, PrintStream sout) {
         if (inputString.toString().trim().equals("r")) {
             sout.println(lastInputString);
             inputString = lastInputString;
@@ -211,12 +240,13 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         if (input.startsWith("setExcel")) {
             String substr = input.substring("setExcel".length()).trim();
             if (!substr.equals("")) {
-                //excelPath01 = substr;
+                // excelPath01 = substr;
             }
-            //sout.println("Excel Path="+excelPath01);
+            // sout.println("Excel Path="+excelPath01);
         } else if (input.startsWith("list vrel")) {
             String substr = input.substring("list vrel".length()).trim();
-            XSQLBluePrintNode node = bluePrint.getBluePrintNodeByTableName(substr);
+            XSQLBluePrintNode node = bluePrint
+                    .getBluePrintNodeByTableName(substr);
             if (node == null) {
                 sout.println("Unknown Interface " + substr);
                 return;
@@ -232,7 +262,8 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
             }
         } else if (input.startsWith("list vfields")) {
             String substr = input.substring("list vfields".length()).trim();
-            XSQLBluePrintNode node = bluePrint.getBluePrintNodeByTableName(substr);
+            XSQLBluePrintNode node = bluePrint
+                    .getBluePrintNodeByTableName(substr);
             if (node == null) {
                 sout.println("Unknown Interface " + substr);
                 return;
@@ -251,50 +282,33 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
             jdbcServer.connectToClient(addr);
             sout.println("Connected To " + addr);
         } else if (input.startsWith("fetch")) {
-            //fetchSize = Integer.parseInt(input.substring(6).trim());
+            // fetchSize = Integer.parseInt(input.substring(6).trim());
         } else if (input.startsWith("list vtables")) {
 
-            String iNames[] =
-                bluePrint.getAllTableNames().toArray(new String[0]);
+            String iNames[] = bluePrint.getAllTableNames().toArray(
+                    new String[0]);
             Arrays.sort(iNames);
             sout.println();
             for (int i = 0; i < iNames.length; i++) {
                 sout.println(iNames[i]);
             }
-        } else if (input.startsWith("cd sid")) {
-            String substr = input.substring("cd sid".length()).trim();
-            for (NEEntry e : elements.values()) {
-                if (((Module) e.ne).getName().equals(substr)) {
-                    tc.currentModule = (Module) e.ne;
-                }
-            }
-        } else if (input.equals("list sid")) {
-            String arr[] = new String[elements.size()];
-
-            int i = 0;
-            for (NEEntry entry : elements.values()) {
-                arr[i] = entry.toString();
-                i++;
-            }
-            Arrays.sort(arr);
-            for (String s : arr) {
-                sout.println(s);
-            }
         } else if (input.equals("help") || input.equals("?")) {
-            //sout.println(getLongDescription());
+            // sout.println(getLongDescription());
         } else if (input.equals("avmdata")) {
             try {
-                //myConnection.getManagedData();
+                // myConnection.getManagedData();
             } catch (Exception err) {
             }
         } else if (input.equals("innerjoin")) {
-            //innerJoin = !innerJoin;
-            //sout.println("Inner Join set to "+innerJoin);
+            // innerJoin = !innerJoin;
+            // sout.println("Inner Join set to "+innerJoin);
         } else if (input.equals("exit")) {
             try {
                 sout.close();
             } catch (Exception err) {
             }
+        } else if (input.equals("save")) {
+            XSQLBluePrint.save(this.bluePrint);
         } else if (input.equals("tocsv")) {
             toCsv = !toCsv;
             sout.println("to csv file is " + toCsv);
@@ -305,8 +319,8 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
             if (toCsv) {
                 if (exportToFileName != null) {
                     try {
-                        PrintStream o =
-                            new PrintStream(new File(exportToFileName));
+                        PrintStream o = new PrintStream(new File(
+                                exportToFileName));
                         executeSql(inputString.toString(), o);
                         o.close();
                     } catch (Exception err) {
@@ -314,8 +328,8 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                     }
                 } else {
                     try {
-                        String fName =
-                            "export-" + System.currentTimeMillis() + ".csv";
+                        String fName = "export-" + System.currentTimeMillis()
+                                + ".csv";
                         PrintStream o = new PrintStream(new File(fName));
                         executeSql(inputString.toString(), o);
                         o.close();
@@ -336,7 +350,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         JDBCResultSet rs = new JDBCResultSet(sql);
         try {
             int count = 0;
-            jdbcServer.execute(rs, this);
+            JDBCServer.execute(rs, this);
             boolean isFirst = true;
             int loc = rs.getFields().size() - 1;
             int totalWidth = 0;
@@ -398,7 +412,6 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                         }
                     }
 
-
                     if (!toCsv) {
                         out.print("|");
                     }
@@ -416,7 +429,6 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                         out.print(" ");
                     }
 
-
                     if (loc > 0) {
                         if (toCsv) {
                             out.print("\",\"");
@@ -437,7 +449,6 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         }
     }
 
-
     public static class NETask implements Runnable {
 
         private JDBCResultSet rs = null;
@@ -445,7 +456,8 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         private XSQLBluePrintNode main = null;
         private XSQLBluePrint bluePrint = null;
 
-        public NETask(JDBCResultSet _rs, Object _modelRoot,XSQLBluePrintNode _main,XSQLBluePrint _bluePrint) {
+        public NETask(JDBCResultSet _rs, Object _modelRoot,
+                XSQLBluePrintNode _main, XSQLBluePrint _bluePrint) {
             this.rs = _rs;
             this.modelRoot = _modelRoot;
             this.main = _main;
@@ -453,7 +465,8 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         }
 
         public void run() {
-            rs.addRecords(modelRoot, main, true, main.getBluePrintNodeName(),bluePrint);
+            rs.addRecords(modelRoot, main, true, main.getBluePrintNodeName(),
+                    bluePrint);
             synchronized (rs) {
                 rs.numberOfTasks--;
                 if (rs.numberOfTasks == 0) {
@@ -464,7 +477,6 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         }
     }
 
-
     private static class NEEntry {
         private Object ne = null;
 
@@ -478,7 +490,6 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
         }
     }
 
-
     private class TelnetConnection extends Thread {
 
         private Socket socket = null;
@@ -508,17 +519,19 @@ public class XSQLAdapter extends Thread implements SchemaContextListener {
                     out.print(prompt);
                     char c = 0;
                     byte data[] = new byte[1];
-                    while (c != '\n') {
+                    while (!socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && c != '\n') {
                         try {
                             in.read(data);
                             c = (char) data[0];
                             inputString.append(c);
                         } catch (Exception err) {
                             err.printStackTrace(out);
+                            stopped = true;
+                            break;
                         }
                     }
 
-                    processCommand(inputString, out, this);
+                    processCommand(inputString, out);
                     inputString = new StringBuffer();
                 }
             } catch (Exception err) {