From 565922bbe60fc0a9d015ce00ef8733e6ddfe905c Mon Sep 17 00:00:00 2001 From: liamfallon Date: Mon, 17 Sep 2018 15:50:34 +0100 Subject: Fix sonar issues in apex utilties This change fixes Sonar issues in apex command line utilities. Issue-ID: POLICY-1034 Change-Id: Ib63a3d4107260c5909405e6f0d899279da869028 Signed-off-by: liamfallon --- .../model/generator/model2cli/Application.java | 43 ++++--- .../tools/model/generator/model2cli/Model2Cli.java | 52 +++++--- .../model/generator/model2event/Application.java | 48 ++++--- .../model2event/Model2JsonEventSchema.java | 138 +++++++++++++++------ .../apex/tools/simple/wsclient/Application.java | 84 ++++++++----- .../apex/tools/simple/wsclient/SimpleConsole.java | 41 +++--- .../apex/tools/simple/wsclient/SimpleEcho.java | 49 +++++--- .../org/onap/policy/apex/tools/common/Console.java | 38 +++--- 8 files changed, 314 insertions(+), 179 deletions(-) diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java index b6c6b774c..70436150c 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Application.java @@ -20,6 +20,8 @@ package org.onap.policy.apex.tools.model.generator.model2cli; +import java.io.PrintStream; + import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; @@ -44,10 +46,15 @@ public final class Application { /** The description 1-liner of the application. */ public static final String APP_DESCRIPTION = "generates CLI Editor Commands from a policy model"; + // Input and output streams + private static final PrintStream OUT_STREAM = System.out; + private static final PrintStream ERR_STREAM = System.err; + /** * Private constructor to prevent instantiation. */ - private Application() {} + private Application() { + } /** * Main method to start the application. @@ -68,16 +75,16 @@ public final class Application { // help is an exit option, print usage and exit if (cmd.hasOption(CliOptions.HELP.getOpt())) { final HelpFormatter formatter = new HelpFormatter(); - System.out.println(APP_NAME + " v" + cli.getAppVersion() + " - " + APP_DESCRIPTION); + OUT_STREAM.println(APP_NAME + " v" + cli.getAppVersion() + " - " + APP_DESCRIPTION); formatter.printHelp(APP_NAME, cli.getOptions()); - System.out.println(); + OUT_STREAM.println(); return; } // version is an exit option, print version and exit if (cmd.hasOption(CliOptions.VERSION.getOpt())) { - System.out.println(APP_NAME + " " + cli.getAppVersion()); - System.out.println(); + OUT_STREAM.println(APP_NAME + " " + cli.getAppVersion()); + OUT_STREAM.println(); return; } @@ -86,8 +93,8 @@ public final class Application { modelFile = cmd.getOptionValue("model"); } if (modelFile == null) { - System.err.println(APP_NAME + ": no '-" + CliOptions.MODELFILE.getOpt() - + "' model file given, cannot proceed (try -h for help)"); + ERR_STREAM.println(APP_NAME + ": no '-" + CliOptions.MODELFILE.getOpt() + + "' model file given, cannot proceed (try -h for help)"); return; } @@ -95,27 +102,27 @@ public final class Application { final String of = cmd.getOptionValue(CliOptions.FILEOUT.getOpt()); final boolean overwrite = cmd.hasOption(CliOptions.OVERWRITE.getOpt()); if (overwrite && of == null) { - System.err.println(APP_NAME + ": error with '-" + CliOptions.OVERWRITE.getOpt() - + "' option. This option is only valid if a '-" + CliOptions.FILEOUT.getOpt() - + "' option is also used. Cannot proceed (try -h for help)"); + ERR_STREAM.println(APP_NAME + ": error with '-" + CliOptions.OVERWRITE.getOpt() + + "' option. This option is only valid if a '-" + CliOptions.FILEOUT.getOpt() + + "' option is also used. Cannot proceed (try -h for help)"); return; } if (of != null) { outfile = new OutputFile(of, overwrite); final String isoutfileok = outfile.validate(); if (isoutfileok != null) { - System.err.println(APP_NAME + ": error with '-" + CliOptions.FILEOUT.getOpt() + "' option: \"" - + isoutfileok + "\". Cannot proceed (try -h for help)"); + ERR_STREAM.println(APP_NAME + ": error with '-" + CliOptions.FILEOUT.getOpt() + "' option: \"" + + isoutfileok + "\". Cannot proceed (try -h for help)"); return; } } if (outfile == null) { - System.out.println(); - System.out.println(APP_NAME + ": starting CLI generator"); - System.out.println(" --> model file: " + modelFile); - System.out.println(); - System.out.println(); + OUT_STREAM.println(); + OUT_STREAM.println(APP_NAME + ": starting CLI generator"); + OUT_STREAM.println(" --> model file: " + modelFile); + OUT_STREAM.println(); + OUT_STREAM.println(); } try { @@ -123,7 +130,7 @@ public final class Application { app.runApp(); } catch (final ApexException aex) { String message = APP_NAME + ": caught APEX exception with message: " + aex.getMessage(); - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, aex); } } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java index e6002208c..f58faf0eb 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2cli/Model2Cli.java @@ -94,6 +94,7 @@ public class Model2Cli { public Model2Cli(final String modelFile, final OutputFile outFile, final boolean validate, final String appName) { Validate.notNull(modelFile, "Model2Cli: given model file name was blank"); Validate.notNull(appName, "Model2Cli: given application name was blank"); + this.modelFile = modelFile; this.outFile = outFile; this.appName = appName; @@ -133,6 +134,15 @@ public class Model2Cli { } } + return generateCli(codeGen, policyModel); + } + + /** + * Generate the CLI from the model. + * @param codeGen the code generator + * @param policyModel the policy model + */ + private int generateCli(final CodeGeneratorCliEditor codeGen, final AxPolicyModel policyModel) { kig = new KeyInfoGetter(policyModel); // Order is important. 0: model, 1: context schemas, 2: tasks, 3: events, 4: ContextAlbums, 5: Policies @@ -145,7 +155,7 @@ public class Model2Cli { final AxArtifactKey key = s.getKey(); codeGen.addSchemaDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), - s.getSchemaFlavour(), s.getSchema()); + s.getSchemaFlavour(), s.getSchema()); } // 2: tasks @@ -158,7 +168,7 @@ public class Model2Cli { final List contextRefs = getCtxtRefsForTask(codeGen, t); codeGen.addTaskDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), - infields, outfields, logic, parameters, contextRefs); + infields, outfields, logic, parameters, contextRefs); } // 3: events @@ -167,7 +177,7 @@ public class Model2Cli { final List fields = getParametersForEvent(codeGen, e); codeGen.addEventDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), - e.getNameSpace(), e.getSource(), e.getTarget(), fields); + e.getNameSpace(), e.getSource(), e.getTarget(), fields); } // 4: context albums @@ -175,8 +185,8 @@ public class Model2Cli { final AxArtifactKey key = a.getKey(); codeGen.addContextAlbumDeclaration(kig.getName(key), kig.getVersion(key), kig.getUuid(key), - kig.getDesc(key), a.getScope(), a.isWritable(), kig.getName(a.getItemSchema()), - kig.getVersion(a.getItemSchema())); + kig.getDesc(key), a.getScope(), a.isWritable(), kig.getName(a.getItemSchema()), + kig.getVersion(a.getItemSchema())); } // 5: policies @@ -184,7 +194,7 @@ public class Model2Cli { final AxArtifactKey key = p.getKey(); final List states = getStatesForPolicy(codeGen, p); codeGen.addPolicyDefinition(kig.getName(key), kig.getVersion(key), kig.getUuid(key), kig.getDesc(key), - p.getTemplate(), p.getFirstState(), states); + p.getTemplate(), p.getFirstState(), states); } final String out = codeGen.getModel().render(); @@ -205,6 +215,7 @@ public class Model2Cli { } else { LOGGER.error(out); } + return 0; } @@ -222,7 +233,7 @@ public class Model2Cli { final AxReferenceKey fkey = f.getKey(); final ST val = cg.createEventFieldDefinition(kig.getPName(fkey), kig.getPVersion(fkey), kig.getLName(fkey), - kig.getName(f.getSchema()), kig.getVersion(f.getSchema()), f.getOptional()); + kig.getName(f.getSchema()), kig.getVersion(f.getSchema()), f.getOptional()); ret.add(val); } @@ -243,7 +254,7 @@ public class Model2Cli { for (final AxArtifactKey ckey : ctxs) { final ST val = cg.createTaskDefinitionContextRef(kig.getName(tkey), kig.getVersion(tkey), kig.getName(ckey), - kig.getVersion(ckey)); + kig.getVersion(ckey)); ret.add(val); } @@ -264,7 +275,7 @@ public class Model2Cli { final AxReferenceKey pkey = p.getKey(); final ST val = cg.createTaskDefinitionParameters(kig.getPName(pkey), kig.getPVersion(pkey), - kig.getLName(pkey), p.getTaskParameterValue()); + kig.getLName(pkey), p.getTaskParameterValue()); ret.add(val); } @@ -299,7 +310,7 @@ public class Model2Cli { final AxReferenceKey fkey = f.getKey(); final ST val = cg.createTaskDefinitionOutfields(kig.getPName(fkey), kig.getPVersion(fkey), - kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema())); + kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema())); ret.add(val); } @@ -320,7 +331,7 @@ public class Model2Cli { final AxReferenceKey fkey = f.getKey(); final ST val = cg.createTaskDefinitionInfields(kig.getPName(fkey), kig.getPVersion(fkey), - kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema())); + kig.getLName(fkey), kig.getName(f.getSchema()), kig.getVersion(f.getSchema())); ret.add(val); } @@ -346,8 +357,9 @@ public class Model2Cli { final List ctxRefs = getCtxtRefsForState(cg, st); final ST val = cg.createPolicyStateDef(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey), - kig.getName(st.getTrigger()), kig.getVersion(st.getTrigger()), kig.getName(st.getDefaultTask()), - kig.getVersion(st.getDefaultTask()), outputs, tasks, tsLogic, finalizerLogics, ctxRefs); + kig.getName(st.getTrigger()), kig.getVersion(st.getTrigger()), + kig.getName(st.getDefaultTask()), kig.getVersion(st.getDefaultTask()), outputs, tasks, + tsLogic, finalizerLogics, ctxRefs); ret.add(val); } @@ -369,7 +381,7 @@ public class Model2Cli { final AxReferenceKey finkey = fin.getKey(); final ST val = cg.createPolicyStateDefFinalizerLogic(kig.getPName(skey), kig.getPVersion(skey), - kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic()); + kig.getLName(skey), kig.getLName(finkey), fin.getLogicFlavour(), fin.getLogic()); ret.add(val); } @@ -390,7 +402,7 @@ public class Model2Cli { for (final AxArtifactKey ctx : ctxs) { final ST val = cg.createPolicyStateDefContextRef(kig.getPName(skey), kig.getPVersion(skey), - kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx)); + kig.getLName(skey), kig.getName(ctx), kig.getVersion(ctx)); ret.add(val); } @@ -409,7 +421,7 @@ public class Model2Cli { if (st.checkSetTaskSelectionLogic()) { final AxTaskSelectionLogic tsl = st.getTaskSelectionLogic(); final ST val = cg.createPolicyStateDefTaskSelLogic(kig.getPName(skey), kig.getPVersion(skey), - kig.getLName(skey), tsl.getLogicFlavour(), tsl.getLogic()); + kig.getLName(skey), tsl.getLogicFlavour(), tsl.getLogic()); return Collections.singletonList(val); } else { return Collections.emptyList(); @@ -433,8 +445,8 @@ public class Model2Cli { final AxReferenceKey trkey = tr.getKey(); final ST val = cg.createPolicyStateTask(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey), - kig.getLName(trkey), kig.getName(tkey), kig.getVersion(tkey), tr.getStateTaskOutputType().name(), - kig.getLName(tr.getOutput())); + kig.getLName(trkey), kig.getName(tkey), kig.getVersion(tkey), + tr.getStateTaskOutputType().name(), kig.getLName(tr.getOutput())); ret.add(val); } @@ -456,8 +468,8 @@ public class Model2Cli { final AxReferenceKey outkey = out.getKey(); final ST val = cg.createPolicyStateOutput(kig.getPName(skey), kig.getPVersion(skey), kig.getLName(skey), - kig.getLName(outkey), kig.getName(out.getOutgingEvent()), kig.getVersion(out.getOutgingEvent()), - kig.getLName(out.getNextState())); + kig.getLName(outkey), kig.getName(out.getOutgingEvent()), + kig.getVersion(out.getOutgingEvent()), kig.getLName(out.getNextState())); ret.add(val); } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java index 9735293cf..a5600ead1 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Application.java @@ -20,6 +20,8 @@ package org.onap.policy.apex.tools.model.generator.model2event; +import java.io.PrintStream; + import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; @@ -44,7 +46,12 @@ public final class Application { public static final String APP_DESCRIPTION = "generates JSON templates for events generated from a policy model"; /** Private constructor to prevent instantiation. */ - private Application() {} + private Application() { + } + + // Input and output streams + private static final PrintStream OUT_STREAM = System.out; + private static final PrintStream ERR_STREAM = System.err; /** * Main method to start the application. @@ -63,25 +70,34 @@ public final class Application { // help is an exit option, print usage and exit if (cmd.hasOption('h') || cmd.hasOption("help")) { final HelpFormatter formatter = new HelpFormatter(); - System.out.println(APP_NAME + " v" + cli.getAppVersion() + " - " + APP_DESCRIPTION); + OUT_STREAM.println(APP_NAME + " v" + cli.getAppVersion() + " - " + APP_DESCRIPTION); formatter.printHelp(APP_NAME, cli.getOptions()); - System.out.println(); + OUT_STREAM.println(); return; } // version is an exit option, print version and exit if (cmd.hasOption('v') || cmd.hasOption("version")) { - System.out.println(APP_NAME + " " + cli.getAppVersion()); - System.out.println(); + OUT_STREAM.println(APP_NAME + " " + cli.getAppVersion()); + OUT_STREAM.println(); return; } + generateJsonEventScheam(cmd); + } + + /** + * Generate the JSON event schema. + * + * @param cmd the command to run + */ + private static void generateJsonEventScheam(final CommandLine cmd) { String modelFile = cmd.getOptionValue('m'); if (modelFile == null) { modelFile = cmd.getOptionValue("model"); } if (modelFile == null) { - System.err.println(APP_NAME + ": no model file given, cannot proceed (try -h for help)"); + ERR_STREAM.println(APP_NAME + ": no model file given, cannot proceed (try -h for help)"); return; } @@ -90,27 +106,27 @@ public final class Application { type = cmd.getOptionValue("type"); } if (type == null) { - System.err.println(APP_NAME + ": no event type given, cannot proceed (try -h for help)"); + ERR_STREAM.println(APP_NAME + ": no event type given, cannot proceed (try -h for help)"); return; } - if (!type.equals("stimuli") && !type.equals("response") && !type.equals("internal")) { - System.err.println(APP_NAME + ": unknown type <" + type + ">, cannot proceed (try -h for help)"); + if (!"stimuli".equals(type) && !"response".equals(type) && !"internal".equals(type)) { + ERR_STREAM.println(APP_NAME + ": unknown type <" + type + ">, cannot proceed (try -h for help)"); return; } - System.out.println(); - System.out.println(APP_NAME + ": starting Event generator"); - System.out.println(" --> model file: " + modelFile); - System.out.println(" --> type: " + type); - System.out.println(); - System.out.println(); + OUT_STREAM.println(); + OUT_STREAM.println(APP_NAME + ": starting Event generator"); + OUT_STREAM.println(" --> model file: " + modelFile); + OUT_STREAM.println(" --> type: " + type); + OUT_STREAM.println(); + OUT_STREAM.println(); try { final Model2JsonEventSchema app = new Model2JsonEventSchema(modelFile, type, APP_NAME); app.runApp(); } catch (final ApexException aex) { String message = APP_NAME + ": caught APEX exception with message: " + aex.getMessage(); - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, aex); } } diff --git a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java index 6acbbbc02..cfd7cb357 100644 --- a/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java +++ b/tools/model-generator/src/main/java/org/onap/policy/apex/tools/model/generator/model2event/Model2JsonEventSchema.java @@ -82,6 +82,7 @@ public class Model2JsonEventSchema { Validate.notNull(modelFile, "Model2JsonEvent: given model file name was blank"); Validate.notNull(type, "Model2JsonEvent: given type was blank"); Validate.notNull(appName, "Model2JsonEvent: given application name was blank"); + this.modelFile = modelFile; this.type = type; this.appName = appName; @@ -124,13 +125,7 @@ public class Model2JsonEventSchema { break; case RECORD: - ret = stg.getInstanceOf("fieldTypeRecord"); - for (final Field field : schema.getFields()) { - final ST st = stg.getInstanceOf("field"); - st.add("name", field.name()); - st.add("type", this.addFieldType(field.schema(), stg)); - ret.add("fields", st); - } + ret = processRecord(schema, stg); break; case NULL: @@ -143,12 +138,30 @@ public class Model2JsonEventSchema { return ret; } + /** + * Process a record entry. + * @param schema the schema to add a type for + * @param stg the STG + * @return a template with the type + */ + private ST processRecord(final Schema schema, final STGroup stg) { + ST ret; + ret = stg.getInstanceOf("fieldTypeRecord"); + for (final Field field : schema.getFields()) { + final ST st = stg.getInstanceOf("field"); + st.add("name", field.name()); + st.add("type", this.addFieldType(field.schema(), stg)); + ret.add("fields", st); + } + return ret; + } + /** * Runs the application. * * - * @return status of the application execution, 0 for success, positive integer for exit - * condition (such as help or version), negative integer for errors + * @return status of the application execution, 0 for success, positive integer for exit condition (such as help or + * version), negative integer for errors * @throws ApexException if any problem occurred in the model */ public int runApp() throws ApexException { @@ -174,41 +187,13 @@ public class Model2JsonEventSchema { final AxPolicies policies = policyModel.getPolicies(); switch (type) { case "stimuli": - for (final AxPolicy policy : policies.getPolicyMap().values()) { - final String firsState = policy.getFirstState(); - for (final AxState state : policy.getStateMap().values()) { - if (state.getKey().getLocalName().equals(firsState)) { - eventKeys.add(state.getTrigger()); - } - } - } + processStimuli(eventKeys, policies); break; case "response": - for (final AxPolicy policy : policies.getPolicyMap().values()) { - for (final AxState state : policy.getStateMap().values()) { - if (state.getNextStateSet().iterator().next().equals("NULL")) { - for (final AxStateOutput output : state.getStateOutputs().values()) { - eventKeys.add(output.getOutgingEvent()); - } - } - } - } + processResponse(eventKeys, policies); break; case "internal": - for (final AxPolicy policy : policies.getPolicyMap().values()) { - final String firsState = policy.getFirstState(); - for (final AxState state : policy.getStateMap().values()) { - if (state.getKey().getLocalName().equals(firsState)) { - continue; - } - if (state.getNextStateSet().iterator().next().equals("NULL")) { - continue; - } - for (final AxStateOutput output : state.getStateOutputs().values()) { - eventKeys.add(output.getOutgingEvent()); - } - } - } + processInternal(eventKeys, policies); break; default: LOGGER.error("{}: unknown type <{}>, cannot proceed", appName, type); @@ -252,6 +237,79 @@ public class Model2JsonEventSchema { return 0; } + /** + * Process the "stimuli" keyword. + * @param eventKeys the event keys + * @param policies the policies to process + */ + private void processStimuli(final Set eventKeys, final AxPolicies policies) { + for (final AxPolicy policy : policies.getPolicyMap().values()) { + final String firsState = policy.getFirstState(); + for (final AxState state : policy.getStateMap().values()) { + if (state.getKey().getLocalName().equals(firsState)) { + eventKeys.add(state.getTrigger()); + } + } + } + } + + /** + * Process the "response" keyword. + * @param eventKeys the event keys + * @param policies the policies to process + */ + private void processResponse(final Set eventKeys, final AxPolicies policies) { + for (final AxPolicy policy : policies.getPolicyMap().values()) { + processState(eventKeys, policy); + } + } + + /** + * Process the state in the response. + * @param eventKeys the event keys + * @param policies the policies to process + */ + private void processState(final Set eventKeys, final AxPolicy policy) { + for (final AxState state : policy.getStateMap().values()) { + if ("NULL".equals(state.getNextStateSet().iterator().next())) { + for (final AxStateOutput output : state.getStateOutputs().values()) { + eventKeys.add(output.getOutgingEvent()); + } + } + } + } + + /** + * Process the "internal" keyword. + * @param eventKeys the event keys + * @param policies the policies to process + */ + private void processInternal(final Set eventKeys, final AxPolicies policies) { + for (final AxPolicy policy : policies.getPolicyMap().values()) { + final String firsState = policy.getFirstState(); + for (final AxState state : policy.getStateMap().values()) { + processInternalState(eventKeys, firsState, state); + } + } + } + + /** + * Process the internal state. + * @param eventKeys the event keys + * @param policies the policies to process + */ + private void processInternalState(final Set eventKeys, final String firsState, final AxState state) { + if (state.getKey().getLocalName().equals(firsState)) { + return; + } + if ("NULL".equals(state.getNextStateSet().iterator().next())) { + return; + } + for (final AxStateOutput output : state.getStateOutputs().values()) { + eventKeys.add(output.getOutgingEvent()); + } + } + /** * Adds a field to the output. * diff --git a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/Application.java b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/Application.java index 7c7d7e9c6..e0b819f60 100644 --- a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/Application.java +++ b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/Application.java @@ -21,6 +21,7 @@ package org.onap.policy.apex.tools.simple.wsclient; import java.io.IOException; +import java.io.PrintStream; import java.net.URISyntaxException; import java.nio.channels.NotYetConnectedException; @@ -41,10 +42,16 @@ public final class Application { // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); + // Input and output streams + private static final PrintStream OUT_STREAM = System.out; + private static final PrintStream ERR_STREAM = System.err; + /** * Private constructor prevents subclassing. */ - private Application() {} + private Application() { + // Prevent subclassing + } /** * The main method for the WS applications. @@ -74,19 +81,29 @@ public final class Application { // help is an exit option, print usage and exit if (cmd.hasOption('h') || cmd.hasOption("help")) { final HelpFormatter formatter = new HelpFormatter(); - System.out.println(appName + " v" + cli.getAppVersion() + " - " + appDescr); + OUT_STREAM.println(appName + " v" + cli.getAppVersion() + " - " + appDescr); formatter.printHelp(appName, cli.getOptions()); - System.out.println(); + OUT_STREAM.println(); return; } // version is an exit option, print version and exit if (cmd.hasOption('v') || cmd.hasOption("version")) { - System.out.println(appName + " " + cli.getAppVersion()); - System.out.println(); + OUT_STREAM.println(appName + " " + cli.getAppVersion()); + OUT_STREAM.println(); return; } + runConsoleOrEcho(appName, console, cmd); + } + + /** + * 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 + */ + private static void runConsoleOrEcho(String appName, boolean console, final CommandLine cmd) { String server = cmd.getOptionValue('s'); if (server == null) { server = cmd.getOptionValue("server"); @@ -108,7 +125,6 @@ public final class Application { } else { runEcho(server, port, appName); } - } /** @@ -123,30 +139,30 @@ public final class Application { Validate.notBlank(port); Validate.notBlank(appName); - System.out.println(); - System.out.println(appName + ": starting simple event echo"); - System.out.println(" --> server: " + server); - System.out.println(" --> port: " + port); - System.out.println(); - System.out.println("Once started, the application will simply print out all received events to standard out."); - System.out.println("Each received event will be prefixed by '---' and suffixed by '===='"); - System.out.println(); - System.out.println(); + OUT_STREAM.println(); + OUT_STREAM.println(appName + ": starting simple event echo"); + OUT_STREAM.println(" --> server: " + server); + OUT_STREAM.println(" --> port: " + port); + OUT_STREAM.println(); + OUT_STREAM.println("Once started, the application will simply print out all received events to standard out."); + OUT_STREAM.println("Each received event will be prefixed by '---' and suffixed by '===='"); + OUT_STREAM.println(); + OUT_STREAM.println(); try { - final SimpleEcho simpleEcho = new SimpleEcho(server, port, appName); + final SimpleEcho simpleEcho = new SimpleEcho(server, port, appName, OUT_STREAM, ERR_STREAM); simpleEcho.connect(); } catch (final URISyntaxException uex) { String message = appName + ": URI exception, could not create URI from server and port settings"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, uex); } catch (final NullPointerException nex) { String message = appName + ": null pointer, server or port were null"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, nex); } catch (final IllegalArgumentException iex) { String message = appName + ": illegal argument, server or port were blank"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, iex); } } @@ -163,38 +179,38 @@ public final class Application { Validate.notBlank(port); Validate.notBlank(appName); - System.out.println(); - System.out.println(appName + ": starting simple event console"); - System.out.println(" --> server: " + server); - System.out.println(" --> port: " + port); - System.out.println(); - System.out.println(" - terminate the application typing 'exit' or using 'CTRL+C'"); - System.out.println(" - events are created by a non-blank starting line and terminated by a blank line"); - System.out.println(); - System.out.println(); + OUT_STREAM.println(); + OUT_STREAM.println(appName + ": starting simple event console"); + OUT_STREAM.println(" --> server: " + server); + OUT_STREAM.println(" --> port: " + port); + OUT_STREAM.println(); + OUT_STREAM.println(" - terminate the application typing 'exit' or using 'CTRL+C'"); + OUT_STREAM.println(" - events are created by a non-blank starting line and terminated by a blank line"); + OUT_STREAM.println(); + OUT_STREAM.println(); try { - final SimpleConsole simpleConsole = new SimpleConsole(server, port, appName); + final SimpleConsole simpleConsole = new SimpleConsole(server, port, appName, OUT_STREAM, ERR_STREAM); simpleConsole.runClient(); } catch (final URISyntaxException uex) { String message = appName + ": URI exception, could not create URI from server and port settings"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, uex); } catch (final NullPointerException nex) { String message = appName + ": null pointer, server or port were null"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, nex); } catch (final IllegalArgumentException iex) { String message = appName + ": illegal argument, server or port were blank"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, iex); } catch (final NotYetConnectedException nex) { String message = appName + ": not yet connected, connection to server took too long"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, nex); } catch (final IOException ioe) { String message = appName + ": IO exception, something went wrong on the standard input"; - System.err.println(message); + ERR_STREAM.println(message); LOGGER.warn(message, ioe); } } diff --git a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java index bb38a37a0..28c494207 100644 --- a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java +++ b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleConsole.java @@ -23,6 +23,7 @@ package org.onap.policy.apex.tools.simple.wsclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.NotYetConnectedException; @@ -41,6 +42,10 @@ public class SimpleConsole extends WebSocketClient { /** Application name, used as prompt. */ private final String appName; + + // Output and error streams + private PrintStream outStream; + private PrintStream errStream; /** * Creates a new simple echo object. @@ -48,51 +53,57 @@ public class SimpleConsole extends WebSocketClient { * @param server the name of the server as either IP address or fully qualified host name, must not be blank * @param port the port to be used, must not be blank * @param appName the application name, used as prompt, must not be blank + * @param outStream the stream for message output + * @param errStream the stream for error messages * @throws URISyntaxException is URI could not be created from server/port settings * @throws RuntimeException if server or port where blank */ - public SimpleConsole(final String server, final String port, final String appName) throws URISyntaxException { + public SimpleConsole(final String server, final String port, final String appName, PrintStream outStream, + PrintStream errStream) throws URISyntaxException { super(new URI("ws://" + server + ":" + port)); Validate.notBlank(appName, "SimpleConsole: given application name was blank"); + this.appName = appName; + this.outStream = outStream; + this.errStream = errStream; } @Override public void onClose(final int code, final String reason, final boolean remote) { - System.out.println(this.appName + ": Connection closed by " + (remote ? "APEX" : "me")); - System.out.print(" ==-->> "); + outStream.println(this.appName + ": Connection closed by " + (remote ? "APEX" : "me")); + outStream.print(" ==-->> "); switch (code) { case CloseFrame.NORMAL: - System.out.println("normal"); + outStream.println("normal"); break; case CloseFrame.GOING_AWAY: - System.out.println("APEX going away"); + outStream.println("APEX going away"); break; case CloseFrame.PROTOCOL_ERROR: - System.out.println("some protocol error"); + outStream.println("some protocol error"); break; case CloseFrame.REFUSE: - System.out.println("received unacceptable type of data"); + outStream.println("received unacceptable type of data"); break; case CloseFrame.NO_UTF8: - System.out.println("expected UTF-8, found something else"); + outStream.println("expected UTF-8, found something else"); break; case CloseFrame.TOOBIG: - System.out.println("message too big"); + outStream.println("message too big"); break; case CloseFrame.UNEXPECTED_CONDITION: - System.out.println("unexpected server condition"); + outStream.println("unexpected server condition"); break; default: - System.out.println("unkown close frame code"); + outStream.println("unkown close frame code"); break; } - System.out.print(" ==-->> " + reason); + outStream.print(" ==-->> " + reason); } @Override public void onError(final Exception ex) { - System.err.println(this.appName + ": " + ex.getMessage()); + errStream.println(this.appName + ": " + ex.getMessage()); } @Override @@ -102,7 +113,7 @@ public class SimpleConsole extends WebSocketClient { @Override public void onOpen(final ServerHandshake handshakedata) { - System.out.println(this.appName + ": opened connection to APEX (" + handshakedata.getHttpStatusMessage() + ")"); + outStream.println(this.appName + ": opened connection to APEX (" + handshakedata.getHttpStatusMessage() + ")"); } /** @@ -125,7 +136,7 @@ public class SimpleConsole extends WebSocketClient { String event = ""; String line; while ((line = in.readLine()) != null) { - if (line.equals("exit")) { + if ("exit".equals(line)) { break; } diff --git a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleEcho.java b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleEcho.java index 4b67cb862..659dd77eb 100644 --- a/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleEcho.java +++ b/tools/simple-wsclient/src/main/java/org/onap/policy/apex/tools/simple/wsclient/SimpleEcho.java @@ -20,6 +20,7 @@ package org.onap.policy.apex.tools.simple.wsclient; +import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; @@ -38,71 +39,81 @@ public class SimpleEcho extends WebSocketClient { /** Application name, used as prompt. */ private final String appName; + // Output and error streams + private PrintStream outStream; + private PrintStream errStream; + /** * Creates a new simple echo object. * * @param server the name of the server as either IP address or fully qualified host name, must not be blank * @param port the port to be used, must not be blank * @param appName the application name, used as prompt, must not be blank + * @param outStream the stream for message output + * @param errStream the stream for error messages * @throws URISyntaxException is URI could not be created from server/port settings * @throws RuntimeException if server or port where blank */ - public SimpleEcho(final String server, final String port, final String appName) throws URISyntaxException { + public SimpleEcho(final String server, final String port, final String appName, PrintStream outStream, + PrintStream errStream) throws URISyntaxException { super(new URI("ws://" + server + ":" + port)); Validate.notBlank(appName, "SimpleEcho: given application name was blank"); + this.appName = appName; + this.outStream = outStream; + this.errStream = errStream; } @Override public void onClose(final int code, final String reason, final boolean remote) { - System.out.println(this.appName + ": Connection closed by " + (remote ? "APEX" : "me")); - System.out.print(" ==-->> "); + outStream.println(this.appName + ": Connection closed by " + (remote ? "APEX" : "me")); + outStream.print(" ==-->> "); switch (code) { case CloseFrame.NORMAL: - System.out.println("normal"); + outStream.println("normal"); break; case CloseFrame.GOING_AWAY: - System.out.println("APEX going away"); + outStream.println("APEX going away"); break; case CloseFrame.PROTOCOL_ERROR: - System.out.println("some protocol error"); + outStream.println("some protocol error"); break; case CloseFrame.REFUSE: - System.out.println("received unacceptable type of data"); + outStream.println("received unacceptable type of data"); break; case CloseFrame.NO_UTF8: - System.out.println("expected UTF-8, found something else"); + outStream.println("expected UTF-8, found something else"); break; case CloseFrame.TOOBIG: - System.out.println("message too big"); + outStream.println("message too big"); break; case CloseFrame.UNEXPECTED_CONDITION: - System.out.println("unexpected server condition"); + outStream.println("unexpected server condition"); break; default: - System.out.println("unkown close frame code"); + outStream.println("unkown close frame code"); break; } - System.out.print(" ==-->> " + reason); + outStream.print(" ==-->> " + reason); } @Override public void onError(final Exception ex) { - System.err.println(this.appName + ": " + ex.getMessage()); + errStream.println(this.appName + ": " + ex.getMessage()); } @Override public void onMessage(final String message) { - System.out.println(this.appName + ": received"); - System.out.println("---------------------------------"); - System.out.println(message); - System.out.println("================================="); - System.out.println(); + outStream.println(this.appName + ": received"); + outStream.println("---------------------------------"); + outStream.println(message); + outStream.println("================================="); + outStream.println(); } @Override public void onOpen(final ServerHandshake handshakedata) { - System.out.println(this.appName + ": opened connection to APEX (" + handshakedata.getHttpStatusMessage() + ")"); + outStream.println(this.appName + ": opened connection to APEX (" + handshakedata.getHttpStatusMessage() + ")"); } } diff --git a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/Console.java b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/Console.java index 267584952..1b4ef06c4 100644 --- a/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/Console.java +++ b/tools/tools-common/src/main/java/org/onap/policy/apex/tools/common/Console.java @@ -20,6 +20,7 @@ package org.onap.policy.apex.tools.common; +import java.io.PrintStream; import java.util.ArrayList; import java.util.List; @@ -72,6 +73,9 @@ public final class Console { /** Configuration for a collecting warning messages. */ public static final int CONFIG_COLLECT_WARNINGS = 0b0010; + // Input and output streams + private static final PrintStream ERR_STREAM = System.err; + /** The setting for message types, set using type flags. */ private int types; @@ -193,7 +197,7 @@ public final class Console { err.append(MessageFormatter.arrayFormat(message, objects).getMessage()); if ((types & TYPE_ERROR) == TYPE_ERROR) { - System.err.println(err.build()); + ERR_STREAM.println(err.build()); } if ((configuration & CONFIG_COLLECT_ERRORS) == CONFIG_COLLECT_ERRORS) { errors.add(err.build()); @@ -222,7 +226,7 @@ public final class Console { warn.append(MessageFormatter.arrayFormat(message, objects).getMessage()); if ((types & TYPE_WARNING) == TYPE_WARNING) { - System.err.println(warn.build()); + ERR_STREAM.println(warn.build()); } if ((configuration & CONFIG_COLLECT_WARNINGS) == CONFIG_COLLECT_WARNINGS) { warnings.add(warn.build()); @@ -243,9 +247,9 @@ public final class Console { if ((types & TYPE_INFO) == TYPE_INFO) { if (appName != null) { - System.err.print(appName + ": "); + ERR_STREAM.print(appName + ": "); } - System.err.println(MessageFormatter.arrayFormat(message, objects).getMessage()); + ERR_STREAM.println(MessageFormatter.arrayFormat(message, objects).getMessage()); } } @@ -263,10 +267,10 @@ public final class Console { if ((types & TYPE_PROGRESS) == TYPE_PROGRESS) { if (appName != null) { - System.err.print(appName + ": "); + ERR_STREAM.print(appName + ": "); } - System.err.print("progress: "); - System.err.println(MessageFormatter.arrayFormat(message, objects).getMessage()); + ERR_STREAM.print("progress: "); + ERR_STREAM.println(MessageFormatter.arrayFormat(message, objects).getMessage()); } } @@ -284,10 +288,10 @@ public final class Console { if ((types & TYPE_DEBUG) == TYPE_DEBUG) { if (appName != null) { - System.err.print(appName + ": "); + ERR_STREAM.print(appName + ": "); } - System.err.print("debug: "); - System.err.println(MessageFormatter.arrayFormat(message, objects).getMessage()); + ERR_STREAM.print("debug: "); + ERR_STREAM.println(MessageFormatter.arrayFormat(message, objects).getMessage()); } } @@ -305,10 +309,10 @@ public final class Console { if ((types & TYPE_TRACE) == TYPE_TRACE) { if (appName != null) { - System.err.print(appName + ": "); + ERR_STREAM.print(appName + ": "); } - System.err.print("trace: "); - System.err.println(MessageFormatter.arrayFormat(message, objects).getMessage()); + ERR_STREAM.print("trace: "); + ERR_STREAM.println(MessageFormatter.arrayFormat(message, objects).getMessage()); } } @@ -324,13 +328,13 @@ public final class Console { if ((types & TYPE_STACKTRACE) == TYPE_STACKTRACE) { if (appName != null) { - System.err.print(appName + ": "); + ERR_STREAM.print(appName + ": "); } - System.err.println(" exception message: " + exception.getMessage()); + ERR_STREAM.println(" exception message: " + exception.getMessage()); if (exception.getCause() != null) { - System.err.println(" exception cause: " + exception.getCause()); + ERR_STREAM.println(" exception cause: " + exception.getCause()); } - System.err.println("for exception stack trace, please refer logs."); + ERR_STREAM.println("for exception stack trace, please refer logs."); XLoggerFactory.getXLogger(Console.class).error("stacktrace", exception); } } -- cgit 1.2.3-korg