summaryrefslogtreecommitdiffstats
path: root/verigraph/src/it/polito/verigraph/grpc
diff options
context:
space:
mode:
Diffstat (limited to 'verigraph/src/it/polito/verigraph/grpc')
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/client/Client.java559
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/server/GrpcUtils.java153
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/server/Service.java466
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/test/GrpcServerTest.java392
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/test/GrpcTest.java422
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/test/MultiThreadTest.java220
-rw-r--r--verigraph/src/it/polito/verigraph/grpc/test/ReachabilityTest.java274
7 files changed, 2486 insertions, 0 deletions
diff --git a/verigraph/src/it/polito/verigraph/grpc/client/Client.java b/verigraph/src/it/polito/verigraph/grpc/client/Client.java
new file mode 100644
index 0000000..0fc76ef
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/client/Client.java
@@ -0,0 +1,559 @@
+/*******************************************************************************
+ * 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.verigraph.grpc.client;
+
+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 it.polito.verigraph.grpc.ConfigurationGrpc;
+import it.polito.verigraph.grpc.GetRequest;
+import it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NeighbourGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.NewNeighbour;
+import it.polito.verigraph.grpc.NewNode;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.grpc.NodeGrpc.FunctionalType;
+import it.polito.verigraph.grpc.Policy;
+import it.polito.verigraph.grpc.Policy.PolicyType;
+import it.polito.verigraph.grpc.RequestID;
+import it.polito.verigraph.grpc.Status;
+import it.polito.verigraph.grpc.VerificationGrpc;
+import it.polito.verigraph.grpc.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("[getGraphs] Graph id : "+graph.getId());
+ if(graph.getErrorMessage().equals("")){
+ System.out.println("[getGraphs] Node id : "+graph.getId());
+ graphsRecveived.add(graph);
+ }else{
+ System.out.println("[getGraphs] Error : " + graph.getErrorMessage());
+ return graphsRecveived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getGraphs] 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("[createGraph] Successful operation ");
+ }else{
+ System.out.println("[createGraph] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[createGraph] 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("[deleteGraph] Successful operation ");
+ return true;
+ }else{
+ System.out.println("[deleteGraph] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[deleteGraph] 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("[updateGraph] Successful operation ");
+ }else{
+ System.out.println("[updateGraph] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[updateGraph] 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("[getGraph] Error in operation: " + graph.getErrorMessage());
+ }
+ return graph;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getGraph] 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("[verify] Error in operation: " + response.getErrorMessage());
+ }
+ System.out.println("[verify] Result : "+response.getResult());
+ System.out.println("[verify] 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("[verify] 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("[getNodes] Node id : "+node.getId());
+ nodesReceived.add(node);
+ }else{
+ System.out.println("[getNodes] Error : " + node.getErrorMessage());
+ return nodesReceived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getNodes] 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("[createNode] Successful operation ");
+ }else{
+ System.out.println("[createNode] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[createNode] 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("[deleteNode] Successful operation ");
+ return true;
+ }else{
+ System.out.println("[deleteNode] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[deleteNode] 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("[updateNode] Successful operation ");
+ }else{
+ System.out.println("[updateNode] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[updateNode] 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("[getNode] Error in operation: " + node.getErrorMessage());
+ }
+ return node;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getNode] 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("[configureNode] Successful operation ");
+ return true;
+ }else{
+ System.out.println("[configureNode] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[configureNode] 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("[getNeighbours] Neighbour id : "+neighbour.getId());
+ neighboursReceived.add(neighbour);
+ }else{
+ System.out.println("[getNeighbours] Error : " + neighbour.getErrorMessage());
+ return neighboursReceived;
+ }
+ }
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getNeighbours] 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("[createNeighbour] Successful operation ");
+ }else{
+ System.out.println("[createNeighbour] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[createNeighbour] 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("[deleteNeighbour] Successful operation ");
+ return true;
+ }else{
+ System.out.println("[deleteNeighbour] Unsuccesful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[deleteNeighbour] 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("[updateNeighbour] Successful operation ");
+ }else{
+ System.out.println("[updateNeighbour] Unsuccessful operation: " + response.getErrorMessage());
+ }
+ } catch (StatusRuntimeException e) {
+ System.err.println("[updateNeighbour] 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("[getNeighbour] Error in operation: " + neighbour.getErrorMessage());
+ }
+ return neighbour;
+ } catch (StatusRuntimeException ex) {
+ System.err.println("[getNeighbour] 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());
+ }
+
+ for(GraphGrpc g : client.getGraphs()){
+ long graph_id = g.getId();
+ System.out.println("graph id: "+graph_id);
+ for (NodeGrpc n: g.getNodeList()){
+ long node_id = n.getId();
+ System.out.println("node id: "+node_id);
+ NodeGrpc nodenew = createNodeGrpc("Newnode","endhost",null,null);
+ //NewNode node = client.updateNode(graph_id, node_id, nodenew);
+ //System.out.println("Client updates node: "+node.getSuccess());
+ System.out.println("end");
+ }
+ }
+
+
+ } 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/it/polito/verigraph/grpc/server/GrpcUtils.java b/verigraph/src/it/polito/verigraph/grpc/server/GrpcUtils.java
new file mode 100644
index 0000000..43859db
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/server/GrpcUtils.java
@@ -0,0 +1,153 @@
+/*******************************************************************************
+ * 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.verigraph.grpc.server;
+
+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 it.polito.verigraph.grpc.ConfigurationGrpc;
+import it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NeighbourGrpc;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.grpc.TestGrpc;
+import it.polito.verigraph.grpc.VerificationGrpc;
+import it.polito.verigraph.grpc.NodeGrpc.FunctionalType;
+import it.polito.verigraph.model.Configuration;
+import it.polito.verigraph.model.Graph;
+import it.polito.verigraph.model.Neighbour;
+import it.polito.verigraph.model.Node;
+import it.polito.verigraph.model.Test;
+import it.polito.verigraph.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/it/polito/verigraph/grpc/server/Service.java b/verigraph/src/it/polito/verigraph/grpc/server/Service.java
new file mode 100644
index 0000000..1839b7e
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/server/Service.java
@@ -0,0 +1,466 @@
+/*******************************************************************************
+ * 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.verigraph.grpc.server;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.FileHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.logging.SimpleFormatter;
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+import io.grpc.stub.StreamObserver;
+import it.polito.verigraph.grpc.ConfigurationGrpc;
+import it.polito.verigraph.grpc.GetRequest;
+import it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NeighbourGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.NewNeighbour;
+import it.polito.verigraph.grpc.NewNode;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.grpc.Policy;
+import it.polito.verigraph.grpc.RequestID;
+import it.polito.verigraph.grpc.Status;
+import it.polito.verigraph.grpc.VerificationGrpc;
+import it.polito.verigraph.grpc.VerigraphGrpc;
+import it.polito.verigraph.exception.BadRequestException;
+import it.polito.verigraph.exception.DataNotFoundException;
+import it.polito.verigraph.exception.ForbiddenException;
+import it.polito.verigraph.model.Configuration;
+import it.polito.verigraph.model.Graph;
+import it.polito.verigraph.model.Neighbour;
+import it.polito.verigraph.model.Node;
+import it.polito.verigraph.model.Verification;
+import it.polito.verigraph.resources.beans.VerificationBean;
+import it.polito.verigraph.service.GraphService;
+import it.polito.verigraph.service.NeighbourService;
+import it.polito.verigraph.service.NodeService;
+import it.polito.verigraph.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 {
+ FileHandler fileTxt = new FileHandler("grpc_server_log.txt");
+ SimpleFormatter formatterTxt = new SimpleFormatter();
+ fileTxt.setFormatter(formatterTxt);
+ logger.addHandler(fileTxt);
+ 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 implementation*/
+ 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.getClass().toString());
+ logger.log(Level.WARNING, ex.getMessage());
+
+ }
+ catch(Exception ex){
+ response.setSuccess(false).setErrorMessage(internalError);
+ logger.log(Level.WARNING, ex.getClass().toString());
+ 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/it/polito/verigraph/grpc/test/GrpcServerTest.java b/verigraph/src/it/polito/verigraph/grpc/test/GrpcServerTest.java
new file mode 100644
index 0000000..e677bdd
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/test/GrpcServerTest.java
@@ -0,0 +1,392 @@
+/*******************************************************************************
+ * 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.verigraph.grpc.test;
+
+import static org.junit.Assert.assertEquals;
+import io.grpc.ManagedChannel;
+import io.grpc.inprocess.InProcessChannelBuilder;
+import io.grpc.inprocess.InProcessServerBuilder;
+import it.polito.verigraph.grpc.ConfigurationGrpc;
+import it.polito.verigraph.grpc.GetRequest;
+import it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NeighbourGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.NewNeighbour;
+import it.polito.verigraph.grpc.NewNode;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.grpc.NodeGrpc.FunctionalType;
+import it.polito.verigraph.grpc.client.Client;
+import it.polito.verigraph.grpc.server.Service;
+import it.polito.verigraph.grpc.RequestID;
+import it.polito.verigraph.grpc.Status;
+import it.polito.verigraph.grpc.VerigraphGrpc;
+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();
+ }
+
+ public void deleteGraphs() {
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+ Iterator<GraphGrpc> iter = stub.getGraphs(GetRequest.newBuilder().build());
+ while(iter.hasNext()){
+ stub.deleteGraph(RequestID.newBuilder().setIdGraph(iter.next().getId()).build());
+ }
+ }
+
+ @Test
+ public void test1Graph() throws Exception {
+ System.out.println("[DEBUG] test1Graphs starts");
+ deleteGraphs();
+ RequestID request = RequestID.newBuilder().setIdGraph(1).build() ;//id not present
+ GraphGrpc ufoundedGraph = GraphGrpc.newBuilder()
+ //.setErrorMessage("Graph with id 1 not found").build();
+ .setErrorMessage("There is no Graph whose Id is '1'").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() ;
+ request = RequestID.newBuilder().setIdGraph(response.getGraph().getId()).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 {
+ System.out.println("[DEBUG] test2Graphs starts");
+ deleteGraphs();
+ // 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);
+
+ NewGraph g1_new = stub.createGraph(g1);
+ NewGraph g2_new = stub.createGraph(g2);
+ NewGraph g3_new = stub.createGraph(g3);
+ NewGraph g4_new = stub.createGraph(g4);
+
+ long g1_id = g1_new.getGraph().getId();
+ long g2_id = g2_new.getGraph().getId();
+ long g3_id = g3_new.getGraph().getId();
+ long g4_id = g4_new.getGraph().getId();
+ g1 = GraphGrpc.newBuilder(g1).setId(g1_id).build();
+ g2 = GraphGrpc.newBuilder(g2).setId(g2_id).build();
+ g3 = GraphGrpc.newBuilder(g3).setId(g3_id).build();
+ g4 = GraphGrpc.newBuilder(g4).setId(g4_id).build();
+ // run
+ Iterator<GraphGrpc> graphs = stub.getGraphs(request);
+
+ while(graphs.hasNext()){
+ graphs.next();
+ }
+
+ if(graphs.hasNext()){
+ graphs.next();
+ 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 {
+ System.out.println("[DEBUG] test3Graphs starts");
+ deleteGraphs();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+ GraphGrpc g2 = GraphGrpc.newBuilder().build();
+ NewGraph g2_new = stub.createGraph(g2);
+ long g2_id = g2_new.getGraph().getId();
+
+ RequestID request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(1).build() ;//id not present
+ // graph not found in the server
+ NodeGrpc node = stub.getNode(request);
+
+ NodeGrpc unfoundedGraph = NodeGrpc.newBuilder()
+ //.setErrorMessage("Node with id 1 not found in graph with id 2").build();
+ //.setErrorMessage("There is no Graph whose Id is '2'").build();
+ .setErrorMessage("There is no Node whose Id is '1'").build();
+
+ assertEquals(unfoundedGraph, node);
+
+ // graph found in the server, but first add it
+ NodeGrpc addedNode = NodeGrpc.newBuilder().setName("client").setIdGraph(g2_id)
+ .setFunctionalType(FunctionalType.endhost).build();
+ NewNode response = stub.createNode(addedNode);
+ long node_id = response.getNode().getId();
+ //addedNode = response.getNode();
+
+ request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(addedNode.getId()).build() ;
+ node = stub.getNode(request);
+
+ assertEquals(addedNode.getId(), node.getId());
+ assertEquals(addedNode.getName(),"client");
+
+ //updateNode
+ NodeGrpc updatedNode = NodeGrpc.newBuilder().setName("Nodo2").setIdGraph(g2_id).setId(node_id)
+ .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(g2_id)
+ .setIdNode(node_id).build();
+
+ Status status = stub.configureNode(config);
+ assertEquals(status.getSuccess(),true);
+ }
+
+ @Test
+ public void test4Nodes() throws Exception {
+ System.out.println("[DEBUG] test4Graphs starts");
+ deleteGraphs();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+ GraphGrpc g2 = GraphGrpc.newBuilder().build();
+ NewGraph g2_new = stub.createGraph(g2);
+ long g2_id = g2_new.getGraph().getId();
+
+ // setup
+ RequestID request = RequestID.newBuilder().setIdGraph(g2_id).build();
+ NodeGrpc n1 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node5", "endhost", null, null))
+ .setIdGraph(g2_id).build();
+ NodeGrpc n2 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node3", "endhost", null, null))
+ .setIdGraph(g2_id).build();
+ NodeGrpc n3 = NodeGrpc.newBuilder(Client.createNodeGrpc("Node4", "endhost", null, null))
+ .setIdGraph(g2_id).build();
+ NodeGrpc n4 = NodeGrpc.newBuilder(Client.createNodeGrpc("client", "endhost", null, null))
+ .setIdGraph(g2_id).build();
+
+ NewNode nn1= stub.createNode(n1);
+ NewNode nn2= stub.createNode(n2);
+ NewNode nn3= stub.createNode(n3);
+ NewNode nn4= stub.createNode(n4);
+
+ n1 = NodeGrpc.newBuilder(n1).setId(nn1.getNode().getId()).setIdGraph(g2_id).build();
+ n2 = NodeGrpc.newBuilder(n2).setId(nn2.getNode().getId()).setIdGraph(g2_id).build();
+ n3 = NodeGrpc.newBuilder(n3).setId(nn3.getNode().getId()).setIdGraph(g2_id).build();
+ n4 = NodeGrpc.newBuilder(n4).setId(nn4.getNode().getId()).setIdGraph(g2_id).build();
+
+ // run
+ Iterator<NodeGrpc> nodes = stub.getNodes(request);
+
+ while(nodes.hasNext()){
+ nodes.next();
+ //System.out.println("[DEBUG - TEST4] graph loaded: " + nodes.next());
+ }
+
+ if(nodes.hasNext()){
+ assertEquals(nodes.next(), n1);
+ assertEquals(nodes.next(), n2);
+ assertEquals(nodes.next(), n3);
+ assertEquals(nodes.next(), n4);
+ }
+
+ //deleteNode
+ RequestID req = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1.getId()).build();
+ stub.deleteNode(req);
+ // run
+ nodes = stub.getNodes(request);
+
+ while(nodes.hasNext()){
+ nodes.next();
+ //System.out.println("[DEBUG - TEST4] graph loaded: " + nodes.next());
+ }
+
+ if(nodes.hasNext()){
+ //assertEquals(nodes.next(), n1);
+ assertEquals(nodes.next(), n2);
+ assertEquals(nodes.next(), n3);
+ assertEquals(nodes.next(), n4);
+ }
+ }
+
+ @Test
+ public void test5Neighbours() throws Exception {
+ System.out.println("[DEBUG] test5Graphs starts");
+ deleteGraphs();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+
+ GraphGrpc g2 = GraphGrpc.newBuilder().build();
+ NewGraph g2_new = stub.createGraph(g2);
+ long g2_id = g2_new.getGraph().getId();
+
+ NodeGrpc n1 = NodeGrpc.newBuilder().setName("Node1").setIdGraph(g2_id).setFunctionalType(FunctionalType.endhost).build();
+ NewNode new_n1 = stub.createNode(n1);
+ long n1_id = new_n1.getNode().getId();
+
+ NodeGrpc n2 = NodeGrpc.newBuilder().setName("client").setIdGraph(g2_id).setFunctionalType(FunctionalType.endhost).build();
+ NewNode new_n2 = stub.createNode(n2);
+ long n2_id = new_n2.getNode().getId();
+
+ RequestID request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1_id).setIdNeighbour(1).build() ;//id not present
+ NeighbourGrpc ufoundedNeighbour = NeighbourGrpc.newBuilder()
+ .setErrorMessage("Neighbour with id 1 not found for node with id "+n1_id+" in graph with id "+g2_id).build();
+
+ // Neighbour not found in the server
+ NeighbourGrpc neighbour = stub.getNeighbour(request);
+
+ assertEquals(ufoundedNeighbour, neighbour);
+
+ // getNeighbour, but first add it
+ NeighbourGrpc addedNeighbour = NeighbourGrpc.newBuilder().setIdGraph(g2_id).setIdNode(n1_id).setName("client").build();
+ NewNeighbour response = stub.createNeighbour(addedNeighbour);
+ addedNeighbour = response.getNeighbour();
+ request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1_id)
+ .setIdNeighbour(addedNeighbour.getId()).build();
+ neighbour = stub.getNeighbour(request);
+
+ assertEquals(addedNeighbour.getId(), neighbour.getId());
+
+ NodeGrpc updatedNode = NodeGrpc.newBuilder().setName("Node4").setIdGraph(g2_id).setId(n2_id)
+ .setFunctionalType(FunctionalType.endhost).build();
+
+ //updateNeighbour
+ NewNode response_node = stub.updateNode(updatedNode);
+ assertEquals(response_node.getSuccess(),true);
+
+ //NeighbourGrpc nu = NeighbourGrpc.newBuilder().setName("Node4")
+ //.setId(addedNeighbour.getId()).setIdGraph(g2_id).setIdNode(n1_id).build();
+ //response = stub.updateNeighbour(nu);
+ //System.out.println(response);
+
+ request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1_id)
+ .setIdNeighbour(addedNeighbour.getId()).build();
+ neighbour = stub.getNeighbour(request);
+ assertEquals(neighbour.getName(),"Node4");
+ }
+
+ @Test
+ public void test6Neighbours() throws Exception {
+ System.out.println("[DEBUG] test6Graphs starts");
+ deleteGraphs();
+
+ VerigraphGrpc.VerigraphBlockingStub stub = VerigraphGrpc.newBlockingStub(inProcessChannel);
+ // setup
+ GraphGrpc g2 = GraphGrpc.newBuilder().build();
+ NewGraph g2_new = stub.createGraph(g2);
+ long g2_id = g2_new.getGraph().getId();
+
+ NodeGrpc node1 = NodeGrpc.newBuilder().setName("Node1").setFunctionalType(FunctionalType.endhost).build();
+ NewNode new_n1 = stub.createNode(node1);
+ long n1_id = new_n1.getNode().getId();
+
+
+
+ NeighbourGrpc n1 = NeighbourGrpc.newBuilder().setIdGraph(g2_id).setIdNode(n1_id)
+ .setName("Node3").build();
+ NeighbourGrpc n2 = NeighbourGrpc.newBuilder().setIdGraph(g2_id).setIdNode(n1_id)
+ .setName("client").build();
+
+
+ stub.createNeighbour(n1);
+ stub.createNeighbour(n2);
+ n1 = NeighbourGrpc.newBuilder(n1).setId(2).setIdGraph(g2_id).setIdNode(n1_id).build();
+ n2 = NeighbourGrpc.newBuilder(n2).setId(3).setIdGraph(g2_id).setIdNode(n1_id).build();
+ // run
+ RequestID request = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1_id).build();
+ Iterator<NeighbourGrpc> neighbours = stub.getNeighbours(request);
+
+ while(neighbours.hasNext()){
+ neighbours.next();
+ }
+
+ if(neighbours.hasNext()){
+ assertEquals(neighbours.next(), n1);
+ assertEquals(neighbours.next(), n2);
+ }
+
+ //deleteNeighbour
+ RequestID req = RequestID.newBuilder().setIdGraph(g2_id).setIdNode(n1_id).setIdNeighbour(n1.getId()).build();
+ stub.deleteNeighbour(req);
+ // run
+ neighbours = stub.getNeighbours(request);
+
+ while(neighbours.hasNext()){
+ neighbours.next();
+ }
+
+ if(neighbours.hasNext()){
+ assertEquals(neighbours.next(), n1);
+ assertEquals(neighbours.next(), n2);
+ }
+ }
+}
diff --git a/verigraph/src/it/polito/verigraph/grpc/test/GrpcTest.java b/verigraph/src/it/polito/verigraph/grpc/test/GrpcTest.java
new file mode 100644
index 0000000..a1830cf
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/test/GrpcTest.java
@@ -0,0 +1,422 @@
+/*******************************************************************************
+ * 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.verigraph.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.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+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 it.polito.verigraph.grpc.ConfigurationGrpc;
+import it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NeighbourGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.NewNeighbour;
+import it.polito.verigraph.grpc.NewNode;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.grpc.client.Client;
+import it.polito.verigraph.grpc.server.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);
+ }
+
+ public void deleteGraphs() {
+ for(GraphGrpc graph : client.getGraphs()){
+ client.deleteGraph(graph.getId());
+ }
+
+ }
+
+ @Test
+ public final void test1Load() throws Exception{
+ System.out.println("[DEBUG] test1Load starts");
+ deleteGraphs();
+ 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{
+ System.out.println("[DEBUG] test2Load starts");
+ deleteGraphs();
+ // 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);
+ GraphGrpc g = client.createGraph(graph).getGraph();
+
+ GraphGrpc get_graph= client.getGraph(g.getId());
+ assertEquals(g.getErrorMessage(), get_graph.getErrorMessage());
+
+ //getGraphs
+ List<GraphGrpc> graph_list = client.getGraphs();
+ TreeSet<GraphGrpc> pts = new TreeSet<GraphGrpc>(new GraphGrpcComparator());
+ pts.addAll(graph_list);
+ Iterator<GraphGrpc> graphs = pts.iterator();
+
+ //assertEquals(graphs.next().getId(), g.getId());
+ if(graphs.hasNext())
+ assertEquals(graphs.next(), g);
+
+ //deleteGraph
+ boolean resp= client.deleteGraph(g.getId());
+ assertEquals(resp, true);
+
+ List<GraphGrpc> listGraphs = client.getGraphs();
+
+ assertEquals(listGraphs.size(), 0);
+ //assertEquals(listGraphs.get(0).getId(), 1);
+ }
+
+ @Test
+ public void test3Node() throws Exception {
+ System.out.println("[DEBUG] test3Load starts");
+ deleteGraphs();
+
+ NodeGrpc ufoundedGraph = NodeGrpc.newBuilder()
+ .setErrorMessage("There is no Graph whose Id is '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);
+ GraphGrpc addedgraph = Client.createGraphGrpc(null);
+ NewGraph response_graph = client.createGraph(addedgraph);
+ NewNode response = client.createNode(addedNode, response_graph.getGraph().getId());
+ addedNode = response.getNode();
+ node = client.getNode(response_graph.getGraph().getId(), addedNode.getId());
+
+ assertEquals(addedNode.getId(), node.getId());
+
+ //updateNode
+ NodeGrpc updatedNode = Client.createNodeGrpc("Node9", "endhost", null, null);
+ response = client.updateNode(response_graph.getGraph().getId(), 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(response_graph.getGraph().getId(), addedNode.getId(), configuration);
+
+ assertEquals(status,true);
+ }
+
+ @Test
+ public void test4Nodes() throws Exception {
+ System.out.println("[DEBUG] test4Load starts");
+ // 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
+ List<NodeGrpc> node_list = client.getNodes(graph.getId());
+ TreeSet<NodeGrpc> pts = new TreeSet<NodeGrpc>(new NodeGrpcComparator());
+ pts.addAll(node_list);
+ Iterator<NodeGrpc> nodes = pts.iterator();
+ //sorted by name
+ if(nodes.hasNext()){
+ assertEquals(nodes.next().getName(), n3.getName());
+ assertEquals(nodes.next().getName(), n4.getName());
+ assertEquals(nodes.next().getName(), n1.getName());
+ assertEquals(nodes.next().getName(), n2.getName());
+ }
+
+ //deleteNode
+ client.deleteNode(graph.getId(), n1.getId());
+ // run
+ node_list = client.getNodes(graph.getId());
+ pts = new TreeSet<NodeGrpc>(new NodeGrpcComparator());
+ pts.addAll(node_list);
+ nodes = pts.iterator();
+
+ assertEquals(nodes.next().getName(), n3.getName());
+ assertEquals(nodes.next().getName(), n4.getName());
+ assertEquals(nodes.next().getName(), n2.getName());
+ }
+
+ @Test
+ public void test5Neighbours() throws Exception {
+ System.out.println("[DEBUG] test5Load starts");
+ NeighbourGrpc ufoundedNeighbour = NeighbourGrpc.newBuilder()
+ .setErrorMessage("There is no Graph whose Id is '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(), nw1.getNode().getId(), addedNeighbour.getId(),updatedNeighbour);
+
+ assertEquals(response.getSuccess(),true);
+ assertEquals(response.getNeighbour().getName(),"Node10");
+ }
+
+ @Test
+ public void test6Neighbours() throws Exception {
+ System.out.println("[DEBUG] test6Load starts");
+ // 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
+ List<NeighbourGrpc> node_list = client.getNeighbours(graph.getId(), nw1.getNode().getId());
+ TreeSet<NeighbourGrpc> pts = new TreeSet<NeighbourGrpc>(new NeighbourGrpcComparator());
+ pts.addAll(node_list);
+ Iterator<NeighbourGrpc> neighbours = pts.iterator();
+
+ while(neighbours.hasNext()){
+ neighbours.next();
+ }
+
+ if(neighbours.hasNext()){
+ assertEquals(neighbours.next(), addedNeighbour1.getNeighbour());
+ assertEquals(neighbours.next(), addedNeighbour2.getNeighbour());
+ assertEquals(neighbours.next(), addedNeighbour3.getNeighbour());
+ }
+
+ //deleteNeighbour
+ boolean succ = client.deleteNeighbour(graph.getId(), nw1.getNode().getId(), addedNeighbour1.getNeighbour().getId());
+ assertEquals(succ, true);
+ // run
+ node_list = client.getNeighbours(graph.getId(), nw1.getNode().getId());
+ pts = new TreeSet<NeighbourGrpc>(new NeighbourGrpcComparator());
+ pts.addAll(node_list);
+ neighbours = pts.iterator();
+
+ while(neighbours.hasNext()){
+ neighbours.next();
+ }
+
+
+ if(neighbours.hasNext()){
+ assertEquals(neighbours.next(), addedNeighbour2.getNeighbour());
+ assertEquals(neighbours.next(), addedNeighbour3.getNeighbour());
+ }
+ }
+}
+
+
+class NodeGrpcComparator implements Comparator<NodeGrpc> {
+ public int compare(NodeGrpc n0, NodeGrpc n1) {
+ return n0.getName().compareTo(n1.getName());
+ }
+}
+
+class NeighbourGrpcComparator implements Comparator<NeighbourGrpc> {
+ public int compare(NeighbourGrpc n0, NeighbourGrpc n1) {
+ return n0.getName().compareTo(n1.getName());
+ }
+}
+
+class GraphGrpcComparator implements Comparator<GraphGrpc> {
+ public int compare(GraphGrpc n0, GraphGrpc n1) {
+ if(n0.getId() == n1.getId())
+ return 0;
+ else if (n0.getId() > n1.getId())
+ return 1;
+ else return -1;
+ }
+} \ No newline at end of file
diff --git a/verigraph/src/it/polito/verigraph/grpc/test/MultiThreadTest.java b/verigraph/src/it/polito/verigraph/grpc/test/MultiThreadTest.java
new file mode 100644
index 0000000..79deaff
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/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.verigraph.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 it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.NodeGrpc;
+import it.polito.verigraph.client.VerifyClientException;
+import it.polito.verigraph.grpc.client.Client;
+import it.polito.verigraph.grpc.server.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/it/polito/verigraph/grpc/test/ReachabilityTest.java b/verigraph/src/it/polito/verigraph/grpc/test/ReachabilityTest.java
new file mode 100644
index 0000000..a256763
--- /dev/null
+++ b/verigraph/src/it/polito/verigraph/grpc/test/ReachabilityTest.java
@@ -0,0 +1,274 @@
+/*******************************************************************************
+ * 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.verigraph.grpc.test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+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 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 it.polito.verigraph.grpc.GraphGrpc;
+import it.polito.verigraph.grpc.NewGraph;
+import it.polito.verigraph.grpc.Policy;
+import it.polito.verigraph.grpc.VerificationGrpc;
+import it.polito.verigraph.client.VerifyClientException;
+import it.polito.verigraph.grpc.client.Client;
+import it.polito.verigraph.grpc.server.GrpcUtils;
+import it.polito.verigraph.grpc.server.Service;
+import it.polito.verigraph.service.ValidationUtils;
+import it.polito.verigraph.test.TestCase;
+import it.polito.verigraph.test.TestExecutionException;
+
+@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] wrongReachability starts");
+ System.out.println("DEBUG: starting testWrongReachability");
+
+ VerificationGrpc nullVer = VerificationGrpc.newBuilder()
+ .setErrorMessage("There is no Graph whose Id is '52'").build();
+ //verification on uncreated graph
+ if(client.getGraph(52) != null){
+ client.deleteGraph(52);
+ }
+ Policy policyToVerify = Client.createPolicy("Node1", "Node4", "reachability", null, 52);
+ VerificationGrpc ver = client.verify(policyToVerify);
+ assertEquals(ver, nullVer);
+
+ //verification on uncreated nodes
+ GraphGrpc graph = GraphGrpc.newBuilder().build();
+ graph = client.createGraph(graph).getGraph();
+ 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, graph.getId());
+ 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, graph.getId());
+ 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 {
+ System.out.println("[DEBUG] runTestCases starts");
+ int counter = 0;
+ for (TestCase tc : this.testCases) {
+ List<String> results = runTestCase(tc);
+ Iterator<String> iter = tc.getResults().iterator();
+
+ if(results.isEmpty()){
+ throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()+ "'.");
+ }
+
+ for(String result : results){
+ if (iter.hasNext()){
+ if( !result.equals(iter.next()))
+ throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
+ + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
+ else
+ System.out.println("Test given in file '"+ this.testFiles.get(counter).getName() + "' returned '"
+ + result + "' as expected");
+ } else throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
+ + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
+ }
+ counter++;
+
+ }
+ System.out.println("All tests PASSED");
+ }
+
+ private List<String> runTestCase(TestCase tc) throws VerifyClientException, TestExecutionException{
+ GraphGrpc graph = GrpcUtils.obtainGraph(tc.getGraph());
+ ArrayList<String> results = new ArrayList<String>();
+
+ 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);
+
+ for(String url : tc.getPolicyUrlParameters()){
+ final Map<String, String> map = GrpcUtils.getParamGivenString(url);
+ Policy policy = Client.createPolicy(map.get("source"),
+ map.get("destination"),
+ map.get("type"),
+ map.get("middlebox"),
+ createdGraph.getId());
+ VerificationGrpc verification = this.client.verify(policy);
+ results.add(verification.getResult());
+ }
+ return results;
+ }
+
+ 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();
+ }
+
+}