summaryrefslogtreecommitdiffstats
path: root/verigraph/src/main/java/it/polito/grpc
diff options
context:
space:
mode:
Diffstat (limited to 'verigraph/src/main/java/it/polito/grpc')
-rw-r--r--verigraph/src/main/java/it/polito/grpc/Client.java550
-rw-r--r--verigraph/src/main/java/it/polito/grpc/GrpcUtils.java156
-rw-r--r--verigraph/src/main/java/it/polito/grpc/README.rst442
-rw-r--r--verigraph/src/main/java/it/polito/grpc/Service.java462
-rw-r--r--verigraph/src/main/java/it/polito/grpc/test/GrpcServerTest.java292
-rw-r--r--verigraph/src/main/java/it/polito/grpc/test/GrpcTest.java349
-rw-r--r--verigraph/src/main/java/it/polito/grpc/test/MultiThreadTest.java220
-rw-r--r--verigraph/src/main/java/it/polito/grpc/test/ReachabilityTest.java252
8 files changed, 2723 insertions, 0 deletions
diff --git a/verigraph/src/main/java/it/polito/grpc/Client.java b/verigraph/src/main/java/it/polito/grpc/Client.java
new file mode 100644
index 0000000..adc16da
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/Client.java
@@ -0,0 +1,550 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import com.google.protobuf.Message;
+
+import io.grpc.ManagedChannel;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.StatusRuntimeException;
+import io.grpc.verigraph.ConfigurationGrpc;
+import io.grpc.verigraph.GetRequest;
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NeighbourGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.NewNeighbour;
+import io.grpc.verigraph.NewNode;
+import io.grpc.verigraph.NodeGrpc;
+import io.grpc.verigraph.NodeGrpc.FunctionalType;
+import io.grpc.verigraph.Policy;
+import io.grpc.verigraph.Policy.PolicyType;
+import io.grpc.verigraph.RequestID;
+import io.grpc.verigraph.Status;
+import io.grpc.verigraph.TestGrpc;
+import io.grpc.verigraph.VerificationGrpc;
+import io.grpc.verigraph.VerigraphGrpc;
+
+public class Client {
+
+ private final ManagedChannel channel;
+ private final VerigraphGrpc.VerigraphBlockingStub blockingStub;
+
+ public Client(String host, int port) {
+ this(ManagedChannelBuilder.forAddress(host, port).usePlaintext(true));
+ }
+
+ /** Construct client for accessing RouteGuide server using the existing channel. */
+ public Client(ManagedChannelBuilder<?> channelBuilder) {
+ channel = channelBuilder.build();
+ blockingStub = VerigraphGrpc.newBlockingStub(channel);
+ }
+
+ /** Get array of graphs */
+ public List<GraphGrpc> getGraphs() {
+ List<GraphGrpc> graphsRecveived = new ArrayList<GraphGrpc>();
+ GetRequest request = GetRequest.newBuilder().build();
+ Iterator<GraphGrpc> graphs;
+ try {
+ graphs = blockingStub.getGraphs(request);
+ while (graphs.hasNext()) {
+ GraphGrpc graph = graphs.next();
+ System.out.println("Graph id : "+graph.getId());
+ if(graph.getErrorMessage().equals("")){
+ System.out.println("Node id : "+graph.getId());
+ graphsRecveived.add(graph);
+ }else{
+ System.out.println("Error : " + graph.getErrorMessage());
+ return graphsRecveived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ }
+ return graphsRecveived;
+ }
+
+ /** Create new Graph */
+ public NewGraph createGraph(GraphGrpc gr) {
+ NewGraph response;
+ try {
+ response = blockingStub.createGraph(gr);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewGraph.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Delete a Graph */
+ public boolean deleteGraph(long idGraph) {
+
+ RequestID id = RequestID.newBuilder().setIdGraph(idGraph).build();
+ Status response;
+ try {
+ response = blockingStub.deleteGraph(id);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ return true;
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ }
+ return false;
+ }
+
+ /** Edits a single graph */
+ public NewGraph updateGraph(long idGraph, GraphGrpc newGraph) {
+
+ GraphGrpc gr = GraphGrpc.newBuilder(newGraph).setId(idGraph).build();
+ NewGraph response;
+ try {
+ response = blockingStub.updateGraph(gr);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewGraph.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Get a single graph*/
+ public GraphGrpc getGraph(long idGraph) {
+
+ RequestID request = RequestID.newBuilder().setIdGraph(idGraph).build() ;
+ try {
+ GraphGrpc graph = blockingStub.getGraph(request);
+ if(!graph.getErrorMessage().equals("")){
+ System.out.println("Error in operation: " + graph.getErrorMessage());
+ }
+ return graph;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ return null;
+ }
+ }
+
+ /** Verify a given policy*/
+ public VerificationGrpc verify(Policy policy) {
+
+ VerificationGrpc response;
+ try {
+ response = blockingStub.verifyPolicy(policy);
+ if(!response.getErrorMessage().equals("")){
+ System.out.println("Error in operation: " + response.getErrorMessage());
+ }
+ System.out.println("Result : "+response.getResult());
+ System.out.println("Comment : "+response.getComment());
+ //uncomment if you want to print the paths
+ /*for(TestGrpc test:response.getTestList()){
+ System.out.println("Test : "+test.getResult()+". Traversed nodes:");
+ for(NodeGrpc node:test.getNodeList()){
+ //prints only the name
+ System.out.println("Node "+node.getName());
+ }
+ }*/
+ return response;
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return null;
+ }
+ }
+
+ /*Node part*/
+
+ /** Get array of nodes */
+ public List<NodeGrpc> getNodes(long idGraph) {
+ List<NodeGrpc> nodesReceived = new ArrayList<NodeGrpc>();
+ RequestID request = RequestID.newBuilder().setIdGraph(idGraph).build() ;
+ Iterator<NodeGrpc> nodes;
+ try {
+ nodes = blockingStub.getNodes(request);
+ while (nodes.hasNext()) {
+ NodeGrpc node = nodes.next();
+ if(node.getErrorMessage().equals("")){
+ System.out.println("Node id : "+node.getId());
+ nodesReceived.add(node);
+ }else{
+ System.out.println("Error : " + node.getErrorMessage());
+ return nodesReceived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ }
+ return nodesReceived;
+ }
+
+ /** Create new Node */
+ public NewNode createNode(NodeGrpc node, long idGraph) {
+
+ NewNode response;
+ try {
+ NodeGrpc n = NodeGrpc.newBuilder(node).setIdGraph(idGraph).build();
+ response = blockingStub.createNode(n);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewNode.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Delete a Node */
+ public boolean deleteNode(long idGraph, long idNode) {
+
+ RequestID id = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build();
+ Status response;
+ try {
+ response = blockingStub.deleteNode(id);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ return true;
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ }
+ return false;
+ }
+
+ /** Edits a single Node */
+ public NewNode updateNode(long idGraph, long idNode, NodeGrpc node) {
+
+ NodeGrpc nu = NodeGrpc.newBuilder(node).setIdGraph(idGraph).setId(idNode).build();
+ NewNode response;
+ try {
+ response = blockingStub.updateNode(nu);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewNode.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Get a single Node*/
+ public NodeGrpc getNode(long idGraph, long idNode) {
+
+ RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build() ;
+ try {
+ NodeGrpc node = blockingStub.getNode(request);
+ if(!node.getErrorMessage().equals("")){
+ System.out.println("Error in operation: " + node.getErrorMessage());
+ }
+ return node;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ return null;
+ }
+ }
+
+ /** Configure a single Node*/
+ public boolean configureNode(long idGraph, long idNode, ConfigurationGrpc configuration) {
+
+ try {
+ ConfigurationGrpc request = ConfigurationGrpc.newBuilder(configuration)
+ .setIdGraph(idGraph).setIdNode(idNode).build() ;
+
+ Status response = blockingStub.configureNode(request);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ return true;
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ }
+ return false;
+ }
+
+ /*Neighbour part*/
+
+ /** Get array of neighbours */
+ public List<NeighbourGrpc> getNeighbours(long idGraph, long idNode) {
+
+ List<NeighbourGrpc> neighboursReceived = new ArrayList<NeighbourGrpc>();
+ RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build() ;
+ Iterator<NeighbourGrpc> neighbours;
+ try {
+ neighbours = blockingStub.getNeighbours(request);
+ while (neighbours.hasNext()) {
+ NeighbourGrpc neighbour = neighbours.next();
+ if(neighbour.getErrorMessage().equals("")){
+ System.out.println("Neighbour id : "+neighbour.getId());
+ neighboursReceived.add(neighbour);
+ }else{
+ System.out.println("Error : " + neighbour.getErrorMessage());
+ return neighboursReceived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ }
+ return neighboursReceived;
+ }
+
+ /** Create new Neighbour */
+ public NewNeighbour createNeighbour(NeighbourGrpc neighbour, long idGraph, long idNode) {
+
+ NewNeighbour response;
+ try {
+ NeighbourGrpc n = NeighbourGrpc.newBuilder(neighbour).setIdGraph(idGraph)
+ .setIdNode(idNode).build();
+ response = blockingStub.createNeighbour(n);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewNeighbour.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Delete a Neighbour */
+ public boolean deleteNeighbour(long idGraph, long idNode, long idNeighbour) {
+
+ RequestID id = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).setIdNeighbour(idNeighbour).build();
+ Status response;
+ try {
+ response = blockingStub.deleteNeighbour(id);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ return true;
+ }else{
+ System.out.println("Unsuccesful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ }
+ return false;
+ }
+
+ /** Edits a single Neighbour */
+ public NewNeighbour updateNeighbour(long idGraph, long idNode, long idNeighbour, NeighbourGrpc neighbour) {
+
+ NeighbourGrpc nu = NeighbourGrpc.newBuilder(neighbour).setIdGraph(idGraph).setIdNode(idNode)
+ .setId(idNeighbour).build();
+ NewNeighbour response;
+ try {
+ response = blockingStub.updateNeighbour(nu);
+ if(response.getSuccess()){
+ System.out.println("Successful operation ");
+ }else{
+ System.out.println("Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("RPC failed: " + e.getStatus());
+ return NewNeighbour.newBuilder().setSuccess(false).build();
+ }
+ return response;
+ }
+
+ /** Get a single Neighbour*/
+ public NeighbourGrpc getNeighbour(long idGraph, long idNode, long idNeighbour) {
+
+ RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).setIdNeighbour(idNeighbour).build() ;
+ try {
+ NeighbourGrpc neighbour = blockingStub.getNeighbour(request);
+ if(!neighbour.getErrorMessage().equals("")){
+ System.out.println("Error in operation: " + neighbour.getErrorMessage());
+ }
+ return neighbour;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("RPC failed: " + ex.getStatus());
+ return null;
+ }
+ }
+
+ public void shutdown() throws InterruptedException {
+ channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
+ }
+
+ /** Test on the Server. */
+ public static void main(String[] args) throws Exception {
+
+ List<Long> listGraph = new ArrayList<Long>(); //list of ID
+
+ Client client = new Client("localhost" , 50051);
+ try {
+ NodeGrpc node1 = createNodeGrpc("Node1", "endhost", null, null);
+ List<NeighbourGrpc> neighbours = new ArrayList<NeighbourGrpc>();
+ NeighbourGrpc nb = createNeighbourGrpc("Node1");
+ neighbours.add(nb);
+ NodeGrpc node2 = createNodeGrpc("Node2", "endpoint", neighbours, null);
+ List<NodeGrpc> nodes = new ArrayList<NodeGrpc>();
+ nodes.add(node1);
+ nodes.add(node2);
+
+ GraphGrpc graph = createGraphGrpc(nodes);
+
+ NewGraph createdGraph = client.createGraph(graph);
+ if(createdGraph.getSuccess() == true){
+ listGraph.add(createdGraph.getGraph().getId());
+ System.out.println("Created graph with id :"+ createdGraph.getGraph().getId());
+ }
+
+ client.getGraphs();
+ } catch(Exception ex){
+ System.out.println("Error: " + ex.getMessage());
+ ex.printStackTrace();
+ }finally {
+ client.shutdown();
+ }
+ }
+
+ public static NeighbourGrpc createNeighbourGrpc(String name){
+ return NeighbourGrpc.newBuilder().setName(name).build();
+ }
+
+ public static NodeGrpc createNodeGrpc(String name, String functionalType, List<NeighbourGrpc> neighbours, ConfigurationGrpc conf) throws Exception{
+ NodeGrpc.Builder nb = NodeGrpc.newBuilder();
+
+ if(name != null)
+ nb.setName(name);
+ else
+ throw new Exception("Node must have a name");
+
+ if(functionalType != null)
+ nb.setFunctionalType(FunctionalType.valueOf(functionalType));
+ else
+ throw new Exception("Node must have a functional type");
+
+ if( neighbours!= null){
+ for(NeighbourGrpc value:neighbours)
+ nb.addNeighbour(value);
+ }
+ if(conf == null){
+ try{
+ conf = createConfigurationGrpc(null, null, null, null);
+ }catch(Exception e){
+ throw new Exception(e.getMessage());
+ }
+ }
+ nb.setConfiguration(conf);
+ return nb.build();
+ }
+
+ public static GraphGrpc createGraphGrpc(List<NodeGrpc> nodes){
+ GraphGrpc.Builder gb = GraphGrpc.newBuilder();
+ if(nodes != null){
+ for(NodeGrpc value:nodes)
+ gb.addNode(value);
+ }
+ return gb.build();
+ }
+
+ public static Policy createPolicy(String src, String dst, String type, String middlebox, long idGraph) throws IllegalArgumentException{
+ if(!validMiddlebox(type, middlebox))
+ throw new IllegalArgumentException("Not valid middlebox valid with this type");
+ Policy.Builder policy = Policy.newBuilder();
+ policy.setIdGraph(idGraph);
+ if(src != null)
+ policy.setSource(src);
+ else{
+ throw new IllegalArgumentException("Please insert source field");
+ }
+ if(dst != null)
+ policy.setDestination(dst);
+ else{
+ throw new IllegalArgumentException("Please insert destination field");
+ }
+ if(type != null)
+ policy.setType(PolicyType.valueOf(type));
+ if(middlebox != null)
+ policy.setMiddlebox(middlebox);
+ return policy.build();
+ }
+
+ public static ConfigurationGrpc createConfigurationGrpc(Map<String,String> parameters, List<String> lists, String id, String description) throws Exception{
+ ConfigurationGrpc.Builder cb = ConfigurationGrpc.newBuilder();
+ StringBuilder sb = new StringBuilder("[");
+ if(parameters != null && lists == null){
+ int i = 0;
+ sb.append("{");
+ for (String key: parameters.keySet()) {
+ sb.append("\"");
+ sb.append(key);
+ sb.append("\":\"");
+ sb.append(parameters.get(key));
+ sb.append("\"");
+ if((i+1)<parameters.keySet().size()){
+ sb.append(", ");
+ }
+ i++;
+ }
+ sb.append("}");
+ }
+ else if(parameters == null && lists != null){
+ int i = 0;
+ for (String value: lists) {
+ sb.append("\"");
+ sb.append(value);
+ sb.append("\"");
+ if((i+1)<lists.size()){
+ sb.append(", ");
+ }
+ i++;
+ }
+ }
+ else if(parameters != null && lists != null){
+ throw new Exception("Error, configuration must contains or a sequence name:value or sequence"
+ + "of string, but not both");
+ }
+ sb.append("]");
+ cb.setConfiguration(sb.toString());
+ if(id != null)
+ cb.setId(id);
+ if(description != null)
+ cb.setDescription(description);
+ return cb.build();
+ }
+
+ private static boolean validMiddlebox(String type, String middlebox) {
+ if(type == null)
+ return false;
+ if(type.equals("reachability") && (middlebox == null || middlebox.equals("")))
+ return true;
+ if(type.equals("isolation") && !(middlebox == null || middlebox.equals("")))
+ return true;
+ if(type.equals("traversal") && !(middlebox == null || middlebox.equals("")))
+ return true;
+ return false;
+ }
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/GrpcUtils.java b/verigraph/src/main/java/it/polito/grpc/GrpcUtils.java
new file mode 100644
index 0000000..0ed002c
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/GrpcUtils.java
@@ -0,0 +1,156 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Splitter;
+
+import io.grpc.verigraph.ConfigurationGrpc;
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NeighbourGrpc;
+import io.grpc.verigraph.NodeGrpc;
+import io.grpc.verigraph.TestGrpc;
+import io.grpc.verigraph.VerificationGrpc;
+import io.grpc.verigraph.NodeGrpc.FunctionalType;
+import it.polito.escape.verify.model.Configuration;
+import it.polito.escape.verify.model.Graph;
+import it.polito.escape.verify.model.Neighbour;
+import it.polito.escape.verify.model.Node;
+import it.polito.escape.verify.model.Test;
+import it.polito.escape.verify.model.Verification;
+
+public class GrpcUtils {
+ private static final Logger logger = Logger.getLogger(GrpcUtils.class.getName());
+
+ public static NeighbourGrpc obtainNeighbour(Neighbour ne){
+ return NeighbourGrpc.newBuilder()
+ .setId(ne.getId())
+ .setName(ne.getName())
+ .build();
+ }
+
+ public static Neighbour deriveNeighbour(NeighbourGrpc request) {
+ //id is not present
+ Neighbour ne = new Neighbour();
+ ne.setName(request.getName());
+ return ne;
+ }
+
+ public static ConfigurationGrpc obtainConfiguration(Configuration conf){
+ return ConfigurationGrpc.newBuilder()
+ .setId(conf.getId())
+ .setDescription(conf.getDescription())
+ .setConfiguration(conf.getConfiguration().toString())
+ .build();
+ }
+
+ public static Configuration deriveConfiguration(ConfigurationGrpc request) {
+ Configuration conf = new Configuration();
+ conf.setId(request.getId());
+ conf.setDescription(request.getDescription());
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode rootNode = null;
+ try {
+ if ("".equals(request.getConfiguration()))
+ rootNode=mapper.readTree("[]");
+ else
+ rootNode = mapper.readTree(request.getConfiguration());
+ } catch (IOException e) {
+ logger.log(Level.WARNING, e.getMessage());
+ }
+ conf.setConfiguration(rootNode);
+ return conf;
+ }
+
+ public static NodeGrpc obtainNode(Node node) {
+ NodeGrpc.Builder nr = NodeGrpc.newBuilder();
+ nr.setId(node.getId());
+ nr.setName(node.getName());
+ nr.setFunctionalType(FunctionalType.valueOf(node.getFunctional_type()));
+ for(Neighbour neighbour:node.getNeighbours().values()){
+ NeighbourGrpc ng = obtainNeighbour(neighbour);
+ nr.addNeighbour(ng);
+ }
+ nr.setConfiguration(obtainConfiguration(node.getConfiguration()));
+ return nr.build();
+ }
+
+ public static Node deriveNode(NodeGrpc request) {
+ //id is not present
+ Node node = new Node();
+ node.setName(request.getName());
+ node.setFunctional_type(request.getFunctionalType().toString());
+ Configuration conf = deriveConfiguration(request.getConfiguration());
+ node.setConfiguration(conf);
+
+ Map<Long,Neighbour> neighours = node.getNeighbours();
+ long i = 1;
+ for(NeighbourGrpc neighbour:request.getNeighbourList()){
+ Neighbour ng = deriveNeighbour(neighbour);
+ neighours.put(i++, ng);
+ }
+
+ return node;
+ }
+
+ public static GraphGrpc obtainGraph(Graph graph){
+ GraphGrpc.Builder gr = GraphGrpc.newBuilder();
+ gr.setId(graph.getId());
+ for(Node node:graph.getNodes().values()){
+ NodeGrpc ng = obtainNode(node);
+ gr.addNode(ng);
+ }
+ return gr.build();
+ }
+
+ public static Graph deriveGraph(GraphGrpc request) {
+ //id is not present
+ Graph graph = new Graph();
+
+ long i=1;
+ Map<Long, Node> nodes = graph.getNodes();
+ for(NodeGrpc node:request.getNodeList()){
+ Node ng = deriveNode(node);
+ nodes.put(i++, ng);
+ }
+
+ return graph;
+ }
+
+ public static VerificationGrpc obtainVerification(Verification verify){
+ VerificationGrpc.Builder ver = VerificationGrpc.newBuilder();
+ ver.setComment(verify.getComment());
+ ver.setResult(verify.getResult());
+ for(Test test:verify.getTests()){
+ TestGrpc.Builder tst = TestGrpc.newBuilder().setResult(test.getResult());
+ for(Node node:test.getPath()){
+ NodeGrpc ng = obtainNode(node);
+ tst.addNode(ng);
+ }
+ ver.addTest(tst);
+ }
+ return ver.build();
+ }
+
+ /**Intended for string that begins with "?"
+ * */
+ public static Map<String,String> getParamGivenString(String str){
+ String string = str.substring(1);
+ final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator("=").
+ split(string);
+ return map;
+ }
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/README.rst b/verigraph/src/main/java/it/polito/grpc/README.rst
new file mode 100644
index 0000000..d089908
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/README.rst
@@ -0,0 +1,442 @@
+.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. http://creativecommons.org/licenses/by/4.0
+
+gRPC Project
+============
+
+This project contains the interfaces for a web service based on gRPC.
+
+How to install:
+---------------
+
+For gRPC interface, add to your ``pom.xml`` (in the project this part is
+already present):
+
+::
+
+ <dependency>
+ <groupId>io.grpc</groupId>
+ <artifactId>grpc-netty</artifactId>
+ <version>${grpc.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>io.grpc</groupId>
+ <artifactId>grpc-protobuf</artifactId>
+ <version>${grpc.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>io.grpc</groupId>
+ <artifactId>grpc-stub</artifactId>
+ <version>${grpc.version}</version>
+ </dependency>
+
+For protobuf-based codegen integrated with the Maven build system, you
+can use protobuf-maven-plugin :
+
+::
+
+ <build>
+ <extensions>
+ <extension>
+ <groupId>kr.motd.maven</groupId>
+ <artifactId>os-maven-plugin</artifactId>
+ <version>1.4.1.Final</version>
+ </extension>
+ </extensions>
+ <plugins>
+ <plugin>
+ <groupId>org.xolstice.maven.plugins</groupId>
+ <artifactId>protobuf-maven-plugin</artifactId>
+ <version>0.5.0</version>
+ <configuration>
+ <protocArtifact>com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}</protocArtifact>
+ <pluginId>grpc-java</pluginId>
+ <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>compile</goal>
+ <goal>compile-custom</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+| In order to run the gRPC server and the junit test, you need to download the Manven Ant Task library
+ from `here <https://mvnrepository.com/artifact/org.apache.maven/maven-ant-tasks/2.1.3>`__
+ and copy into ``[verigraph]/lib/``
+
+| Due to the fact that the project is intended for Eclipse, you need to
+ install an additional Eclipse plugin because
+ `m2e <https://www.eclipse.org/m2e/>`__ does not evaluate the extension
+ specified in a ``pom.xml``. `Download
+ ``os-maven-plugin-1.5.0.Final.jar`` <http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.5.0.Final/os-maven-plugin-1.5.0.Final.jar>`__
+ and put it into the ``<ECLIPSE_HOME>/plugins`` directory.
+| (As you might have noticed, ``os-maven-plugin`` is a Maven extension,
+ a Maven plugin, and an Eclipse plugin.)
+
+If you are using IntelliJ IDEA, you should not have any problem.
+
+If you are using other IDEs such as NetBeans, you need to set the system
+properties ``os-maven-plugin`` sets manually when your IDE is launched.
+You usually use JVM's ``-D`` flags like the following:
+
+ | -Dos.detected.name=linux
+ | -Dos.detected.arch=x86\_64
+ | -Dos.detected.classifier=linux-x86\_64
+
+Included files:
+---------------
+
+Here you can find a brief description about useful files for the gRPC
+interface:
+
+**src/main/java:**
+
+- *it.polito.grpc:*
+
+This package includes 2 classes that represent the client and server.
+
+ **Client.java:**
+
+ | Client of gRPC application. It implements all possible methods
+ necessary for communicate with server.
+ | It prints out the received response.
+ | Moreover it provides some static methods that are used for
+ creating the instances of requests.
+
+ **Service.java:**
+
+ | Server of gRPC application. It implements all possible methods
+ necessary for communicate with client.
+ | It saves the received request on log.
+ | This server could be accessed by multiple clients, because
+ synchronizes concurrent accesses.
+ | Each method that is possible to call is has the equivalent
+ operation in REST-interface.
+
+ **GrpcUtils.java:**
+
+ | This class provides some static methods that are used by
+ ``Service.java`` in order to translate a request into a class that
+ is accepted by Verigraph.
+ | Other methods are used to translate the class of Verigraph in the
+ proper gRPC response.
+ | These functionalities are exploited by test classes.
+ | Furthermore this set of methods is public, so in your application
+ you could call them, even if this should not be useful because
+ ``Client.java`` provides other high-level functions.
+
+- *it.polito.grpc.test:*
+
+ This package includes classes for testing the gRPC application.
+
+ **GrpcServerTest.java:**
+
+ | For each possible method we test if works correctly.
+ | We create a fake client (so this test doesn't use the method that
+ are present in client class) and test if it receives the expected
+ response.
+ | In a nutshell, it tests the methods of Client in case of a fake
+ server.
+ | Please notice that the test prints some errors but this is
+ intentional, because the program tests also error case.
+ | Indeed, not all methods are tested, because we have another class
+ (ReachabilityTest.java) that is specialized for testing the
+ verification method.
+
+ **GrpcTest.java:**
+
+ | This set of tests is intended to control the most common use
+ cases, in particular all methods that are callable in Client and
+ Service class, apart from verifyPolicy for the same reason as
+ before.
+ | It tries also to raise an exception and verify if the behavior is
+ as expected.
+
+ **MultiThreadTest.java:**
+
+ | This test creates multiple clients that connect to the server and
+ verify is the result is correct. These methods test the
+ synchronization on
+ | server-side.
+
+ **ReachabilityTest.java:**
+
+ | This file tests the verification method, it exploits the test case
+ already present in the project and consequently has the certainty
+ of testing not so simple case. In particular it reads the file in
+ "src/main/webapp/json" and use this as starting point.
+ | Some exceptions are thrown in order to verify if they are handled
+ in a correct way.
+
+**src/main/proto:**
+
+ **verigraph.proto:**
+
+ | File containing the description of the service. This includes the
+ definition of all classes used in the application.
+ | Moreover contains the definition of the methods that is possible
+ to call.
+ | Each possible method called by REST API is mapped on a proper gRPC
+ method.
+ | In case of error a message containing the reason is returned to
+ the client.
+ | More details are available in the section about Proto Buffer.
+
+**taget/generated-sources/protobuf/java:**
+
+- *io.grpc.verigraph:*
+
+ This package includes all classes generated from verigraph.proto by
+ means of protoc. For each object you can find 2 classes :
+
+ **{NameObject}Grpc.java**
+
+ **{NameObject}GrpcOrBuilder.java**
+
+ The first is the real implementation, the second is the
+ interface.
+
+**taget/generated-sources/protobuf/grpc-java:**
+
+- *io.grpc.verigraph:*
+
+ This package includes a single class generated from verigraph.proto
+ by means of protoc.
+
+ **VerigraphGrpc.java:**
+
+ This is useful in order to create the stubs that are necessary to
+ communicate both for client and server.
+
+**lib:**
+
+This folder includes a jar used for compiling the project with Ant.
+
+ \*\*maven-ant-tasks-2.1.3.\ jar:**
+
+ This file is used by build.xml in order to include the maven
+ dependencies.
+
+**pom.xml:**
+
+| Modified in order to add all necessary dependencies. It contains also
+ the build tag used for create the generated-sources folders.
+| This part is added according to documentation of gRPC for java as
+ explained above in How To Install section.
+| For further clarification go to `this
+ link <https://github.com/grpc/grpc-java/blob/master/README.md>`__.
+
+**build.xml:**
+
+This ant file permit to run and compile the program in a simple way, it
+exploits the maven-ant-tasks-2.1.3.jar already present in project.
+
+It contains 3 fundamental tasks for gRPC interface:
+
+- **build:** compile the program
+
+- **run:** run both client and server
+
+- **run-client :** run only client
+
+- **run-server :** run only server
+
+- **run-test :** launch all tests that are present in the package,
+ prints out the partial results and global result.
+
+Note that the execution of these tests may take up to 1-2 minutes when
+successful, according to your computer architecture.
+
+More Information About Proto Buffer:
+------------------------------------
+
+Further clarification about verigraph.proto:
+
+- A ``simple RPC`` where the client sends a request to the server using
+ the stub and waits for a response to come back, just like a normal
+ function call.
+
+ .. code:: xml
+
+ // Obtains a graph
+ rpc GetGraph (RequestID) returns (GraphGrpc) {}
+
+In this case we send a request that contains the id of the graph and the
+response is a Graph.
+
+- A ``server-side streaming RPC`` where the client sends a request to
+ the server and gets a stream to read a sequence of messages back. The
+ client reads from the returned stream until there are no more
+ messages. As you can see in our example, you specify a server-side
+ streaming method by placing the stream keyword before the response
+ type.
+
+ .. code:: xml
+
+
+ // Obtains a list of Nodes
+ rpc GetNodes (RequestID) returns (stream NodeGrpc) {}
+
+In this case we send a request that contains the id of the graph and the
+response is a list of Nodes that are inside graph.
+
+Further possibilities are available but in this project are not
+expolied. If you are curious see
+`here <http://www.grpc.io/docs/tutorials/basic/java.html#defining-the-service>`__.
+
+Our ``.proto`` file also contains protocol buffer message type
+definitions for all the request and response types used in our service
+methods - for example, hereÂ’s the ``RequestID`` message type:
+
+.. code:: xml
+
+ message RequestID {
+ int64 idGraph = 1;
+ int64 idNode = 2;
+ int64 idNeighbour = 3;
+ }
+
+The " = 1", " = 2" markers on each element identify the unique "tag"
+that field uses in the binary encoding. Tag numbers 1-15 require one
+less byte to encode than higher numbers, so as an optimization you can
+decide to use those tags for the commonly used or repeated elements,
+leaving tags 16 and higher for less-commonly used optional elements.
+Each element in a repeated field requires re-encoding the tag number, so
+repeated fields are particularly good candidates for this optimization.
+
+Protocol buffers are the flexible, efficient, automated solution to
+solve exactly the problem of serialization. With protocol buffers, you
+write a .proto description of the data structure you wish to store. From
+that, the protocol buffer compiler creates a class that implements
+automatic encoding and parsing of the protocol buffer data with an
+efficient binary format. The generated class provides getters and
+setters for the fields that make up a protocol buffer and takes care of
+the details of reading and writing the protocol buffer as a unit.
+Importantly, the protocol buffer format supports the idea of extending
+the format over time in such a way that the code can still read data
+encoded with the old format.
+
+::
+
+ syntax = "proto3";
+
+ package verigraph;
+
+ option java_multiple_files = true;
+ option java_package = "io.grpc.verigraph";
+ option java_outer_classname = "VerigraphProto";
+ ```
+
+This .proto file works for protobuf 3, that is slightly different from
+the version 2, so be careful if you have code already installed.
+
+The .proto file starts with a package declaration, which helps to
+prevent naming conflicts between different projects. In Java, the
+package name is used as the ``Java package`` unless you have explicitly
+specified a java\_package, as we have here. Even if you do provide a
+``java_package``, you should still define a normal ``package`` as well
+to avoid name collisions in the Protocol Buffers name space as well as
+in non-Java languages.
+
+| After the package declaration, you can see two options that are
+ Java-specific: ``java_package`` and ``java_outer_classname``.
+ ``java_package`` specifies in what Java package name your generated
+ classes should live. If you don't specify this explicitly, it simply
+ matches the package name given by the package declaration, but these
+ names usually aren't appropriate Java package names (since they
+ usually don't start with a domain name). The ``java_outer_classname``
+ option defines the class name which should contain all of the classes
+ in this file. If you don't give a ``java_outer_classname explicitly``,
+ it will be generated by converting the file name to camel case. For
+ example, "my\_proto.proto" would, by default, use "MyProto" as the
+ outer class name.
+| In this case this file is not generated, because
+ ``java_multiple_files`` option is true, so for each message we
+ generate a different class.
+
+For further clarifications see
+`here <https://developers.google.com/protocol-buffers/docs/javatutorial>`__
+
+Notes
+-----
+
+For gRPC interface you need that neo4jmanager service is already
+deployed, so if this is not the case, please follow the instructions at
+this
+`link <https://github.com/netgroup-polito/verigraph/blob/a3c008a971a8b16552a20bf2484ebf8717735dd6/README.md>`__.
+
+In this version there are some modified files compared to the original
+`Verigraph project <https://github.com/netgroup-polito/verigraph>`__
+
+**it.polito.escape.verify.service.NodeService:**
+
+At line 213 we modified the path, because this service is intended to
+run not only in container, as Tomcat, so we added other possibility that
+files is placed in src/main/webapp/json/ folder.
+
+**it.polito.escape.verify.service.VerificationService:**
+
+In the original case it searches for python files in "webapps" folder,
+that is present if the service is deployed in a container, but absent
+otherwise. So we added another string that will be used in the case the
+service doesn't run in Tomcat.
+
+**it.polito.escape.verify.databese.DatabaseClass:**
+
+Like before we added the possibility that files are not in "webapps"
+folder, so is modified in order to run in any environment. Modification
+in method loadDataBase() and persistDatabase().
+
+| Pay attention that Python is needed for the project. If it is not
+ already present on your computer, please `download
+ it <https://www.python.org/download/releases/2.7.3/>`__.
+| It works fine with Python 2.7.3, or in general Python 2.
+
+| If you have downloaded a Python version for 64-bit architecture please
+ copy the files in "service/z3\_64" and paste in "service/build" and
+ substitute them,
+| because this project works with Python for 32-bit architecture.
+
+Python and Z3 must support the same architetcure.
+
+Moreover you need the following dependencies installed on your python
+distribution:
+
+- "requests" python package ->
+http://docs.python-requests.org/en/master/
+
+- "jsonschema" python package -> https://pypi.python.org/pypi/jsonschema
+
+| HINT - to install a package you can raise the following command (Bash
+ on Linux or DOS shell on Windows): python -m pip install jsonschema
+ python -m pip install requests
+| Pay attention that it is possible that you have to modify the PATH
+ environment variable because is necessary to address the python
+ folder, used for verification phase.
+
+Remember to read the
+`README.rtf <https://gitlab.com/serena.spinoso/DP2.2017.SpecialProject2.gRPC/tree/master>`__
+and to follow the instructions in order to deploy the Verigraph service.
+
+| In the latest version of Maven there is the possibility that the
+ downloaded files are incompatible with Java Version of the project
+ (1.8).
+| In this case you have to modify the file ``hk2-parent-2.4.0-b31.pom``
+ under your local Maven repository (e.g.
+ 'C:\\Users\\Standard.m2\\repository')
+| and in the path ``\org\glassfish\hk2\hk2-parent\2.4.0-b31`` find the
+ file and modify at line 1098 (in section ``profile``) the ``jdk``
+ version to ``[1.8,)`` .
+
+| Admittedly, the version that is supported by the downloaded files from
+ Maven Dependencies is incompatible with jdk of the project.
+| So modify the file ``gson-2.3.pom`` in Maven repository, under
+ ``com\google\code\gson\gson\2.3`` directory, in particular line 91,
+ from ``[1.8,`` to ``[1.8,)``.
+
+This project was also tested on Linux Ubuntu 15.10.
diff --git a/verigraph/src/main/java/it/polito/grpc/Service.java b/verigraph/src/main/java/it/polito/grpc/Service.java
new file mode 100644
index 0000000..8a77d05
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/Service.java
@@ -0,0 +1,462 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+import io.grpc.stub.StreamObserver;
+import io.grpc.verigraph.ConfigurationGrpc;
+import io.grpc.verigraph.GetRequest;
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NeighbourGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.NewNeighbour;
+import io.grpc.verigraph.NewNode;
+import io.grpc.verigraph.NodeGrpc;
+import io.grpc.verigraph.Policy;
+import io.grpc.verigraph.RequestID;
+import io.grpc.verigraph.Status;
+import io.grpc.verigraph.VerificationGrpc;
+import io.grpc.verigraph.VerigraphGrpc;
+import it.polito.escape.verify.exception.BadRequestException;
+import it.polito.escape.verify.exception.DataNotFoundException;
+import it.polito.escape.verify.exception.ForbiddenException;
+import it.polito.escape.verify.model.Configuration;
+import it.polito.escape.verify.model.Graph;
+import it.polito.escape.verify.model.Neighbour;
+import it.polito.escape.verify.model.Node;
+import it.polito.escape.verify.model.Verification;
+import it.polito.escape.verify.resources.beans.VerificationBean;
+import it.polito.escape.verify.service.GraphService;
+import it.polito.escape.verify.service.NeighbourService;
+import it.polito.escape.verify.service.NodeService;
+import it.polito.escape.verify.service.VerificationService;
+
+public class Service {
+ /** Port on which the server should run. */
+ private static final Logger logger = Logger.getLogger(Service.class.getName());
+ private static final int port = 50051;
+ private static final String internalError = "Internal Server Error";
+ private Server server;
+ private GraphService graphService = new GraphService();
+ private VerificationService verificationService = new VerificationService();
+ private NodeService nodeService = new NodeService();
+ private NeighbourService neighboursService = new NeighbourService();
+
+ public Service(int port) {
+ this(ServerBuilder.forPort(port), port);
+ }
+
+ /** Create a RouteGuide server using serverBuilder as a base and features as data. */
+ public Service(ServerBuilder<?> serverBuilder, int port) {
+ server = serverBuilder.addService(new VerigraphImpl())
+ .build();
+ }
+
+ public void start() throws IOException {
+ server.start();
+ logger.info("Server started, listening on "+ port);
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+ logger.info("*** Shutting down gRPC server since JVM is shutting down");
+ Service.this.stop();
+ logger.info("*** Server shut down");
+ }
+ });
+ }
+
+ public void stop() {
+ if (server != null) {
+ server.shutdown();
+ }
+ }
+
+ private void blockUntilShutdown() throws InterruptedException {
+ if (server != null) {
+ server.awaitTermination();
+ }
+ }
+
+ /** Main function to launch server from cmd. */
+ public static void main(String[] args) throws IOException, InterruptedException {
+ try{
+ Service server = new Service(port);
+ server.start();
+ server.blockUntilShutdown();
+ }
+ catch(Exception ex){
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ }
+
+ /**Here start method of my impementation*/
+ private class VerigraphImpl extends VerigraphGrpc.VerigraphImplBase{
+
+ /** Here start methods of GraphResource*/
+ @Override
+ public void getGraphs(GetRequest request, StreamObserver<GraphGrpc> responseObserver) {
+ try{
+ for(Graph item : graphService.getAllGraphs()) {
+ GraphGrpc gr = GrpcUtils.obtainGraph(item);
+ responseObserver.onNext(gr);
+ }
+ }catch(Exception ex){
+ GraphGrpc nr = GraphGrpc.newBuilder().setErrorMessage(internalError).build();
+ responseObserver.onNext(nr);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void createGraph(GraphGrpc request, StreamObserver<NewGraph> responseObserver) {
+ NewGraph.Builder response = NewGraph.newBuilder();
+ try{
+ Graph graph = GrpcUtils.deriveGraph(request);
+ Graph newGraph = graphService.addGraph(graph);
+ response.setSuccess(true).setGraph(GrpcUtils.obtainGraph(newGraph));
+ }catch(BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void deleteGraph(RequestID request, StreamObserver<Status> responseObserver) {
+
+ Status.Builder response = Status.newBuilder();
+ try{
+ graphService.removeGraph(request.getIdGraph());
+ response.setSuccess(true);
+ }catch(ForbiddenException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ } catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void getGraph(RequestID request, StreamObserver<GraphGrpc> responseObserver) {
+ try{
+ Graph graph = graphService.getGraph(request.getIdGraph());
+ GraphGrpc gr = GrpcUtils.obtainGraph(graph);
+ responseObserver.onNext(gr);
+ }catch(ForbiddenException | DataNotFoundException ex){
+ GraphGrpc grError = GraphGrpc.newBuilder().setErrorMessage(ex.getMessage()).build();
+ responseObserver.onNext(grError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ GraphGrpc grError = GraphGrpc.newBuilder().setErrorMessage(internalError).build();
+ responseObserver.onNext(grError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void updateGraph(GraphGrpc request, StreamObserver<NewGraph> responseObserver) {
+ NewGraph.Builder response = NewGraph.newBuilder();
+ try{
+ Graph graph = GrpcUtils.deriveGraph(request);
+ graph.setId(request.getId());
+ Graph newGraph = graphService.updateGraph(graph);
+ response.setSuccess(true).setGraph(GrpcUtils.obtainGraph(newGraph));
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void verifyPolicy(Policy request, StreamObserver<VerificationGrpc> responseObserver) {
+
+ VerificationGrpc.Builder verification;
+ try{
+ //Convert request
+ VerificationBean verify = new VerificationBean();
+ verify.setDestination(request.getDestination());
+ verify.setSource(request.getSource());
+ verify.setType(request.getType().toString());
+ verify.setMiddlebox(request.getMiddlebox());
+
+ //Convert Response
+ Verification ver = verificationService.verify(request.getIdGraph(), verify);
+ verification = VerificationGrpc.newBuilder(GrpcUtils.obtainVerification(ver))
+ .setSuccessOfOperation(true);
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ verification = VerificationGrpc.newBuilder().setSuccessOfOperation(false)
+ .setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ } catch(Exception ex){
+ verification = VerificationGrpc.newBuilder().setSuccessOfOperation(false)
+ .setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(verification.build());
+ responseObserver.onCompleted();
+ }
+
+ /** Here start methods of NodeResource*/
+
+ @Override
+ public void getNodes(RequestID request, StreamObserver<NodeGrpc> responseObserver) {
+ try{
+ for (Node item : nodeService.getAllNodes(request.getIdGraph())) {
+ NodeGrpc nr = GrpcUtils.obtainNode(item);
+ responseObserver.onNext(nr);
+ }
+ }catch(ForbiddenException | DataNotFoundException ex){
+ NodeGrpc nr = NodeGrpc.newBuilder().setErrorMessage(ex.getMessage()).build();
+ responseObserver.onNext(nr);
+ logger.log(Level.WARNING, ex.getMessage());
+ } catch(Exception ex){
+ NodeGrpc nr = NodeGrpc.newBuilder().setErrorMessage(internalError).build();
+ responseObserver.onNext(nr);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void createNode(NodeGrpc request, StreamObserver<NewNode> responseObserver) {
+ NewNode.Builder response = NewNode.newBuilder();
+ try{
+ Node node = GrpcUtils.deriveNode(request);
+ Node newNode = nodeService.addNode(request.getIdGraph(), node);
+ response.setSuccess(true).setNode(GrpcUtils.obtainNode(newNode));
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void deleteNode(RequestID request, StreamObserver<Status> responseObserver) {
+ Status.Builder response = Status.newBuilder();
+ try{
+ nodeService.removeNode(request.getIdGraph(), request.getIdNode());
+ response.setSuccess(true);
+ }catch(ForbiddenException | DataNotFoundException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void getNode(RequestID request, StreamObserver<NodeGrpc> responseObserver) {
+ NodeGrpc nr;
+ try{
+ Node node = nodeService.getNode(request.getIdGraph(), request.getIdNode());
+ nr= GrpcUtils.obtainNode(node);
+ }catch(ForbiddenException | DataNotFoundException ex){
+ nr = NodeGrpc.newBuilder().setErrorMessage(ex.getMessage()).build();
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ nr = NodeGrpc.newBuilder().setErrorMessage(internalError).build();
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(nr);
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void updateNode(NodeGrpc request, StreamObserver<NewNode> responseObserver) {
+ NewNode.Builder response = NewNode.newBuilder();
+ try{
+ Node node = GrpcUtils.deriveNode(request);
+ node.setId(request.getId());
+ Node newNode = nodeService.updateNode(request.getIdGraph(), node);
+ response.setSuccess(true).setNode(GrpcUtils.obtainNode(newNode));
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void configureNode(ConfigurationGrpc request, StreamObserver<Status> responseObserver) {
+ Status.Builder response = Status.newBuilder();
+ try{
+ if (request.getIdGraph() <= 0) {
+ throw new ForbiddenException("Illegal graph id: " + request.getIdGraph());
+ }
+ if (request.getIdNode() <= 0) {
+ throw new ForbiddenException("Illegal node id: " + request.getIdNode());
+ }
+ Graph graph = new GraphService().getGraph(request.getIdGraph());
+ if (graph == null){
+ throw new BadRequestException("Graph with id " + request.getIdGraph() + " not found");
+ }
+ Node node = nodeService.getNode(request.getIdGraph(), request.getIdNode());
+ if (node == null){
+ throw new BadRequestException("Node with id " + request.getIdNode() + " not found in graph with id " + request.getIdGraph());
+ }
+ Configuration nodeConfiguration = GrpcUtils.deriveConfiguration(request);
+ Node nodeCopy = new Node();
+ nodeCopy.setId(node.getId());
+ nodeCopy.setName(node.getName());
+ nodeCopy.setFunctional_type(node.getFunctional_type());
+ Map<Long,Neighbour> nodes = new HashMap<Long,Neighbour>();
+ nodes.putAll(node.getNeighbours());
+ nodeCopy.setNeighbours(nodes);
+ nodeConfiguration.setId(nodeCopy.getName());
+ nodeCopy.setConfiguration(nodeConfiguration);
+
+ Graph graphCopy = new Graph();
+ graphCopy.setId(graph.getId());
+ graphCopy.setNodes(new HashMap<Long, Node>(graph.getNodes()));
+ graphCopy.getNodes().remove(node.getId());
+
+ NodeService.validateNode(graphCopy, nodeCopy);
+
+ graph.getNodes().put(request.getIdNode(), nodeCopy);
+ response.setSuccess(true);
+ }catch(ForbiddenException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ /** Here start methods of NeighbourResource*/
+ @Override
+ public void getNeighbours(RequestID request, StreamObserver<NeighbourGrpc> responseObserver) {
+ try{
+ for(Neighbour item : neighboursService.getAllNeighbours(request.getIdGraph(), request.getIdNode())) {
+ NeighbourGrpc nr = GrpcUtils.obtainNeighbour(item);
+ responseObserver.onNext(nr);
+ }
+ }catch(ForbiddenException | DataNotFoundException ex){
+ NeighbourGrpc nr = NeighbourGrpc.newBuilder().setErrorMessage(ex.getMessage()).build();
+ responseObserver.onNext(nr);
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ NeighbourGrpc nr = NeighbourGrpc.newBuilder().setErrorMessage(internalError).build();
+ responseObserver.onNext(nr);
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void createNeighbour(NeighbourGrpc request, StreamObserver<NewNeighbour> responseObserver) {
+ NewNeighbour.Builder response = NewNeighbour.newBuilder();
+ try{
+ Neighbour neighbour = GrpcUtils.deriveNeighbour(request);
+ Neighbour newNeighbour = neighboursService.addNeighbour(request.getIdGraph(), request.getIdNode(), neighbour);
+ response.setSuccess(true).setNeighbour(GrpcUtils.obtainNeighbour(newNeighbour));
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void deleteNeighbour(RequestID request, StreamObserver<Status> responseObserver) {
+ Status.Builder response = Status.newBuilder();
+ try{
+ neighboursService.removeNeighbour(request.getIdGraph(), request.getIdNode(), request.getIdNeighbour());
+ response.setSuccess(true);
+ }catch(ForbiddenException | DataNotFoundException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void getNeighbour(RequestID request, StreamObserver<NeighbourGrpc> responseObserver) {
+ NeighbourGrpc nr;
+ try{
+ Neighbour neighbour = neighboursService.getNeighbour(request.getIdGraph(),
+ request.getIdNode(), request.getIdNeighbour());
+ nr = GrpcUtils.obtainNeighbour(neighbour);
+
+ }catch(ForbiddenException | DataNotFoundException ex){
+ nr = NeighbourGrpc.newBuilder().setErrorMessage(ex.getMessage()).build();
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ nr = NeighbourGrpc.newBuilder().setErrorMessage(internalError).build();
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(nr);
+ responseObserver.onCompleted();
+ }
+
+ @Override
+ public void updateNeighbour(NeighbourGrpc request, StreamObserver<NewNeighbour> responseObserver) {
+ NewNeighbour.Builder response = NewNeighbour.newBuilder();
+ try{
+ Neighbour neighbour = GrpcUtils.deriveNeighbour(request);
+ neighbour.setId(request.getId());
+ Neighbour newNeighbour = neighboursService.updateNeighbour(request.getIdGraph(), request.getIdNode(), neighbour);
+ response.setSuccess(true).setNeighbour(GrpcUtils.obtainNeighbour(newNeighbour));
+ }catch(ForbiddenException | DataNotFoundException | BadRequestException ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(ex.getMessage());
+ logger.log(Level.WARNING, ex.getMessage());
+ }
+ responseObserver.onNext(response.build());
+ responseObserver.onCompleted();
+ }
+ }
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/test/GrpcServerTest.java b/verigraph/src/main/java/it/polito/grpc/test/GrpcServerTest.java
new file mode 100644
index 0000000..7344447
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/test/GrpcServerTest.java
@@ -0,0 +1,292 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc.test;
+
+import static org.junit.Assert.assertEquals;
+
+import io.grpc.ManagedChannel;
+import io.grpc.inprocess.InProcessChannelBuilder;
+import io.grpc.inprocess.InProcessServerBuilder;
+import io.grpc.verigraph.ConfigurationGrpc;
+import io.grpc.verigraph.GetRequest;
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NeighbourGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.NewNeighbour;
+import io.grpc.verigraph.NewNode;
+import io.grpc.verigraph.NodeGrpc;
+import io.grpc.verigraph.NodeGrpc.FunctionalType;
+import io.grpc.verigraph.RequestID;
+import io.grpc.verigraph.Status;
+import io.grpc.verigraph.VerigraphGrpc;
+import it.polito.grpc.Client;
+import it.polito.grpc.Service;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.FixMethodOrder;
+import org.junit.runners.MethodSorters;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * Unit tests for {@link Service}.
+ * For testing basic gRPC unit test only.
+ * Not intended to provide a high code coverage or to test every major usecase.
+ */
+@RunWith(JUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class GrpcServerTest {
+ private Service server;
+ private ManagedChannel inProcessChannel;
+
+ @Before
+ public void setUp() throws Exception {
+ String uniqueServerName = "in-process server for " + getClass();
+ // use directExecutor for both InProcessServerBuilder and InProcessChannelBuilder can reduce the
+ // usage timeouts and latches in test. But we still add timeout and latches where they would be
+ // needed if no directExecutor were used, just for demo purpose.
+ server = new Service(InProcessServerBuilder.forName(uniqueServerName).directExecutor(),0);
+ server.start();
+ inProcessChannel = InProcessChannelBuilder.forName(uniqueServerName).directExecutor().build();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ inProcessChannel.shutdownNow();
+ server.stop();
+ }
+
+ @Test
+ public void test1Graph() throws Exception {
+ RequestID request = RequestID.newBuilder().setIdGraph(1).build() ;//id not present
+ GraphGrpc ufoundedGraph = GraphGrpc.newBuilder()
+ .setErrorMessage("Graph with id 1 not found").build();
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ // graph not found in the server
+ GraphGrpc graph = stub.getGraph(request);
+
+ assertEquals(ufoundedGraph, graph);
+
+ // getGraph in the server, but first add it
+ GraphGrpc addedGraph = GraphGrpc.newBuilder().build();
+ NewGraph response = stub.createGraph(addedGraph);
+ addedGraph = response.getGraph();
+ request = RequestID.newBuilder().setIdGraph(1).build() ;
+ graph = stub.getGraph(request);
+
+ assertEquals(addedGraph.getId(), graph.getId());
+
+ //updateGraph
+ GraphGrpc updatedGraph = GraphGrpc.newBuilder().setId(response.getGraph().getId()).build();
+ response = stub.updateGraph(updatedGraph);
+
+ assertEquals(response.getSuccess(),true);
+ }
+
+ @Test
+ public void test2Graphs() throws Exception {
+ // setup
+ GetRequest request = GetRequest.newBuilder().build();
+ GraphGrpc g1 = GraphGrpc.newBuilder().build();
+ GraphGrpc g2 = GraphGrpc.newBuilder().build();
+ GraphGrpc g3 = GraphGrpc.newBuilder().build();
+ GraphGrpc g4 = GraphGrpc.newBuilder().build();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ stub.createGraph(g1);
+ stub.createGraph(g2);
+ stub.createGraph(g3);
+ stub.createGraph(g4);
+ g1 = GraphGrpc.newBuilder(g1).setId(1).build();
+ g2 = GraphGrpc.newBuilder(g2).setId(2).build();
+ g3 = GraphGrpc.newBuilder(g3).setId(3).build();
+ g4 = GraphGrpc.newBuilder(g4).setId(4).build();
+ // run
+ Iterator<GraphGrpc> graphs = stub.getGraphs(request);
+
+ assertEquals(graphs.next(), g1);
+ assertEquals(graphs.next(), g2);
+ assertEquals(graphs.next(), g3);
+ assertEquals(graphs.next(), g4);
+
+ //deleteGraph
+ RequestID req = RequestID.newBuilder().setIdGraph(g1.getId()).build();
+ stub.deleteGraph(req);
+ // run
+ graphs = stub.getGraphs(request);
+
+ assertEquals(graphs.next(), g2);
+ assertEquals(graphs.next(), g3);
+ assertEquals(graphs.next(), g4);
+ }
+
+ @Test
+ public void test3Node() throws Exception {
+ RequestID request = RequestID.newBuilder().setIdGraph(2).setIdNode(1).build() ;//id not present
+ NodeGrpc ufoundedGraph = NodeGrpc.newBuilder()
+ .setErrorMessage("Node with id 1 not found in graph with id 2").build();
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ // graph not found in the server
+ NodeGrpc node = stub.getNode(request);
+
+ assertEquals(ufoundedGraph, node);
+
+ // graph found in the server, but first add it
+ NodeGrpc addedNode = NodeGrpc.newBuilder().setName("client").setIdGraph(2)
+ .setFunctionalType(FunctionalType.endhost).build();
+ NewNode response = stub.createNode(addedNode);
+ addedNode = response.getNode();
+ request = RequestID.newBuilder().setIdGraph(2).setIdNode(1).build() ;
+ node = stub.getNode(request);
+
+ assertEquals(addedNode.getId(), node.getId());
+ assertEquals(addedNode.getName(),"client");
+
+ //updateNode
+ NodeGrpc updatedNode = NodeGrpc.newBuilder().setName("Nodo2").setIdGraph(2).setId(1)
+ .setFunctionalType(FunctionalType.endhost).build();
+ response = stub.updateNode(updatedNode);
+
+ assertEquals(response.getSuccess(),true);
+ assertEquals(response.getNode().getName(),"Nodo2");
+
+ //configureNode
+ Map<String,String> params = new HashMap<String,String>();
+ params.put("url", "www.facebook.com");
+ params.put("body", "word");
+ params.put("destination","server");
+ params.put("protocol", "HTTP_REQUEST");
+ ConfigurationGrpc configuration = Client.createConfigurationGrpc(params, null, null, null);
+ ConfigurationGrpc config = ConfigurationGrpc.newBuilder(configuration).setIdGraph(2)
+ .setIdNode(1).build();
+
+ Status status = stub.configureNode(config);
+
+ assertEquals(status.getSuccess(),true);
+ }
+
+ @Test
+ public void test4Nodes() throws Exception {
+ // setup
+ RequestID request = RequestID.newBuilder().setIdGraph(2).build();
+ NodeGrpc n1 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node5", "endhost", null, null))
+ .setIdGraph(2).build();
+ NodeGrpc n2 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node3", "endhost", null, null))
+ .setIdGraph(2).build();
+ NodeGrpc n3 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node4", "endhost", null, null))
+ .setIdGraph(2).build();
+ NodeGrpc n4 = NodeGrpc.newBuilder(Client.createNodeGrpc("client", "endhost", null, null))
+ .setIdGraph(2).build();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ stub.createNode(n1);
+ stub.createNode(n2);
+ stub.createNode(n3);
+ stub.createNode(n4);
+ n1 = NodeGrpc.newBuilder(n1).setId(2).setIdGraph(0).build();
+ n2 = NodeGrpc.newBuilder(n2).setId(3).setIdGraph(0).build();
+ n3 = NodeGrpc.newBuilder(n3).setId(4).setIdGraph(0).build();
+ n4 = NodeGrpc.newBuilder(n4).setId(5).setIdGraph(0).build();
+ // run
+ Iterator<NodeGrpc> nodes = stub.getNodes(request);
+
+ nodes.next();
+ assertEquals(nodes.next(), n1);
+ assertEquals(nodes.next(), n2);
+ assertEquals(nodes.next(), n3);
+ assertEquals(nodes.next(), n4);
+
+ //deleteNode
+ RequestID req = RequestID.newBuilder().setIdGraph(2).setIdNode(1).build();
+ stub.deleteNode(req);
+ // run
+ nodes = stub.getNodes(request);
+
+ assertEquals(nodes.next(), n1);
+ assertEquals(nodes.next(), n2);
+ assertEquals(nodes.next(), n3);
+ assertEquals(nodes.next(), n4);
+ }
+
+ @Test
+ public void test5Neighbours() throws Exception {
+ RequestID request = RequestID.newBuilder().setIdGraph(2).setIdNode(2).setIdNeighbour(1).build() ;//id not present
+ NeighbourGrpc ufoundedNeighbour = NeighbourGrpc.newBuilder()
+ .setErrorMessage("Neighbour with id 1 not found for node with id 2 in graph with id 2").build();;
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ // Neighbour not found in the server
+ NeighbourGrpc neighbour = stub.getNeighbour(request);
+
+ assertEquals(ufoundedNeighbour, neighbour);
+
+ // getNeighbour, but first add it
+ NeighbourGrpc addedNeighbour = NeighbourGrpc.newBuilder().setIdGraph(2).setIdNode(2)
+ .setName("client").build();
+ NewNeighbour response = stub.createNeighbour(addedNeighbour);
+ addedNeighbour = response.getNeighbour();
+ request = RequestID.newBuilder().setIdGraph(2).setIdNode(2)
+ .setIdNeighbour(addedNeighbour.getId()).build();
+ neighbour = stub.getNeighbour(request);
+
+ assertEquals(addedNeighbour.getId(), neighbour.getId());
+
+ //updateNeighbour
+ NeighbourGrpc updatedNeighbour = Client.createNeighbourGrpc("Node4");
+ NeighbourGrpc nu = NeighbourGrpc.newBuilder(updatedNeighbour)
+ .setId(response.getNeighbour().getId()).setIdGraph(2).setIdNode(2).build();
+ response = stub.updateNeighbour(nu);
+
+ assertEquals(response.getSuccess(),true);
+ assertEquals(response.getNeighbour().getName(),"Node4");
+ }
+
+ @Test
+ public void test6Neighbours() throws Exception {
+ // setup
+ RequestID request = RequestID.newBuilder().setIdGraph(2).setIdNode(2).build();
+ NeighbourGrpc n1 = NeighbourGrpc.newBuilder().setIdGraph(2).setIdNode(2)
+ .setName("Node3").build();
+ NeighbourGrpc n2 = NeighbourGrpc.newBuilder().setIdGraph(2).setIdNode(2)
+ .setName("client").build();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ stub.createNeighbour(n1);
+ stub.createNeighbour(n2);
+ n1 = NeighbourGrpc.newBuilder(n1).setId(2).setIdGraph(0).setIdNode(0).build();
+ n2 = NeighbourGrpc.newBuilder(n2).setId(3).setIdGraph(0).setIdNode(0).build();
+ // run
+ Iterator<NeighbourGrpc> neighbours = stub.getNeighbours(request);
+
+ neighbours.next();
+ assertEquals(neighbours.next(), n1);
+ assertEquals(neighbours.next(), n2);
+
+ //deleteNeighbour
+ RequestID req = RequestID.newBuilder().setIdGraph(2).setIdNode(2).setIdNeighbour(1).build();
+ stub.deleteNeighbour(req);
+ // run
+ neighbours = stub.getNeighbours(request);
+
+ assertEquals(neighbours.next(), n1);
+ assertEquals(neighbours.next(), n2);
+ }
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/test/GrpcTest.java b/verigraph/src/main/java/it/polito/grpc/test/GrpcTest.java
new file mode 100644
index 0000000..41f9cad
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/test/GrpcTest.java
@@ -0,0 +1,349 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.junit.runners.MethodSorters;
+
+import io.grpc.verigraph.ConfigurationGrpc;
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NeighbourGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.NewNeighbour;
+import io.grpc.verigraph.NewNode;
+import io.grpc.verigraph.NodeGrpc;
+import it.polito.grpc.Client;
+import it.polito.grpc.Service;
+
+@RunWith(JUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class GrpcTest {
+ private Service server;
+ private Client client;
+
+ @Before
+ public void setUpBeforeClass() throws Exception {
+ client = new Client("localhost" , 50051);
+ server = new Service(50051);
+ server.start();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ server.stop();
+ client.shutdown();
+ }
+
+ // method for comparing two non-null strings
+ private void compareString(String rs, String ts, String meaning) {
+ assertNotNull("NULL "+meaning, ts);
+ assertEquals("Wrong "+meaning, rs, ts);
+ }
+
+ @Test
+ public final void test1Load() throws Exception{
+ String funcType1 = "vpnaccess";
+ String funcType2 = "vpnexit";
+
+ // load an existing graph with 2 nodes
+ Map<String,String> map = new HashMap<String,String>();
+ map.put("vpnexit", "Node2");
+ ConfigurationGrpc conf = Client.createConfigurationGrpc(map, null, null, null);
+ NodeGrpc node1 = Client.createNodeGrpc("Node1", funcType1, null, conf);
+ List<NeighbourGrpc> neighbours = new ArrayList<NeighbourGrpc>();
+ NeighbourGrpc nb = Client.createNeighbourGrpc("Node1");
+ neighbours.add(nb);
+ map.clear();
+ map.put("vpnaccess", "Node1");
+ conf = Client.createConfigurationGrpc(map, null, null, null);
+ NodeGrpc node2 = Client.createNodeGrpc("Node2", funcType2, neighbours, conf);
+ List<NodeGrpc> nodes = new ArrayList<NodeGrpc>();
+ nodes.add(node1);
+ nodes.add(node2);
+ GraphGrpc graph = Client.createGraphGrpc(nodes);
+ //createGraph
+ graph = client.createGraph(graph).getGraph();
+
+ //getGraph
+ GraphGrpc retreivedGraph = client.getGraph(graph.getId());
+
+ assertNotNull("NULL Graph ",retreivedGraph);
+ assertEquals(graph.getId(), retreivedGraph.getId());
+
+ // check the name of first node and the id
+ compareString(retreivedGraph.getNodeList().get(0).getName(), graph.getNodeList().get(0).getName(), "node name");
+ assertEquals(retreivedGraph.getNodeList().get(0).getId(), graph.getNodeList().get(0).getId());
+
+ // check the name of second node and the id
+ compareString(retreivedGraph.getNodeList().get(1).getName(), graph.getNodeList().get(1).getName(), "node name");
+ assertEquals(retreivedGraph.getNodeList().get(1).getId(), graph.getNodeList().get(1).getId());
+
+ //updateGraph
+ GraphGrpc updatedGraph = GraphGrpc.newBuilder().build();
+ NewGraph response = client.updateGraph(graph.getId(),updatedGraph);
+
+ assertEquals(response.getSuccess(),true);
+ }
+
+ @Test
+ public final void test2LoadWithError() throws Exception{
+ // try to load a graph with node without functionalType
+ NodeGrpc node = null;
+ try{
+ node = Client.createNodeGrpc("Node1", null, null, null);
+ fail( "createNodeGrpc didn't throw when I expected it to" );
+ }
+ catch(Exception ex){
+ }
+ List<NodeGrpc> nodes = new ArrayList<NodeGrpc>();
+ if(node != null)
+ nodes.add(node);
+
+ GraphGrpc graph = Client.createGraphGrpc(nodes);
+ graph = client.createGraph(graph).getGraph();
+
+ assertEquals(graph.getId(), 2);
+
+ //getGraphs
+ Iterator<GraphGrpc> graphs = client.getGraphs().iterator();
+
+ assertEquals(graphs.next().getId(), 1);
+ assertEquals(graphs.next(), graph);
+
+ //deleteGraph
+ boolean resp= client.deleteGraph(graph.getId());
+ assertEquals(resp, true);
+
+ List<GraphGrpc> listGraphs = client.getGraphs();
+
+ assertEquals(listGraphs.size(), 1);
+ assertEquals(listGraphs.get(0).getId(), 1);
+ }
+
+ @Test
+ public void test3Node() throws Exception {
+ NodeGrpc ufoundedGraph = NodeGrpc.newBuilder()
+ .setErrorMessage("Node with id 1 not found in graph with id 1").build();
+
+ // graph not found in the server
+ NodeGrpc node = client.getNode(1, 1);//id not present
+
+ assertEquals(ufoundedGraph, node);
+
+ // graph found in the server, but first add it
+ NodeGrpc addedNode = Client.createNodeGrpc("Node4", "firewall", null, null);
+ NewNode response = client.createNode(addedNode, 1);
+ addedNode = response.getNode();
+ node = client.getNode(1, 1);
+
+ assertEquals(addedNode.getId(), node.getId());
+
+ //updateNode
+ NodeGrpc updatedNode = Client.createNodeGrpc("Node9", "endhost", null, null);
+ response = client.updateNode(1, addedNode.getId(), updatedNode);
+
+ assertEquals(response.getSuccess(),true);
+
+ //configureNode
+ //this configuration is valid only on endhost!
+ Map<String,String> params = new HashMap<String,String>();
+ params.put("url", "www.facebook.com");
+ params.put("body", "word");
+ params.put("destination","server");
+ params.put("protocol", "HTTP_REQUEST");
+ ConfigurationGrpc configuration = Client.createConfigurationGrpc(params, null, null, null);
+
+ boolean status = client.configureNode(1, 1, configuration);
+
+ assertEquals(status,true);
+ }
+
+ @Test
+ public void test4Nodes() throws Exception {
+ // setup
+ GraphGrpc graph = Client.createGraphGrpc(null);
+ //createGraph
+ graph = client.createGraph(graph).getGraph();
+
+ List<NeighbourGrpc> neighbours = new ArrayList<NeighbourGrpc>();
+ NeighbourGrpc nb = Client.createNeighbourGrpc("Node6");
+ neighbours.add(nb);
+ NodeGrpc n1 = Client.createNodeGrpc("Node6", "mailserver", null, null);
+ NodeGrpc n2 = Client.createNodeGrpc("Node9", "endhost", neighbours, null);
+ Map<String,String> map = new HashMap<String,String>();
+ map.put("mailserver", "Node6");
+ ConfigurationGrpc conf = Client.createConfigurationGrpc(map, null, null, null);
+ NodeGrpc n3 = Client.createNodeGrpc("Node10", "mailclient", null, conf);
+ NodeGrpc n4 = Client.createNodeGrpc("Node11", "nat", null, null);
+
+ NewNode nw1 = client.createNode(n1, graph.getId());
+ NewNode nw2 = client.createNode(n2, graph.getId());
+ NewNode nw3 = client.createNode(n3, graph.getId());
+ NewNode nw4 = client.createNode(n4, graph.getId());
+ assertEquals(nw1.getSuccess(),true);
+ assertEquals(nw2.getSuccess(),true);
+ assertEquals(nw3.getSuccess(),true);
+ assertEquals(nw4.getSuccess(),true);
+ n1 = NodeGrpc.newBuilder(n1).setId(nw1.getNode().getId()).build();
+ n2 = NodeGrpc.newBuilder(n2).setId(nw2.getNode().getId()).build();
+ n3 = NodeGrpc.newBuilder(n3).setId(nw3.getNode().getId()).build();
+ n4 = NodeGrpc.newBuilder(n4).setId(nw4.getNode().getId()).build();
+
+ // getNodes
+ Iterator<NodeGrpc> nodes = client.getNodes(graph.getId()).iterator();
+
+ assertEquals(nodes.next().getName(), n1.getName());
+ assertEquals(nodes.next().getName(), n2.getName());
+ assertEquals(nodes.next().getName(), n3.getName());
+ assertEquals(nodes.next().getName(), n4.getName());
+
+ //deleteNode
+ client.deleteNode(graph.getId(), 1);
+ // run
+ nodes = client.getNodes(graph.getId()).iterator();
+
+ assertEquals(nodes.next().getName(), n2.getName());
+ assertEquals(nodes.next().getName(), n3.getName());
+ assertEquals(nodes.next().getName(), n4.getName());
+ }
+
+ @Test
+ public void test5Neighbours() throws Exception {
+ NeighbourGrpc ufoundedNeighbour = NeighbourGrpc.newBuilder()
+ .setErrorMessage("Neighbour with id 1 not found for node with id 1 in graph with id 1").build();;
+
+ // Neighbour not found in the server
+ NeighbourGrpc neighbour = client.getNeighbour(1, 1, 1);//id not present
+
+ assertEquals(ufoundedNeighbour, neighbour);
+
+ GraphGrpc graph = Client.createGraphGrpc(null);
+ graph = client.createGraph(graph).getGraph();
+
+ List<NeighbourGrpc> neighbours = new ArrayList<NeighbourGrpc>();
+ NeighbourGrpc nb = Client.createNeighbourGrpc("Node1");
+ neighbours.add(nb);
+ NodeGrpc n1 = Client.createNodeGrpc("Node1", "antispam", null, null);
+ NodeGrpc n2 = Client.createNodeGrpc("Node2", "endhost", neighbours, null);
+ NodeGrpc n3 = Client.createNodeGrpc("Node3", "endhost", null, null);
+ NodeGrpc n4 = Client.createNodeGrpc("Node4", "endpoint", null, null);
+ NodeGrpc n5 = Client.createNodeGrpc("Node5", "webserver", null, null);
+ Map<String,String> map = new HashMap<String,String>();
+ map.put("webserver", "Node5");
+ ConfigurationGrpc conf = Client.createConfigurationGrpc(map, null, null, null);
+ NodeGrpc n6 = Client.createNodeGrpc("Node6", "webclient", null, conf);
+ NodeGrpc n7 = Client.createNodeGrpc("Node7", "cache", null, null);
+ NodeGrpc n8 = Client.createNodeGrpc("Node8", "firewall", null, null);
+ NodeGrpc n9 = Client.createNodeGrpc("Node9", "fieldmodifier", null, null);
+ NodeGrpc n10 = Client.createNodeGrpc("Node10", "dpi", null, null);
+ NewNode nw1 = client.createNode(n1, graph.getId());
+ NewNode nw2 = client.createNode(n2, graph.getId());
+ NewNode nw3 = client.createNode(n3, graph.getId());
+ NewNode nw4 = client.createNode(n4, graph.getId());
+ NewNode nw5 = client.createNode(n5, graph.getId());
+ NewNode nw6 = client.createNode(n6, graph.getId());
+ NewNode nw7 = client.createNode(n7, graph.getId());
+ NewNode nw8 = client.createNode(n8, graph.getId());
+ NewNode nw9 = client.createNode(n9, graph.getId());
+ NewNode nw10 = client.createNode(n10, graph.getId());
+ assertEquals(nw1.getSuccess(),true);
+ assertEquals(nw2.getSuccess(),true);
+ assertEquals(nw3.getSuccess(),true);
+ assertEquals(nw4.getSuccess(),true);
+ assertEquals(nw5.getSuccess(),true);
+ assertEquals(nw6.getSuccess(),true);
+ assertEquals(nw7.getSuccess(),true);
+ assertEquals(nw8.getSuccess(),true);
+ assertEquals(nw9.getSuccess(),true);
+ assertEquals(nw10.getSuccess(),true);
+
+ // getNeighbour, but first add it
+ NeighbourGrpc addedNeighbour = Client.createNeighbourGrpc("Node9");
+ NewNeighbour response = client.createNeighbour(addedNeighbour, graph.getId(), nw1.getNode().getId());
+ addedNeighbour = response.getNeighbour();
+ neighbour = client.getNeighbour(graph.getId(), nw1.getNode().getId(), addedNeighbour.getId());
+
+ assertEquals(addedNeighbour.getId(), neighbour.getId());
+
+ //updateNeighbour
+ NeighbourGrpc updatedNeighbour = Client.createNeighbourGrpc("Node10");
+
+ response = client.updateNeighbour(graph.getId(), 1, addedNeighbour.getId(),updatedNeighbour);
+
+ assertEquals(response.getSuccess(),true);
+ assertEquals(response.getNeighbour().getName(),"Node10");
+ }
+
+ @Test
+ public void test6Neighbours() throws Exception {
+ // setup
+ GraphGrpc graph = Client.createGraphGrpc(null);
+ //createGraph
+ graph = client.createGraph(graph).getGraph();
+
+ NodeGrpc n1 = Client.createNodeGrpc("Node1", "antispam", null, null);
+ NodeGrpc n2 = Client.createNodeGrpc("Node2", "endhost", null, null);
+ NodeGrpc n3 = Client.createNodeGrpc("Node3", "endhost", null, null);
+ NodeGrpc n4 = Client.createNodeGrpc("Node4", "endpoint", null, null);
+ NewNode nw1 = client.createNode(n1, graph.getId());
+ NewNode nw2 = client.createNode(n2, graph.getId());
+ NewNode nw3 = client.createNode(n3, graph.getId());
+ NewNode nw4 = client.createNode(n4, graph.getId());
+ assertEquals(nw1.getSuccess(),true);
+ assertEquals(nw2.getSuccess(),true);
+ assertEquals(nw3.getSuccess(),true);
+ assertEquals(nw4.getSuccess(),true);
+
+ //createNeighbour
+ NeighbourGrpc nn1 = Client.createNeighbourGrpc("Node2");
+ NewNeighbour addedNeighbour1 = client.createNeighbour(nn1, graph.getId(), nw1.getNode().getId());
+ assertEquals(addedNeighbour1.getSuccess(),true);
+ NeighbourGrpc nn2 = Client.createNeighbourGrpc("Node3");
+ NewNeighbour addedNeighbour2 = client.createNeighbour(nn2, graph.getId(), nw1.getNode().getId());
+ assertEquals(addedNeighbour2.getSuccess(),true);
+ NeighbourGrpc nn3 = Client.createNeighbourGrpc("Node4");
+ NewNeighbour addedNeighbour3 = client.createNeighbour(nn3, graph.getId(), nw1.getNode().getId());
+ assertEquals(addedNeighbour3.getSuccess(),true);
+
+ nn1 = NeighbourGrpc.newBuilder(nn1).setId(1).build();
+ nn2 = NeighbourGrpc.newBuilder(nn2).setId(2).build();
+ nn3 = NeighbourGrpc.newBuilder(nn3).setId(3).build();
+ // run
+ Iterator<NeighbourGrpc> neighbours = client.getNeighbours(graph.getId(), nw1.getNode().getId()).iterator();
+
+ assertEquals(neighbours.next(), nn1);
+ assertEquals(neighbours.next(), nn2);
+ assertEquals(neighbours.next(), nn3);
+
+ //deleteNeighbour
+ boolean succ = client.deleteNeighbour(graph.getId(), nw1.getNode().getId(), 1);
+ assertEquals(succ, true);
+ // run
+ neighbours = client.getNeighbours(graph.getId(), nw1.getNode().getId()).iterator();
+
+ assertEquals(neighbours.next(), nn2);
+ assertEquals(neighbours.next(), nn3);
+ }
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/test/MultiThreadTest.java b/verigraph/src/main/java/it/polito/grpc/test/MultiThreadTest.java
new file mode 100644
index 0000000..5b76bea
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/test/MultiThreadTest.java
@@ -0,0 +1,220 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc.test;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.junit.runners.MethodSorters;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.NodeGrpc;
+import it.polito.escape.verify.client.VerifyClientException;
+import it.polito.grpc.Client;
+import it.polito.grpc.Service;
+
+/**
+ * Unit tests for gRPC project.
+ * For testing concurrency on server side.
+ */
+@RunWith(JUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class MultiThreadTest {
+ private Service server;
+ private Client client;
+
+ @Before
+ public void setUp() throws Exception {
+ client = new Client("localhost" , 50051);
+ server = new Service(50051);
+
+ server.start();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ server.stop();
+ client.shutdown();
+ }
+
+ private void testUpdateGraphStatus(final int threadCount) throws InterruptedException, ExecutionException, JsonParseException, JsonMappingException, IOException, VerifyClientException {
+ GraphGrpc retrieveGraphResponse =client.getGraph(1);
+
+ UpdateGraph task = new UpdateGraph(client, 1, retrieveGraphResponse);
+
+ List<MultiThreadTest.UpdateGraph> tasks = Collections.nCopies(threadCount, task);
+ ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
+
+ List<Future<NewGraph>> futures = executorService.invokeAll(tasks);
+ List<Boolean> resultList = new ArrayList<Boolean>(futures.size());
+
+ // Check for exceptions
+ for (Future<NewGraph> future : futures) {
+ // Throws an exception if an exception was thrown by the task.
+ resultList.add(future.get().getSuccess());
+ }
+ // Validate the dimensions
+ Assert.assertEquals(threadCount, futures.size());
+
+ List<Boolean> expectedList = new ArrayList<Boolean>(threadCount);
+ for (int i = 1; i <= threadCount; i++) {
+ expectedList.add(true);
+ }
+ // Validate expected results
+ Assert.assertEquals(expectedList, resultList);
+ }
+
+ private void testUpdateGraph(final int threadCount) throws Exception {
+ GraphGrpc retrieveGraph = client.getGraph(2L);
+ NodeGrpc nodeToEdit = Client.createNodeGrpc("client",
+ "endpoint",
+ null,
+ Client.createConfigurationGrpc(null, null, "client", ""));
+
+ GraphGrpc graphToUpdate = GraphGrpc.newBuilder(retrieveGraph).addNode(nodeToEdit).build();
+
+ String graphAsString = graphToUpdate.toString();
+
+ UpdateGraph task = new UpdateGraph(client, 2, graphToUpdate);
+
+ List<MultiThreadTest.UpdateGraph> tasks = Collections.nCopies(threadCount, task);
+ ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
+
+ List<Future<NewGraph>> futures = executorService.invokeAll(tasks);
+ List<String> resultList = new ArrayList<String>(futures.size());
+
+ // Check for exceptions
+ for (Future<NewGraph> future : futures) {
+ // Throws an exception if an exception was thrown by the task.
+ GraphGrpc graphReceived = future.get().getGraph();
+ NodeGrpc node = NodeGrpc.newBuilder(graphReceived.getNode(0)).setId(0).build();
+ GraphGrpc graph = GraphGrpc.newBuilder(graphReceived).setNode(0, node).build();
+ resultList.add(graph.toString());
+ }
+ // Validate dimensions
+ Assert.assertEquals(threadCount, futures.size());
+
+ List<String> expectedList = new ArrayList<String>(threadCount);
+ for (int i = 1; i <= threadCount; i++) {
+ expectedList.add(graphAsString);
+ }
+ // Validate expected results
+ Assert.assertEquals(expectedList, resultList);
+ }
+
+ private void testCreateGraphStatus(final int threadCount) throws InterruptedException, ExecutionException, JsonParseException, JsonMappingException, IOException {
+
+ GraphGrpc graph = GraphGrpc.newBuilder().build();
+
+ CreateGraph task = new CreateGraph(client, graph);
+
+ List<MultiThreadTest.CreateGraph> tasks = Collections.nCopies(threadCount, task);
+ ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
+
+ List<Future<Boolean>> futures = executorService.invokeAll(tasks);
+ List<Boolean> resultList = new ArrayList<Boolean>(futures.size());
+
+ // Check for exceptions
+ for (Future<Boolean> future : futures) {
+ // Throws an exception if an exception was thrown by the task.
+ resultList.add(future.get());
+ }
+ // Validate the IDs
+ Assert.assertEquals(threadCount, futures.size());
+
+ List<Boolean> expectedList = new ArrayList<Boolean>(threadCount);
+ for (int i = 1; i <= threadCount; i++) {
+ expectedList.add(true);
+ }
+ // Validate expected results
+ Assert.assertEquals(expectedList, resultList);
+ }
+
+ private int randInt(int min, int max){
+ Random rand = new Random();
+ int randomNum = rand.nextInt((max - min) + 1) + min;
+ return randomNum;
+ }
+
+ @Test
+ public void updateGraphStatusCheck() throws InterruptedException, ExecutionException, JsonParseException, JsonMappingException, IOException, VerifyClientException {
+ testUpdateGraphStatus(64);
+ }
+
+ @Test
+ public void updateGraphResponseCheck() throws Exception {
+ testUpdateGraph(16);
+ }
+
+ @Test
+ public void createGraphStatusCheck() throws JsonParseException, JsonMappingException, InterruptedException, ExecutionException, IOException {
+ testCreateGraphStatus(8);
+ }
+
+ class UpdateGraph implements Callable<NewGraph> {
+
+ private Client verifyClient;
+
+ private int graphId;
+
+ private GraphGrpc graph;
+
+ public UpdateGraph(Client verifyClient, int graphId, GraphGrpc graph) {
+ this.graphId = graphId;
+ this.graph = graph;
+ this.verifyClient = verifyClient;
+ }
+
+ @Override
+ public NewGraph call() throws Exception {
+ Thread.sleep(randInt(0,2000));
+ return this.verifyClient.updateGraph(this.graphId, this.graph);
+ }
+ }
+
+ class CreateGraph implements Callable<Boolean> {
+
+ private Client verifyClient;
+
+ private GraphGrpc graph;
+
+ public CreateGraph(Client verifyClient, GraphGrpc graph) {
+ this.graph = graph;
+ this.verifyClient = verifyClient;
+ }
+
+ @Override
+ public Boolean call() throws Exception {
+ Thread.sleep(randInt(0,2000));
+ return this.verifyClient.createGraph(this.graph).getSuccess();
+ }
+
+ }
+
+}
diff --git a/verigraph/src/main/java/it/polito/grpc/test/ReachabilityTest.java b/verigraph/src/main/java/it/polito/grpc/test/ReachabilityTest.java
new file mode 100644
index 0000000..a120aff
--- /dev/null
+++ b/verigraph/src/main/java/it/polito/grpc/test/ReachabilityTest.java
@@ -0,0 +1,252 @@
+/*******************************************************************************
+ * Copyright (c) 2017 Politecnico di Torino and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Apache License, Version 2.0
+ * which accompanies this distribution, and is available at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *******************************************************************************/
+
+package it.polito.grpc.test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.junit.runners.MethodSorters;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.FilenameFilter;
+import java.io.InputStreamReader;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jsonschema.core.exceptions.ProcessingException;
+import com.github.fge.jsonschema.main.JsonSchema;
+
+import io.grpc.verigraph.GraphGrpc;
+import io.grpc.verigraph.NewGraph;
+import io.grpc.verigraph.Policy;
+import io.grpc.verigraph.VerificationGrpc;
+import it.polito.escape.verify.client.VerifyClientException;
+import it.polito.escape.verify.service.ValidationUtils;
+import it.polito.escape.verify.test.TestCase;
+import it.polito.escape.verify.test.TestExecutionException;
+import it.polito.grpc.Client;
+import it.polito.grpc.GrpcUtils;
+import it.polito.grpc.Service;
+
+@RunWith(JUnit4.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class ReachabilityTest {
+ private File schema;
+ private List<File> testFiles = new ArrayList<File>();
+ private List<TestCase> testCases = new ArrayList<TestCase>();
+ private Client client;
+ private Service server;
+
+ @Before
+ public void setUpBeforeClass() throws Exception {
+ client = new Client("localhost" , 50051);
+ server = new Service(50051);
+ server.start();
+
+ String folderName = System.getProperty("user.dir") + "/tester/testcases";
+ File folder = new File(folderName);
+ if (!folder.exists()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ String s;
+ do{
+ System.out.println("Please enter the testcases folder path: ");
+ s = in.readLine();
+ if (isValidpath(s)){
+ folder = new File(s);
+ break;
+ }
+ }while (s != null && s.length() != 0);
+ if(s == null)
+ System.exit(0);
+ }
+ String schemaName = System.getProperty("user.dir") + "/tester/testcase_schema.json";
+ File schema = new File(schemaName);
+ if (!schema.exists()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ String s;
+ do{
+ System.out.println("Please enter the full path of 'testcase_schema.json': ");
+ s = in.readLine();
+ if (isValidpath(s)){
+ folder = new File(s);
+ break;
+ }
+ }while (s != null && s.length() != 0);
+ if(s == null)
+ System.exit(0);
+ }
+
+ this.schema = schema;
+ this.testFiles = getTests(folder);
+ this.testCases = getTestCases(this.testFiles);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ server.stop();
+ client.shutdown();
+ }
+
+ @Test
+ public final void wrongReachability() {
+ System.out.println("DEBUG: starting testWrongReachability");
+
+ VerificationGrpc nullVer = VerificationGrpc.newBuilder()
+ .setErrorMessage("Graph with id 52 not found").build();
+ //verification on uncreated graph
+ Policy policyToVerify = Client.createPolicy("Node1", "Node4", "reachability", null, 52);
+ VerificationGrpc ver = client.verify(policyToVerify);
+ assertEquals(ver, nullVer);
+
+ //verification on uncreated nodes
+ nullVer = VerificationGrpc.newBuilder()
+ .setErrorMessage("The \'source\' parameter \'Node5\' is not valid, please insert the name of an existing node").build();
+ policyToVerify = Client.createPolicy("Node5", "Node4", "reachability", null, 1);
+ ver = client.verify(policyToVerify);
+ assertEquals(ver, nullVer);
+
+ //verification on uncreated nodes
+ nullVer = VerificationGrpc.newBuilder()
+ .setErrorMessage("The \'source\' parameter \'Node1\' is not valid, please insert the name of an existing node").build();
+
+ policyToVerify = Client.createPolicy("Node1", "Node10", "reachability", null, 1);
+ ver = client.verify(policyToVerify);
+ assertEquals(ver, nullVer);
+
+ }
+
+ public List<File> getTests(File folder) {
+ List<File> filesList = new ArrayList<File>();
+
+ System.out.println("Test folder set to '" + folder.getAbsolutePath() + "'");
+
+ File[] files = folder.listFiles(new FilenameFilter() {
+
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".json");
+ }
+ });
+
+ for (File f : files) {
+ filesList.add(f);
+ System.out.println("File '" + f.getName() + "' added to test files");
+ }
+
+ return filesList;
+ }
+
+ public List<TestCase> getTestCases(List<File> files) throws JsonParseException, JsonMappingException, IOException,
+ Exception {
+ List<TestCase> testCases = new ArrayList<TestCase>();
+
+ for (File file : files) {
+ validateTestFile(file);
+ try {
+ TestCase tc = new ObjectMapper().readValue(file, TestCase.class);
+ testCases.add(tc);
+ }
+ catch (Exception e) {
+ throw e;
+ }
+ }
+
+ return testCases;
+ }
+
+ @Test
+ public void runTestCases() throws VerifyClientException, TestExecutionException {
+ int counter = 0;
+ for (TestCase tc : this.testCases) {
+ String result = runTestCase(tc);
+ if (!result.equals(tc.getResult()))
+ throw new TestExecutionException("Error running test given in file '" + this.testFiles.get(counter).getName()
+ + "'. Test returned '" + result + "' instead of '" + tc.getResult() + "'.");
+ else
+ System.out.println("Test given in file '" + this.testFiles.get(counter).getName() + "' returned '"
+ + result + "' as expected");
+ counter++;
+
+ }
+ System.out.println("All tests PASSED");
+ }
+
+ private String runTestCase(TestCase tc) throws VerifyClientException, TestExecutionException{
+ GraphGrpc graph = GrpcUtils.obtainGraph(tc.getGraph());
+
+ NewGraph newGraph = this.client.createGraph(graph);
+ if(newGraph.getSuccess() == false)
+ throw new VerifyClientException("gRPC request failed");
+ GraphGrpc createdGraph = newGraph.getGraph();
+
+ GraphGrpc addedgraph = client.getGraph(createdGraph.getId());
+ System.out.println(addedgraph);
+
+ final Map<String, String> map = GrpcUtils.getParamGivenString(tc.getPolicyUrlParameters());
+
+ Policy policy = Client.createPolicy(map.get("source"),
+ map.get("destination"),
+ map.get("type"),
+ map.get("middlebox"),
+ createdGraph.getId());
+ VerificationGrpc verification = this.client.verify(policy);
+ return verification.getResult();
+ }
+
+ public void validateTestFile(File testFile) throws Exception {
+ JsonSchema schemaNode = null;
+ try {
+ schemaNode = ValidationUtils.getSchemaNode(schema);
+ }
+ catch (IOException e) {
+ throw new Exception("Unable to load '" + schema.getAbsolutePath() + "' schema file");
+ }
+ catch (ProcessingException e) {
+ throw new Exception("Unable to resolve '" + schema.getAbsolutePath() + "' schema file as a schema node");
+ }
+
+ JsonNode jsonNode;
+ try {
+ jsonNode = ValidationUtils.getJsonNode(testFile);
+ }
+ catch (IOException e) {
+ throw new Exception("Unable to load '" + testFile.getAbsolutePath() + "' as a json node");
+ }
+
+ try {
+ ValidationUtils.validateJson(schemaNode, jsonNode);
+ }
+ catch (ProcessingException e) {
+ throw new Exception("There were errors in the validation of file '" + testFile.getAbsolutePath()
+ + "' against the json schema '" + schema.getAbsolutePath() + "': " + e.getMessage());
+
+ }
+ }
+
+ private static boolean isValidpath(String s) {
+ if (s==null)
+ return false;
+ File file = new File(s);
+ return file.exists();
+ }
+}