From: serena.spinoso Date: Sun, 29 Apr 2018 08:48:44 +0000 (+0200) Subject: Add CLI in verigraph. X-Git-Tag: 1.1.0~2^2 X-Git-Url: https://gerrit.opnfv.org/gerrit/gitweb?a=commitdiff_plain;h=refs%2Fchanges%2F75%2F56875%2F1;p=parser.git Add CLI in verigraph. JIRA: PARSER-180 Add CLI to select one of the available interfaces (i.e. REST or gRPC), one of the supported service descriptor formats (i.e. TOSCA/XML, TOSCA/YAML, JSON), and the operations to perform (i.e. read, create, update, delete graphs and run verifications). Change-Id: I02f4d86e221baf0ac583d0ffd0ebe028aa6209be Signed-off-by: serena.spinoso --- diff --git a/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateException.java b/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateException.java new file mode 100644 index 0000000..b5fb868 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateException.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2018 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.exception; + +public class InvalidServiceTemplateException extends RuntimeException { + + private static final long serialVersionUID = -3138131670694139585L; + + public InvalidServiceTemplateException(String message) { + super(message); + } +} diff --git a/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateExceptionMapper.java b/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateExceptionMapper.java new file mode 100644 index 0000000..e796119 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/exception/InvalidServiceTemplateExceptionMapper.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2018 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.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import it.polito.verigraph.model.ErrorMessage; + +@Provider +public class InvalidServiceTemplateExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(InvalidServiceTemplateException exception) { + ErrorMessage errorMessage = new ErrorMessage( exception.getMessage(), + 400, + "http://localhost:8080/verigraph/api-docs/"); + return Response.status(Status.BAD_REQUEST).entity(errorMessage).build(); + } + +} \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/MappingUtils.java b/verigraph/src/it/polito/verigraph/tosca/MappingUtils.java new file mode 100644 index 0000000..a415ad2 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/MappingUtils.java @@ -0,0 +1,215 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.InjectableValues; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; + +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TDocumentation; +import it.polito.tosca.jaxb.TServiceTemplate; +import it.polito.verigraph.grpc.ToscaConfigurationGrpc; +import it.polito.verigraph.model.Graph; +import it.polito.verigraph.model.Node; +import it.polito.verigraph.model.Test; +import it.polito.verigraph.model.Verification; +import it.polito.verigraph.tosca.converter.xml.GraphToXml; +import it.polito.verigraph.tosca.converter.yaml.GraphToYaml; +import it.polito.verigraph.tosca.deserializer.XmlConfigurationDeserializer; +import it.polito.verigraph.tosca.serializer.XmlConfigSerializer; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.VerificationYaml; + +public class MappingUtils { + + public static String prettyPrintJsonString(JsonNode jsonNode) { + try { + ObjectMapper mapper = new ObjectMapper(); + Object json = mapper.readValue(jsonNode.toString(), Object.class); + return System.getProperty("line.separator") + mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(json) + System.getProperty("line.separator"); + } catch (Exception e) { + return "Sorry, pretty print didn't work"; + } + } + + // From a list of nodes (path) returns a Definitions object that contains all the paths as different service templates + public static Definitions mapPathsToXml(List> paths) { + Definitions definitions = new Definitions(); + List tempGraphs = new ArrayList(); + + int i = 0; + for (List path: paths) { + Graph tempGraph = new Graph(); + tempGraph.setId(i++); + for (Node node : path) + tempGraph.getNodes().put(node.getId(), node); + tempGraphs.add(tempGraph); + } + + for (Graph g: tempGraphs) { + definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(GraphToXml.mapPathToXml(g)); + } + + return definitions; + } + + + // From a list of nodes (path) returns a list of ServiceTemplateYaml object that represent the paths + public static List mapPathsToYaml(List> paths) { + List serviceTemplates = new ArrayList(); + List tempGraphs = new ArrayList(); + + int i = 0; + for (List path: paths) { + Graph tempGraph = new Graph(); + tempGraph.setId(i++); + for (Node node : path) + tempGraph.getNodes().put(node.getId(), node); + tempGraphs.add(tempGraph); + } + + for (Graph g: tempGraphs) { + serviceTemplates.add(GraphToYaml.mapGraphYaml(g)); + } + + return serviceTemplates; + } + + + public static Definitions mapVerificationToXml(Verification verification) { + Definitions toscaVerification = new Definitions(); + TDocumentation toscaVerificationResult = new TDocumentation(); + toscaVerificationResult.setSource(verification.getResult() + ": " + verification.getComment()); + toscaVerification.getDocumentation().add(toscaVerificationResult); + + List toscaPaths = new ArrayList(); + + int i = 0; + for (Test test: verification.getTests()) { + Graph tempGraph = new Graph(); + tempGraph.setId(i++); + for (Node node : test.getPath()) + tempGraph.getNodes().put(node.getId(), node); + + TServiceTemplate toscaPath = GraphToXml.mapPathToXml(tempGraph); + TDocumentation toscaTestResult = new TDocumentation(); + toscaTestResult.setSource(test.getResult()); + toscaPath.getDocumentation().add(toscaTestResult); + toscaPaths.add(toscaPath); + } + + toscaVerification.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().addAll(0, toscaPaths); + return toscaVerification; + } + + + public static VerificationYaml mapVerificationToYaml(Verification verification) { + VerificationYaml verificationYaml = new VerificationYaml(); + verificationYaml.setResult(verification.getResult()); + verificationYaml.setComment(verification.getComment()); + + List toscaPaths = new ArrayList(); + + int i = 0; + for (Test test: verification.getTests()) { + Graph tempGraph = new Graph(); + tempGraph.setId(i++); + for (Node node : test.getPath()) + tempGraph.getNodes().put(node.getId(), node); + + ServiceTemplateYaml toscaPath = GraphToYaml.mapGraphYaml(tempGraph); + toscaPath.getMetadata().put("result", test.getResult()); + toscaPaths.add(toscaPath); + } + + verificationYaml.setPaths(toscaPaths); + return verificationYaml; + } + + + /** Return a string that represent the Tosca Configuration in json string. + * + * The string can be converted in JsonNode to be inserted in Model Configuration. + * + * Used for: xml-->model + * @throws JsonProcessingException*/ + public static String obtainStringConfiguration(it.polito.tosca.jaxb.Configuration nodeConfig) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + module.addSerializer(it.polito.tosca.jaxb.Configuration.class, new XmlConfigSerializer()); + mapper.registerModule(module); + + String stringConfiguration = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(nodeConfig); + if (stringConfiguration.equals("") || stringConfiguration == null) + return "[]"; + else + return stringConfiguration; + } + + + /** Return a Tosca Configuration with inside the representation of a model Configuration (only its JsonNode) + * + * Used for: model-->xml + * @throws JsonProcessingException */ + public static it.polito.tosca.jaxb.Configuration obtainToscaConfiguration(it.polito.verigraph.model.Configuration modelConfig, String type) throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + + //Passing the configuration type to the Deserializer context + module.addDeserializer(it.polito.tosca.jaxb.Configuration.class, new XmlConfigurationDeserializer()); + mapper.registerModule(module); + + it.polito.tosca.jaxb.Configuration toscaConfig = new it.polito.tosca.jaxb.Configuration(); + try { + toscaConfig = mapper.reader(new InjectableValues.Std().addValue("type", type)) + .forType(it.polito.tosca.jaxb.Configuration.class) + .readValue(modelConfig.getConfiguration()); + } catch (IOException e) { + //TODO shall we suppose that configuration stored on DB are always correct? + } + + return toscaConfig; + } + + /** Return a Tosca Configuration from a ConfigurationGrpc + * + * Used for: grpc-->xml + * @throws JsonProcessingException */ + public static it.polito.tosca.jaxb.Configuration obtainToscaConfiguration(ToscaConfigurationGrpc grpcConfig, String type) throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + + //Passing the configuration type to the Deserializer context + module.addDeserializer(it.polito.tosca.jaxb.Configuration.class, new XmlConfigurationDeserializer()); + mapper.registerModule(module); + + it.polito.tosca.jaxb.Configuration toscaConfig = new it.polito.tosca.jaxb.Configuration(); + try { + toscaConfig = mapper.reader(new InjectableValues.Std().addValue("type", type)) + .forType(it.polito.tosca.jaxb.Configuration.class) + .readValue(grpcConfig.getConfiguration()); + } catch (IOException e) { + //TODO shall we suppose that configuration stored on DB are always correct? + } + + return toscaConfig; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/README_CLI.txt b/verigraph/src/it/polito/verigraph/tosca/README_CLI.txt new file mode 100644 index 0000000..6ee1332 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/README_CLI.txt @@ -0,0 +1,66 @@ +** Verigraph Verification Service - Command Line Interface ** + +The CLI allows to interact with the Verigraph Verification Service using both the RESTful and gRPC interface. +The CLI allows CRUD operations on graphs and three kind of verification. + + +-- Available commands -- +> CONFIGURE -use -format -port -host +> HELP +> EXIT +> GETALL +> GET +> CREATE +> UPDATE +> DELETE +> VERIFY [ ] + + +-- CLI commands -- +> CONFIGURE -use -format +Allows to configure connection parameters (host and port ), the interface (REST or gRPC ) and the data format +(JSON, XML or YAML ) to be used to communicate with the verification service, XML and YAML formats exploit an extension +of TOSCA specification. At program start the default configuration uses the REST interface with XML data format. +Note that the JSON format is not supported by the grpc interface. + +> HELP +Prints on screen the CLI documentation. + +> EXIT +Closes REST/gRPC client and exits. + + +-- CRUD on graphs -- +> GETALL +Performs a request without specifying a particular graph id. The service will return +a list of graph templates in the currently selected format and will print them on screen. + +> GET +Performs a request for a specific graph whose id MUST be specified as a long integer +value. If present the graph will be returned and printed on screen in the currently selected format. + +> CREATE +Performs a create graph request providing a graph template as a file. +The must point to an existing file whose filenme must be coherent with the currently selected +data format. The server can accept or not the provided graph upon its validation against Tosca Verigraph specification +for XML/YAML or against Verigraph JSON schema. For further info see Verigraph Service documentation at [...]. + +> UPDATE +Performs an update request for a specific graph providing a graph template as a file. +The provided filename must be coherent with the currently selected data format and the must be a long integer +corresponding to one of the graphs previously created. The server can accept or not the provided graph upon its +validation against Tosca Verigraph specification for XML/YAML or against Verigraph JSON schema. +For further info see Verigraph Service documentation at [...]. + +> DELETE +Performs a delete request for a specific graph. +The provided id must be a long integer corresponding to a previously created graph. + + +-- Verification -- +> VERIFY [ ] +Performs a verification request for a specific graph. +The must be the long integer id of a previously created graph. Three types of verification services are +available: reachability, isolation and traversal. The source, destination and middlebox node parameters +must be provided as string and must correspond to the name of a Node in the specified graph. The middlebox parameter +must not be provided in case of reachability verification. \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/ToscaCLI.java b/verigraph/src/it/polito/verigraph/tosca/ToscaCLI.java new file mode 100644 index 0000000..c9f01c2 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/ToscaCLI.java @@ -0,0 +1,1055 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +import javax.ws.rs.ProcessingException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; +import com.sun.research.ws.wadl.ObjectFactory; + +import it.polito.tosca.jaxb.Configuration; +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TDefinitions; +import it.polito.verigraph.grpc.GraphGrpc; +import it.polito.verigraph.grpc.TopologyTemplateGrpc; +import it.polito.verigraph.grpc.ToscaPolicy; +import it.polito.verigraph.grpc.client.ToscaClient; +import it.polito.verigraph.grpc.server.GrpcUtils; +import it.polito.verigraph.model.Graph; +import it.polito.verigraph.tosca.converter.grpc.GraphToGrpc; +import it.polito.verigraph.tosca.converter.grpc.GrpcToGraph; +import it.polito.verigraph.tosca.converter.grpc.GrpcToXml; +import it.polito.verigraph.tosca.converter.grpc.GrpcToYaml; +import it.polito.verigraph.tosca.converter.grpc.XmlToGrpc; +import it.polito.verigraph.tosca.converter.grpc.YamlToGrpc; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; + + +public class ToscaCLI { + + private static final String helper = "./README_CLI.txt"; + + //Service parameters. + private String host; + private int port; + + //New media type for yaml rest request + private static final MediaType yamlMedia = new MediaType("application", "x-yaml"); + private static final String defaultHost = "localhost"; + private static final int defaultRestPort = 8080; + private static final int defaultGrpcPort = 50051; + + //Input validation patterns + private static final Pattern yamlSource = Pattern.compile(".*\\.yaml$"); + private static final Pattern xmlSource = Pattern.compile(".*\\.xml"); + private static final Pattern jsonSource = Pattern.compile(".*\\.json$"); + private static final Pattern configOpt = Pattern.compile("-use|-format|-port|-host", Pattern.CASE_INSENSITIVE); + private static final Pattern useOpt = Pattern.compile("grpc|rest", Pattern.CASE_INSENSITIVE); + private static final Pattern formatOpt = Pattern.compile("yaml|json|xml", Pattern.CASE_INSENSITIVE); + private static final Pattern policies = Pattern.compile("reachability|isolation|traversal", Pattern.CASE_INSENSITIVE); + + //Configuration parameters + private Boolean useRest; + private String mediatype; + private Client restClient; + private ToscaClient grpcClient; + + public ToscaCLI(){ + //Variables representing the client environment + this.useRest = true; + this.port = defaultRestPort; + this.host = defaultHost; + this.mediatype = MediaType.APPLICATION_XML; + this.restClient = null; + this.grpcClient = null; + } + + + public static void main(String[] args) { + ToscaCLI myclient = new ToscaCLI(); + try { + myclient.clientStart(); + } catch (Exception e) { + System.out.println("-- Unexpected error, service closing."); + } + return; + } + + //Build base Uri for REST service + private String buildBaseUri() { + return "http://" + this.host + ":" + String.valueOf(this.port) + "/verigraph/api/graphs"; + } + + //Function iterating getting user commands. + public void clientStart(){ + System.out.println("++ Welcome to Verigraph Verification Service..."); + System.out.println("++ Type HELP for instructions on client use..."); + + Scanner reader = null; + InputStream input = System.in; + Scanner scan = new Scanner(System.in); + String commandline; + + while(true) { + System.out.print("++ Please insert command : "); + try{ + + while(input.available()!=0) input.skip(input.available()); + commandline = scan.nextLine(); + reader = new Scanner(commandline); + + switch (reader.next().toUpperCase()) { + case "GETALL": + if(useRest) this.restGetAll(reader); + else this.grpcGetAll(reader); + break; + case "GET": + if(useRest) this.restGet(reader); + else this.grpcGet(reader); + break; + case "CREATE": + if(useRest) this.restCreate(reader); + else this.grpcCreate(reader); + break; + case "DELETE": + if(useRest) this.restDelete(reader); + else grpcDelete(reader); + break; + case "UPDATE": + if(useRest) this.restUpdate(reader); + else this.grpcUpdate(reader); + break; + case "VERIFY": + if(useRest) this.restVerify(reader); + else this.grpcVerify(reader); + break; + case "HELP": + this.printHelper(); + break; + case "CONFIGURE": + this.setConfig(reader); + break; + case "EXIT": + System.out.println("++ Client closing..."); + scan.close(); + input.close(); + reader.close(); + if(grpcClient != null) this.grpcClient.shutdown(); + if(restClient != null) this.restClient.close(); + System.out.println("++ Goodbye!"); + System.exit(0); + break; + default: + System.out.println("-- Unknown or bad formed command, type HELP to show commands documentation."); + break; + } + + }catch(NoSuchElementException ex) { + System.err.println("-- Unrecognized or incorrect command," + + " type help to know how to use the client..."); + continue; + }catch(IOException | InterruptedException ex){ + handleError(ex); + }finally { + reader.close(); + } + } + + } + + + public void printHelper() { + Scanner filereader = null; + try { + File inputfile = new File(helper); + filereader = new Scanner(inputfile).useDelimiter("\\Z"); + String content = filereader.next(); + if (filereader.ioException() != null) { + throw new IOException(filereader.ioException()); + } + if(content != null) System.out.println(content); + } catch (IOException e) { + handleError(e); + }finally { + if(filereader != null) filereader.close(); + } + + } + + public void setConfig(Scanner reader) throws InterruptedException { + if(!reader.hasNext(configOpt)) { + System.out.println("-- No or bad formed configuration options provided."); + return; + } + while(reader.hasNext(configOpt)) { + switch(reader.next().toLowerCase()) { + case "-use": + if(reader.hasNext(useOpt)) { + if(reader.next().toLowerCase().equals("rest")) { + if(grpcClient != null) { + grpcClient.shutdown(); + grpcClient = null; + } + this.port = defaultRestPort; + restClient = ClientBuilder.newClient(); + useRest = true; + } + else { + if(restClient != null) { + restClient.close(); + restClient = null; + } + this.port = defaultGrpcPort; + grpcClient = new ToscaClient(host, port); + useRest = false; + } + }else { + System.out.println("-- Unrecognized values for option -use, accepted values are: rest, grpc."); + } + break; + case "-format": + if(reader.hasNext(formatOpt)) { + String command = reader.next(); + if(command.toLowerCase().equals("json")) mediatype = MediaType.APPLICATION_JSON; + else if(command.toLowerCase().equals("xml")) mediatype = MediaType.APPLICATION_XML; + else if(command.toLowerCase().equals("yaml")) mediatype = "application/x-yaml"; + }else { + System.out.println("-- Unrecognized values for option -format, accepted formats are: json, xml, yaml."); + } + break; + case "-host": + if(reader.hasNext()) { + this.host = reader.next(); + if(grpcClient != null) { + grpcClient.shutdown(); + grpcClient = new ToscaClient(host, port); + System.out.println("++ Host configuration changed restarting grpc client..."); + } + } + else { + System.out.println("-- Provide a valid hostname."); + } + break; + case "-port": + if(reader.hasNextInt()) { + int newvalue = reader.nextInt(); + if(0 > newvalue || 65535 < newvalue) { + System.out.println("-- The provided port number is not valid, port has not been modified."); + }else { + this.port = newvalue; + if(grpcClient != null) { + grpcClient.shutdown(); + grpcClient = new ToscaClient(host, port); + System.out.println("++ Port configuration changed restarting grpc client..."); + } + } + } + else { + System.out.println("-- Provide a port as an integer."); + } + break; + default: + System.out.println("-- Unrecognized option!"); + } + } + + } + + //Utility function used only to print exception message + public void handleError(Exception e) { + String errMsg = e.getMessage(); + if(errMsg == null) { + System.out.println("-- Error: unexpected error occurred."); + }else { + System.out.println("-- Error: " + errMsg); + } + return; + } + + + // RESTful service interface CRUD and Verify functions + public void restGetAll(Scanner reader) { + try { + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + // targeting the graphs resource + WebTarget target = restClient.target(this.buildBaseUri()); + + // Performing the request and reading the response + Response res = target.request(mediatype).get(); + this.readResponseRest("GETALL", res); + + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + }catch (Exception e) { + handleError(e); + } + return; + } + + + public void restGet(Scanner reader) { + + try { + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + if (!reader.hasNextLong()) { + System.out.println("-- Provide the integer Id for the requested graph."); + return; + } + + // Targeting the specified graph resource + WebTarget target = restClient.target(this.buildBaseUri() + "/" + String.valueOf(reader.nextLong())); + + // Performing the request and reading the response + Response res = target.request(mediatype).get(); + this.readResponseRest("GET", res); + + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + } catch (Exception e) { + handleError(e); + } + + } + + + + public void restCreate(Scanner reader) { + + try { + // Getting file content + String content = readFile(reader); + if (content == null) { + System.out.println("-- The required operation can't be performed."); + return; + } + + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + // Targeting the resource + WebTarget target = restClient.target(this.buildBaseUri()); + + // Performing the request and reading the response + Builder mypost = target.request(mediatype); + Response res = null; + switch (mediatype) { + case MediaType.APPLICATION_JSON: + res = mypost.post(Entity.json(content)); + break; + case MediaType.APPLICATION_XML: + res = mypost.post(Entity.xml(content)); + break; + case "application/x-yaml": + res = mypost.post(Entity.entity(content, yamlMedia)); + break; + } + + this.readResponseRest("CREATE", res); + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + } catch (Exception e) { + handleError(e); + } + + return; + } + + + + public void restDelete(Scanner reader) { + try { + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + if (!reader.hasNextLong()) { + System.out.println("-- Provide the integer Id of the graph you want to delete."); + return; + } + + // Targeting the specified graph resource + WebTarget target = restClient.target(this.buildBaseUri() + "/" + String.valueOf(reader.nextLong())); + + // Performing the request and reading the response + Response res = target.request(mediatype).delete(); + this.readResponseRest("DELETE", res); + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + } catch (Exception e) { + handleError(e); + } + + return; + } + + + public void restUpdate(Scanner reader) { + try { + + //Getting the target graph + if(!reader.hasNextLong()) { + System.out.println("-- Please provide a valid id for the graph to be update"); + return; + } + + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + // Targeting the resource + WebTarget target = restClient.target(this.buildBaseUri() + "/" + reader.next()); + + // Getting file content + String content = readFile(reader); + if (content == null) { + System.out.println("-- The required operation can't be performed."); + return; + } + + // Performing the request and reading the resonse + Builder myupdate = target.request(mediatype); + Response res = null; + switch (mediatype) { + case MediaType.APPLICATION_JSON: + res = myupdate.put(Entity.json(content)); + break; + case MediaType.APPLICATION_XML: + res = myupdate.put(Entity.xml(content)); + break; + case "application/x-yaml": + res = myupdate.put(Entity.entity(content, yamlMedia)); + break; + } + + this.readResponseRest("UPDATE", res); + + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + } catch (Exception e) { + handleError(e); + } + + } + + + public void restVerify(Scanner reader) { + String whichpolicy = null; + String graphId, source, destination, middlebox = null; + + try { + if(!reader.hasNextLong()) { + System.out.println("-- Provide the graph on which you want to perform verification."); + return; + } + graphId = reader.next(); + + if (!reader.hasNext(policies)) { + System.out.println("-- Provide the requested type of verfication."); + return; + } + whichpolicy = reader.next().toLowerCase(); + + try { + source = reader.next(); + destination = reader.next(); + if(!whichpolicy.equals("reachability")) { + middlebox = reader.next(); + } + }catch(NoSuchElementException ex) { + System.out.println("-- Wrong or missing verification parameters."); + return; + } + + // Build a new client if it does not exist + if (restClient == null) + restClient = ClientBuilder.newClient(); + + // Targeting the resource + WebTarget target = restClient.target(this.buildBaseUri() + "/" + graphId + "/policy") + .queryParam("source", source) + .queryParam("destination", destination) + .queryParam("type", whichpolicy); + if(!whichpolicy.equals("reachability")) { + target = target.queryParam("middlebox", middlebox); + } + + Response res = target.request(mediatype).get(); + this.readResponseRest("VERIFY", res); + }catch(ProcessingException e) { + System.out.println("-- Error: the provided host address is not valid."); + } catch (Exception e) { + handleError(e); + } + + } + + //gRPC service interface CRUD and Verify functions + public void grpcGetAll(Scanner reader) { + + try { + if(grpcClient == null) + grpcClient = new ToscaClient(host, port); + + //Added for backward compatibility with JSON grpc + if(mediatype == MediaType.APPLICATION_JSON) { + List receivedGraphsGrpc = grpcClient.getGraphs(); + + if(receivedGraphsGrpc == null) { + System.out.println("-- GET Failed : was not possible to perform the required operations."); + return; + } + else if(receivedGraphsGrpc.isEmpty()) { + System.out.println("++ GET Success no graph was returned."); + return; + } + + List receivedGraphs = new ArrayList(); + for(GraphGrpc curr : receivedGraphsGrpc) { + receivedGraphs.add(GrpcUtils.deriveGraph(curr)); + } + this.marshallToJson(receivedGraphs); + return; + } + + //Code for the Tosca compliant implementation + List templates; + templates = grpcClient.getTopologyTemplates(); + + if(templates == null) { + System.out.println("-- GET Failed : was not possible to perform the required operations."); + return; + } + else if(templates.isEmpty()) { + System.out.println("++ GET Success no graph was returned."); + return; + } + + switch(mediatype) { + case MediaType.APPLICATION_XML: + List receivedDefs = new ArrayList(); + for(TopologyTemplateGrpc curr : templates) { + receivedDefs.add(GrpcToXml.mapGraph(curr)); + } + this.marshallToXml(receivedDefs); + break; + + case "application/x-yaml": + List receivedTempls = new ArrayList(); + for(TopologyTemplateGrpc curr : templates) { + receivedTempls.add(GrpcToYaml.mapGraphYaml(curr)); + } + this.marshallToYaml(receivedTempls); + break; + + } + } catch (Exception e) { + handleError(e); + } + + } + + + public void grpcGet(Scanner reader) { + + try { + if (grpcClient == null) + grpcClient = new ToscaClient(host, port); + + if (!reader.hasNextLong()) { + System.out.println("-- Provide the integer Id for the requested graph."); + return; + } + + //Added for backward compatibility with JSON grpc + if(mediatype == MediaType.APPLICATION_JSON) { + GraphGrpc graph = grpcClient.getGraph(reader.nextLong()); + if(graph == null || !graph.getErrorMessage().equals("")); + List receivedGraphs = new ArrayList(); + receivedGraphs.add(GrpcUtils.deriveGraph(graph)); + this.marshallToJson(receivedGraphs); + return; + } + + //Code for Tosca compliant implementation + TopologyTemplateGrpc templ = grpcClient.getTopologyTemplate(reader.next()); + if(templ == null || !templ.getErrorMessage().equals("")) { + return; + } + switch(mediatype) { + // case MediaType.APPLICATION_JSON: + // Graph obt = GrpcToGraph.deriveGraph(templ); + // List list = new ArrayList(); + // list.add(obt); + // marshallToJson(list); + // break; + case MediaType.APPLICATION_XML: + List receivedDefs = new ArrayList(); + receivedDefs.add(GrpcToXml.mapGraph(templ)); + this.marshallToXml(receivedDefs); + break; + + case "application/x-yaml": + List receivedTempls = new ArrayList(); + receivedTempls.add(GrpcToYaml.mapGraphYaml(templ)); + this.marshallToYaml(receivedTempls); + break; + } + + } catch (Exception e) { + handleError(e); + } + } + + public void grpcCreate(Scanner reader) { + try { + if (grpcClient == null) + grpcClient = new ToscaClient(host, port); + + switch (mediatype) { + case MediaType.APPLICATION_JSON: + if(reader.hasNext(jsonSource)) { + ObjectMapper mapper = new ObjectMapper(); + Graph modelGraph = mapper.readValue(readFile(reader), Graph.class); + GraphGrpc graph = GrpcUtils.obtainGraph(modelGraph); + grpcClient.createGraph(graph); + }else { + System.out.println("-- The provided file is not compatible with the current configuration [json]."); + return; + } + break; + case MediaType.APPLICATION_XML: + if (reader.hasNext(xmlSource)) { + grpcClient.createTopologyTemplate(XmlToGrpc.obtainTopologyTemplateGrpc(reader.next())); + } else { + System.out.println("-- The provided file is not compatible with the current configuration [xml]."); + return; + } + break; + + case "application/x-yaml": + if (reader.hasNext(yamlSource)) { + grpcClient.createTopologyTemplate(YamlToGrpc.obtainTopologyTemplateGrpc(reader.next())); + } else { + System.out.println("-- The provided file is not compatible with the current configuration [yaml]."); + return; + } + break; + } + + } catch (JAXBException je) { + System.out.println("-- Error while parsing xml : " + je.getMessage()); + } catch (IOException ie) { + System.out.println("-- Error reading the file : " + ie.getMessage()); + } catch(Exception e) { + handleError(e); + } + + return; + } + + + public void grpcDelete(Scanner reader) { + + try { + if (grpcClient == null) + grpcClient = new ToscaClient(host, port); + + if (!reader.hasNextLong()) { + System.out.println("-- Provide the integer Id of the graph you want to delete."); + return; + } + + grpcClient.deleteTopologyTemplate(reader.next()); + + } catch (Exception e) { + handleError(e); + } + + return; + } + + + public void grpcUpdate(Scanner reader) { + try { + if (grpcClient == null) + grpcClient = new ToscaClient(host, port); + + //Checking if user ha provided the id of the graph to be updated and retrieving it + if(!reader.hasNextLong()) { + System.out.println("-- Please provide a valid id for the graph to be update"); + return; + } + String id = reader.next(); + + //Reading the file and performing the request according to current configuration + switch (mediatype) { + case MediaType.APPLICATION_JSON: + if(reader.hasNext(jsonSource)) { + ObjectMapper mapper = new ObjectMapper(); + Graph modelGraph = mapper.readValue(readFile(reader), Graph.class); + GraphGrpc graph = GrpcUtils.obtainGraph(modelGraph); + grpcClient.updateGraph(new Long(id), graph); + }else { + System.out.println("-- The provided file is not compatible with the current configuration [json]."); + return; + } + break; + case MediaType.APPLICATION_XML: + if (reader.hasNext(xmlSource)) { + grpcClient.updateTopologyTemplate(XmlToGrpc.obtainTopologyTemplateGrpc(reader.next()), id); + } else { + System.out.println("-- The provided file is not compatible with the current configuration."); + return; + } + break; + + case "application/x-yaml": + if (reader.hasNext(yamlSource)) { + grpcClient.updateTopologyTemplate(YamlToGrpc.obtainTopologyTemplateGrpc(reader.next()), id); + } else { + System.out.println("-- The provided file is not compatible with the current configuration."); + return; + } + break; + } + } catch (JAXBException je) { + System.out.println("-- Error while parsing xml : " + je.getMessage()); + } catch (IOException ie) { + System.out.println("-- Error reading the file : " + ie.getMessage()); + } catch(Exception e) { + handleError(e); + } + } + + + public void grpcVerify(Scanner reader) { + ToscaPolicy.Builder policyBuilder = ToscaPolicy.newBuilder(); + String graphId, whichPolicy, source, destination, middlebox = null; + + try { + if(!reader.hasNextLong()) { + System.out.println("-- Provide the graph on which you want to perform verification."); + return; + } + graphId = reader.next(); + + if (!reader.hasNext(policies)) { + System.out.println("-- Provide the requested type of verfication."); + return; + } + whichPolicy = reader.next().toLowerCase(); + + try { + source = reader.next(); + destination = reader.next(); + if(!whichPolicy.equals("reachability")) { + middlebox = reader.next(); + } + }catch(NoSuchElementException ex) { + System.out.println("-- Wrong or missing verification parameters."); + return; + } + + policyBuilder.setIdTopologyTemplate(graphId); + policyBuilder.setDestination(destination); + policyBuilder.setSource(source); + switch(whichPolicy) { + case "reachability": + policyBuilder.setType(ToscaPolicy.PolicyType.forNumber(0)); + break; + case "isolation": + policyBuilder.setType(ToscaPolicy.PolicyType.forNumber(1)); + policyBuilder.setMiddlebox(middlebox); + break; + case "traversal": + policyBuilder.setType(ToscaPolicy.PolicyType.forNumber(2)); + policyBuilder.setMiddlebox(middlebox); + break; + } + + if (grpcClient == null) + grpcClient = new ToscaClient(host, port); + + //Sending verification request + grpcClient.verifyPolicy(policyBuilder.build()); + + } catch (Exception e) { + handleError(e); + } + + return; + } + + + public void readResponseRest(String responseOf, Response res) { + switch(responseOf) { + case "GETALL": + switch (res.getStatus()) { + case 200: + System.out.println("++ GET success :"); + break; + case 500: + System.out.println("-- GET failed : internal server error."); + break; + default: + System.out.println("** Unexpected response"); + break; + } + break; + + case "GET": + switch (res.getStatus()) { + case 200: + System.out.println("++ GET success :"); + break; + case 404: + System.out.println("-- GET failed : graph not found."); + break; + case 500: + System.out.println("-- GET failed : internal server error."); + break; + default: + System.out.println("** Unexpected response **"); + break; + } + break; + + case "CREATE": + switch (res.getStatus()) { + case 201: + System.out.println("++ POST success : graph created."); + break; + case 400: + System.out.println("-- POST failed : bad request."); + break; + case 500: + System.out.println("-- POST failed : internal server error."); + break; + default: + System.out.println("** Unexpected response **"); + break; + } + break; + case "DELETE": + switch (res.getStatus()) { + case 204: + System.out.println("++ DELETE success : graph deleted."); + break; + case 403: + System.out.println("-- DELETE failed : invalid graph ID."); + break; + case 404: + System.out.println("-- DELETE failed : invalid graph id."); + break; + case 500: + System.out.println("-- DELETE failed : internal server error."); + break; + default: + System.out.println("** Unexpected response **"); + break; + } + break; + case "UPDATE": + switch (res.getStatus()) { + case 200: + System.out.println("++ PUT success : graph correctly updated."); + break; + case 400: + System.out.println("-- PUT failed : invalid graph object."); + break; + case 403: + System.out.println("-- PUT failed : invalid graph ID."); + break; + case 404: + System.out.println("-- PUT failed : graph not found."); + break; + case 500: + System.out.println("-- PUT failed : internal server error."); + break; + default: + System.out.println("** Unexpected response **"); + break; + } + break; + + default: + + } + + //In case of errors we do not read the message body + if(res.hasEntity() && res.getStatus() <= 300) { + String responseBody = prettyFormat(res.readEntity(String.class)); + if(responseBody != null) System.out.println(responseBody); + } + else { + System.out.println("++ No content in the message body"); + } + + return; + } + + + public void marshallToXml(List defs) { + try { + JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class, TDefinitions.class, Configuration.class); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + for (Definitions def : defs) { + // To be tested, in case of problems def must be converted to a JAXBElement + m.marshal(def, System.out); + System.out.println("\n"); + } + + } catch (JAXBException je) { + System.out.println("-- Error while marshalling : " + je.getMessage()); + } + return; + } + + public void marshallToYaml(List templates) { + try { + YAMLMapper mapper = new YAMLMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + for (ServiceTemplateYaml templ : templates) { + System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(templ)); + System.out.println("\n"); + } + + } catch (JsonProcessingException je) { + System.out.println("-- Error while marshalling : " + je.getMessage()); + + } + return; + } + + public void marshallToJson(List templates) { + try { + ObjectMapper mapper = new ObjectMapper(); + //mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + for (Graph templ : templates) { + System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(templ)); + System.out.println("\n"); + } + + } catch (JsonProcessingException je) { + System.out.println("-- Error while marshalling : " + je.getMessage()); + + } + return; + } + + + // Reads the whole file into a string and performs a minimum validation on file type + public String readFile(Scanner reader) { + + String content = null; + Scanner filereader = null; + if ((mediatype.equals("application/x-yaml") && reader.hasNext(yamlSource)) + || (mediatype.equals(MediaType.APPLICATION_XML) && reader.hasNext(xmlSource)) + || (mediatype.equals(MediaType.APPLICATION_JSON) && reader.hasNext(jsonSource))) { + try { + File inputfile = new File(reader.next()); + filereader = new Scanner(inputfile).useDelimiter("\\Z"); + content = filereader.next(); + if (filereader.ioException() != null) { + throw new IOException(filereader.ioException()); + } else { + System.out.println("++ File correctly read."); + } + } catch (FileNotFoundException ex) { + System.out.println("-- Error : the provided file does not exist!"); + }catch (IOException ex) { + System.out.println("-- Error : an error occurred reading the input file!"); + }catch (Exception e) { + handleError(e); + }finally { + if(filereader != null) filereader.close(); + } + + } else { + System.out.println("-- Error : the file provided in input does not match with the current client configuration."); + } + + return content; + } + + + public String prettyFormat(String input) { + String formattedString = null; + + try { + switch(mediatype) { + case MediaType.APPLICATION_XML: + Source xmlInput = new StreamSource(new StringReader(input)); + StringWriter stringWriter = new StringWriter(); + StreamResult xmlOutput = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + transformerFactory.setAttribute("indent-number", 2); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.transform(xmlInput, xmlOutput); + formattedString = xmlOutput.getWriter().toString(); + break; + case MediaType.APPLICATION_JSON: + ObjectMapper mapper = new ObjectMapper(); + Object jsonObj = mapper.readValue(input, Object.class); + formattedString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObj); + break; + case "application/x-yaml": + formattedString = input; + break; + } + } catch (Exception e) { + formattedString = e.getCause().toString(); + } + + return formattedString; + } + + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/XmlParsingUtils.java b/verigraph/src/it/polito/verigraph/tosca/XmlParsingUtils.java new file mode 100644 index 0000000..5830bf8 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/XmlParsingUtils.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2017/18 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.tosca; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.util.List; +import java.util.stream.Collectors; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; + +import com.sun.research.ws.wadl.ObjectFactory; + +import it.polito.verigraph.exception.DataNotFoundException; +import it.polito.tosca.jaxb.Configuration; +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TDefinitions; +import it.polito.tosca.jaxb.TEntityTemplate; +import it.polito.tosca.jaxb.TExtensibleElements; +import it.polito.tosca.jaxb.TNodeTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate; +import it.polito.tosca.jaxb.TServiceTemplate; +import it.polito.tosca.jaxb.TTopologyTemplate; +import it.polito.verigraph.tosca.converter.grpc.ToscaGrpcUtils; + + +public class XmlParsingUtils { + + /** Returns a List of TServiceTemplate JAXB-generated objects, parsed from a TOSCA-compliant XML. */ + public static Definitions obtainDefinitions(String file) throws JAXBException, IOException, ClassCastException, DataNotFoundException { + // Create a JAXBContext capable of handling the generated classes + JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class, TDefinitions.class, Configuration.class); + Unmarshaller u = jc.createUnmarshaller(); + + //Retrieve the TDefinitions object + Source source = new StreamSource(new FileInputStream(file)); + + JAXBElement rootElement = (JAXBElement)u.unmarshal(source, Definitions.class); + Definitions definitions = rootElement.getValue(); + return definitions; + } + + /** Returns a List of TServiceTemplate JAXB-generated objects, parsed from a TOSCA-compliant XML. */ + public static List obtainServiceTemplates(String file) throws JAXBException, IOException, ClassCastException, DataNotFoundException { + // Create a JAXBContext capable of handling the generated classes + JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class, TDefinitions.class, Configuration.class); + Unmarshaller u = jc.createUnmarshaller(); + + //Retrieve the TDefinitions object + Source source = new StreamSource(new FileInputStream(file)); + + JAXBElement rootElement = (JAXBElement)u.unmarshal(source, TDefinitions.class); + TDefinitions definitions = rootElement.getValue(); + List elements = definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation(); + + //Retrieve the list of ServiceTemplate in Definitions + List serviceTemplates = elements.stream() + .filter(p -> p instanceof TServiceTemplate) + .map(obj -> (TServiceTemplate) obj).collect(Collectors.toList()); + + if (serviceTemplates.isEmpty()) + throw new DataNotFoundException("There is no ServiceTemplate into the TOSCA XML file"); + return serviceTemplates; // Could be an empty list if there are no TServiceTemplate objects + } + + + /** Returns a List of TNodeTemplate JAXB-generated TOSCA objects. */ + public static List obtainNodeTemplates(TServiceTemplate serviceTemplate) throws DataNotFoundException { + TTopologyTemplate topologyTemplate = serviceTemplate.getTopologyTemplate(); + + // Retrieving a list of TNodeTemplate and TRelationshipTemplate JAXB objects + List entities = topologyTemplate.getNodeTemplateOrRelationshipTemplate(); + + // Retrieving a List containing only TNodeTemplates objects + List nodeTemplates = entities.stream() + .filter(p -> p instanceof TNodeTemplate) + .map(obj -> (TNodeTemplate) obj).collect(Collectors.toList()); + + if (nodeTemplates.isEmpty()) + throw new DataNotFoundException("There is no NodeTemplate into ServiceTemplate " + serviceTemplate.toString() + " and TopologyTemplate " + topologyTemplate.toString()); + return nodeTemplates; // Could be an empty list if there are no TNodeTemplate objects + } + + + /** Returns a List of TRelationshipTemplate JAXB-generated TOSCA objects. */ + public static List obtainRelationshipTemplates(TServiceTemplate serviceTemplate) throws DataNotFoundException { + TTopologyTemplate topologyTemplate = serviceTemplate.getTopologyTemplate(); + + // Retrieving a List of TNodeTemplate and TRelationshipTemplate JAXB objects + List entities = topologyTemplate.getNodeTemplateOrRelationshipTemplate(); + + // Retrieving a List containing only TRelationshipTemplate objects + List relationshipTemplates = entities.stream() + .filter(p -> p instanceof TRelationshipTemplate) + .map(obj -> (TRelationshipTemplate) obj).collect(Collectors.toList()); + + if (relationshipTemplates.isEmpty()) + throw new DataNotFoundException("There is no RelationshipTemplate into ServiceTemplate " + serviceTemplate.toString() + " and TopologyTemplate " + topologyTemplate.toString()); + return relationshipTemplates; // Could be an empty list if there are no TRelationshipTemplate objects + } + + + /** Returns the it.polito.tosca.jaxb.Configuration JAXB-generated TOSCA object of a TOSCA NodeTemplate. */ + public static Configuration obtainConfiguration(TNodeTemplate nodeTemplate) { + try { + Configuration configuration = (Configuration)nodeTemplate.getProperties().getAny(); + + //This could be eventually used to cross check node type and configuration type + //String typename = nodeTemplate.getType().getLocalPart().toLowerCase(); + return configuration; + + + } catch (NullPointerException | ClassCastException ex) { + //To be eventually defined a mechanism to distinguish hostnode from forwarder + System.out.println("[Warning] Node " + nodeTemplate.getId().toString() + + ": missing or invalid configuration, the node will be configured as a forwarder!" ); + Configuration defConf = new Configuration(); + defConf.setConfDescr(ToscaGrpcUtils.defaultDescr); + defConf.setConfID(ToscaGrpcUtils.defaultConfID); + + Configuration.FieldmodifierConfiguration defaultForward = new Configuration.FieldmodifierConfiguration(); + defaultForward.setName("DefaultForwarder"); + + defConf.setFieldmodifierConfiguration(defaultForward); + return defConf; + } + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/YamlParsingUtils.java b/verigraph/src/it/polito/verigraph/tosca/YamlParsingUtils.java new file mode 100644 index 0000000..6e65ac9 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/YamlParsingUtils.java @@ -0,0 +1,160 @@ +/******************************************************************************* + * Copyright (c) 2017/18 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.tosca; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.util.Map; + +import javax.xml.bind.JAXBException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.exception.DataNotFoundException; +import it.polito.verigraph.exception.InvalidServiceTemplateException; +import it.polito.verigraph.tosca.serializer.YamlConfigSerializer; +import it.polito.verigraph.tosca.yaml.beans.AntispamNode; +import it.polito.verigraph.tosca.yaml.beans.CacheNode; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiNode; +import it.polito.verigraph.tosca.yaml.beans.EndhostNode; +import it.polito.verigraph.tosca.yaml.beans.EndpointNode; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierNode; +import it.polito.verigraph.tosca.yaml.beans.FirewallNode; +import it.polito.verigraph.tosca.yaml.beans.MailClientNode; +import it.polito.verigraph.tosca.yaml.beans.MailServerNode; +import it.polito.verigraph.tosca.yaml.beans.NatNode; +import it.polito.verigraph.tosca.yaml.beans.NodeTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.RelationshipTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.TopologyTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessNode; +import it.polito.verigraph.tosca.yaml.beans.VpnExitNode; +import it.polito.verigraph.tosca.yaml.beans.WebClientNode; +import it.polito.verigraph.tosca.yaml.beans.WebServerNode; + +public class YamlParsingUtils { + + public static ServiceTemplateYaml obtainServiceTemplate(String filePath) throws InvalidServiceTemplateException { + ServiceTemplateYaml yamlServiceTemplate = new ServiceTemplateYaml(); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); + + try { + yamlServiceTemplate = mapper.readValue(new File(filePath), ServiceTemplateYaml.class); + return yamlServiceTemplate; + + } catch (JsonParseException e) { + throw new InvalidServiceTemplateException("The NodeTemplate IDs and the RelationshipTemplate IDs must be unique."); + } catch (JsonMappingException e) { + throw new InvalidServiceTemplateException("The provided file does not match the expected structure."); + } catch (InvalidServiceTemplateException e) { + throw new InvalidServiceTemplateException("The provided template contains errors or missing informations."); + } catch (IOException e) { + throw new InvalidServiceTemplateException("I/O error."); + } + + } + + + public static Map obtainNodeTemplates(ServiceTemplateYaml yamlService) throws DataNotFoundException { + TopologyTemplateYaml yamlTopology; + try { + yamlTopology = yamlService.getTopology_template(); + } catch(NullPointerException ex) { + throw new DataNotFoundException("The ServiceTemplate provided does not contain a TopologyTemplate."); + } + try { + Map nodes = yamlTopology.getNode_templates(); + return nodes; + } catch(NullPointerException ex) { + throw new DataNotFoundException("The ServiceTemplate provided does not contain any NodeTemplates."); + } + + } + + + public static Map obtainRelationshipTemplates(ServiceTemplateYaml yamlService) throws DataNotFoundException { + TopologyTemplateYaml yamlTopology; + try { + yamlTopology = yamlService.getTopology_template(); + } catch(NullPointerException ex) { + throw new DataNotFoundException("The ServiceTemplate provided does not contain a TopologyTemplate."); + } + try { + Map relats = yamlTopology.getRelationship_templates(); + return relats; + } catch(NullPointerException ex) { + throw new DataNotFoundException("The ServiceTemplate provided does not contain any RelationshipTemplates."); + } + + } + + + public static String obtainConfiguration(NodeTemplateYaml node) throws BadRequestException { + ConfigurationYaml yamlConfiguration = null; + ObjectMapper mapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + module.addSerializer(ConfigurationYaml.class, new YamlConfigSerializer()); + mapper.registerModule(module); + + // Find out node type, retrieve the corresponding configuration and convert it properly + try { + if(node instanceof AntispamNode) { + yamlConfiguration = ((AntispamNode)node).getProperties(); + }else if(node instanceof CacheNode) { + yamlConfiguration = ((CacheNode)node).getProperties(); + }else if(node instanceof DpiNode) { + yamlConfiguration = ((DpiNode)node).getProperties(); + }else if(node instanceof EndhostNode) { + yamlConfiguration = ((EndhostNode)node).getProperties(); + }else if(node instanceof EndpointNode) { + yamlConfiguration = ((EndpointNode)node).getProperties(); + }else if(node instanceof FieldModifierNode) { + yamlConfiguration = ((FieldModifierNode)node).getProperties(); + }else if(node instanceof FirewallNode) { + yamlConfiguration = ((FirewallNode)node).getProperties(); + }else if(node instanceof MailClientNode) { + yamlConfiguration = ((MailClientNode)node).getProperties(); + }else if(node instanceof MailServerNode) { + yamlConfiguration = ((MailServerNode)node).getProperties(); + }else if(node instanceof NatNode) { + yamlConfiguration = ((NatNode)node).getProperties(); + }else if(node instanceof VpnAccessNode) { + yamlConfiguration = ((VpnAccessNode)node).getProperties(); + }else if(node instanceof VpnExitNode) { + yamlConfiguration = ((VpnExitNode)node).getProperties(); + }else if(node instanceof WebClientNode) { + yamlConfiguration = ((WebClientNode)node).getProperties(); + }else if(node instanceof WebServerNode) { + yamlConfiguration = ((WebServerNode)node).getProperties(); + }else { + throw new BadRequestException("The provided node is of unknown type, unable to retrieve the node configuration"); + } + + String stringConfiguration = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(yamlConfiguration); + if (!stringConfiguration.equals("null")) + return stringConfiguration; + else + return "[]"; + + } catch (JsonProcessingException | NullPointerException e) { + throw new BadRequestException("Not able to retrieve a valid configuration"); + } + } + +} \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToXml.java b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToXml.java new file mode 100644 index 0000000..002737a --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToXml.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.grpc; + +import java.io.IOException; +import java.util.List; + +import javax.xml.namespace.QName; + +import it.polito.tosca.jaxb.Configuration; +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TEntityTemplate.Properties; +import it.polito.tosca.jaxb.TNodeTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate.SourceElement; +import it.polito.tosca.jaxb.TRelationshipTemplate.TargetElement; +import it.polito.tosca.jaxb.TServiceTemplate; +import it.polito.tosca.jaxb.TTopologyTemplate; +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.grpc.NodeTemplateGrpc; +import it.polito.verigraph.grpc.RelationshipTemplateGrpc; +import it.polito.verigraph.grpc.TopologyTemplateGrpc; +import it.polito.verigraph.grpc.ToscaConfigurationGrpc; +import it.polito.verigraph.tosca.MappingUtils; + +public class GrpcToXml { + + public static Definitions mapGraph(TopologyTemplateGrpc topologyGrpc) { + Definitions definitions = new Definitions(); + TServiceTemplate serviceTemplate = new TServiceTemplate(); + TTopologyTemplate topologyTemplate = new TTopologyTemplate(); + + for(NodeTemplateGrpc node : topologyGrpc.getNodeTemplateList()) { + TNodeTemplate nodeTemplate = mapNode(node); + topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate); + } + for(RelationshipTemplateGrpc relat : topologyGrpc.getRelationshipTemplateList()) { + TRelationshipTemplate relationshipTemplate = mapRelationship(relat, topologyGrpc.getNodeTemplateList()); + topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relationshipTemplate); + } + + try { + serviceTemplate.setId(String.valueOf(topologyGrpc.getId())); + } catch (NullPointerException e) { + throw new NullPointerException("The TopologyTemplateGrpc must have an ID."); + } + serviceTemplate.setTopologyTemplate(topologyTemplate); + definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(serviceTemplate); + return definitions; + } + + + private static TNodeTemplate mapNode(NodeTemplateGrpc node){ + TNodeTemplate nodeTemplate = new TNodeTemplate(); + + try { + nodeTemplate.setId(String.valueOf(node.getId())); + } catch (NullPointerException e) { + throw new NullPointerException("The NodeTemplateGrpc must have an ID."); + } + try { + nodeTemplate.setName(node.getName()); + } catch (NullPointerException e) { + throw new NullPointerException("The NodeTemplateGrpc must have a name."); + } + + try { + //QName type = new QName("http://docs.oasis-open.org/tosca/ns/2011/12/ToscaVerigraphDefinition") + QName type = new QName("http://docs.oasis-open.org/tosca/ns/2011/12", + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1) + "Type"); + nodeTemplate.setType(type); + } catch (NullPointerException e) { + throw new NullPointerException("The NodeTemplateGrpc must have a valid type."); + } + + Configuration config = mapModelConfiguration(node.getConfiguration(), node.getType().toString().toLowerCase()); + nodeTemplate.setProperties(new Properties()); + nodeTemplate.getProperties().setAny(config); + return nodeTemplate; + } + + + private static TRelationshipTemplate mapRelationship(RelationshipTemplateGrpc relat, List nodeList) { + TRelationshipTemplate relationship = new TRelationshipTemplate(); + SourceElement source = new SourceElement(); + TargetElement target = new TargetElement(); + int check = 0; + + TNodeTemplate sourceNode = new TNodeTemplate(); + TNodeTemplate targetNode = new TNodeTemplate(); + + try { + for(NodeTemplateGrpc node : nodeList) { + if(node.getId().equals(relat.getIdSourceNodeTemplate())) { + sourceNode = mapNode(node); + check++; + } + if(node.getId().equals(relat.getIdTargetNodeTemplate())) { + targetNode = mapNode(node); + check++; + } + } + } catch (NullPointerException e) { + throw new BadRequestException("A RelationshipTemplateGrpc must contain both source and target node ID."); + } + if(check != 2) + throw new BadRequestException("A RelationshipTemplateGrpc must contain both source and target node ID."); + + source.setRef(sourceNode); + target.setRef(targetNode); + + relationship.setId(relat.getId()); //TODO da valutare + relationship.setSourceElement(source); + relationship.setTargetElement(target); + relationship.setName(sourceNode.getName()+"To"+targetNode.getName()); + + return relationship; + } + + + private static it.polito.tosca.jaxb.Configuration mapModelConfiguration(ToscaConfigurationGrpc toscaConfigurationGrpc, String type) { + it.polito.tosca.jaxb.Configuration configuration = new it.polito.tosca.jaxb.Configuration(); + try { + //We are passing the configuration type to the Deserializer context + configuration = MappingUtils.obtainToscaConfiguration(toscaConfigurationGrpc, type); + + //In Graph, ID and DESCRIPTION are always empty + //configuration.setConfID(confGrpc.getId()); + //configuration.setConfDescr(confGrpc.getDescription()); + + } catch (IOException | NullPointerException e) { + e.printStackTrace(); + } + return configuration; + } + +} + diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToYaml.java b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToYaml.java new file mode 100644 index 0000000..64f8ae4 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/GrpcToYaml.java @@ -0,0 +1,284 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.grpc; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.InjectableValues; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import it.polito.neo4j.jaxb.FunctionalTypes; +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.grpc.NodeTemplateGrpc; +import it.polito.verigraph.grpc.RelationshipTemplateGrpc; +import it.polito.verigraph.grpc.TopologyTemplateGrpc; +import it.polito.verigraph.tosca.deserializer.YamlConfigurationDeserializer; +import it.polito.verigraph.tosca.yaml.beans.AntispamConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.AntispamNode; +import it.polito.verigraph.tosca.yaml.beans.CacheConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.CacheNode; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiNode; +import it.polito.verigraph.tosca.yaml.beans.EndhostConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndhostNode; +import it.polito.verigraph.tosca.yaml.beans.EndpointConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndpointNode; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierNode; +import it.polito.verigraph.tosca.yaml.beans.FirewallConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FirewallNode; +import it.polito.verigraph.tosca.yaml.beans.MailClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailClientNode; +import it.polito.verigraph.tosca.yaml.beans.MailServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailServerNode; +import it.polito.verigraph.tosca.yaml.beans.NatConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.NatNode; +import it.polito.verigraph.tosca.yaml.beans.NodeTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.RelationshipTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.TopologyTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessNode; +import it.polito.verigraph.tosca.yaml.beans.VpnExitConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnExitNode; +import it.polito.verigraph.tosca.yaml.beans.WebClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebClientNode; +import it.polito.verigraph.tosca.yaml.beans.WebServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebServerNode; + +public class GrpcToYaml { + public static ServiceTemplateYaml mapGraphYaml(TopologyTemplateGrpc topologyGrpc) { + ServiceTemplateYaml serviceYaml = new ServiceTemplateYaml(); + TopologyTemplateYaml topologyYaml = new TopologyTemplateYaml(); + + topologyYaml.setNode_templates(new HashMap()); + topologyYaml.setRelationship_templates(new HashMap()); + serviceYaml.setMetadata(new HashMap()); + + for(NodeTemplateGrpc node : topologyGrpc.getNodeTemplateList()) { + NodeTemplateYaml nodeTemplate = new NodeTemplateYaml(); + try { + nodeTemplate = mapNodeYaml(node); + } catch (IOException e) { + throw new BadRequestException("Error while mapping a Node in Yaml object."); + } + topologyYaml.getNode_templates().put(String.valueOf(node.getId()), nodeTemplate); + //shall we catch NumberFormatException? + } + for(RelationshipTemplateGrpc relationship : topologyGrpc.getRelationshipTemplateList()) { + RelationshipTemplateYaml rel = mapRelationshipYaml(relationship, topologyGrpc.getNodeTemplateList()); + topologyYaml.getRelationship_templates().put(String.valueOf(relationship.getId()), rel); + } + + serviceYaml.getMetadata().put("template_id", String.valueOf(topologyGrpc.getId())); + serviceYaml.setTopology_template(topologyYaml); + return serviceYaml; + } + + + private static NodeTemplateYaml mapNodeYaml(NodeTemplateGrpc node) throws JsonParseException, JsonMappingException, IOException { + + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + SimpleModule module = new SimpleModule(); + String stringConfig = null; + try { + stringConfig = node.getConfiguration().getConfiguration(); + } catch (NullPointerException e) { + throw new NullPointerException("A NodeTemplateGrpc does not contain the configuration."); + } + JsonNode nodeConfig = mapper.readTree(stringConfig); + //Passing the configuration type to the Deserializer context + module.addDeserializer(ConfigurationYaml.class, new YamlConfigurationDeserializer()); + mapper.registerModule(module); + + if(node.getType() == null) + throw new NullPointerException("A NodeTemplateGrpc does not contain a type."); + ConfigurationYaml yamlConfig = mapper + .reader(new InjectableValues.Std().addValue("type", node.getType().toString().toLowerCase())) + .forType(ConfigurationYaml.class) + .readValue(nodeConfig); + + + FunctionalTypes nodeType = FunctionalTypes.valueOf(node.getType().toString().toUpperCase()); + switch(nodeType) { + case ANTISPAM: + AntispamNode antispamNode = new AntispamNode(); + antispamNode.setName(node.getName()); + antispamNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + antispamNode.setProperties((AntispamConfigurationYaml) yamlConfig); + return antispamNode; + + case CACHE: + CacheNode cacheNode = new CacheNode(); + cacheNode.setName(node.getName()); + cacheNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + cacheNode.setProperties((CacheConfigurationYaml) yamlConfig); + return cacheNode; + + case DPI: + DpiNode dpiNode = new DpiNode(); + dpiNode.setName(node.getName()); + dpiNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + dpiNode.setProperties((DpiConfigurationYaml) yamlConfig); + return dpiNode; + + case ENDHOST: + EndhostNode endhostNode = new EndhostNode(); + endhostNode.setName(node.getName()); + endhostNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + endhostNode.setProperties((EndhostConfigurationYaml) yamlConfig); + return endhostNode; + + case ENDPOINT: + EndpointNode endpointNode = new EndpointNode(); + endpointNode.setName(node.getName()); + endpointNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + endpointNode.setProperties((EndpointConfigurationYaml) yamlConfig); + return endpointNode; + + case FIELDMODIFIER: + FieldModifierNode fieldmodifierNode = new FieldModifierNode(); + fieldmodifierNode.setName(node.getName()); + fieldmodifierNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + fieldmodifierNode.setProperties((FieldModifierConfigurationYaml) yamlConfig); + return fieldmodifierNode; + + case FIREWALL: + FirewallNode firewallNode = new FirewallNode(); + firewallNode.setName(node.getName()); + firewallNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + firewallNode.setProperties((FirewallConfigurationYaml) yamlConfig); + return firewallNode; + + case MAILCLIENT: + MailClientNode mailclientNode = new MailClientNode(); + mailclientNode.setName(node.getName()); + mailclientNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + mailclientNode.setProperties((MailClientConfigurationYaml) yamlConfig); + return mailclientNode; + + case MAILSERVER: + MailServerNode mailserverNode = new MailServerNode(); + mailserverNode.setName(node.getName()); + mailserverNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + mailserverNode.setProperties((MailServerConfigurationYaml) yamlConfig); + return mailserverNode; + + case NAT: + NatNode natNode = new NatNode(); + natNode.setName(node.getName()); + natNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + natNode.setProperties((NatConfigurationYaml) yamlConfig); + return natNode; + + case VPNACCESS: + VpnAccessNode vpnaccessNode = new VpnAccessNode(); + vpnaccessNode.setName(node.getName()); + vpnaccessNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + vpnaccessNode.setProperties((VpnAccessConfigurationYaml) yamlConfig); + return vpnaccessNode; + + case VPNEXIT: + VpnExitNode vpnexitNode = new VpnExitNode(); + vpnexitNode.setName(node.getName()); + vpnexitNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + vpnexitNode.setProperties((VpnExitConfigurationYaml) yamlConfig); + return vpnexitNode; + + case WEBCLIENT: + WebClientNode webclientNode = new WebClientNode(); + webclientNode.setName(node.getName()); + webclientNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + webclientNode.setProperties((WebClientConfigurationYaml) yamlConfig); + return webclientNode; + + case WEBSERVER: + WebServerNode webserverNode = new WebServerNode(); + webserverNode.setName(node.getName()); + webserverNode.setType("verigraph.nodeTypes." + + node.getType().toString().substring(0, 1).toUpperCase() + + node.getType().toString().substring(1)); + webserverNode.setProperties((WebServerConfigurationYaml) yamlConfig); + return webserverNode; + + default: + FieldModifierNode defaultNode = new FieldModifierNode(); + defaultNode.setName(node.getName()); + defaultNode.setType("verigraph.nodeTypes.Fieldmodifier"); + defaultNode.setProperties(new FieldModifierConfigurationYaml()); + return defaultNode; + } + + } + + private static RelationshipTemplateYaml mapRelationshipYaml(RelationshipTemplateGrpc relat, List nodeList) { + RelationshipTemplateYaml relationship = new RelationshipTemplateYaml(); + relationship.setProperties(new HashMap()); + String sourceNode = null; + String targetNode = null; + int check = 0; + + relationship.setType("verigraph.relationshipType.generic"); + relationship.getProperties().put("source_id", String.valueOf(relat.getIdSourceNodeTemplate())); //to be catched? + relationship.getProperties().put("target_id", String.valueOf(relat.getIdTargetNodeTemplate())); + + for(NodeTemplateGrpc node : nodeList) { + if(node.getId().equals(relat.getIdSourceNodeTemplate())) { + sourceNode = node.getName(); + check++; + } + if(node.getId().equals(relat.getIdTargetNodeTemplate())) { + targetNode = node.getName(); + check++; + } + } + + if(check!=2) + throw new BadRequestException("A RelationshipTemplateGrpc must contain both source and target node ID."); + + relationship.getProperties().put("name", sourceNode+"To"+targetNode); + + return relationship; + } +} + diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/grpc/ToscaGrpcUtils.java b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/ToscaGrpcUtils.java new file mode 100644 index 0000000..e43ef21 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/ToscaGrpcUtils.java @@ -0,0 +1,18 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.grpc; + +public class ToscaGrpcUtils { + + /** Default configuration for a Tosca NodeTemplate non compliant with Verigraph types*/ + public static final String defaultConfID = new String(""); + public static final String defaultDescr = new String("Default Configuration"); + public static final String defaultConfig = new String("[]"); + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/grpc/XmlToGrpc.java b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/XmlToGrpc.java new file mode 100644 index 0000000..426bb4a --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/XmlToGrpc.java @@ -0,0 +1,160 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.grpc; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBException; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import it.polito.tosca.jaxb.TNodeTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate; +import it.polito.tosca.jaxb.TServiceTemplate; +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.exception.DataNotFoundException; +import it.polito.verigraph.grpc.NodeTemplateGrpc; +import it.polito.verigraph.grpc.NodeTemplateGrpc.Type; +import it.polito.verigraph.grpc.RelationshipTemplateGrpc; +import it.polito.verigraph.grpc.TopologyTemplateGrpc; +import it.polito.verigraph.grpc.ToscaConfigurationGrpc; +import it.polito.verigraph.tosca.MappingUtils; +import it.polito.verigraph.tosca.XmlParsingUtils; + +public class XmlToGrpc { + + /** Returns the (first) TopologyTemplate found in the TOSCA-compliant XML file */ + public static TopologyTemplateGrpc obtainTopologyTemplateGrpc (String filepath) + throws IOException, JAXBException, DataNotFoundException, ClassCastException, BadRequestException{ + List serviceTList = XmlParsingUtils.obtainServiceTemplates(filepath); + TServiceTemplate serviceTemplate = serviceTList.get(0); //obtain only the first ServiceTemplate of the TOSCA compliance file + + //Retrieving of list of NodeTemplate and RelationshipTemplate + List nodes = new ArrayList(); + List relats = new ArrayList(); + List tNodes = XmlParsingUtils.obtainNodeTemplates(serviceTemplate); + for(TNodeTemplate nt : tNodes) { + for(NodeTemplateGrpc alreadyAddedNode : nodes) + if(alreadyAddedNode.getId().equals(nt.getId())) + throw new BadRequestException("The NodeTemplate ID must be unique."); + nodes.add(parseNodeTemplate(nt)); + } + for(TRelationshipTemplate rt : XmlParsingUtils.obtainRelationshipTemplates(serviceTemplate)) { + if(!tNodes.contains(rt.getSourceElement().getRef()) || !tNodes.contains(rt.getTargetElement().getRef())) + throw new BadRequestException("Invalid references to a Node in a Relationship."); + if(rt.getSourceElement().getRef() == rt.getTargetElement().getRef()) + throw new BadRequestException("Source and Target cannot be equal in a Relationship."); + relats.add(parseRelationshipTemplate(rt)); + } + + //Creating TopologyTemplateGrpc object to be sent to server + return TopologyTemplateGrpc.newBuilder() + .setId("0") //useless value since the server chooses the actual value for the GraphID + .addAllNodeTemplate(nodes) + .addAllRelationshipTemplate(relats) + .build(); + } + + + /** Parsing method: TNodeTemplate(tosca) --> NodeTemplateGrpc */ + private static NodeTemplateGrpc parseNodeTemplate(TNodeTemplate nodeTempl) + throws ClassCastException, NullPointerException { + Boolean isVerigraphCompl = true; + Type type; + + //NodeTemplateGrpc building + NodeTemplateGrpc.Builder nodegrpc = NodeTemplateGrpc.newBuilder(); + + //ID cannot be null + try { + nodegrpc.setId(nodeTempl.getId()); + } catch (NullPointerException ex) { + throw new NullPointerException("An ID must be specified for each Node"); + } + //Name can be null + try { + nodegrpc.setName(nodeTempl.getName()); + } catch (NullPointerException ex) { + nodegrpc.setName(""); + } + + //Type cannot be null but it can be invalid + try { + String typestring = nodeTempl.getType().getLocalPart().toLowerCase(); + type = Type.valueOf(nodeTempl.getType().getLocalPart().toLowerCase().substring(0,typestring.length()-4)); + } catch (IllegalArgumentException | NullPointerException ex) { + //in case the NodeTemplate is not TOSCA-Verigraph compliant, we assume it to be a fieldmodifier node + type = Type.fieldmodifier; + isVerigraphCompl = false; + } + nodegrpc.setType(type); + ToscaConfigurationGrpc.Builder grpcConfig; + if(isVerigraphCompl) { + it.polito.tosca.jaxb.Configuration nodeConfig = XmlParsingUtils.obtainConfiguration(nodeTempl); + grpcConfig = ToscaConfigurationGrpc.newBuilder(); + //These fields are optional in TOSCA xml + try { + grpcConfig.setId(nodeConfig.getConfID()); + } catch(NullPointerException ex) { + grpcConfig.setId(ToscaGrpcUtils.defaultConfID); + } + try { + grpcConfig.setDescription(nodeConfig.getConfDescr()); + } catch(NullPointerException ex) { + grpcConfig.setDescription(ToscaGrpcUtils.defaultDescr); + } + try {; + grpcConfig.setConfiguration(MappingUtils.obtainStringConfiguration(nodeConfig)); + } catch(NullPointerException | JsonProcessingException ex) { + grpcConfig.setConfiguration(ToscaGrpcUtils.defaultConfig); + } + } + else { + grpcConfig = ToscaConfigurationGrpc.newBuilder() + .setId(ToscaGrpcUtils.defaultConfID) + .setDescription(ToscaGrpcUtils.defaultDescr) + .setConfiguration(ToscaGrpcUtils.defaultConfig); + } + nodegrpc.setConfiguration(grpcConfig.build()); + return nodegrpc.build(); + } + + + /** Parsing method: TRelationshipTemplate(tosca) --> RelationshipTemplateGrpc */ + private static RelationshipTemplateGrpc parseRelationshipTemplate(TRelationshipTemplate relatTempl) + throws ClassCastException{ + String source, target; + //RelationshipTemplateGrpc building + RelationshipTemplateGrpc.Builder relatgrpc = RelationshipTemplateGrpc.newBuilder(); + + //ID and Name can be null + try { + relatgrpc.setId(relatTempl.getId()); + } catch (NullPointerException ex) {}//Different Relationship with same ID are considered valid. + try { + relatgrpc.setName(relatTempl.getName()); + } catch (NullPointerException ex) {} + + //Source and Target values cannot be null + try { + TNodeTemplate sourceNode = (TNodeTemplate) relatTempl.getSourceElement().getRef(); + TNodeTemplate targetNode = (TNodeTemplate) relatTempl.getTargetElement().getRef(); + source = sourceNode.getId(); + target = targetNode.getId(); + } catch (NullPointerException ex) { + throw new NullPointerException("Invalid NodeTemplate reference in RelationshipTemplate with id:" + + relatTempl.getId()); + } + relatgrpc.setIdSourceNodeTemplate(source) + .setIdTargetNodeTemplate(target); + return relatgrpc.build(); + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/grpc/YamlToGrpc.java b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/YamlToGrpc.java new file mode 100644 index 0000000..1a713bd --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/grpc/YamlToGrpc.java @@ -0,0 +1,147 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.grpc; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.bind.JAXBException; + +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.exception.DataNotFoundException; +import it.polito.verigraph.grpc.NodeTemplateGrpc; +import it.polito.verigraph.grpc.NodeTemplateGrpc.Type; +import it.polito.verigraph.grpc.RelationshipTemplateGrpc; +import it.polito.verigraph.grpc.TopologyTemplateGrpc; +import it.polito.verigraph.grpc.ToscaConfigurationGrpc; +import it.polito.verigraph.tosca.YamlParsingUtils; +import it.polito.verigraph.tosca.yaml.beans.NodeTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.RelationshipTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; + +public class YamlToGrpc { + + /** Returns the (first) TopologyTemplate found in the TOSCA-compliant yaml file */ + public static TopologyTemplateGrpc obtainTopologyTemplateGrpc (String filepath) + throws IOException, JAXBException, DataNotFoundException, ClassCastException, BadRequestException{ + ServiceTemplateYaml serviceTemplate = YamlParsingUtils.obtainServiceTemplate(filepath); + + //Retrieving of list of NodeTemplate and RelationshipTemplate + List nodes = new ArrayList(); + List relats = new ArrayList(); + + try { + for(Map.Entry node : YamlParsingUtils.obtainNodeTemplates(serviceTemplate).entrySet()) { + for(NodeTemplateGrpc alreadyAddedNode : nodes) + if(alreadyAddedNode.getId().equals(node.getKey())) + throw new BadRequestException("The NodeTemplate ID must be unique."); + nodes.add(parseNodeTemplate(node)); + } + } catch (NullPointerException e) { + throw new BadRequestException("There is not any NodeTemplate in the ServiceTemplate provided."); + } + + try { + for(Map.Entry rel : YamlParsingUtils.obtainRelationshipTemplates(serviceTemplate).entrySet()) { + relats.add(parseRelationshipTemplate(rel, nodes)); + } + } catch (NullPointerException e) { + throw new BadRequestException("There is not any RelationshipTemplate in the ServiceTemplate provided."); + } + + //Creating TopologyTemplateGrpc object to be sent to server + return TopologyTemplateGrpc.newBuilder() + .setId("0") //useless value since the server chooses the actual value for the GraphID + .addAllNodeTemplate(nodes) + .addAllRelationshipTemplate(relats) + .build(); + } + + /** Parsing method: RelationshipTemplateYaml(tosca) --> RelationshipTemplateGrpc */ + private static RelationshipTemplateGrpc parseRelationshipTemplate(Entry rel, List nodes) throws BadRequestException{ + String source, target; + boolean valid_source = false; + boolean valid_target = false; + + //RelationshipTemplateGrpc building + RelationshipTemplateGrpc.Builder relatgrpc = RelationshipTemplateGrpc.newBuilder(); + + //ID can be null + try { + relatgrpc.setId(rel.getKey()); + relatgrpc.setName(rel.getValue().getProperties().get("name")); + source = rel.getValue().getProperties().get("source_id"); + target = rel.getValue().getProperties().get("target_id"); + } catch (NullPointerException ex) { + throw new BadRequestException("Incorrect fields in RelationshipTemplate:" + rel.getKey()); + } + + //Source and Target values must correctly refer to a NodeTemplate + if(source.equals(target)) + throw new BadRequestException("Source and Target cannot be the same value"); + for(NodeTemplateGrpc node : nodes) { + if(node.getId().equals(source)) + valid_source = true; + if(node.getId().equals(target)) + valid_target = true; + } + if(!(valid_source && valid_target)) + throw new BadRequestException("Invalid NodeTemplate reference in RelationshipTemplate:" + rel.getKey()); + + return relatgrpc.setIdSourceNodeTemplate(source).setIdTargetNodeTemplate(target).build(); + + } + + /** Parsing method: NodeTemplateYaml(tosca) --> NodeTemplateGrpc */ + private static NodeTemplateGrpc parseNodeTemplate(Entry node) + throws ClassCastException, NullPointerException, BadRequestException { + Boolean isVerigraphCompl = true; + Type type; + + //NodeTemplateGrpc building + NodeTemplateGrpc.Builder nodegrpc = NodeTemplateGrpc.newBuilder() + .setId(node.getKey()); + + try { + nodegrpc.setName(node.getValue().getName()); + } catch (NullPointerException ex) { + throw new BadRequestException("Invalid name in a NodeTemplate."); + } + + //Type cannot be null but it can be invalid + try { + type = Type.valueOf(node.getValue().getType().replace("verigraph.nodeTypes.", "").toLowerCase()); + } catch (IllegalArgumentException | NullPointerException ex) { + //in case the NodeTemplate is not TOSCA-Verigraph compliant, we assume it to be a fieldmodifier node + type = Type.fieldmodifier; + isVerigraphCompl = false; + } + nodegrpc.setType(type); + ToscaConfigurationGrpc.Builder grpcConfig; + if(isVerigraphCompl) { + String jsonConfig = YamlParsingUtils.obtainConfiguration(node.getValue()); + grpcConfig = ToscaConfigurationGrpc.newBuilder() + .setId("") + .setDescription("") + .setConfiguration(jsonConfig); + } + else { + grpcConfig = ToscaConfigurationGrpc.newBuilder() + .setId(ToscaGrpcUtils.defaultConfID) + .setDescription(ToscaGrpcUtils.defaultDescr) + .setConfiguration(ToscaGrpcUtils.defaultConfig); + } + nodegrpc.setConfiguration(grpcConfig.build()); + return nodegrpc.build(); + } + +} \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/xml/GraphToXml.java b/verigraph/src/it/polito/verigraph/tosca/converter/xml/GraphToXml.java new file mode 100644 index 0000000..613588f --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/xml/GraphToXml.java @@ -0,0 +1,134 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.xml; + +import java.io.IOException; +import java.util.Map; + +import javax.xml.namespace.QName; + +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.tosca.MappingUtils; +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TEntityTemplate.Properties; +import it.polito.tosca.jaxb.TNodeTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate.SourceElement; +import it.polito.tosca.jaxb.TRelationshipTemplate.TargetElement; +import it.polito.tosca.jaxb.TServiceTemplate; +import it.polito.tosca.jaxb.TTopologyTemplate; + +public class GraphToXml { + /** model --> tosca_xml*/ + + public static Definitions mapGraph(Graph graph) { + Definitions definitions = new Definitions(); + TServiceTemplate serviceTemplate = mapPathToXml(graph); + definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(serviceTemplate); + + return definitions; + } + + // These functions have been split so that they can be reused for obtaining all the paths + //into a single Definitions (see mapPathsToXml) + public static TServiceTemplate mapPathToXml(Graph graph) { + + TServiceTemplate serviceTemplate = new TServiceTemplate(); + TTopologyTemplate topologyTemplate = new TTopologyTemplate(); + + for(Node node : graph.getNodes().values()) { + long i = 0; + TNodeTemplate nodeTemplate = mapNode(node); + topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate); + + // RelationshipTemplate mapping + Map neighMap = node.getNeighbours(); + for (Map.Entry myentry : neighMap.entrySet()) { + Neighbour neigh = myentry.getValue(); + if (graph.getNodes().containsKey(neigh.getId())) { + // I have to check that because if I'm mapping a path (and not a graph) I could have + //as neighbour a node which is not in the path + TRelationshipTemplate relat = mapRelationship(graph, node, neigh, i); + topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relat); + i++; //Neighbour does not have a neighbourID! RelationshipTemplate does, + //so it is an incremental number for each node + } + } + } + + serviceTemplate.setId(String.valueOf(graph.getId())); + serviceTemplate.setTopologyTemplate(topologyTemplate); + + return serviceTemplate; + } + + + private static TNodeTemplate mapNode(Node node){ + TNodeTemplate nodeTemplate = new TNodeTemplate(); + + nodeTemplate.setId(String.valueOf(node.getId())); + nodeTemplate.setName(node.getName()); + + //QName type = new QName("http://docs.oasis-open.org/tosca/ns/2011/12/ToscaVerigraphDefinition") + QName type = new QName("http://docs.oasis-open.org/tosca/ns/2011/12", + node.getFunctional_type().substring(0, 1).toUpperCase() + node. + getFunctional_type().substring(1) + "Type"); + nodeTemplate.setType(type); + + it.polito.tosca.jaxb.Configuration config = mapModelConfiguration(node.getConfiguration(), + node.getFunctional_type().toLowerCase()); + //nodeTemplate.getAny().add(config); + nodeTemplate.setProperties(new Properties()); + nodeTemplate.getProperties().setAny(config); + return nodeTemplate; + } + + + private static TRelationshipTemplate mapRelationship(Graph graph, Node sourceNode, Neighbour neigh, long i) { + TRelationshipTemplate relationship = new TRelationshipTemplate(); + SourceElement source = new SourceElement(); + TargetElement target = new TargetElement(); + + Node targetNode = graph.getNodes().get(neigh.getId()); + + TNodeTemplate sourceNT = mapNode(sourceNode); + TNodeTemplate targetNT = mapNode(targetNode); + + source.setRef(sourceNT); + target.setRef(targetNT); + + relationship.setId(String.valueOf(i)); + relationship.setSourceElement(source); + relationship.setTargetElement(target); + relationship.setName(sourceNode.getName()+"to"+neigh.getName()); + + return relationship; + } + + + private static it.polito.tosca.jaxb.Configuration mapModelConfiguration(Configuration conf, String type) { + it.polito.tosca.jaxb.Configuration configuration = new it.polito.tosca.jaxb.Configuration(); + try { + //We are passing the configuration type to the Deserializer context + configuration = MappingUtils.obtainToscaConfiguration(conf, type); + + //In Graph, ID and DESCRIPTION are always empty + //configuration.setConfID(conf.getId()); + //configuration.setConfDescr(conf.getDescription()); + + } catch (IOException | NullPointerException e) { + e.printStackTrace(); + } + return configuration; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/xml/XmlToGraph.java b/verigraph/src/it/polito/verigraph/tosca/converter/xml/XmlToGraph.java new file mode 100644 index 0000000..3744ba2 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/xml/XmlToGraph.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.xml; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.exception.DataNotFoundException; +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.tosca.MappingUtils; +import it.polito.verigraph.tosca.XmlParsingUtils; +import it.polito.tosca.jaxb.Definitions; +import it.polito.tosca.jaxb.TExtensibleElements; +import it.polito.tosca.jaxb.TNodeTemplate; +import it.polito.tosca.jaxb.TRelationshipTemplate; +import it.polito.tosca.jaxb.TServiceTemplate; + +public class XmlToGraph { + public static Graph mapTopologyTemplate(Definitions definitions) throws DataNotFoundException, BadRequestException { + Graph graph = new Graph(); + Map nodes = new HashMap<>(); + + List elements = definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation(); + + // Retrieve the list of ServiceTemplate in Definitions + List serviceTemplates = elements.stream().filter(p -> p instanceof TServiceTemplate) + .map(obj -> (TServiceTemplate) obj).collect(Collectors.toList()); + if (serviceTemplates.isEmpty()) + throw new DataNotFoundException("There is no ServiceTemplate into the Definitions object"); + + List nodeTemplates = XmlParsingUtils.obtainNodeTemplates(serviceTemplates.get(0)); + + for (TNodeTemplate nodeTemplate : nodeTemplates) { + Node node = mapNodeTemplate(nodeTemplate); + nodes.put(Long.valueOf(nodeTemplate.getId()), node); + } + + // Add Neighbour to the Node of the list + List relationshipTemplates = XmlParsingUtils.obtainRelationshipTemplates(serviceTemplates.get(0)); + mapRelationshipTemplates(nodes, relationshipTemplates); + + // Add Nodes and ID to the graph + graph.setNodes(nodes); + + try { + graph.setId(Long.valueOf(serviceTemplates.get(0).getId())); + } catch (NumberFormatException ex) { + throw new BadRequestException("If you want to store your TopologyTemplate on this server, " + + "the TopologyTemplate ID must be a number."); + } + + return graph; + } + + + private static Node mapNodeTemplate(TNodeTemplate nodeTemplate) { + Node node = new Node(); + + String toscaType = nodeTemplate.getType().toString(); + toscaType = toscaType.replace("Type", "").replace("{http://docs.oasis-open.org/tosca/ns/2011/12}", ""); + toscaType = toscaType.toLowerCase(); + + try { + node.setId(Long.valueOf(nodeTemplate.getId())); + } catch(NumberFormatException ex) { + throw new BadRequestException("The NodeTemplate ID must be a number."); + } + try { + node.setName(nodeTemplate.getName()); + Configuration conf = mapToscaConfiguration(XmlParsingUtils.obtainConfiguration(nodeTemplate)); + node.setConfiguration(conf); + node.setFunctional_type(toscaType); + } catch(NullPointerException | IOException ex) { + throw new BadRequestException("The NodeTemplate id:"+node.getId()+" has wrong fields representation."); + } + return node; + } + + + private static void mapRelationshipTemplates(Map nodes, List relationshipTemplates) { + //update of nodes... (update = Node + its Neighbours) + for(TRelationshipTemplate relationshipTemplate : relationshipTemplates) { + if (relationshipTemplate != null) { + try { + if(relationshipTemplate.getSourceElement().getRef() == relationshipTemplate.getTargetElement().getRef()) + throw new BadRequestException("Source and Target cannot be equal in a Relationship."); + + // Retrieve the target Node name and generate a new Neighbour + TNodeTemplate targetNodeTemplate = (TNodeTemplate) relationshipTemplate.getTargetElement().getRef(); + String neighName = nodes.get(Long.valueOf(targetNodeTemplate.getId())).getName(); + //this manages invalid/inexistent node ID for target node + Neighbour neigh = new Neighbour(); + neigh.setName(neighName); + neigh.setId(Long.valueOf(relationshipTemplate.getId())); + + //Retrieve the Neighbour map of the source Node and add the Neighbour + TNodeTemplate sourceNodeTemplate = (TNodeTemplate) relationshipTemplate.getSourceElement().getRef(); + Node source = nodes.get(Long.valueOf(sourceNodeTemplate.getId())); + //this manages invalid/inexistent node ID for source node + Map sourceNodeNeighMap = source.getNeighbours(); + if(sourceNodeNeighMap.containsKey(neigh.getId())) + throw new BadRequestException("The RelationshipTemplate ID must be unique."); + else + sourceNodeNeighMap.put(neigh.getId(), neigh); + source.setNeighbours(sourceNodeNeighMap); + + //Update the Node list + nodes.put(Long.valueOf(sourceNodeTemplate.getId()), source); + } catch(NullPointerException | NumberFormatException ex) { + throw new BadRequestException("A RelationshipTemplate has wrong fields representation."); + } + } + } + } + + private static Configuration mapToscaConfiguration(it.polito.tosca.jaxb.Configuration configuration) + throws JsonProcessingException, IOException { + Configuration conf = new Configuration(); + ObjectMapper mapper = new ObjectMapper(); + String stringConfiguration; + + //Retrieve configuration ID (optional) + if (configuration.getConfID() != null) + conf.setId(configuration.getConfID()); + else + conf.setId(""); + + //Retrieve description (optional) + if (configuration.getConfDescr() != null) + conf.setDescription(configuration.getConfDescr()); + else + conf.setDescription(""); + + //Retrieve string of configuration + try { + stringConfiguration = MappingUtils.obtainStringConfiguration(configuration); + } catch(IOException ex) { + conf.setConfiguration(mapper.readTree("[]")); + System.out.println("[WARNING] Provided default configuration."); + return conf; + } + + //Retrieve JsonNode from the string of configuration + try { + conf.setConfiguration(mapper.readTree(stringConfiguration)); + return conf; + } catch (IOException e) { + throw new BadRequestException("NodeTemplate configuration is invalid."); + } + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/yaml/GraphToYaml.java b/verigraph/src/it/polito/verigraph/tosca/converter/yaml/GraphToYaml.java new file mode 100644 index 0000000..8766ac5 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/yaml/GraphToYaml.java @@ -0,0 +1,270 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.yaml; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.InjectableValues; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import it.polito.neo4j.jaxb.FunctionalTypes; +import it.polito.verigraph.exception.BadRequestException; +import it.polito.verigraph.model.Graph; +import it.polito.verigraph.model.Neighbour; +import it.polito.verigraph.model.Node; +import it.polito.verigraph.tosca.deserializer.YamlConfigurationDeserializer; +import it.polito.verigraph.tosca.yaml.beans.AntispamConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.AntispamNode; +import it.polito.verigraph.tosca.yaml.beans.CacheConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.CacheNode; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiNode; +import it.polito.verigraph.tosca.yaml.beans.EndhostConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndhostNode; +import it.polito.verigraph.tosca.yaml.beans.EndpointConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndpointNode; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierNode; +import it.polito.verigraph.tosca.yaml.beans.FirewallConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FirewallNode; +import it.polito.verigraph.tosca.yaml.beans.MailClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailClientNode; +import it.polito.verigraph.tosca.yaml.beans.MailServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailServerNode; +import it.polito.verigraph.tosca.yaml.beans.NatConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.NatNode; +import it.polito.verigraph.tosca.yaml.beans.NodeTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.RelationshipTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.TopologyTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessNode; +import it.polito.verigraph.tosca.yaml.beans.VpnExitConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnExitNode; +import it.polito.verigraph.tosca.yaml.beans.WebClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebClientNode; +import it.polito.verigraph.tosca.yaml.beans.WebServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebServerNode; + +public class GraphToYaml { + public static ServiceTemplateYaml mapGraphYaml(Graph graph) { + ServiceTemplateYaml serviceTemplate = new ServiceTemplateYaml(); + TopologyTemplateYaml topologyTemplate = new TopologyTemplateYaml(); + + topologyTemplate.setNode_templates(new HashMap()); + topologyTemplate.setRelationship_templates(new HashMap()); + serviceTemplate.setMetadata(new HashMap()); + + //Neighbour does not have a neighbourID! + //RelationshipTemplate does, so it is an incremental number for each node + long i = 0; //This counter will act as a fake incremental id of relationships + for(Node node : graph.getNodes().values()) { + NodeTemplateYaml nodeTemplate; + try { + nodeTemplate = mapNodeYaml(node); + } catch (IOException e) { + throw new BadRequestException("Error while mapping a Node in Yaml object."); + } + topologyTemplate.getNode_templates().put(String.valueOf(node.getId()), nodeTemplate); + //shall we catch NumberFormatException? + + Map neighMap = node.getNeighbours(); + for (Map.Entry myentry : neighMap.entrySet()) { + Neighbour neigh = myentry.getValue(); + if (graph.getNodes().containsKey(neigh.getId())) { + // I have to check that because if I'm mapping a path (and not a graph) + //I could have as neighbour a node which is not in the path + RelationshipTemplateYaml relat = mapRelationshipYaml(node, neigh); + topologyTemplate.getRelationship_templates().put(String.valueOf(i), relat); + i++; + } + } + } + + serviceTemplate.getMetadata().put("template_id", String.valueOf(graph.getId())); + serviceTemplate.setTopology_template(topologyTemplate); + return serviceTemplate; + } + + + private static NodeTemplateYaml mapNodeYaml(Node node) throws JsonParseException, JsonMappingException, IOException { + + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + JsonNode configNode = node.getConfiguration().getConfiguration(); + SimpleModule module = new SimpleModule(); + + //Passing the configuration type to the Deserializer context + module.addDeserializer(ConfigurationYaml.class, new YamlConfigurationDeserializer()); + mapper.registerModule(module); + + //Here we use the custom deserializer to convert the JsonNode into a Yaml bean + //The injectable value allows to provide an additional info to the deserializer that will be able to + //know that it is parsing a certain type of Configuration. + ConfigurationYaml yamlConfig = mapper + .reader(new InjectableValues.Std().addValue("type", node.getFunctional_type().toLowerCase())) + .forType(ConfigurationYaml.class).readValue(configNode); + + FunctionalTypes nodeType = FunctionalTypes.valueOf(node.getFunctional_type().toUpperCase()); + switch(nodeType) { + case ANTISPAM: + AntispamNode antispamNode = new AntispamNode(); + antispamNode.setName(node.getName()); + antispamNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + antispamNode.setProperties((AntispamConfigurationYaml) yamlConfig); + return antispamNode; + + case CACHE: + CacheNode cacheNode = new CacheNode(); + cacheNode.setName(node.getName()); + cacheNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + cacheNode.setProperties((CacheConfigurationYaml) yamlConfig); + return cacheNode; + + case DPI: + DpiNode dpiNode = new DpiNode(); + dpiNode.setName(node.getName()); + dpiNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + dpiNode.setProperties((DpiConfigurationYaml) yamlConfig); + return dpiNode; + + case ENDHOST: + EndhostNode endhostNode = new EndhostNode(); + endhostNode.setName(node.getName()); + endhostNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + endhostNode.setProperties((EndhostConfigurationYaml) yamlConfig); + return endhostNode; + + case ENDPOINT: + EndpointNode endpointNode = new EndpointNode(); + endpointNode.setName(node.getName()); + endpointNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + endpointNode.setProperties((EndpointConfigurationYaml) yamlConfig); + return endpointNode; + + case FIELDMODIFIER: + FieldModifierNode fieldmodifierNode = new FieldModifierNode(); + fieldmodifierNode.setName(node.getName()); + fieldmodifierNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + fieldmodifierNode.setProperties((FieldModifierConfigurationYaml) yamlConfig); + return fieldmodifierNode; + + case FIREWALL: + FirewallNode firewallNode = new FirewallNode(); + firewallNode.setName(node.getName()); + firewallNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + firewallNode.setProperties((FirewallConfigurationYaml) yamlConfig); + return firewallNode; + + case MAILCLIENT: + MailClientNode mailclientNode = new MailClientNode(); + mailclientNode.setName(node.getName()); + mailclientNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + mailclientNode.setProperties((MailClientConfigurationYaml) yamlConfig); + return mailclientNode; + + case MAILSERVER: + MailServerNode mailserverNode = new MailServerNode(); + mailserverNode.setName(node.getName()); + mailserverNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + mailserverNode.setProperties((MailServerConfigurationYaml) yamlConfig); + return mailserverNode; + + case NAT: + NatNode natNode = new NatNode(); + natNode.setName(node.getName()); + natNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + natNode.setProperties((NatConfigurationYaml) yamlConfig); + return natNode; + + case VPNACCESS: + VpnAccessNode vpnaccessNode = new VpnAccessNode(); + vpnaccessNode.setName(node.getName()); + vpnaccessNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + vpnaccessNode.setProperties((VpnAccessConfigurationYaml) yamlConfig); + return vpnaccessNode; + + case VPNEXIT: + VpnExitNode vpnexitNode = new VpnExitNode(); + vpnexitNode.setName(node.getName()); + vpnexitNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + vpnexitNode.setProperties((VpnExitConfigurationYaml) yamlConfig); + return vpnexitNode; + + case WEBCLIENT: + WebClientNode webclientNode = new WebClientNode(); + webclientNode.setName(node.getName()); + webclientNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + webclientNode.setProperties((WebClientConfigurationYaml) yamlConfig); + return webclientNode; + + case WEBSERVER: + WebServerNode webserverNode = new WebServerNode(); + webserverNode.setName(node.getName()); + webserverNode.setType("verigraph.nodeTypes." + + node.getFunctional_type().substring(0, 1).toUpperCase() + + node.getFunctional_type().substring(1)); + webserverNode.setProperties((WebServerConfigurationYaml) yamlConfig); + return webserverNode; + + default: + FieldModifierNode defaultNode = new FieldModifierNode(); + defaultNode.setName(node.getName()); + defaultNode.setType("verigraph.nodeTypes.Fieldmodifier"); + defaultNode.setProperties(new FieldModifierConfigurationYaml()); + return defaultNode; + } + + } + + private static RelationshipTemplateYaml mapRelationshipYaml(Node sourceNode, Neighbour neigh) { + RelationshipTemplateYaml relationship = new RelationshipTemplateYaml(); + relationship.setProperties(new HashMap()); + + relationship.setType("verigraph.relationshipType.generic"); + relationship.getProperties().put("source_id", String.valueOf(sourceNode.getId())); //to be catched? + relationship.getProperties().put("target_id", String.valueOf(neigh.getId())); + relationship.getProperties().put("name", sourceNode.getName()+"to"+neigh.getName()); + + return relationship; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/converter/yaml/YamlToGraph.java b/verigraph/src/it/polito/verigraph/tosca/converter/yaml/YamlToGraph.java new file mode 100644 index 0000000..3922cf6 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/converter/yaml/YamlToGraph.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.converter.yaml; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; + +import it.polito.verigraph.exception.BadRequestException; +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.tosca.YamlParsingUtils; +import it.polito.verigraph.tosca.serializer.YamlConfigSerializer; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.NodeTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.RelationshipTemplateYaml; +import it.polito.verigraph.tosca.yaml.beans.ServiceTemplateYaml; + +public class YamlToGraph { + public static Graph mapTopologyTemplateYaml(ServiceTemplateYaml yamlServiceTemplate) throws BadRequestException { + Graph graph = new Graph(); + Map graphNodes = new HashMap<>(); + Map nodes = new HashMap<>(); + Map relats = new HashMap<>(); + + nodes = yamlServiceTemplate.getTopology_template().getNode_templates(); + + for (Map.Entry nodeYamlEntry : nodes.entrySet()) { + Node node = mapNodeTemplateYaml(nodeYamlEntry.getValue()); + + try { + graphNodes.put(Long.valueOf(nodeYamlEntry.getKey()), node); + } catch (NumberFormatException e) { + throw new BadRequestException("The NodeTemplate ID must be a number."); + } + + } + + // Add Neighbours to the Nodes of the list + relats = yamlServiceTemplate.getTopology_template().getRelationship_templates(); + mapRelationshipTemplatesYaml(graphNodes, relats); + + // Add Nodes and ID to the graph + graph.setNodes(graphNodes); + try { + graph.setId(Long.valueOf(yamlServiceTemplate.getMetadata().get("template_id"))); + } catch (NumberFormatException ex) { + throw new BadRequestException("If you want to use this service, the TopologyTemplate ID must be a number."); + } catch (NullPointerException ex) {} //ID is not mandatory for the user since VeriGraph provides its IDs + + return graph; + } + + + private static Node mapNodeTemplateYaml(NodeTemplateYaml yamlNodeTemplate) { + Node node = new Node(); + + String type = yamlNodeTemplate.getType().replace("verigraph.nodeTypes.", "").toLowerCase(); + + try { + node.setName(yamlNodeTemplate.getName()); + Configuration conf = mapConfigurationYaml(yamlNodeTemplate); + node.setConfiguration(conf); + node.setFunctional_type(type); + } catch(NullPointerException ex) { + throw new BadRequestException("A NodeTemplate has wrong fields representation."); + } + return node; + } + + + private static void mapRelationshipTemplatesYaml(Map graphNodes, Map relats) { + //updated nodes (update = Node + its Neighbours) + for(Map.Entry yamlRelationshipTemplate : relats.entrySet()) { + try { + // Retrieve relationship information + String target = yamlRelationshipTemplate.getValue().getProperties().get("target_id"); + String source = yamlRelationshipTemplate.getValue().getProperties().get("source_id"); + String name = graphNodes.get(Long.valueOf(target)).getName(); + + Neighbour neigh = new Neighbour(); + neigh.setName(name); + neigh.setId(Long.valueOf(target)); + + //Retrieve the Neighbour map of the source Node and add the Neighbour + Node sourceNode = graphNodes.get(Long.valueOf(source)); + Map sourceNodeNeighMap = sourceNode.getNeighbours(); + if(sourceNodeNeighMap.containsKey(neigh.getId())) + throw new BadRequestException("The RelationshipTemplate ID must be unique."); + else + sourceNodeNeighMap.put(neigh.getId(), neigh); + sourceNode.setNeighbours(sourceNodeNeighMap); + + //Update the Node list + graphNodes.put(Long.valueOf(source), sourceNode); + + } catch(NullPointerException | NumberFormatException ex) { + throw new BadRequestException("A RelationshipTemplate has wrong fields representation."); + } + + } + + } + + + private static Configuration mapConfigurationYaml(NodeTemplateYaml node) { + Configuration config = new Configuration(); + JsonNode jsonConfiguration = null; + ObjectMapper mapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + module.addSerializer(ConfigurationYaml.class, new YamlConfigSerializer()); + mapper.registerModule(module); + + try{ + String stringConfiguration = YamlParsingUtils.obtainConfiguration(node); + jsonConfiguration = mapper.readTree(stringConfiguration); + config.setConfiguration(jsonConfiguration); + config.setDescription(""); + config.setId(""); + } catch (NullPointerException | IOException | BadRequestException e) { + throw new BadRequestException("Not able to retrieve a valid configuration"); + } + + return config; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/deserializer/XmlConfigurationDeserializer.java b/verigraph/src/it/polito/verigraph/tosca/deserializer/XmlConfigurationDeserializer.java new file mode 100644 index 0000000..7e2ee4d --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/deserializer/XmlConfigurationDeserializer.java @@ -0,0 +1,177 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.deserializer; + +import it.polito.tosca.jaxb.Configuration; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class XmlConfigurationDeserializer extends JsonDeserializer { + + @Override + public Configuration deserialize(JsonParser jp, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + Configuration deserialized; + + try { + //Get the content from the array wrapping the JSON configuration + final Iterator elements = node.elements(); + deserialized = new Configuration(); + + + if(!elements.hasNext()) { + //System.out.println("The provided configuration is empty."); + //return null; //TODO shall we return an empty configuration? + + return new Configuration(); + } + + switch ((String) ctxt.findInjectableValue("type", null, null)) { + + case "antispam": + Configuration.AntispamConfiguration antispam = new Configuration.AntispamConfiguration(); + List sources = antispam.getSource(); + while (elements.hasNext()) { + sources.add(elements.next().asText()); + } + deserialized.setAntispamConfiguration(antispam); + break; + + case "cache": + Configuration.CacheConfiguration cache = new Configuration.CacheConfiguration(); + List resources = cache.getResource(); + while(elements.hasNext()) { + resources.add(elements.next().asText()); + } + deserialized.setCacheConfiguration(cache); + break; + + case "endhost": + Configuration.EndhostConfiguration endhost = new Configuration.EndhostConfiguration(); + JsonNode thisnode = elements.next(); + + if(thisnode.has("body")) + endhost.setBody(thisnode.findValue("body").asText()); + if(thisnode.has("sequence")) + endhost.setSequence(BigInteger.valueOf(Long.valueOf(thisnode.findValue("sequence").asText()))); + if(thisnode.has("protocol")) + endhost.setProtocol(thisnode.findValue("protocol").asText()); + if(thisnode.has("email_from")) + endhost.setEmailFrom(thisnode.findValue("email_from").asText()); + if(thisnode.has("url")) + endhost.setUrl(thisnode.findValue("url").asText()); + if(thisnode.has("options")) + endhost.setOptions(thisnode.findValue("options").asText()); + if(thisnode.has("destination")) + endhost.setDestination(thisnode.findValue("destination").asText()); + + deserialized.setEndhostConfiguration(endhost); + break; + + case "endpoint": + Configuration.EndpointConfiguration endpoint = new Configuration.EndpointConfiguration(); + deserialized.setEndpointConfiguration(endpoint); + break; + + case "fieldmodifier": + Configuration.FieldmodifierConfiguration fieldmodifier = new Configuration.FieldmodifierConfiguration(); + deserialized.setFieldmodifierConfiguration(fieldmodifier); + break; + + case "firewall": + Configuration.FirewallConfiguration firewall = new Configuration.FirewallConfiguration(); + List fwelements = firewall.getElements(); + Configuration.FirewallConfiguration.Elements element; + + Iterator> current = elements.next().fields(); + Map.Entry entry; + while(current.hasNext()) { + entry = current.next(); + element = new Configuration.FirewallConfiguration.Elements(); + element.setSource(entry.getKey()); + element.setDestination(entry.getValue().asText()); + fwelements.add(element); + } + + deserialized.setFirewallConfiguration(firewall); + break; + + case "mailclient": + Configuration.MailclientConfiguration mailclient = new Configuration.MailclientConfiguration(); + mailclient.setMailserver(elements.next().findValue("mailserver").asText()); + deserialized.setMailclientConfiguration(mailclient); + break; + + case "mailserver": + Configuration.MailserverConfiguration mailserver = new Configuration.MailserverConfiguration(); + deserialized.setMailserverConfiguration(mailserver); + break; + + case "nat": + Configuration.NatConfiguration nat = new Configuration.NatConfiguration(); + List natsource = nat.getSource(); + while(elements.hasNext()) { + natsource.add(elements.next().asText()); + } + deserialized.setNatConfiguration(nat); + break; + + case "vpnaccess": + Configuration.VpnaccessConfiguration vpnaccess = new Configuration.VpnaccessConfiguration(); + vpnaccess.setVpnexit(elements.next().findValue("vpnexit").asText()); + deserialized.setVpnaccessConfiguration(vpnaccess); + break; + + case "vpnexit": + Configuration.VpnexitConfiguration vpnexit = new Configuration.VpnexitConfiguration(); + vpnexit.setVpnaccess(elements.next().findValue("vpnaccess").asText()); + deserialized.setVpnexitConfiguration(vpnexit); + break; + + case "webclient": + Configuration.WebclientConfiguration webclient = new Configuration.WebclientConfiguration(); + webclient.setNameWebServer(elements.next().findValue("webserver").asText()); + deserialized.setWebclientConfiguration(webclient); + break; + + case "webserver": + Configuration.WebserverConfiguration webserver = new Configuration.WebserverConfiguration(); + deserialized.setWebserverConfiguration(webserver); + break; + + default: + Configuration.FieldmodifierConfiguration defaultForwarder = new Configuration.FieldmodifierConfiguration(); + deserialized.setFieldmodifierConfiguration(defaultForwarder); + break; + } + + + } catch (Exception e) { + // TODO Auto-generated catch block + System.err.println("Error converting the Json to XmlConfiguration"); + e.printStackTrace(); + return null; + } + + return deserialized; + + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/deserializer/YamlConfigurationDeserializer.java b/verigraph/src/it/polito/verigraph/tosca/deserializer/YamlConfigurationDeserializer.java new file mode 100644 index 0000000..8fb7e52 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/deserializer/YamlConfigurationDeserializer.java @@ -0,0 +1,251 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.deserializer; + + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import it.polito.verigraph.tosca.yaml.beans.AntispamConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.CacheConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndhostConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndpointConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FirewallConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.NatConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnExitConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebServerConfigurationYaml; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class YamlConfigurationDeserializer extends JsonDeserializer { + + @Override + public ConfigurationYaml deserialize(JsonParser jp, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + ConfigurationYaml deserialized; + boolean emptyConfig = false; + + try { + //Get the content from the array wrapping the JSON configuration + final Iterator elements = node.elements(); + + if(!elements.hasNext()) { + //System.out.println("The provided configuration is empty."); + emptyConfig = true; + } + + switch ((String)ctxt.findInjectableValue("type", null, null)) { + + case "antispam": + if(emptyConfig) { + deserialized = new AntispamConfigurationYaml(); + break; + } + AntispamConfigurationYaml antispam = new AntispamConfigurationYaml(); + antispam.setSources(new ArrayList()); + while (elements.hasNext()) { + antispam.getSources().add(elements.next().asText()); + } + deserialized = antispam; + break; + + case "cache": + if(emptyConfig) { + deserialized = new CacheConfigurationYaml(); + break; + } + CacheConfigurationYaml cache = new CacheConfigurationYaml(); + cache.setResources(new ArrayList()); + while(elements.hasNext()) { + cache.getResources().add(elements.next().asText()); + } + deserialized = cache; + break; + + case "dpi": + if(emptyConfig) { + deserialized = new DpiConfigurationYaml(); + break; + } + DpiConfigurationYaml dpi = new DpiConfigurationYaml(); + dpi.setNotAllowedList(new ArrayList()); + while(elements.hasNext()) { + dpi.getNotAllowedList().add(elements.next().asText()); + } + deserialized = dpi; + break; + + case "endhost": + if(emptyConfig) { + deserialized = new EndhostConfigurationYaml(); + break; + } + EndhostConfigurationYaml endhost = new EndhostConfigurationYaml(); + JsonNode thisnode = elements.next(); + if(thisnode.has("body")) + endhost.setBody(thisnode.findValue("body").asText()); + if(thisnode.has("sequence")) + endhost.setSequence(Integer.valueOf(thisnode.findValue("sequence").asText())); + if(thisnode.has("protocol")) + endhost.setProtocol(thisnode.findValue("protocol").asText()); + if(thisnode.has("email_from")) + endhost.setEmail_from(thisnode.findValue("email_from").asText()); + if(thisnode.has("options")) + endhost.setOptions(thisnode.findValue("options").asText()); + if(thisnode.has("url")) + endhost.setUrl(thisnode.findValue("url").asText()); + if(thisnode.has("destination")) + endhost.setDestination(thisnode.findValue("destination").asText()); + + deserialized = endhost; + break; + + case "endpoint": + if(emptyConfig) { + deserialized = new EndpointConfigurationYaml(); + break; + } + EndpointConfigurationYaml endpoint = new EndpointConfigurationYaml(); + deserialized = endpoint; + break; + + case "fieldmodifier": + if(emptyConfig) { + deserialized = new FieldModifierConfigurationYaml(); + break; + } + FieldModifierConfigurationYaml fieldmodifier = new FieldModifierConfigurationYaml(); + deserialized = fieldmodifier; + break; + + case "firewall": + if(emptyConfig) { + deserialized = new FirewallConfigurationYaml(); + break; + } + FirewallConfigurationYaml firewall = new FirewallConfigurationYaml(); + firewall.setElements(new HashMap()); + JsonNode current = elements.next(); + Iterator> iter = current.fields(); + + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + firewall.getElements().put(entry.getKey(), entry.getValue().asText()); + } + + deserialized = firewall; + break; + + case "mailclient": + if(emptyConfig) { + deserialized = new MailClientConfigurationYaml(); + break; + } + MailClientConfigurationYaml mailclient = new MailClientConfigurationYaml(); + mailclient.setMailserver(elements.next().findValue("mailserver").asText()); + deserialized = mailclient; + break; + + case "mailserver": + if(emptyConfig) { + deserialized = new MailServerConfigurationYaml(); + break; + } + MailServerConfigurationYaml mailserver = new MailServerConfigurationYaml(); + deserialized = mailserver; + break; + + case "nat": + if(emptyConfig) { + deserialized = new NatConfigurationYaml(); + break; + } + NatConfigurationYaml nat = new NatConfigurationYaml(); + nat.setSources(new ArrayList()); + while(elements.hasNext()) { + nat.getSources().add(elements.next().asText()); + } + deserialized = nat; + break; + + case "vpnaccess": + if(emptyConfig) { + deserialized = new VpnAccessConfigurationYaml(); + break; + } + VpnAccessConfigurationYaml vpnaccess = new VpnAccessConfigurationYaml(); + vpnaccess.setVpnexit(elements.next().findValue("vpnexit").asText()); + deserialized = vpnaccess; + break; + + case "vpnexit": + if(emptyConfig) { + deserialized = new VpnExitConfigurationYaml(); + break; + } + VpnExitConfigurationYaml vpnexit = new VpnExitConfigurationYaml(); + vpnexit.setVpnaccess(elements.next().findValue("vpnaccess").asText()); + deserialized = vpnexit; + break; + + case "webclient": + if(emptyConfig) { + deserialized = new WebClientConfigurationYaml(); + break; + } + WebClientConfigurationYaml webclient = new WebClientConfigurationYaml(); + webclient.setNameWebServer(elements.next().findValue("webserver").asText()); + deserialized = webclient; + break; + + case "webserver": + if(emptyConfig) { + deserialized = new WebServerConfigurationYaml(); + break; + } + WebServerConfigurationYaml webserver = new WebServerConfigurationYaml(); + deserialized = webserver; + break; + + default: + deserialized = new FieldModifierConfigurationYaml(); + break; + } + + + } catch (Exception e) { + // TODO Auto-generated catch block + //System.err.println("Error converting the Json to YamlConfiguration"); + e.printStackTrace(); + return new FieldModifierConfigurationYaml(); + } + + return deserialized; + + } + +} \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/serializer/XmlConfigSerializer.java b/verigraph/src/it/polito/verigraph/tosca/serializer/XmlConfigSerializer.java new file mode 100644 index 0000000..b650420 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/serializer/XmlConfigSerializer.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.serializer; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import it.polito.tosca.jaxb.Configuration; + +//Custom serializer for XmlToscaConfigurationObject conversion to JSON +public class XmlConfigSerializer extends StdSerializer { + + //Automatically generated VersionUID + private static final long serialVersionUID = 9102508941195129607L; + + public XmlConfigSerializer() { + this(null); + } + + public XmlConfigSerializer(Class t) { + super(t); + } + + @Override + public void serialize( + Configuration value, JsonGenerator jgen, SerializerProvider provider) + throws IOException, JsonProcessingException { + + if (value.getAntispamConfiguration() != null) { + jgen.writeStartArray(); + for(String source : value.getAntispamConfiguration().getSource()) { + jgen.writeString(source); + } + jgen.writeEndArray(); + + } else if (value.getCacheConfiguration() != null) { + jgen.writeStartArray(); + for(String resource : value.getCacheConfiguration().getResource()) { + jgen.writeString(resource); + } + jgen.writeEndArray(); + + } else if (value.getDpiConfiguration() != null) { + jgen.writeStartArray(); + for(String notAllowed : value.getDpiConfiguration().getNotAllowed()) { + jgen.writeString(notAllowed); + } + jgen.writeEndArray(); + + } else if (value.getEndhostConfiguration() != null) { + jgen.writeStartArray(); + jgen.writeStartObject(); + + Configuration.EndhostConfiguration endhost = value.getEndhostConfiguration(); + if (endhost.getBody() != null) jgen.writeObjectField("body", endhost.getBody()); + if (endhost.getSequence() != null) jgen.writeObjectField("sequence", endhost.getSequence()); + if (endhost.getProtocol() != null) jgen.writeObjectField("protocol", endhost.getProtocol()); + if (endhost.getEmailFrom() != null) jgen.writeObjectField("email_from", endhost.getEmailFrom()); + if (endhost.getUrl() != null) jgen.writeObjectField("url", endhost.getUrl()); + if (endhost.getOptions() != null) jgen.writeObjectField("options", endhost.getOptions()); + if (endhost.getDestination() != null) jgen.writeObjectField("destination", endhost.getDestination()); + + jgen.writeEndObject(); + jgen.writeEndArray(); + + } else if (value.getEndpointConfiguration() != null) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + } else if (value.getFieldmodifierConfiguration() != null) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + } else if (value.getFirewallConfiguration() != null) { + jgen.writeStartArray(); + + for(Configuration.FirewallConfiguration.Elements elem : value.getFirewallConfiguration().getElements()) { + if ((elem.getSource() != null) && (elem.getDestination() != null)) { + jgen.writeStartObject(); + jgen.writeObjectField(elem.getSource(), elem.getDestination()); + jgen.writeEndObject(); + } + } + + jgen.writeEndArray(); + + } else if (value.getMailclientConfiguration() != null) { + jgen.writeStartArray(); + + if (value.getMailclientConfiguration().getMailserver() != null) { + jgen.writeStartObject(); + jgen.writeObjectField("mailserver", value.getMailclientConfiguration().getMailserver()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + } else if (value.getMailserverConfiguration() != null) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + } else if (value.getNatConfiguration() != null) { + jgen.writeStartArray(); + for(String source : value.getNatConfiguration().getSource()) { + jgen.writeString(source); + } + jgen.writeEndArray(); + + } else if (value.getVpnaccessConfiguration() != null) { + jgen.writeStartArray(); + + if (value.getVpnaccessConfiguration().getVpnexit()!= null) { + jgen.writeStartObject(); + jgen.writeObjectField("vpnexit", value.getVpnaccessConfiguration().getVpnexit()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + } else if (value.getVpnexitConfiguration() != null) { + jgen.writeStartArray(); + + if (value.getVpnexitConfiguration().getVpnaccess()!= null) { + jgen.writeStartObject(); + jgen.writeObjectField("vpnaccess", value.getVpnexitConfiguration().getVpnaccess()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + } else if (value.getWebclientConfiguration() != null) { + jgen.writeStartArray(); + + if (value.getWebclientConfiguration().getNameWebServer() != null) { + jgen.writeStartObject(); + jgen.writeObjectField("webserver", value.getWebclientConfiguration().getNameWebServer()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + } else if (value.getWebserverConfiguration() != null) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + } else { + //Case of empty Configuration + jgen.writeStartArray(); + jgen.writeEndArray(); + } + + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/serializer/YamlConfigSerializer.java b/verigraph/src/it/polito/verigraph/tosca/serializer/YamlConfigSerializer.java new file mode 100644 index 0000000..05a1629 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/serializer/YamlConfigSerializer.java @@ -0,0 +1,186 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.serializer; + +import java.io.IOException; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import it.polito.verigraph.tosca.yaml.beans.AntispamConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.CacheConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.ConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.DpiConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndhostConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.EndpointConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FieldModifierConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.FirewallConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.MailServerConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.NatConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnAccessConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.VpnExitConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebClientConfigurationYaml; +import it.polito.verigraph.tosca.yaml.beans.WebServerConfigurationYaml; + +//Custom serializer for YamlToscaConfigurationObject conversion to JSON +public class YamlConfigSerializer extends StdSerializer { + + //Automatically generated VersionUID + private static final long serialVersionUID = 9102508941195129607L; + + public YamlConfigSerializer() { + this(null); + } + + public YamlConfigSerializer(Class t) { + super(t); + } + + @Override + public void serialize( + ConfigurationYaml value, JsonGenerator jgen, SerializerProvider provider) + throws IOException, JsonProcessingException { + + if(value instanceof AntispamConfigurationYaml) { + jgen.writeStartArray(); + for(String source : ((AntispamConfigurationYaml) value).getSources()) { + jgen.writeString(source); + } + jgen.writeEndArray(); + + }else if(value instanceof CacheConfigurationYaml) { + jgen.writeStartArray(); + for(String resource : ((CacheConfigurationYaml) value).getResources()) { + jgen.writeString(resource); + } + jgen.writeEndArray(); + + }else if(value instanceof DpiConfigurationYaml) { + jgen.writeStartArray(); + for(String notAllowed : ((DpiConfigurationYaml) value).getNotAllowedList()) { + jgen.writeString(notAllowed); + } + jgen.writeEndArray(); + + }else if(value instanceof EndhostConfigurationYaml) { + jgen.writeStartArray(); + jgen.writeStartObject(); + + EndhostConfigurationYaml endhost = (EndhostConfigurationYaml) value; + + if(endhost.getBody() != null) + jgen.writeObjectField("body", endhost.getBody()); + if(endhost.getSequence() != 0) + jgen.writeObjectField("sequence", endhost.getSequence()); + if(endhost.getProtocol() != null) + jgen.writeObjectField("protocol", endhost.getProtocol()); + if(endhost.getEmail_from() != null) + jgen.writeObjectField("email_from", endhost.getEmail_from()); + if(endhost.getUrl() != null) + jgen.writeObjectField("url", endhost.getUrl()); + if(endhost.getOptions() != null) + jgen.writeObjectField("options", endhost.getOptions()); + if(endhost.getDestination() != null) + jgen.writeObjectField("destination", endhost.getDestination()); + + jgen.writeEndObject(); + jgen.writeEndArray(); + + }else if(value instanceof EndpointConfigurationYaml) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + }else if(value instanceof FieldModifierConfigurationYaml) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + }else if(value instanceof FirewallConfigurationYaml) { + jgen.writeStartArray(); + FirewallConfigurationYaml fw = (FirewallConfigurationYaml) value; + + for(Map.Entry entry : fw.getElements().entrySet()) { + if(entry.getKey()!= null && entry.getValue() != null) { + jgen.writeStartObject(); + jgen.writeObjectField(entry.getKey(), entry.getValue()); + jgen.writeEndObject(); + } + } + jgen.writeEndArray(); + + }else if(value instanceof MailClientConfigurationYaml) { + jgen.writeStartArray(); + + if(((MailClientConfigurationYaml) value).getMailserver() != null) { + jgen.writeStartObject(); + jgen.writeObjectField("mailserver", ((MailClientConfigurationYaml) value).getMailserver()); + jgen.writeEndObject(); + } + jgen.writeEndArray(); + + }else if(value instanceof MailServerConfigurationYaml) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + }else if(value instanceof NatConfigurationYaml) { + jgen.writeStartArray(); + + for(String source : ((NatConfigurationYaml) value).getSources()) { + jgen.writeString(source); + } + + jgen.writeEndArray(); + + }else if(value instanceof VpnAccessConfigurationYaml) { + jgen.writeStartArray(); + + if(((VpnAccessConfigurationYaml) value).getVpnexit()!= null) { + jgen.writeStartObject(); + jgen.writeObjectField("vpnexit", ((VpnAccessConfigurationYaml) value).getVpnexit()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + }else if(value instanceof VpnExitConfigurationYaml) { + jgen.writeStartArray(); + + if(((VpnExitConfigurationYaml) value).getVpnaccess()!= null) { + jgen.writeStartObject(); + jgen.writeObjectField("vpnaccess", ((VpnExitConfigurationYaml) value).getVpnaccess()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + }else if(value instanceof WebClientConfigurationYaml) { + jgen.writeStartArray(); + + if(((WebClientConfigurationYaml) value).getNameWebServer() != null) { + jgen.writeStartObject(); + jgen.writeObjectField("webserver", ((WebClientConfigurationYaml) value).getNameWebServer()); + jgen.writeEndObject(); + } + + jgen.writeEndArray(); + + }else if(value instanceof WebServerConfigurationYaml) { + jgen.writeStartArray(); + jgen.writeEndArray(); + + }else { + jgen.writeStartArray(); + jgen.writeEndArray(); + } + + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamConfigurationYaml.java new file mode 100644 index 0000000..b0a082d --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamConfigurationYaml.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; + +public class AntispamConfigurationYaml implements ConfigurationYaml { + private List sources; + + public List getSources() { + return sources; + } + + public void setSources(List sources) { + this.sources = sources; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamNode.java new file mode 100644 index 0000000..9d02e87 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/AntispamNode.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class AntispamNode extends NodeTemplateYaml { + private AntispamConfigurationYaml properties; + + public AntispamConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(AntispamConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheConfigurationYaml.java new file mode 100644 index 0000000..5cf03cd --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheConfigurationYaml.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CacheConfigurationYaml implements ConfigurationYaml { + private List resources; + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheNode.java new file mode 100644 index 0000000..99adb2e --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/CacheNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class CacheNode extends NodeTemplateYaml { + private CacheConfigurationYaml properties; + + public CacheConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(CacheConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ConfigurationYaml.java new file mode 100644 index 0000000..b0e4000 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ConfigurationYaml.java @@ -0,0 +1,16 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + + +//Empty interface implemented by all the Yaml configuration beans allowing +//an easier and type indipendet use of the objects +public interface ConfigurationYaml { + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiConfigurationYaml.java new file mode 100644 index 0000000..3074780 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiConfigurationYaml.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DpiConfigurationYaml implements ConfigurationYaml{ + private List notAllowedList; + + public List getNotAllowedList() { + return notAllowedList; + } + + public void setNotAllowedList(List notAllowedList) { + this.notAllowedList = notAllowedList; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiNode.java new file mode 100644 index 0000000..d200cc2 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/DpiNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class DpiNode extends NodeTemplateYaml { + private DpiConfigurationYaml properties; + + public DpiConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(DpiConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostConfigurationYaml.java new file mode 100644 index 0000000..e1cfbd8 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostConfigurationYaml.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class EndhostConfigurationYaml implements ConfigurationYaml{ + private String body; + private int sequence; + private String protocol; + private String email_from; + private String url; + private String options; + private String destination; + + public String getBody() { + return body; + } + public void setBody(String body) { + this.body = body; + } + public int getSequence() { + return sequence; + } + public void setSequence(int sequence) { + this.sequence = sequence; + } + public String getProtocol() { + return protocol; + } + public void setProtocol(String protocol) { + this.protocol = protocol; + } + public String getEmail_from() { + return email_from; + } + public void setEmail_from(String email_from) { + this.email_from = email_from; + } + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getOptions() { + return options; + } + public void setOptions(String options) { + this.options = options; + } + public String getDestination() { + return destination; + } + public void setDestination(String destination) { + this.destination = destination; + } + + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostNode.java new file mode 100644 index 0000000..c47b14e --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndhostNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class EndhostNode extends NodeTemplateYaml{ + private EndhostConfigurationYaml properties; + + public EndhostConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(EndhostConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointConfigurationYaml.java new file mode 100644 index 0000000..76cbec6 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointConfigurationYaml.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class EndpointConfigurationYaml implements ConfigurationYaml{ + private List names; + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointNode.java new file mode 100644 index 0000000..06b50cd --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/EndpointNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class EndpointNode extends NodeTemplateYaml { + private EndpointConfigurationYaml properties; + + public EndpointConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(EndpointConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierConfigurationYaml.java new file mode 100644 index 0000000..64ff4c7 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierConfigurationYaml.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class FieldModifierConfigurationYaml implements ConfigurationYaml{ + private List names; + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierNode.java new file mode 100644 index 0000000..f805337 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FieldModifierNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class FieldModifierNode extends NodeTemplateYaml { + private FieldModifierConfigurationYaml properties; + + public FieldModifierConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(FieldModifierConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallConfigurationYaml.java new file mode 100644 index 0000000..85634d4 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallConfigurationYaml.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.Map; + +public class FirewallConfigurationYaml implements ConfigurationYaml{ + private Map elements; + + public Map getElements() { + return elements; + } + + public void setElements(Map elements) { + this.elements = elements; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallNode.java new file mode 100644 index 0000000..d8952ae --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/FirewallNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class FirewallNode extends NodeTemplateYaml { + private FirewallConfigurationYaml properties; + + public FirewallConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(FirewallConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientConfigurationYaml.java new file mode 100644 index 0000000..2120c4d --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientConfigurationYaml.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class MailClientConfigurationYaml implements ConfigurationYaml { + private String mailserver; + + public String getMailserver() { + return mailserver; + } + + public void setMailserver(String mailserver) { + this.mailserver = mailserver; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientNode.java new file mode 100644 index 0000000..fa75154 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailClientNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class MailClientNode extends NodeTemplateYaml { + private MailClientConfigurationYaml properties; + + public MailClientConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(MailClientConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerConfigurationYaml.java new file mode 100644 index 0000000..3672727 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerConfigurationYaml.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class MailServerConfigurationYaml implements ConfigurationYaml { + private List names; + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerNode.java new file mode 100644 index 0000000..6f7d493 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/MailServerNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class MailServerNode extends NodeTemplateYaml { + private MailServerConfigurationYaml properties; + + public MailServerConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(MailServerConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatConfigurationYaml.java new file mode 100644 index 0000000..49d34c8 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatConfigurationYaml.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class NatConfigurationYaml implements ConfigurationYaml { + private List sources; + + public List getSources() { + return sources; + } + + public void setSources(List sources) { + this.sources = sources; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatNode.java new file mode 100644 index 0000000..cd30172 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NatNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class NatNode extends NodeTemplateYaml { + private NatConfigurationYaml properties; + + public NatConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(NatConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NodeTemplateYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NodeTemplateYaml.java new file mode 100644 index 0000000..9821f7c --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/NodeTemplateYaml.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.*; + +//These annotations allow polimorphic deserialization of yaml text into beans by using the type field of each node +//In case a specified type is unknown the default implementation will be FieldModifierNode +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type", defaultImpl=FieldModifierNode.class, visible= true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = AntispamNode.class, name="verigraph.nodeTypes.Antispam"), + @JsonSubTypes.Type(value = CacheNode.class, name="verigraph.nodeTypes.Cache"), + @JsonSubTypes.Type(value = DpiNode.class, name="verigraph.nodeTypes.Dpi"), + @JsonSubTypes.Type(value = EndhostNode.class, name="verigraph.nodeTypes.Endhost"), + @JsonSubTypes.Type(value = EndpointNode.class, name="verigraph.nodeTypes.Endpoint"), + @JsonSubTypes.Type(value = FieldModifierNode.class, name="verigraph.nodeTypes.FieldModifier"), + @JsonSubTypes.Type(value = FirewallNode.class, name="verigraph.nodeTypes.Firewall"), + @JsonSubTypes.Type(value = MailClientNode.class, name="verigraph.nodeTypes.MailClient"), + @JsonSubTypes.Type(value = MailServerNode.class, name="verigraph.nodeTypes.MailServer"), + @JsonSubTypes.Type(value = NatNode.class, name="verigraph.nodeTypes.Nat"), + @JsonSubTypes.Type(value = VpnAccessNode.class, name="verigraph.nodeTypes.VpnAccess"), + @JsonSubTypes.Type(value = VpnExitNode.class, name="verigraph.nodeTypes.VpnExit"), + @JsonSubTypes.Type(value = WebClientNode.class, name="verigraph.nodeTypes.WebClient"), + @JsonSubTypes.Type(value = WebServerNode.class, name="verigraph.nodeTypes.WebServer") +}) +public class NodeTemplateYaml { + private String name; + private String type; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + // //Generic YamlNode configuration to be extended in single nodes + // public interface ConfigurationYaml { + // } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/RelationshipTemplateYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/RelationshipTemplateYaml.java new file mode 100644 index 0000000..d828775 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/RelationshipTemplateYaml.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.util.Map; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RelationshipTemplateYaml { + private String type; + private Map properties; + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ServiceTemplateYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ServiceTemplateYaml.java new file mode 100644 index 0000000..0955a7d --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/ServiceTemplateYaml.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.Map; +import com.fasterxml.jackson.annotation.*; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceTemplateYaml { + private Map metadata; + private String description; + private TopologyTemplateYaml topology_template; + + public Map getMetadata() { + return metadata; + } + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public TopologyTemplateYaml getTopology_template() { + return topology_template; + } + public void setTopology_template(TopologyTemplateYaml topology_template) { + this.topology_template = topology_template; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/TopologyTemplateYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/TopologyTemplateYaml.java new file mode 100644 index 0000000..2653697 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/TopologyTemplateYaml.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class TopologyTemplateYaml { + private Map node_templates; + private Map relationship_templates; + + public Map getRelationship_templates() { + return relationship_templates; + } + + public void setRelationship_templates(Map relationship_templates) { + this.relationship_templates = relationship_templates; + } + + public Map getNode_templates() { + return node_templates; + } + + public void setNode_templates(Map node_templates) { + this.node_templates = node_templates; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VerificationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VerificationYaml.java new file mode 100644 index 0000000..2f572a6 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VerificationYaml.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; +import com.fasterxml.jackson.annotation.*; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class VerificationYaml { + /* private Map metadata; + private String description;*/ + private String result; + private String comment; + private List paths; + + /* public Map getMetadata() { + return metadata; + } + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + }*/ + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public List getPaths() { + return paths; + } + + public void setPaths(List paths) { + this.paths = paths; + } + +} \ No newline at end of file diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessConfigurationYaml.java new file mode 100644 index 0000000..807059f --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessConfigurationYaml.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class VpnAccessConfigurationYaml implements ConfigurationYaml { + private String vpnexit; + + public String getVpnexit() { + return vpnexit; + } + + public void setVpnexit(String vpnexit) { + this.vpnexit = vpnexit; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessNode.java new file mode 100644 index 0000000..9058615 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnAccessNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class VpnAccessNode extends NodeTemplateYaml{ + private VpnAccessConfigurationYaml properties; + + public VpnAccessConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(VpnAccessConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitConfigurationYaml.java new file mode 100644 index 0000000..090e337 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitConfigurationYaml.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class VpnExitConfigurationYaml implements ConfigurationYaml { + private String vpnaccess; + + public String getVpnaccess() { + return vpnaccess; + } + + public void setVpnaccess(String vpnaccess) { + this.vpnaccess = vpnaccess; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitNode.java new file mode 100644 index 0000000..775b8d3 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/VpnExitNode.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class VpnExitNode extends NodeTemplateYaml { + private VpnExitConfigurationYaml properties; + + public VpnExitConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(VpnExitConfigurationYaml properties) { + this.properties = properties; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientConfigurationYaml.java new file mode 100644 index 0000000..02825ed --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientConfigurationYaml.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class WebClientConfigurationYaml implements ConfigurationYaml{ + private String nameWebServer; + + public String getNameWebServer() { + return nameWebServer; + } + + public void setNameWebServer(String nameWebServer) { + this.nameWebServer = nameWebServer; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientNode.java new file mode 100644 index 0000000..5e01194 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebClientNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class WebClientNode extends NodeTemplateYaml { + private WebClientConfigurationYaml properties; + + public WebClientConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(WebClientConfigurationYaml properties) { + this.properties = properties; + } +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerConfigurationYaml.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerConfigurationYaml.java new file mode 100644 index 0000000..1f37c09 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerConfigurationYaml.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +import java.util.List; + +public class WebServerConfigurationYaml implements ConfigurationYaml{ + public List names; + + public List getNames() { + return names; + } + + public void setNames(List names) { + this.names = names; + } + +} diff --git a/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerNode.java b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerNode.java new file mode 100644 index 0000000..5340b77 --- /dev/null +++ b/verigraph/src/it/polito/verigraph/tosca/yaml/beans/WebServerNode.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2018 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.tosca.yaml.beans; + +public class WebServerNode extends NodeTemplateYaml { + private WebServerConfigurationYaml properties; + + public WebServerConfigurationYaml getProperties() { + return properties; + } + + public void setProperties(WebServerConfigurationYaml properties) { + this.properties = properties; + } +}