Add JUnit for web service client tool 71/69371/1
authorliamfallon <liam.fallon@ericsson.com>
Thu, 27 Sep 2018 15:52:23 +0000 (16:52 +0100)
committerliamfallon <liam.fallon@ericsson.com>
Thu, 27 Sep 2018 15:52:34 +0000 (16:52 +0100)
JUnit, SOnar fixes, and some minor bug fixes.

Issue-ID: POLICY-1034
Change-Id: I72f46e944051f7d65d6b106afe33c759975283af
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/BatchDeployer.java
core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/EngineServiceFacade.java
tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java
tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java
tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/WsClientMain.java
tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java [new file with mode: 0644]

index 321d615..1748a06 100644 (file)
@@ -83,7 +83,7 @@ public class BatchDeployer {
      * @throws IOException on IO exceptions from the operating system
      */
     public void deployModel(final String modelFileName, final boolean ignoreConflicts, final boolean force)
-                    throws ApexException, IOException {
+                    throws ApexException {
         engineServiceFacade.deployModel(modelFileName, ignoreConflicts, force);
     }
 
@@ -144,7 +144,7 @@ public class BatchDeployer {
             deployer.init();
             deployer.deployModel(args[2], false, false);
             deployer.startEngines();
-        } catch (final ApexException | IOException e) {
+        } catch (final ApexException e) {
             LOGGER.error("model deployment failed on parameters {}", args, e);
         } finally {
             if (deployer != null) {
index 9b24bcd..e27bf5d 100644 (file)
@@ -195,7 +195,7 @@ public class EngineServiceFacade {
      * @throws IOException on IO exceptions from the operating system
      */
     public void deployModel(final String modelFileName, final boolean ignoreConflicts, final boolean force)
-                    throws ApexException, IOException {
+                    throws ApexException {
         if (engineServiceKey == null || engineKeyArray == null || engineKeyArray.length == 0) {
             LOGGER.error("cound not deploy apex model, deployer is not initialized");
             throw new ApexDeploymentException("cound not deploy apex model, deployer is not initialized");
@@ -212,7 +212,13 @@ public class EngineServiceFacade {
             }
         }
 
-        deployModel(modelFileName, apexModelUrl.openStream(), ignoreConflicts, force);
+        try {
+            deployModel(modelFileName, apexModelUrl.openStream(), ignoreConflicts, force);
+        } catch (Exception deployException) {
+            String errorMessage = "could not deploy apex model from " + modelFileName;
+            LOGGER.error(errorMessage, deployException);
+            throw new ApexDeploymentException(errorMessage, deployException);
+        }
     }
 
     /**
index cfd7cb3..86a826b 100644 (file)
@@ -26,6 +26,7 @@ import java.util.Set;
 
 import org.apache.avro.Schema;
 import org.apache.avro.Schema.Field;
+import org.apache.avro.Schema.Type;
 import org.apache.commons.lang3.Validate;
 import org.onap.policy.apex.context.parameters.SchemaParameters;
 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
@@ -40,6 +41,7 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
 import org.onap.policy.apex.model.policymodel.concepts.AxState;
 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
 import org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters;
+import org.onap.policy.apex.service.engine.event.ApexEventException;
 import org.onap.policy.apex.tools.model.generator.SchemaUtils;
 import org.slf4j.ext.XLogger;
 import org.slf4j.ext.XLoggerFactory;
@@ -97,19 +99,14 @@ public class Model2JsonEventSchema {
      */
     protected ST addFieldType(final Schema schema, final STGroup stg) {
         ST ret = null;
-        switch (schema.getType()) {
-            case BOOLEAN:
-            case BYTES:
-            case DOUBLE:
-            case FIXED:
-            case FLOAT:
-            case INT:
-            case LONG:
-            case STRING:
-                ret = stg.getInstanceOf("fieldTypeAtomic");
-                ret.add("type", schema.getType());
-                break;
 
+        if (isSimpleType(schema.getType())) {
+            ret = stg.getInstanceOf("fieldTypeAtomic");
+            ret.add("type", schema.getType());
+            return ret;
+        }
+        
+        switch (schema.getType()) {
             case ARRAY:
                 ret = stg.getInstanceOf("fieldTypeArray");
                 ret.add("array", this.addFieldType(schema.getElementType(), stg));
@@ -138,6 +135,31 @@ public class Model2JsonEventSchema {
         return ret;
     }
 
+    /**
+     * Check if a schema is a simple type.
+     * 
+     * @param schemaType the type of the schema
+     * @return true if the schema is a simple type
+     */
+    private boolean isSimpleType(Type schemaType) {
+        switch (schemaType) {
+            case BOOLEAN:
+            case BYTES:
+            case DOUBLE:
+            case FIXED:
+            case FLOAT:
+            case INT:
+            case LONG:
+            case STRING: {
+                return true;
+            }
+            
+            default: {
+                return false;
+            }
+        }
+    }
+
     /**
      * Process a record entry.
      * @param schema the schema to add a type for
@@ -208,6 +230,22 @@ public class Model2JsonEventSchema {
             }
         }
 
+        String renderMessage = renderEvents(stg, stEvents, events);
+        LOGGER.error(renderMessage);
+        return 0;
+    }
+
+    /**
+     * Render the events.
+     * 
+     * @param stg the string template
+     * @param stEvents the event template
+     * @param events the events to render
+     * @return the rendered events
+     * @throws ApexEventException on rendering exceptions
+     */
+    private String renderEvents(final STGroupFile stg, final ST stEvents, final Set<AxEvent> events)
+                    throws ApexEventException {
         for (final AxEvent event : events) {
             final ST stEvent = stg.getInstanceOf("event");
             stEvent.add("name", event.getKey().getName());
@@ -232,9 +270,7 @@ public class Model2JsonEventSchema {
             }
             stEvents.add("event", stEvent);
         }
-        String renderMessage = stEvents.render();
-        LOGGER.error(renderMessage);
-        return 0;
+        return stEvents.render();
     }
 
     /**
index 28c4942..edad2eb 100644 (file)
@@ -130,8 +130,9 @@ public class SimpleConsole extends WebSocketClient {
                 connect();
             }
         };
+        thread.setName("ClientThread");
         thread.start();
-
+        
         final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         String event = "";
         String line;
index 9376cad..29a5de0 100644 (file)
@@ -22,6 +22,8 @@ package org.onap.policy.apex.tools.simple.wsclient;
 
 import java.io.IOException;
 import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.net.URISyntaxException;
 import java.nio.channels.NotYetConnectedException;
 
@@ -42,6 +44,11 @@ public final class WsClientMain {
     // Get a reference to the logger
     private static final Logger LOGGER = LoggerFactory.getLogger(WsClientMain.class);
 
+    // String constants
+    private static final String APP_NAME = "ws-client";
+    private static final String APP_DESCRIPTION = "takes events from stdin and sends via WS to APEX"
+                    + " and/or receives events from APEX via WS and prints them to standard out";
+
     /**
      * Run the command.
      * 
@@ -49,8 +56,6 @@ public final class WsClientMain {
      * @param outStream stream for output
      */
     WsClientMain(final String[] args, final PrintStream outStream) {
-        String appName = "ws-simple-echo";
-        String appDescr = "receives events from APEX via WS and prints them to standard out";
         boolean console = false;
 
         final CliParser cli = new CliParser();
@@ -62,41 +67,35 @@ public final class WsClientMain {
 
         final CommandLine cmd = cli.parseCli(args);
 
-        if (cmd.hasOption('c') || cmd.hasOption("console")) {
-            appName = "ws-simple-console";
-            appDescr = "takes events from stdin and sends via WS to APEX";
-            console = true;
-        }
-
         // help is an exit option, print usage and exit
-        if (cmd.hasOption('h') || cmd.hasOption("help")) {
-            final HelpFormatter formatter = new HelpFormatter();
-            outStream.println(appName + " v" + cli.getAppVersion() + " - " + appDescr);
-            formatter.printHelp(appName, cli.getOptions());
+        if (cmd == null || cmd.hasOption('h') || cmd.hasOption("help")) {
+            outStream.println(getHelpString(cli));
             outStream.println();
             return;
         }
 
+        if (cmd.hasOption('c') || cmd.hasOption("console")) {
+            console = true;
+        }
+
         // version is an exit option, print version and exit
         if (cmd.hasOption('v') || cmd.hasOption("version")) {
-            outStream.println(appName + " " + cli.getAppVersion());
+            outStream.println(APP_NAME + " " + cli.getAppVersion());
             outStream.println();
             return;
         }
 
-        runConsoleOrEcho(appName, console, cmd, outStream);
+        runConsoleOrEcho(console, cmd, outStream);
     }
 
     /**
      * Run the console or echo.
      * 
-     * @param appName the application name
      * @param console if true, run the console otherwise run echo
      * @param cmd the command line to run
      * @param outStream stream for output
      */
-    private static void runConsoleOrEcho(String appName, boolean console, final CommandLine cmd,
-                    final PrintStream outStream) {
+    private static void runConsoleOrEcho(final boolean console, final CommandLine cmd, final PrintStream outStream) {
         String server = cmd.getOptionValue('s');
         if (server == null) {
             server = cmd.getOptionValue("server");
@@ -114,9 +113,9 @@ public final class WsClientMain {
         }
 
         if (console) {
-            runConsole(server, port, appName, outStream);
+            runConsole(server, port, outStream);
         } else {
-            runEcho(server, port, appName, outStream);
+            runEcho(server, port, outStream);
         }
     }
 
@@ -125,17 +124,14 @@ public final class WsClientMain {
      *
      * @param server the server, must not be blank
      * @param port the port, must not be blank
-     * @param appName the application name, must not be blank
      * @param outStream stream for output
      */
-    public static void runEcho(final String server, final String port, final String appName,
-                    final PrintStream outStream) {
+    public static void runEcho(final String server, final String port, final PrintStream outStream) {
         Validate.notBlank(server);
         Validate.notBlank(port);
-        Validate.notBlank(appName);
 
         outStream.println();
-        outStream.println(appName + ": starting simple event echo");
+        outStream.println(APP_NAME + ": starting simple event echo");
         outStream.println(" --> server: " + server);
         outStream.println(" --> port: " + port);
         outStream.println();
@@ -145,18 +141,18 @@ public final class WsClientMain {
         outStream.println();
 
         try {
-            final SimpleEcho simpleEcho = new SimpleEcho(server, port, appName, outStream, outStream);
+            final SimpleEcho simpleEcho = new SimpleEcho(server, port, APP_NAME, outStream, outStream);
             simpleEcho.connect();
         } catch (final URISyntaxException uex) {
-            String message = appName + ": URI exception, could not create URI from server and port settings";
+            String message = APP_NAME + ": URI exception, could not create URI from server and port settings";
             outStream.println(message);
             LOGGER.warn(message, uex);
         } catch (final NullPointerException nex) {
-            String message = appName + ": null pointer, server or port were null";
+            String message = APP_NAME + ": null pointer, server or port were null";
             outStream.println(message);
             LOGGER.warn(message, nex);
         } catch (final IllegalArgumentException iex) {
-            String message = appName + ": illegal argument, server or port were blank";
+            String message = APP_NAME + ": illegal argument, server or port were blank";
             outStream.println(message);
             LOGGER.warn(message, iex);
         }
@@ -167,17 +163,15 @@ public final class WsClientMain {
      *
      * @param server the server, must not be blank
      * @param port the port, must not be blank
-     * @param appName the application name, must not be blank
      * @param outStream stream for output
      */
-    public static void runConsole(final String server, final String port, final String appName,
-                    final PrintStream outStream) {
+    public static void runConsole(final String server, final String port, final PrintStream outStream) {
         Validate.notBlank(server);
         Validate.notBlank(port);
-        Validate.notBlank(appName);
+        Validate.notBlank(APP_NAME);
 
         outStream.println();
-        outStream.println(appName + ": starting simple event console");
+        outStream.println(APP_NAME + ": starting simple event console");
         outStream.println(" --> server: " + server);
         outStream.println(" --> port: " + port);
         outStream.println();
@@ -187,31 +181,48 @@ public final class WsClientMain {
         outStream.println();
 
         try {
-            final SimpleConsole simpleConsole = new SimpleConsole(server, port, appName, outStream, outStream);
+            final SimpleConsole simpleConsole = new SimpleConsole(server, port, APP_NAME, outStream, outStream);
             simpleConsole.runClient();
         } catch (final URISyntaxException uex) {
-            String message = appName + ": URI exception, could not create URI from server and port settings";
+            String message = APP_NAME + ": URI exception, could not create URI from server and port settings";
             outStream.println(message);
             LOGGER.warn(message, uex);
         } catch (final NullPointerException nex) {
-            String message = appName + ": null pointer, server or port were null";
+            String message = APP_NAME + ": null pointer, server or port were null";
             outStream.println(message);
             LOGGER.warn(message, nex);
         } catch (final IllegalArgumentException iex) {
-            String message = appName + ": illegal argument, server or port were blank";
+            String message = APP_NAME + ": illegal argument, server or port were blank";
             outStream.println(message);
             LOGGER.warn(message, iex);
         } catch (final NotYetConnectedException nex) {
-            String message = appName + ": not yet connected, connection to server took too long";
+            String message = APP_NAME + ": not yet connected, connection to server took too long";
             outStream.println(message);
             LOGGER.warn(message, nex);
         } catch (final IOException ioe) {
-            String message = appName + ": IO exception, something went wrong on the standard input";
+            String message = APP_NAME + ": IO exception, something went wrong on the standard input";
             outStream.println(message);
             LOGGER.warn(message, ioe);
         }
     }
 
+    /**
+     * Get the help string for the application.
+     * 
+     * @param cli the command line options
+     * @return the help string
+     */
+    private String getHelpString(final CliParser cli) {
+        HelpFormatter formatter = new HelpFormatter();
+
+        final StringWriter helpStringWriter = new StringWriter();
+        final PrintWriter helpPrintWriter = new PrintWriter(helpStringWriter);
+
+        formatter.printHelp(helpPrintWriter, 120, APP_NAME, APP_DESCRIPTION, cli.getOptions(), 2, 4, "");
+
+        return helpStringWriter.toString();
+    }
+
     /**
      * The main method for the WS applications.
      *
diff --git a/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java b/tools/simple-wsclient/src/test/java/org/onap/policy/apex/tools/simple/wsclient/WsClientTest.java
new file mode 100644 (file)
index 0000000..0b097a0
--- /dev/null
@@ -0,0 +1,170 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * 
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.apex.tools.simple.wsclient;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.PrintStream;
+
+import org.junit.Test;
+
+/**
+ * Test the WsClient utility.
+ */
+public class WsClientTest {
+    @Test
+    public void testWsClient() {
+        try {
+            final String[] EventArgs =
+                { "-h" };
+
+            WsClientMain.main(EventArgs);
+        } catch (Exception exc) {
+            fail("test should not throw an exception");
+        }
+    }
+
+    @Test
+    public void testWsClientNoOptions() {
+        final String[] EventArgs = new String[]
+            {};
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client: starting simple event echo"));
+    }
+
+    @Test
+    public void testWsClientBadOptions() {
+        final String[] EventArgs =
+            { "-zabbu" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("usage: ws-client"));
+    }
+
+    @Test
+    public void testWsClientHelp() {
+        final String[] EventArgs =
+            { "-h" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("usage: ws-client"));
+    }
+
+    @Test
+    public void testWsClientVersion() {
+        final String[] EventArgs =
+            { "-v" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client"));
+    }
+
+    @Test
+    public void testWsClientNoServerArg() {
+        final String[] EventArgs =
+            { "-s" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client"));
+    }
+
+    @Test
+    public void testWsClientNoPortArg() {
+        final String[] EventArgs =
+            { "-p" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client"));
+    }
+
+    @Test
+    public void testWsClientBadPortArg() {
+        final String[] EventArgs =
+            { "-p", "hello" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client"));
+    }
+
+    @Test
+    public void testWsClientBadServerArg() {
+        final String[] EventArgs =
+            { "-s", "asdsadadasd:asdasdsadasd@@" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("ws-client"));
+    }
+
+    @Test
+    public void testWsClientConsole() {
+        final String[] EventArgs =
+            { "-c", "-s", "AServerThatDoesntExist", "-p", "99999999" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains("terminate the application typing"));
+    }
+
+    @Test
+    public void testWsClientEcho() {
+        final String[] EventArgs =
+            { "-s", "AServerThatDoesntExist", "-p", "99999999" };
+
+        final String outputString = runWsClient(EventArgs);
+
+        assertTrue(outputString.contains(
+                        "Once started, the application will simply print out all received events to standard out"));
+    }
+
+    /**
+     * Run the application.
+     * 
+     * @param eventArgs the command arguments
+     * @return a string containing the command output
+     */
+    private String runWsClient(final String[] eventArgs) {
+        final ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
+        final ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
+
+        new WsClientMain(eventArgs, new PrintStream(baosOut, true));
+
+        InputStream testInput = new ByteArrayInputStream("Test Data for Input to WS".getBytes());
+        System.setIn(testInput);
+
+        String outString = baosOut.toString();
+        String errString = baosErr.toString();
+
+        return "*** StdOut ***\n" + outString + "\n*** StdErr ***\n" + errString;
+    }
+}