This page contains coding examples for using the HUGIN Web Service API from C# and Java programs and PHP scripting, as well as examples for using the JavaScript for HUGIN Web Service API and the HUGIN Widgets Library from a web browser. All examples are based on the simple and well-known Build and Propagate demo which can be found in the other HUGIN APIs as well.
Examples | This page contains coding examples for using the HUGIN Web Service API from C# and Java programs and PHP scripting, as well as examples for using the JavaScript for HUGIN Web Service API and the HUGIN Widgets Library from a web browser. |
C# Example | This example demonstrates how to use the HUGIN Web Service API from C#. |
Java Example | This example demonstrates how to use the HUGIN Web Service API from Java. |
PHP Example | This example demonstrates how to use the HUGIN Web Service API from a PHP script. |
Browser example using JavaScript | This example demonstrates how to use the JavaScript for HUGIN Web Service API and the HUGIN Widgets Library from a web browser. |
This example demonstrates how to use the HUGIN Web Service API from C#. Interaction with the decision engine is performed over HTTP using System.Net.WebRequest, the .NET Framework’s request/response model for accessing data from the Internet.
using System; using System.Net; using System.IO; using System.Text; using System.Globalization; namespace Example { public class WebService { //service method for performing an HTTP POST request public static String POST(String url, String data) { WebRequest request = WebRequest.Create(url); request.Method = "POST"; if (data != null) { data = data.Replace("+", "%2b"); byte[] byteData = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteData.Length; using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteData, 0, byteData.Length); } } else { request.ContentLength = 0; } using (WebResponse response = request.GetResponse()) { return GetResponseString(response); } } //service method for performing an HTTP GET request public static String GET(String url) { WebRequest request = WebRequest.Create(url); request.Method = "GET"; using (WebResponse response = request.GetResponse()) { return GetResponseString(response); } } //service method for extracting server response as a string private static String GetResponseString(WebResponse response) { if (response == null) return null; using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseFromServer = reader.ReadToEnd(); return responseFromServer.Trim(); } } } //entry point public static void Main(String[] args) { if (args.Length == 0) { Console.WriteLine("HUGIN WebService Example"); Console.WriteLine("Usage: WebService <SERVER-URL> (e.g., webservice http://192.168.0.100:8001)"); return; } String wshome = args[0]; BAP(wshome); } //Build a Bayesian network and print node marginals. private static void BAP(String wshome) { try { //create domain String domain = POST(wshome + "/rest/newDomain", null); //create nodes String nodeA = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeA + "/setName", "=A"); POST(wshome + nodeA + "/setLabel", "=A1234567890123"); POST(wshome + nodeA + "/setNumberOfStates", "=3"); for (int i = 0; i < 3; i++) { POST(wshome + nodeA + "/setStateValue", "=" + i + "&=" + i); } String nodeB = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeB + "/setName", "=B"); POST(wshome + nodeB + "/setLabel", "=B"); POST(wshome + nodeB + "/setNumberOfStates", "=3"); for (int i = 0; i < 3; i++) { POST(wshome + nodeB + "/setStateValue", "=" + i + "&=" + i); } String nodeC = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeC + "/setName", "=C"); POST(wshome + nodeC + "/setLabel", "=C"); POST(wshome + nodeC + "/setNumberOfStates", "=5"); for (int i = 0; i < 5; i++) { POST(wshome + nodeC + "/setStateValue", "=" + i + "&=" + i); } //build structure POST(wshome + nodeC + "/addParent", "=" + nodeA); POST(wshome + nodeC + "/addParent", "=" + nodeB); //build expression for C String model = POST(wshome + domain + "/getNewModel", "=" + nodeC + "&="); String expression = "A + B"; POST(wshome + model + "/setExpression", "=0&=" + expression); //tables String tableA = GET(wshome + nodeA + "/getTable"); POST(wshome + tableA + "/setData", "=0&=0.1 0.2 0.7"); String tableB = GET(wshome + nodeB + "/getTable"); POST(wshome + tableB + "/setData", "=0&=0.2 0.2 0.6"); //compile POST(wshome + domain + "/compile", null); //print node marginals String nodes = GET(wshome + domain + "/getNodes"); foreach (String node in nodes.Split(new char[] {' '})) { int states = int.Parse(GET(wshome + node + "/getNumberOfStates"), CultureInfo.InvariantCulture); String label = GET(wshome + node + "/getLabel"); Console.WriteLine(label); for (int i = 0; i < states; i++) { String stateLabel = GET(wshome + node + "/getStateLabel?=" + i); double belief = double.Parse(GET(wshome + node + "/getBelief?=" + i), CultureInfo.InvariantCulture); Console.WriteLine("-" + stateLabel + " " + belief); } } //clean up after ourselves on the server POST(wshome + domain + "/delete", null); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); if (ex is WebException) Console.WriteLine("Response: " + GetResponseString(((WebException)ex).Response)); } } } }
java -classpath huginws.jar;<PATH-hapi.jar> -Djava.library.path=<PATH-.dll/.so-DIR> COM.hugin.WEBSERVICE.Main
csc WebService.cs
webservice.exe http://localhost:8080
This example demonstrates how to use the HUGIN Web Service API from Java. Interaction with the decision engine is performed over HTTP using Java.Net.HttpURLConnection, for representing a communications link between the application and HTTP URL.
import java.net.*; import java.io.*; public class WebService { //service class for handling HTTP errors private static class WebError extends Throwable { private int result; private String message; public WebError(int argResult, String argMessage) { result = argResult; message = argMessage; } public String getMessage() { return message; } public int getResult() { return result; } } //service method for performing an HTTP POST request public static String POST(String url, String data) throws WebError, Exception { String response = ""; int result = 0; URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection)u.openConnection(); conn.setDoInput (true); conn.setDoOutput (data != null); conn.setUseCaches (false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod("POST"); if (data != null) { data = data.replaceAll("\\+", "%2b"); DataOutputStream out = new DataOutputStream (conn.getOutputStream ()); out.writeBytes(data); out.flush (); out.close (); } result = conn.getResponseCode(); BufferedReader in = null; if (result == 200) in = new BufferedReader (new InputStreamReader(conn.getInputStream ())); else in = new BufferedReader (new InputStreamReader(conn.getErrorStream ())); String temp; while ((temp = in.readLine()) != null){ response += temp + "\n"; } in.close (); if (result != 200) throw new WebError(result, response); return response.trim(); } //service method for performing an HTTP GET request public static String GET(String url) throws WebError, Exception { String response = ""; int result = 0; URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection)u.openConnection(); conn.setDoInput (true); conn.setDoOutput (false); conn.setUseCaches (false); conn.setRequestMethod("GET"); result = conn.getResponseCode(); BufferedReader in = null; if (result == 200) in = new BufferedReader (new InputStreamReader(conn.getInputStream ())); else in = new BufferedReader (new InputStreamReader(conn.getErrorStream ())); String temp; while ((temp = in.readLine()) != null) { response += temp + "\n"; } in.close (); if (result != 200) throw new WebError(result, response); return response.trim(); } //entry point public static void main(String[] args) { if (args.length == 0) { System.out.println("HUGIN WebService Example"); System.out.println("Usage: java WebService <SERVER-URL> (e.g., java WebService http://192.168.0.100:8001)"); return; } String wshome = args[0]; BAP(wshome); } //Build a Bayesian network and print node marginals. private static void BAP(String wshome) { try { //create domain String domain = POST(wshome + "/rest/newDomain", null); //create nodes String nodeA = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeA + "/setName", "=A"); POST(wshome + nodeA + "/setLabel", "=A1234567890123"); POST(wshome + nodeA + "/setNumberOfStates", "=3"); for (int i = 0; i < 3; i++) { POST(wshome + nodeA + "/setStateValue", "=" + i + "&=" + i); } String nodeB = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeB + "/setName", "=B"); POST(wshome + nodeB + "/setLabel", "=B"); POST(wshome + nodeB + "/setNumberOfStates", "=3"); for (int i = 0; i < 3; i++) { POST(wshome + nodeB + "/setStateValue", "=" + i + "&=" + i); } String nodeC = POST(wshome + domain + "/getNewNode", "=chance&=discrete&=number"); POST(wshome + nodeC + "/setName", "=C"); POST(wshome + nodeC + "/setLabel", "=C"); POST(wshome + nodeC + "/setNumberOfStates", "=5"); for (int i = 0; i < 5; i++) { POST(wshome + nodeC + "/setStateValue", "=" + i + "&=" + i); } //build structure POST(wshome + nodeC + "/addParent", "=" + nodeA); POST(wshome + nodeC + "/addParent", "=" + nodeB); //build expression for C String model = POST(wshome + domain + "/getNewModel", "=" + nodeC + "&="); String expression = "A + B"; POST(wshome + model + "/setExpression", "=0&=" + expression); //tables String tableA = GET(wshome + nodeA + "/getTable"); POST(wshome + tableA + "/setData", "=0&=0.1 0.2 0.7"); String tableB = GET(wshome + nodeB + "/getTable"); POST(wshome + tableB + "/setData", "=0&=0.2 0.2 0.6"); //compile POST(wshome + domain + "/compile", null); //print node marginals String nodes = GET(wshome + domain + "/getNodes"); for (String node : nodes.split(" ")) { int states = Integer.parseInt(GET(wshome + node + "/getNumberOfStates")); String label = GET(wshome + node + "/getLabel"); System.out.println(label); for (int i = 0; i < states; i++) { String stateLabel = GET(wshome + node + "/getStateLabel?=" + i); double belief = Double.parseDouble(GET(wshome + node + "/getBelief?=" + i)); System.out.println("-" + stateLabel + " " + belief); } } //clean up after ourselves on the server POST(wshome + domain + "/delete", null); } catch (WebError err) { System.out.println("Error: " + err.result + " " + err.getMessage()); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
java -classpath huginws.jar;<PATH-hapi.jar> -Djava.library.path=<PATH-.dll/.so-DIR> COM.hugin.WEBSERVICE.Main
javac WebService.java
java WebService http://localhost:8080
This example demonstrates how to use the HUGIN Web Service API from a PHP script. Interaction with the decision engine is performed over HTTP using internet socket connection (see fsockopen http://www.php.net
<?php //NOTE: //php.ini must have allow_url_fopen = On //helper functions for performing POST and GET requests class WebService { public static $HTTPSTATUS = 0; public static $HTTPMESSAGE = ''; public static $RESPONSE = ''; private static function Error($statuscode, $str) { WebService::$HTTPSTATUS = $statuscode; WebService::$HTTPMESSAGE = $str; WebService::$RESPONSE = ''; throw new Exception($statuscode . ' ' . $str); } private static function HTTP($method, $url, $data) { $statuscode = -1; $statusstring = ''; $contents = ''; WebService::$HTTPSTATUS = 0; WebService::$HTTPMESSAGE = ''; WebService::$RESPONSE = ''; try { $HOST = parse_url($url, PHP_URL_HOST); $PORT = parse_url($url, PHP_URL_PORT); if ($PORT == NULL) $PORT = 80; $PATH = parse_url($url, PHP_URL_PATH); if ($PATH == NULL) $PATH = "/"; $QUERY = parse_url($url, PHP_URL_QUERY); if ($QUERY == NULL) $QUERY = ""; else $QUERY = "?" . $QUERY; if ($HOST == NULL) { $statuscode = 500; $statusstring = "Invalid URL specified: " . $url; } else if ($method == 'GET' || $method == 'POST') { $fp = fsockopen($HOST, $PORT, $errno, $errstr, 30); if (!$fp) { $statuscode = 500; $statusstring = "Could not open socket! " . $errstr . "(" . $errno . ")"; } else { $out = ''; if ($method == 'GET') $out .= "GET " . $PATH . $QUERY . " HTTP/1.1\r\n"; else $out .= "POST " . $PATH . " HTTP/1.1\r\n"; $out .= "Host: " . $HOST . "\r\n"; if ($method == 'POST') { $data = str_replace("+", "%2b", $data); $encoded = utf8_encode($data); $out .= "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"; $out .= "Content-Length: " . strlen($encoded) . "\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); fwrite($fp, $data); } else { $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); } $emptylines = 0; while (!feof($fp)) { $hs = fgets($fp, 128); if ($hs != "\r\n") { if ($statuscode < 0) { $httpstatus = explode(' ', $hs, 3); $statuscode = (int)$httpstatus[1]; $statusstring = $httpstatus[2]; } } else { $emptylines++; if ($emptylines==1) break; } } while (!feof($fp)) { $contents .= fread($fp, 8192); } fclose($fp); WebService::$HTTPSTATUS = $statuscode; WebService::$HTTPMESSAGE = $statusstring; WebService::$RESPONSE = trim($contents); } } } catch (Exception $e) { $statuscode = 500; $statusstring = $e->getMessage(); } if ($statuscode != 200) { WebService::Error($statuscode, $statusstring); } } public static function POST($url, $data) { WebService::HTTP("POST", $url, $data); return WebService::$RESPONSE; } public static function GET($url) { WebService::HTTP("GET", $url, ''); return WebService::$RESPONSE; } } ?>
<?php require_once('WebService.php'); //Build a Bayesian network and print node marginals. function BAP($wshome) { try { //create domain $domain = WebService::POST("$wshome/rest/newDomain", ""); //create nodes $nodeA = WebService::POST("$wshome$domain/getNewNode", "=chance&=discrete&=number"); WebService::POST("$wshome$nodeA/setName", "=A"); WebService::POST("$wshome$nodeA/setLabel", "=A1234567890123"); WebService::POST("$wshome$nodeA/setNumberOfStates", "=3"); for ($i = 0; $i < 3; $i++) { WebService::POST("$wshome$nodeA/setStateValue", "=$i&=$i"); } $nodeB = WebService::POST("$wshome$domain/getNewNode", "=chance&=discrete&=number"); WebService::POST("$wshome$nodeB/setName", "=B"); WebService::POST("$wshome$nodeB/setLabel", "=B"); WebService::POST("$wshome$nodeB/setNumberOfStates", "=3"); for ($i = 0; $i < 3; $i++) { WebService::POST("$wshome$nodeB/setStateValue", "=$i&=$i"); } $nodeC = WebService::POST("$wshome$domain/getNewNode", "=chance&=discrete&=number"); WebService::POST("$wshome$nodeC/setName", "=C"); WebService::POST("$wshome$nodeC/setLabel", "=C"); WebService::POST("$wshome$nodeC/setNumberOfStates", "=5"); for ($i = 0; $i < 5; $i++) { WebService::POST("$wshome$nodeC/setStateValue", "=$i&=$i"); } //build structure WebService::POST("$wshome$nodeC/addParent", "=$nodeA"); WebService::POST("$wshome$nodeC/addParent", "=$nodeB"); //build expression for C $model = WebService::POST("$wshome$domain/getNewModel", "=$nodeC&="); $expression = "A + B"; WebService::POST("$wshome$model/setExpression", "=0&=$expression"); //tables $tableA = WebService::GET("$wshome$nodeA/getTable"); WebService::POST("$wshome$tableA/setData", "=0&=0.1 0.2 0.7"); $tableB = WebService::GET("$wshome$nodeB/getTable"); WebService::POST("$wshome$tableB/setData", "=0&=0.2 0.2 0.6"); //compile WebService::POST("$wshome$domain/compile", ""); //print node marginals $nodes = WebService::GET("$wshome$domain/getNodes"); foreach (explode(' ', $nodes) as $node) { $states = (int)WebService::GET("$wshome$node/getNumberOfStates"); $label = WebService::GET("$wshome$node/getLabel"); echo $label . "\n"; for ($i = 0; $i < $states; $i++) { $stateLabel = WebService::GET("$wshome$node/getStateLabel?=$i"); $belief = (double)WebService::GET("$wshome$node/getBelief?=$i"); echo "-$stateLabel $belief\n"; } } //clean up after ourselves on the server WebService::POST("$wshome$domain/delete", ""); } catch (Exception $ex) { echo "Error: " . $ex->getMessage() . "\n"; echo "HTTP STATUS: " . WebService::$HTTPSTATUS . "\n"; echo "HTTP MESSAGE: " . WebService::$HTTPMESSAGE . "\n"; echo "RESPONSE: " . WebService::$RESPONSE . "\n"; } } header("Content-Type: text/plain"); BAP("http://127.0.0.1:8080"); ?>
java -classpath huginws.jar;<PATH-hapi.jar> -Djava.library.path=<PATH-.dll/.so-DIR> COM.hugin.WEBSERVICE.Main
This example demonstrates how to use the JavaScript for HUGIN Web Service API and the HUGIN Widgets Library from a web browser. Interaction with the decision engine is performed over HTTP using the HAPI object by including the HUGIN library file hugin.js.
The script inside <HEAD> corresponds to the Build-and-propagate example found in the other coding samples on this page. The scripting inside the <BODY> demonstrates how to use the HUGIN Widgets Library (included in the library file hwidgets.js).
<!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="/webservice/hugin.php/hugin.js"></script> <script type="text/javascript" src="/webservice/hugin.php/hwidgets.js"></script> <script type="text/javascript"> try { alert("Start building and propagate code"); //create an HAPI instance - point it to the correct URL for the HUGIN Web Service entry point hapi = new HAPI("/webservice/hugin.php"); //create domain domain = hapi.getNewDomain(); //create nodes A = domain.getNewNode(HAPI.H_CATEGORY_CHANCE, HAPI.H_KIND_DISCRETE, HAPI.H_SUBTYPE_NUMBER); A.setName("A"); A.setLabel("A1234567890123"); A.setNumberOfStates(3); for (var i = 0; i < 3; i++) { A.setStateValue(i, i); } B = domain.getNewNode(HAPI.H_CATEGORY_CHANCE, HAPI.H_KIND_DISCRETE, HAPI.H_SUBTYPE_NUMBER); B.setName("B"); B.setLabel("B"); B.setNumberOfStates(3); for (var i = 0; i < 3; i++) { B.setStateValue(i, i); } C = domain.getNewNode(HAPI.H_CATEGORY_CHANCE, HAPI.H_KIND_DISCRETE, HAPI.H_SUBTYPE_NUMBER); C.setName("C"); C.setLabel("C"); C.setNumberOfStates(5); for (var i = 0; i < 5; i++) { C.setStateValue(i, i); } //build structure C.addParent(A); C.addParent(B); //build expression for C model = domain.getNewModel(C, []); model.setExpression(0, "A + B"); //tables tableA = A.getTable(); tableA.setData([0.1, 0.2, 0.7], 0, 3); tableB = B.getTable(); tableB.setData([0.2, 0.2, 0.6], 0, 3); //compile domain.compile(); //print node marginals var result = ""; nodes = domain.getNodes(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; var states = node.getNumberOfStates(); var label = node.getLabel(); result += label + "\n"; for (var j = 0; j < states; j++) { var statelabel = node.getStateLabel(j); var belief = node.getBelief(j); result += "-" + statelabel + " " + belief + "\n"; } } alert(result); } catch (e) { alert("An error occured: " + e.name + "\n" + e.message); } </script> <title>Build And Propagate</title> </head> <body> <h1>Build And Propagate</h1><script type="text/javascript"> try { //create a widget manager instance - we need it for adding widgets widMan = new HuginWidgetManager(domain, { prefetch_by_name: ["A", "B", "C"] }); } catch (e) { alert("An error occured: " + e.name + "\n" + e.message); } </script> <p>Node A</p> <p><script type="text/javascript"> widMan.addStateSelectOption(A, { labels: ["state 0", "state 1", "state 2"] }); </script></p> <p>P(state 0)=<script type="text/javascript"> widMan.addBeliefLabel(A, 0, {}); </script><br /> P(state 1)=<script type="text/javascript"> widMan.addBeliefLabel(A, 1, {}); </script><br /> P(state 2)=<script type="text/javascript"> widMan.addBeliefLabel(A, 2, {}); </script></p> <p>Node B</p> <p><script type="text/javascript"> widMan.addStateSelectOption(B, { labels: ["state 0", "state 1", "state 2"] }); </script></p> <p>P(state 0)=<script type="text/javascript"> widMan.addBeliefLabel(B, 0, {}); </script><br /> P(state 1)=<script type="text/javascript"> widMan.addBeliefLabel(B, 1, {}); </script><br /> P(state 2)=<script type="text/javascript"> widMan.addBeliefLabel(B, 2, {}); </script></p> <p>Node C</p> <p>P(state 0)=<script type="text/javascript"> widMan.addBeliefLabel(C, 0, {}); </script><br /> P(state 1)=<script type="text/javascript"> widMan.addBeliefLabel(C, 1, {}); </script><br /> P(state 2)=<script type="text/javascript"> widMan.addBeliefLabel(C, 2, {}); </script><br /> P(state 3)=<script type="text/javascript"> widMan.addBeliefLabel(C, 3, {}); </script><br /> P(state 4)=<script type="text/javascript"> widMan.addBeliefLabel(C, 4, {}); </script></p> <p><script type="text/javascript"> widMan.addButtonInitialize({}); </script></p> </body> </html>
java -classpath huginws.jar;<PATH-hapi.jar> -Djava.library.path=<PATH-.dll/.so-DIR> COM.hugin.WEBSERVICE.Main