diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLICompleter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLICompleter.java index dad5416588..7889b306f5 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLICompleter.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLICompleter.java @@ -20,7 +20,7 @@ import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.session.SessionCommandGroup; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; import org.jline.builtins.Completers; import org.jline.reader.Candidate; import org.jline.reader.Completer; @@ -50,14 +50,16 @@ public class CLICompleter implements Completer { args.add("-" + CommandOption.PROPERTIES.getShortName()); args.add("-" + CommandOption.INPUT_SOURCE.getShortName()); args.add("-" + CommandOption.OUTPUT_FILE.getShortName()); + args.add("-" + CommandOption.NIFI_REG_PROPS.getShortName()); + args.add("-" + CommandOption.NIFI_PROPS.getShortName()); FILE_COMPLETION_ARGS = Collections.unmodifiableSet(args); } private static final Set FILE_COMPLETION_VARS; static { final Set vars = new HashSet<>(); - vars.add(SessionVariables.NIFI_CLIENT_PROPS.getVariableName()); - vars.add(SessionVariables.NIFI_REGISTRY_CLIENT_PROPS.getVariableName()); + vars.add(SessionVariable.NIFI_CLIENT_PROPS.getVariableName()); + vars.add(SessionVariable.NIFI_REGISTRY_CLIENT_PROPS.getVariableName()); FILE_COMPLETION_VARS = Collections.unmodifiableSet(vars); } @@ -178,7 +180,7 @@ public class CLICompleter implements Completer { // if we have two args then we are completing the variable name // if we have three args, and the third is one a variable that is a file path, then we need a file completer if (line.wordIndex() == 2) { - addCandidates(SessionVariables.getAllVariableNames(), candidates); + addCandidates(SessionVariable.getAllVariableNames(), candidates); } else if (line.wordIndex() == 3) { final String currWord = line.word(); final String prevWord = line.words().get(line.wordIndex() - 1); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLIMain.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLIMain.java index 95da2fc2be..643fe0336f 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLIMain.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/CLIMain.java @@ -23,7 +23,6 @@ import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultType; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.impl.client.NiFiClientFactory; import org.apache.nifi.toolkit.cli.impl.client.NiFiRegistryClientFactory; @@ -31,8 +30,6 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.command.CommandFactory; import org.apache.nifi.toolkit.cli.impl.command.CommandProcessor; import org.apache.nifi.toolkit.cli.impl.context.StandardContext; -import org.apache.nifi.toolkit.cli.impl.result.JsonResultWriter; -import org.apache.nifi.toolkit.cli.impl.result.SimpleResultWriter; import org.apache.nifi.toolkit.cli.impl.session.InMemorySession; import org.apache.nifi.toolkit.cli.impl.session.PersistentSession; import org.jline.reader.Completer; @@ -195,8 +192,6 @@ public class CLIMain { .nifiClientFactory(niFiClientFactory) .nifiRegistryClientFactory(nifiRegClientFactory) .interactive(isInteractive) - .resultWriter(ResultType.SIMPLE, new SimpleResultWriter()) - .resultWriter(ResultType.JSON, new JsonResultWriter()) .build(); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Command.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Command.java index 1a21a8bbc6..3dffcf7598 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Command.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Command.java @@ -22,7 +22,7 @@ import org.apache.commons.cli.Options; /** * Represents a command to execute. */ -public interface Command { +public interface Command { /** * Called directly after instantiation of the given command before any other method is called. @@ -57,7 +57,20 @@ public interface Command { * Executes the command with the given CLI params. * * @param cli the parsed CLI for the command + * @return the Result of the command */ - void execute(CommandLine cli) throws CommandException; + R execute(CommandLine cli) throws CommandException; + + /** + * @return the implementation class of the result + */ + Class getResultImplType(); + + /** + * @return true if the type of result produced is considered Referenceable + */ + default boolean isReferencable() { + return Referenceable.class.isAssignableFrom(getResultImplType()); + } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Context.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Context.java index 14b518617e..3053f787f7 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Context.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Context.java @@ -36,6 +36,4 @@ public interface Context { boolean isInteractive(); - ResultWriter getResultWriter(ResultType resultType); - } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ReferenceResolver.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ReferenceResolver.java new file mode 100644 index 0000000000..de0feb8548 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ReferenceResolver.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.api; + +/** + * An object that is capable of resolving a positional reference to some value that corresponds with the reference. + */ +public interface ReferenceResolver { + + /** + * Resolves the passed in positional reference to it's corresponding value. + * + * @param position a position in this back reference + * @return the resolved value for the given position + */ + String resolve(Integer position); + + /** + * @return true if the there are no references to resolve, false otherwise + */ + boolean isEmpty(); + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Referenceable.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Referenceable.java new file mode 100644 index 0000000000..af44152f0c --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Referenceable.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.api; + +/** + * An object that is capable of producing a ReferenceResolver. + */ +public interface Referenceable { + + /** + * @return a ReferenceResolver for this Referenceable + */ + ReferenceResolver createReferenceResolver(Context context); + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Result.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Result.java new file mode 100644 index 0000000000..751f9d3b7f --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/Result.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.api; + +/** + * A result returned from a command. + * + * @param the type of result + */ +public interface Result { + + /** + * @return the result of a command + */ + T getResult(); + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ResultWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ResultWriter.java deleted file mode 100644 index b7b07419da..0000000000 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/ResultWriter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package org.apache.nifi.toolkit.cli.api; - -import org.apache.nifi.registry.authorization.CurrentUser; -import org.apache.nifi.registry.bucket.Bucket; -import org.apache.nifi.registry.flow.VersionedFlow; -import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; -import org.apache.nifi.web.api.entity.CurrentUserEntity; -import org.apache.nifi.web.api.entity.ProcessGroupEntity; -import org.apache.nifi.web.api.entity.RegistryClientsEntity; -import org.apache.nifi.web.api.entity.VariableRegistryEntity; -import org.apache.nifi.web.api.entity.VersionControlInformationEntity; -import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataSetEntity; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; - -/** - * Responsible for writing entities to the given stream. - */ -public interface ResultWriter { - - void writeBuckets(List buckets, PrintStream output) throws IOException; - - void writeBucket(Bucket bucket, PrintStream output) throws IOException; - - void writeFlows(List versionedFlows, PrintStream output) throws IOException; - - void writeFlow(VersionedFlow versionedFlow, PrintStream output) throws IOException; - - void writeSnapshotMetadata(List versions, PrintStream output) throws IOException; - - void writeSnapshotMetadata(VersionedFlowSnapshotMetadata version, PrintStream output) throws IOException; - - void writeRegistryClients(RegistryClientsEntity clientsEntity, PrintStream output) throws IOException; - - void writeVariables(VariableRegistryEntity variableRegistryEntity, PrintStream output) throws IOException; - - void writeSnapshotMetadata(VersionedFlowSnapshotMetadataSetEntity versionedFlowSnapshotMetadataSetEntity, PrintStream output) throws IOException; - - void writeVersionControlInfo(VersionControlInformationEntity versionControlInformationEntity, PrintStream output) throws IOException; - - void writeProcessGroups(List processGroupEntities, PrintStream output) throws IOException; - - void writeCurrentUser(CurrentUserEntity currentUserEntity, PrintStream output) throws IOException; - - void writeCurrentUser(CurrentUser currentUser, PrintStream output) throws IOException; - -} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/WritableResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/WritableResult.java new file mode 100644 index 0000000000..c827447eaf --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/api/WritableResult.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.api; + +import java.io.IOException; +import java.io.PrintStream; + +/** + * A result that can be written to a PrintStream. + * + * @param the type of result + */ +public interface WritableResult extends Result { + + /** + * Writes this result to the given output stream. + * + * @param output the output stream + * @throws IOException if an error occurs writing the result + */ + void write(PrintStream output) throws IOException; +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiRegistryClientFactory.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiRegistryClientFactory.java index cb12edf806..a8d1608329 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiRegistryClientFactory.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/client/NiFiRegistryClientFactory.java @@ -97,7 +97,6 @@ public class NiFiRegistryClientFactory implements ClientFactory implements Command { private final String name; + private final Class resultClass; private final Options options; private Context context; private PrintStream output; - public AbstractCommand(final String name) { + public AbstractCommand(final String name, final Class resultClass) { this.name = name; + this.resultClass = resultClass; Validate.notNull(this.name); + Validate.notNull(this.resultClass); - this.options = new Options(); + this.options = createBaseOptions(); + Validate.notNull(this.options); + } - this.options.addOption(CommandOption.URL.createOption()); - this.options.addOption(CommandOption.PROPERTIES.createOption()); + protected Options createBaseOptions() { + final Options options = new Options(); - this.options.addOption(CommandOption.KEYSTORE.createOption()); - this.options.addOption(CommandOption.KEYSTORE_TYPE.createOption()); - this.options.addOption(CommandOption.KEYSTORE_PASSWORD.createOption()); - this.options.addOption(CommandOption.KEY_PASSWORD.createOption()); + options.addOption(CommandOption.URL.createOption()); + options.addOption(CommandOption.PROPERTIES.createOption()); - this.options.addOption(CommandOption.TRUSTSTORE.createOption()); - this.options.addOption(CommandOption.TRUSTSTORE_TYPE.createOption()); - this.options.addOption(CommandOption.TRUSTSTORE_PASSWORD.createOption()); + options.addOption(CommandOption.KEYSTORE.createOption()); + options.addOption(CommandOption.KEYSTORE_TYPE.createOption()); + options.addOption(CommandOption.KEYSTORE_PASSWORD.createOption()); + options.addOption(CommandOption.KEY_PASSWORD.createOption()); - this.options.addOption(CommandOption.PROXIED_ENTITY.createOption()); + options.addOption(CommandOption.TRUSTSTORE.createOption()); + options.addOption(CommandOption.TRUSTSTORE_TYPE.createOption()); + options.addOption(CommandOption.TRUSTSTORE_PASSWORD.createOption()); - this.options.addOption(CommandOption.OUTPUT_TYPE.createOption()); - this.options.addOption(CommandOption.VERBOSE.createOption()); - this.options.addOption(CommandOption.HELP.createOption()); + options.addOption(CommandOption.PROXIED_ENTITY.createOption()); + + options.addOption(CommandOption.OUTPUT_TYPE.createOption()); + options.addOption(CommandOption.VERBOSE.createOption()); + options.addOption(CommandOption.HELP.createOption()); + + return options; } @Override @@ -89,10 +99,15 @@ public abstract class AbstractCommand implements Command { } @Override - public String getName() { + public final String getName() { return name; } + @Override + public final Class getResultImplType() { + return resultClass; + } + @Override public Options getOptions() { return options; @@ -116,6 +131,11 @@ public abstract class AbstractCommand implements Command { hf.printWrapped(printWriter, width, getDescription()); hf.printWrapped(printWriter, width, ""); + if (isReferencable()) { + hf.printWrapped(printWriter, width, "PRODUCES BACK-REFERENCES"); + hf.printWrapped(printWriter, width, ""); + } + hf.printHelp(printWriter, hf.getWidth(), getName(), null, getOptions(), hf.getLeftPadding(), hf.getDescPadding(), null, false); @@ -136,11 +156,6 @@ public abstract class AbstractCommand implements Command { output.println(); } - protected ResultWriter getResultWriter(final Properties properties) { - final ResultType resultType = getResultType(properties); - return context.getResultWriter(resultType); - } - protected ResultType getResultType(final Properties properties) { final ResultType resultType; if (properties.containsKey(CommandOption.OUTPUT_TYPE.getLongName())) { diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractCommandGroup.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractCommandGroup.java index 531c025d80..40a95dadf4 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractCommandGroup.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractCommandGroup.java @@ -81,6 +81,11 @@ public abstract class AbstractCommandGroup implements CommandGroup { hf.printWrapped(printWriter, width, ""); hf.printWrapped(printWriter, width, "- " + c.getDescription()); hf.printWrapped(printWriter, width, ""); + + if (c.isReferencable()) { + hf.printWrapped(printWriter, width, "PRODUCES BACK-REFERENCES"); + hf.printWrapped(printWriter, width, ""); + } }); printWriter.flush(); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractPropertyCommand.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractPropertyCommand.java index fb4dc7f1a6..fca901c4e9 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractPropertyCommand.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/AbstractPropertyCommand.java @@ -20,8 +20,9 @@ import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.toolkit.cli.api.CommandException; +import org.apache.nifi.toolkit.cli.api.Result; import org.apache.nifi.toolkit.cli.api.Session; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; import java.io.FileInputStream; import java.io.InputStream; @@ -30,14 +31,14 @@ import java.util.Properties; /** * Base class for commands that support loading properties from the session or an argument. */ -public abstract class AbstractPropertyCommand extends AbstractCommand { +public abstract class AbstractPropertyCommand extends AbstractCommand { - public AbstractPropertyCommand(String name) { - super(name); + public AbstractPropertyCommand(final String name, final Class resultClass) { + super(name, resultClass); } @Override - public void execute(final CommandLine commandLine) throws CommandException { + public final R execute(final CommandLine commandLine) throws CommandException { try { final Properties properties = new Properties(); @@ -51,7 +52,7 @@ public abstract class AbstractPropertyCommand extends AbstractCommand { } } else { // no properties file was specified so see if there is anything in the session - final SessionVariables sessionVariable = getPropertiesSessionVariable(); + final SessionVariable sessionVariable = getPropertiesSessionVariable(); if (sessionVariable != null) { final Session session = getContext().getSession(); final String sessionPropsFiles = session.get(sessionVariable.getVariableName()); @@ -70,7 +71,7 @@ public abstract class AbstractPropertyCommand extends AbstractCommand { } // delegate to sub-classes - doExecute(properties); + return doExecute(properties); } catch (CommandException ce) { throw ce; @@ -80,16 +81,17 @@ public abstract class AbstractPropertyCommand extends AbstractCommand { } /** - * @return the SessionVariables that specifies the properties file for this command, or null if not supported + * @return the SessionVariable that specifies the properties file for this command, or null if not supported */ - protected abstract SessionVariables getPropertiesSessionVariable(); + protected abstract SessionVariable getPropertiesSessionVariable(); /** * Sub-classes implement specific command logic. * * @param properties the properties which represent the arguments - * @throws CommandException if an error occurrs + * @return the Result of executing the command + * @throws CommandException if an error occurs */ - protected abstract void doExecute(final Properties properties) throws CommandException; + public abstract R doExecute(final Properties properties) throws CommandException; } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandFactory.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandFactory.java index aec0ae46bf..c3dd7917fc 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandFactory.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandFactory.java @@ -19,6 +19,7 @@ package org.apache.nifi.toolkit.cli.impl.command; import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.impl.command.composite.DemoCommandGroup; import org.apache.nifi.toolkit.cli.impl.command.misc.Exit; import org.apache.nifi.toolkit.cli.impl.command.misc.Help; import org.apache.nifi.toolkit.cli.impl.command.nifi.NiFiCommandGroup; @@ -55,6 +56,7 @@ public class CommandFactory { final List groups = new ArrayList<>(); groups.add(new NiFiRegistryCommandGroup()); groups.add(new NiFiCommandGroup()); + groups.add(new DemoCommandGroup()); groups.add(new SessionCommandGroup()); final Map groupMap = new TreeMap<>(); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java index cf325a1bf9..9990b22cab 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java @@ -30,6 +30,9 @@ public enum CommandOption { PROPERTIES("p", "properties", "A properties file to load arguments from, " + "command line values will override anything in the properties file, must contain full path to file", true), + NIFI_PROPS("nifiProps", "nifiProps", "A properties file to load for NiFi config", true), + NIFI_REG_PROPS("nifiRegProps", "nifiRegProps", "A properties file to load for NiFi Registry config", true), + // Registry - Buckets BUCKET_ID("b", "bucketIdentifier", "A bucket identifier", true), BUCKET_NAME("bn", "bucketName", "A bucket name", true), diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandProcessor.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandProcessor.java index 6cf31144d0..98fc5f89a2 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandProcessor.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandProcessor.java @@ -25,21 +25,30 @@ import org.apache.commons.lang3.Validate; import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.api.ReferenceResolver; +import org.apache.nifi.toolkit.cli.api.Referenceable; +import org.apache.nifi.toolkit.cli.api.Result; +import org.apache.nifi.toolkit.cli.api.WritableResult; import java.io.PrintStream; import java.util.Arrays; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * Takes the arguments from the shell and executes the appropriate command, or prints appropriate usage. */ public class CommandProcessor { + public static final String BACK_REF_INDICATOR = "&"; + private final Map topLevelCommands; private final Map commandGroups; private final Context context; private final PrintStream out; + private final AtomicReference backReferenceHolder = new AtomicReference<>(null); + public CommandProcessor(final Map topLevelCommands, final Map commandGroups, final Context context) { this.topLevelCommands = topLevelCommands; this.commandGroups = commandGroups; @@ -67,12 +76,17 @@ public class CommandProcessor { out.println(); commandGroups.entrySet().stream().forEach(e -> e.getValue().printUsage(verbose)); - out.println("-------------------------------------------------------------------------------"); + if (verbose) { + out.println("-------------------------------------------------------------------------------"); + } topLevelCommands.keySet().stream().forEach(k -> out.println("\t" + k)); out.println(); } - private CommandLine parseCli(Command command, String[] args) throws ParseException { + private CommandLine parseCli(final Command command, final String[] args) throws ParseException { + // resolve any back-references so the CommandLine ends up with the resolved values in the Options + resolveBackReferences(args); + final Options options = command.getOptions(); final CommandLineParser parser = new DefaultParser(); final CommandLine commandLine = parser.parse(options, args); @@ -85,6 +99,42 @@ public class CommandProcessor { return commandLine; } + /** + * Finds any args that indicate a back-reference and replaces the value of the arg with the + * resolved back-reference. + * + * If the reference does not resolve, or non-numeric position is given, then the arg is left unchanged. + * + * @param args the args to process + */ + private void resolveBackReferences(final String[] args) { + final ReferenceResolver referenceResolver = backReferenceHolder.get(); + if (referenceResolver == null) { + return; + } + + for (int i=0; i < args.length; i++) { + final String arg = args[i]; + if (arg == null || !arg.startsWith(BACK_REF_INDICATOR)) { + continue; + } + + if (context.isInteractive()) { + context.getOutput().println(); + } + + try { + final Integer pos = Integer.valueOf(arg.substring(1)); + final String resolvedReference = referenceResolver.resolve(pos); + if (resolvedReference != null) { + args[i] = resolvedReference; + } + } catch (Exception e) { + // skip + } + } + } + public void process(String[] args) { if (args == null || args.length == 0) { printBasicUsage(null); @@ -123,20 +173,7 @@ public class CommandProcessor { return; } - try { - if (otherArgs.length == 1 && CommandOption.HELP.getLongName().equalsIgnoreCase(otherArgs[0])) { - command.printUsage(null); - } else { - command.execute(commandLine); - } - } catch (Exception e) { - command.printUsage(e.getMessage()); - if (commandLine.hasOption(CommandOption.VERBOSE.getLongName())) { - out.println(); - e.printStackTrace(out); - out.println(); - } - } + processCommand(otherArgs, commandLine, command); } catch (Exception e) { out.println(); @@ -172,20 +209,7 @@ public class CommandProcessor { return; } - try { - if (otherArgs.length == 1 && CommandOption.HELP.getLongName().equalsIgnoreCase(otherArgs[0])) { - command.printUsage(null); - } else { - command.execute(commandLine); - } - } catch (Exception e) { - command.printUsage(e.getMessage()); - if (commandLine.hasOption(CommandOption.VERBOSE.getLongName())) { - out.println(); - e.printStackTrace(out); - out.println(); - } - } + processCommand(otherArgs, commandLine, command); } catch (Exception e) { out.println(); @@ -194,5 +218,39 @@ public class CommandProcessor { } } + private void processCommand(final String[] args, final CommandLine commandLine, final Command command) { + try { + if (args.length == 1 && CommandOption.HELP.getLongName().equalsIgnoreCase(args[0])) { + command.printUsage(null); + } else { + final Result result = command.execute(commandLine); + + if (result instanceof WritableResult) { + final WritableResult writableResult = (WritableResult) result; + writableResult.write(out); + } + + // if the Result is Referenceable then create the resolver and store it in the holder for the next command + if (result instanceof Referenceable) { + final Referenceable referenceable = (Referenceable) result; + final ReferenceResolver referenceResolver = referenceable.createReferenceResolver(context); + + // only set the resolve if its not empty so that a resolver that was already in there sticks around + // and can be used again if the current command didn't produce anything to resolve + if (!referenceResolver.isEmpty()) { + backReferenceHolder.set(referenceResolver); + } + } + } + } catch (Exception e) { + command.printUsage(e.getMessage()); + if (commandLine.hasOption(CommandOption.VERBOSE.getLongName())) { + out.println(); + e.printStackTrace(out); + out.println(); + } + } + } + } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/AbstractCompositeCommand.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/AbstractCompositeCommand.java new file mode 100644 index 0000000000..1c1e8dba03 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/AbstractCompositeCommand.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.command.composite; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.lang3.StringUtils; +import org.apache.nifi.registry.client.NiFiRegistryClient; +import org.apache.nifi.registry.client.NiFiRegistryException; +import org.apache.nifi.toolkit.cli.api.ClientFactory; +import org.apache.nifi.toolkit.cli.api.CommandException; +import org.apache.nifi.toolkit.cli.api.Result; +import org.apache.nifi.toolkit.cli.api.Session; +import org.apache.nifi.toolkit.cli.api.SessionException; +import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; +import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; +import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.command.CommandOption; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Base class for higher-level marco commands that interact with NiFi & Registry to perform a series of actions. + */ +public abstract class AbstractCompositeCommand extends AbstractCommand { + + public AbstractCompositeCommand(final String name, final Class resultClass) { + super(name, resultClass); + } + + @Override + protected final Options createBaseOptions() { + final Options options = new Options(); + options.addOption(CommandOption.NIFI_PROPS.createOption()); + options.addOption(CommandOption.NIFI_REG_PROPS.createOption()); + options.addOption(CommandOption.VERBOSE.createOption()); + return options; + } + + @Override + public final R execute(final CommandLine cli) throws CommandException { + try { + final Properties nifiProperties = createProperties(cli, CommandOption.NIFI_PROPS, SessionVariable.NIFI_CLIENT_PROPS); + if (nifiProperties == null) { + throw new CommandException("Unable to find NiFi config, must specify --" + + CommandOption.NIFI_PROPS.getLongName() + ", or setup session config"); + } + + final ClientFactory nifiClientFactory = getContext().getNiFiClientFactory(); + final NiFiClient nifiClient = nifiClientFactory.createClient(nifiProperties); + + final Properties registryProperties = createProperties(cli, CommandOption.NIFI_REG_PROPS, SessionVariable.NIFI_REGISTRY_CLIENT_PROPS); + if (registryProperties == null) { + throw new CommandException("Unable to find NiFi Registry config, must specify --" + + CommandOption.NIFI_REG_PROPS.getLongName() + ", or setup session config"); + } + + final ClientFactory registryClientFactory = getContext().getNiFiRegistryClientFactory(); + final NiFiRegistryClient registryClient = registryClientFactory.createClient(registryProperties); + + return doExecute(cli, nifiClient, nifiProperties, registryClient, registryProperties); + } catch (CommandException ce) { + throw ce; + } catch (Exception e) { + throw new CommandException("Error executing command '" + getName() + "' : " + e.getMessage(), e); + } + } + + /** + * Creates a Properties instance by looking at the propertOption and falling back to the session. + * + * @param commandLine the current command line + * @param propertyOption the options specifying a properties to load + * @param sessionVariable the session variable specifying a properties file + * @return a Properties instance or null if the option wasn't specified and nothing is in the session + */ + private Properties createProperties(final CommandLine commandLine, final CommandOption propertyOption, final SessionVariable sessionVariable) + throws IOException, SessionException { + + // use the properties file specified by the properyOption if it exists + if (commandLine.hasOption(propertyOption.getLongName())) { + final String propertiesFile = commandLine.getOptionValue(propertyOption.getLongName()); + if (!StringUtils.isBlank(propertiesFile)) { + try (final InputStream in = new FileInputStream(propertiesFile)) { + final Properties properties = new Properties(); + properties.load(in); + return properties; + } + } + } else { + // no properties file was specified so see if there is anything in the session + if (sessionVariable != null) { + final Session session = getContext().getSession(); + final String sessionPropsFiles = session.get(sessionVariable.getVariableName()); + if (!StringUtils.isBlank(sessionPropsFiles)) { + try (final InputStream in = new FileInputStream(sessionPropsFiles)) { + final Properties properties = new Properties(); + properties.load(in); + return properties; + } + } + } + } + + return null; + } + + /** + * Sub-classes implement specific logic using both clients. + */ + public abstract R doExecute(final CommandLine commandLine, + final NiFiClient nifiClient, + final Properties nifiProperties, + final NiFiRegistryClient nifiRegistryClient, + final Properties nifiRegistryProperties) + throws CommandException, IOException, NiFiRegistryException, ParseException, NiFiClientException; + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/DemoCommandGroup.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/DemoCommandGroup.java new file mode 100644 index 0000000000..3dbfea35f1 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/DemoCommandGroup.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.command.composite; + +import org.apache.nifi.toolkit.cli.api.Command; +import org.apache.nifi.toolkit.cli.impl.command.AbstractCommandGroup; + +import java.util.ArrayList; +import java.util.List; + +/** + * Command group for quick demo commands. + */ +public class DemoCommandGroup extends AbstractCommandGroup { + + public static final String NAME = "demo"; + + public DemoCommandGroup() { + super(NAME); + } + + @Override + protected List createCommands() { + final List commands = new ArrayList<>(); + commands.add(new QuickImport()); + return commands; + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/QuickImport.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/QuickImport.java new file mode 100644 index 0000000000..5c504a4e2b --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/composite/QuickImport.java @@ -0,0 +1,248 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.command.composite; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.MissingOptionException; +import org.apache.commons.cli.ParseException; +import org.apache.commons.lang3.StringUtils; +import org.apache.nifi.registry.bucket.Bucket; +import org.apache.nifi.registry.client.NiFiRegistryClient; +import org.apache.nifi.registry.client.NiFiRegistryException; +import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; +import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; +import org.apache.nifi.toolkit.cli.impl.command.CommandOption; +import org.apache.nifi.toolkit.cli.impl.command.nifi.pg.PGImport; +import org.apache.nifi.toolkit.cli.impl.command.nifi.registry.CreateRegistryClient; +import org.apache.nifi.toolkit.cli.impl.command.nifi.registry.GetRegistryClientId; +import org.apache.nifi.toolkit.cli.impl.command.registry.bucket.CreateBucket; +import org.apache.nifi.toolkit.cli.impl.command.registry.bucket.ListBuckets; +import org.apache.nifi.toolkit.cli.impl.command.registry.flow.CreateFlow; +import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ImportFlowVersion; +import org.apache.nifi.toolkit.cli.impl.result.BucketsResult; +import org.apache.nifi.toolkit.cli.impl.result.RegistryClientIDResult; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; + +import java.io.IOException; +import java.util.Date; +import java.util.Properties; + +/** + * Command to demonstrate a quick import capability. + */ +public class QuickImport extends AbstractCompositeCommand { + + public static final String BUCKET_NAME = "Quick Import"; + public static final String BUCKET_DESC = "Created to demonstrate quickly importing a flow with NiFi CLI."; + + public static final String FLOW_NAME = "Quick Import - "; + public static final String FLOW_DESC = "Automatically imported on "; + + public static final String REG_CLIENT_NAME = "Quick Import"; + public static final String REG_CLIENT_DESC = "Automatically created on "; + + private final ListBuckets listBuckets; + private final CreateBucket createBucket; + private final CreateFlow createFlow; + private final ImportFlowVersion importFlowVersion; + private final GetRegistryClientId getRegistryClientId; + private final CreateRegistryClient createRegistryClient; + private final PGImport pgImport; + + public QuickImport() { + super("quick-import", StringResult.class); + this.listBuckets = new ListBuckets(); + this.createBucket = new CreateBucket(); + this.createFlow = new CreateFlow(); + this.importFlowVersion = new ImportFlowVersion(); + this.getRegistryClientId = new GetRegistryClientId(); + this.createRegistryClient = new CreateRegistryClient(); + this.pgImport = new PGImport(); + } + + @Override + public String getDescription() { + return "Imports a flow from a file or a public URL into a pre-defined bucket named '" + BUCKET_NAME + "'. This command will " + + "create the bucket if it doesn't exist, and will create a new flow for each execution. The flow will then be imported " + + "to the given NiFi instance."; + } + + @Override + protected void doInitialize(Context context) { + // add additional options + addOption(CommandOption.INPUT_SOURCE.createOption()); + + // initialize sub-commands since we are managing their lifecycle ourselves here + listBuckets.initialize(context); + createBucket.initialize(context); + createFlow.initialize(context); + importFlowVersion.initialize(context); + getRegistryClientId.initialize(context); + createRegistryClient.initialize(context); + pgImport.initialize(context); + } + + @Override + public StringResult doExecute(final CommandLine cli, final NiFiClient nifiClient, final Properties nifiProps, + final NiFiRegistryClient registryClient, final Properties registryProps) + throws IOException, NiFiRegistryException, ParseException, NiFiClientException { + + final boolean isInteractive = getContext().isInteractive(); + + // determine the registry client in NiFi to use, or create one + // do this first so that we don't get through creating buckets, flows, etc, and then fail on the reg client + final String registryClientBaseUrl = registryProps.getProperty(CommandOption.URL.getLongName()); + final String registryClientId = getRegistryClientId(nifiClient, registryClientBaseUrl, isInteractive); + + // get or create the quick import bucket + final String quickImportBucketId = getQuickImportBucketId(registryClient, isInteractive); + + // create a new flow in the quick-import bucket + final String quickImportFlowId = createQuickImportFlow(registryClient, quickImportBucketId, isInteractive); + + // import the versioned flow snapshot into newly created quick-import flow + final String inputSource = cli.getOptionValue(CommandOption.INPUT_SOURCE.getLongName()); + if (StringUtils.isBlank(inputSource)) { + throw new MissingOptionException("Missing required option --" + CommandOption.INPUT_SOURCE.getLongName()); + } + + final String quickImportFlowVersion = importFlowVersion(registryClient, quickImportFlowId, isInteractive, inputSource); + + // pg-import to nifi + final Properties pgImportProps = new Properties(); + pgImportProps.setProperty(CommandOption.REGISTRY_CLIENT_ID.getLongName(), registryClientId); + pgImportProps.setProperty(CommandOption.BUCKET_ID.getLongName(), quickImportBucketId); + pgImportProps.setProperty(CommandOption.FLOW_ID.getLongName(), quickImportFlowId); + pgImportProps.setProperty(CommandOption.FLOW_VERSION.getLongName(), quickImportFlowVersion); + + final StringResult createdPgResult = pgImport.doExecute(nifiClient, pgImportProps); + + if (isInteractive) { + println(); + println("Imported process group to NiFi..."); + println(); + } + + return createdPgResult; + } + + private String importFlowVersion(final NiFiRegistryClient registryClient, final String quickImportFlowId, final boolean isInteractive, final String inputSource) + throws ParseException, IOException, NiFiRegistryException { + final Properties importVersionProps = new Properties(); + importVersionProps.setProperty(CommandOption.FLOW_ID.getLongName(), quickImportFlowId); + importVersionProps.setProperty(CommandOption.INPUT_SOURCE.getLongName(), inputSource); + + final StringResult createdVersion = importFlowVersion.doExecute(registryClient, importVersionProps); + final String quickImportFlowVersion = createdVersion.getResult(); + + if (isInteractive) { + println(); + println("Imported flow version..."); + } + return quickImportFlowVersion; + } + + private String createQuickImportFlow(final NiFiRegistryClient registryClient, final String quickImportBucketId, final boolean isInteractive) + throws ParseException, IOException, NiFiRegistryException { + final String flowName = FLOW_NAME + System.currentTimeMillis(); + final String flowDescription = FLOW_DESC + (new Date()).toString(); + + final Properties createFlowProps = new Properties(); + createFlowProps.setProperty(CommandOption.FLOW_NAME.getLongName(), flowName); + createFlowProps.setProperty(CommandOption.FLOW_DESC.getLongName(), flowDescription); + createFlowProps.setProperty(CommandOption.BUCKET_ID.getLongName(), quickImportBucketId); + + final StringResult createdFlow = createFlow.doExecute(registryClient, createFlowProps); + final String quickImportFlowId = createdFlow.getResult(); + + if (isInteractive) { + println(); + println("Created new flow '" + flowName + "'..."); + } + return quickImportFlowId; + } + + private String getQuickImportBucketId(final NiFiRegistryClient registryClient, final boolean isInteractive) + throws IOException, NiFiRegistryException, MissingOptionException { + + final BucketsResult bucketsResult = listBuckets.doExecute(registryClient, new Properties()); + + final Bucket quickImportBucket = bucketsResult.getResult().stream() + .filter(b -> BUCKET_NAME.equals(b.getName())) + .findFirst().orElse(null); + + // if it doesn't exist, then create the quick import bucket + String quickImportBucketId = null; + if (quickImportBucket != null) { + quickImportBucketId = quickImportBucket.getIdentifier(); + if (isInteractive) { + println(); + println("Found existing bucket '" + BUCKET_NAME + "'..."); + } + } else { + final Properties createBucketProps = new Properties(); + createBucketProps.setProperty(CommandOption.BUCKET_NAME.getLongName(), BUCKET_NAME); + createBucketProps.setProperty(CommandOption.BUCKET_DESC.getLongName(), BUCKET_DESC); + + final StringResult createdBucketId = createBucket.doExecute(registryClient, createBucketProps); + quickImportBucketId = createdBucketId.getResult(); + if (isInteractive) { + println(); + println("Created new bucket '" + BUCKET_NAME + "'..."); + } + } + return quickImportBucketId; + } + + private String getRegistryClientId(final NiFiClient nifiClient, final String registryClientBaseUrl, final boolean isInteractive) + throws NiFiClientException, IOException, MissingOptionException { + + final Properties getRegClientProps = new Properties(); + getRegClientProps.setProperty(CommandOption.REGISTRY_CLIENT_URL.getLongName(), registryClientBaseUrl); + + String registryClientId; + try { + final RegistryClientIDResult registryClientResult = getRegistryClientId.doExecute(nifiClient, getRegClientProps); + registryClientId = registryClientResult.getResult().getId(); + if (isInteractive) { + println(); + println("Found existing registry client '" + registryClientResult.getResult().getName() + "'..."); + } + } catch (Exception e) { + registryClientId = null; + } + + if (registryClientId == null) { + final Properties createRegClientProps = new Properties(); + createRegClientProps.setProperty(CommandOption.REGISTRY_CLIENT_NAME.getLongName(), REG_CLIENT_NAME); + createRegClientProps.setProperty(CommandOption.REGISTRY_CLIENT_DESC.getLongName(), REG_CLIENT_DESC + new Date().toString()); + createRegClientProps.setProperty(CommandOption.REGISTRY_CLIENT_URL.getLongName(), registryClientBaseUrl); + + final StringResult createdRegClient = createRegistryClient.doExecute(nifiClient, createRegClientProps); + registryClientId = createdRegClient.getResult(); + + if (isInteractive) { + println(); + println("Created new registry client '" + REG_CLIENT_NAME + "'..."); + } + } + + return registryClientId; + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Exit.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Exit.java index 974f7f0f45..c8c61668bf 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Exit.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Exit.java @@ -19,13 +19,13 @@ package org.apache.nifi.toolkit.cli.impl.command.misc; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.nifi.toolkit.cli.api.Command; -import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; /** * Command for exiting the shell. */ -public class Exit implements Command { +public class Exit implements Command { @Override public void initialize(final Context context) { @@ -53,8 +53,14 @@ public class Exit implements Command { } @Override - public void execute(final CommandLine cli) throws CommandException { + public VoidResult execute(final CommandLine cli) { System.exit(0); + return VoidResult.getInstance(); + } + + @Override + public Class getResultImplType() { + return VoidResult.class; } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Help.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Help.java index 05440891e4..76440e275e 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Help.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/misc/Help.java @@ -19,13 +19,13 @@ package org.apache.nifi.toolkit.cli.impl.command.misc; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.nifi.toolkit.cli.api.Command; -import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; /** * Place-holder so "help" shows up in top-level commands. */ -public class Help implements Command { +public class Help implements Command { @Override public void initialize(final Context context) { @@ -53,8 +53,12 @@ public class Help implements Command { } @Override - public void execute(final CommandLine cli) throws CommandException { - // nothing to do + public VoidResult execute(final CommandLine cli) { + return VoidResult.getInstance(); } + @Override + public Class getResultImplType() { + return VoidResult.class; + } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/AbstractNiFiCommand.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/AbstractNiFiCommand.java index cfe3e53e2a..4cf95db418 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/AbstractNiFiCommand.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/AbstractNiFiCommand.java @@ -19,10 +19,11 @@ package org.apache.nifi.toolkit.cli.impl.command.nifi; import org.apache.commons.cli.MissingOptionException; import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.CommandException; +import org.apache.nifi.toolkit.cli.api.Result; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.AbstractPropertyCommand; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; import org.apache.nifi.web.api.dto.RevisionDTO; import java.io.IOException; @@ -31,22 +32,22 @@ import java.util.Properties; /** * Base class for all NiFi commands. */ -public abstract class AbstractNiFiCommand extends AbstractPropertyCommand { +public abstract class AbstractNiFiCommand extends AbstractPropertyCommand { - public AbstractNiFiCommand(final String name) { - super(name); + public AbstractNiFiCommand(final String name, final Class resultClass) { + super(name, resultClass); } @Override - protected SessionVariables getPropertiesSessionVariable() { - return SessionVariables.NIFI_CLIENT_PROPS; + protected SessionVariable getPropertiesSessionVariable() { + return SessionVariable.NIFI_CLIENT_PROPS; } @Override - protected void doExecute(final Properties properties) throws CommandException { + public final R doExecute(final Properties properties) throws CommandException { final ClientFactory clientFactory = getContext().getNiFiClientFactory(); try (final NiFiClient client = clientFactory.createClient(properties)) { - doExecute(client, properties); + return doExecute(client, properties); } catch (Exception e) { throw new CommandException("Error executing command '" + getName() + "' : " + e.getMessage(), e); } @@ -57,8 +58,9 @@ public abstract class AbstractNiFiCommand extends AbstractPropertyCommand { * * @param client a NiFi client * @param properties properties for the command + * @return the Result of executing the command */ - protected abstract void doExecute(final NiFiClient client, final Properties properties) + public abstract R doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException; diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/CurrentUser.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/CurrentUser.java index 4c09510ec7..3f21dea4ec 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/CurrentUser.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/CurrentUser.java @@ -16,11 +16,12 @@ */ package org.apache.nifi.toolkit.cli.impl.command.nifi.flow; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.CurrentUserEntityResult; +import org.apache.nifi.web.api.entity.CurrentUserEntity; import java.io.IOException; import java.util.Properties; @@ -28,10 +29,10 @@ import java.util.Properties; /** * Command to get information about the current user accessing the NiFi instance. */ -public class CurrentUser extends AbstractNiFiCommand { +public class CurrentUser extends AbstractNiFiCommand { public CurrentUser() { - super("current-user"); + super("current-user", CurrentUserEntityResult.class); } @Override @@ -41,10 +42,10 @@ public class CurrentUser extends AbstractNiFiCommand { } @Override - protected void doExecute(NiFiClient client, Properties properties) + public CurrentUserEntityResult doExecute(NiFiClient client, Properties properties) throws NiFiClientException, IOException { final FlowClient flowClient = client.getFlowClient(); - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeCurrentUser(flowClient.getCurrentUser(), getContext().getOutput()); + final CurrentUserEntity currentUserEntity = flowClient.getCurrentUser(); + return new CurrentUserEntityResult(getResultType(properties), currentUserEntity); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/GetRootId.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/GetRootId.java index bf1fb75630..be27f336b5 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/GetRootId.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/flow/GetRootId.java @@ -20,6 +20,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import java.io.IOException; import java.util.Properties; @@ -27,10 +28,10 @@ import java.util.Properties; /** * Returns the id of the root process group of the given NiFi instance. */ -public class GetRootId extends AbstractNiFiCommand { +public class GetRootId extends AbstractNiFiCommand { public GetRootId() { - super("get-root-id"); + super("get-root-id", StringResult.class); } @Override @@ -39,10 +40,10 @@ public class GetRootId extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public StringResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException { final FlowClient flowClient = client.getFlowClient(); - println(flowClient.getRootGroupId()); + return new StringResult(flowClient.getRootGroupId()); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGChangeVersion.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGChangeVersion.java index 87d7845ada..cf332b00c6 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGChangeVersion.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGChangeVersion.java @@ -25,6 +25,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.client.nifi.VersionsClient; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import org.apache.nifi.web.api.dto.VersionControlInformationDTO; import org.apache.nifi.web.api.entity.VersionControlInformationEntity; import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataEntity; @@ -37,10 +38,10 @@ import java.util.Properties; /** * Command to change the version of a version controlled process group. */ -public class PGChangeVersion extends AbstractNiFiCommand { +public class PGChangeVersion extends AbstractNiFiCommand { public PGChangeVersion() { - super("pg-change-version"); + super("pg-change-version", VoidResult.class); } @Override @@ -57,7 +58,7 @@ public class PGChangeVersion extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VoidResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); @@ -117,6 +118,7 @@ public class PGChangeVersion extends AbstractNiFiCommand { versionsClient.deleteUpdateRequest(updateRequestId); } + return VoidResult.getInstance(); } private int getLatestVersion(final NiFiClient client, final VersionControlInformationDTO existingVersionControlDTO) diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetAllVersions.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetAllVersions.java index b26dffd47e..b3cd36c713 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetAllVersions.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetAllVersions.java @@ -17,15 +17,14 @@ package org.apache.nifi.toolkit.cli.impl.command.nifi.pg; import org.apache.commons.cli.MissingOptionException; -import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.client.nifi.VersionsClient; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VersionedFlowSnapshotMetadataSetResult; import org.apache.nifi.web.api.dto.VersionControlInformationDTO; import org.apache.nifi.web.api.entity.VersionControlInformationEntity; import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataSetEntity; @@ -36,10 +35,10 @@ import java.util.Properties; /** * Command to get all the available versions for a given process group that is under version control. */ -public class PGGetAllVersions extends AbstractNiFiCommand { +public class PGGetAllVersions extends AbstractNiFiCommand { public PGGetAllVersions() { - super("pg-get-all-versions"); + super("pg-get-all-versions", VersionedFlowSnapshotMetadataSetResult.class); } @Override public String getDescription() { @@ -52,8 +51,9 @@ public class PGGetAllVersions extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) - throws NiFiClientException, IOException, MissingOptionException, CommandException { + public VersionedFlowSnapshotMetadataSetResult doExecute(final NiFiClient client, final Properties properties) + throws NiFiClientException, IOException, MissingOptionException { + final String pgId = getRequiredArg(properties, CommandOption.PG_ID); final VersionsClient versionsClient = client.getVersionsClient(); @@ -75,8 +75,7 @@ public class PGGetAllVersions extends AbstractNiFiCommand { throw new NiFiClientException("No versions available"); } - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeSnapshotMetadata(versions, getContext().getOutput()); + return new VersionedFlowSnapshotMetadataSetResult(getResultType(properties), versions); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVars.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVars.java index 6c5072cd88..dfd1a1c50e 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVars.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVars.java @@ -19,12 +19,12 @@ package org.apache.nifi.toolkit.cli.impl.command.nifi.pg; import org.apache.commons.cli.MissingOptionException; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.client.nifi.ProcessGroupClient; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VariableRegistryResult; import org.apache.nifi.web.api.entity.VariableRegistryEntity; import java.io.IOException; @@ -33,10 +33,10 @@ import java.util.Properties; /** * Commands to get the variables of a process group. */ -public class PGGetVars extends AbstractNiFiCommand { +public class PGGetVars extends AbstractNiFiCommand { public PGGetVars() { - super("pg-get-vars"); + super("pg-get-vars", VariableRegistryResult.class); } @Override @@ -50,13 +50,12 @@ public class PGGetVars extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VariableRegistryResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); final ProcessGroupClient pgClient = client.getProcessGroupClient(); final VariableRegistryEntity varEntity = pgClient.getVariables(pgId); - - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeVariables(varEntity, getContext().getOutput()); + return new VariableRegistryResult(getResultType(properties), varEntity); } + } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVersion.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVersion.java index 855cb9e890..6c9da87e68 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVersion.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGGetVersion.java @@ -19,11 +19,11 @@ package org.apache.nifi.toolkit.cli.impl.command.nifi.pg; import org.apache.commons.cli.MissingOptionException; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VersionControlInfoResult; import org.apache.nifi.web.api.entity.VersionControlInformationEntity; import java.io.IOException; @@ -32,10 +32,10 @@ import java.util.Properties; /** * Command to get the version control info for a given process group. */ -public class PGGetVersion extends AbstractNiFiCommand { +public class PGGetVersion extends AbstractNiFiCommand { public PGGetVersion() { - super("pg-get-version"); + super("pg-get-version", VersionControlInfoResult.class); } @Override @@ -49,16 +49,14 @@ public class PGGetVersion extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VersionControlInfoResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); final VersionControlInformationEntity entity = client.getVersionsClient().getVersionControlInfo(pgId); if (entity.getVersionControlInformation() == null) { throw new NiFiClientException("Process group is not under version control"); } - - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeVersionControlInfo(entity, getContext().getOutput()); + return new VersionControlInfoResult(getResultType(properties), entity); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGImport.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGImport.java index 494b3fbccd..cb5a636790 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGImport.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGImport.java @@ -26,6 +26,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.ProcessGroupBox; import org.apache.nifi.toolkit.cli.impl.client.nifi.ProcessGroupClient; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import org.apache.nifi.web.api.dto.PositionDTO; import org.apache.nifi.web.api.dto.ProcessGroupDTO; import org.apache.nifi.web.api.dto.VersionControlInformationDTO; @@ -40,10 +41,10 @@ import java.util.Set; /** * Command for importing a flow to NiFi from NiFi Registry. */ -public class PGImport extends AbstractNiFiCommand { +public class PGImport extends AbstractNiFiCommand { public PGImport() { - super("pg-import"); + super("pg-import", StringResult.class); } @Override @@ -63,7 +64,7 @@ public class PGImport extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public StringResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException { final String bucketId = getRequiredArg(properties, CommandOption.BUCKET_ID); @@ -118,7 +119,7 @@ public class PGImport extends AbstractNiFiCommand { final ProcessGroupClient pgClient = client.getProcessGroupClient(); final ProcessGroupEntity createdEntity = pgClient.createProcessGroup(parentPgId, pgEntity); - println(createdEntity.getId()); + return new StringResult(createdEntity.getId()); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGList.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGList.java index cf143ef5ac..da5f45a058 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGList.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGList.java @@ -16,16 +16,14 @@ */ package org.apache.nifi.toolkit.cli.impl.command.nifi.pg; -import org.apache.commons.cli.MissingOptionException; import org.apache.commons.lang3.StringUtils; -import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.ProcessGroupsResult; import org.apache.nifi.web.api.dto.flow.FlowDTO; import org.apache.nifi.web.api.dto.flow.ProcessGroupFlowDTO; import org.apache.nifi.web.api.entity.ProcessGroupEntity; @@ -39,10 +37,10 @@ import java.util.Properties; /** * Command to list process-groups for a given parent process group. */ -public class PGList extends AbstractNiFiCommand { +public class PGList extends AbstractNiFiCommand { public PGList() { - super("pg-list"); + super("pg-list", ProcessGroupsResult.class); } @Override @@ -57,8 +55,8 @@ public class PGList extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) - throws NiFiClientException, IOException, MissingOptionException, CommandException { + public ProcessGroupsResult doExecute(final NiFiClient client, final Properties properties) + throws NiFiClientException, IOException { final FlowClient flowClient = client.getFlowClient(); @@ -77,8 +75,7 @@ public class PGList extends AbstractNiFiCommand { flowDTO.getProcessGroups().stream().forEach(pg -> processGroups.add(pg)); } - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeProcessGroups(processGroups, getContext().getOutput()); + return new ProcessGroupsResult(getResultType(properties), processGroups); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGSetVar.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGSetVar.java index afbde9d316..91a4511e84 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGSetVar.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGSetVar.java @@ -24,6 +24,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.client.nifi.ProcessGroupClient; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import org.apache.nifi.web.api.dto.VariableDTO; import org.apache.nifi.web.api.dto.VariableRegistryDTO; import org.apache.nifi.web.api.entity.VariableEntity; @@ -37,10 +38,10 @@ import java.util.Properties; /** * Command to set the value of a variable in a process group. */ -public class PGSetVar extends AbstractNiFiCommand { +public class PGSetVar extends AbstractNiFiCommand { public PGSetVar() { - super("pg-set-var"); + super("pg-set-var", VoidResult.class); } @Override @@ -56,7 +57,7 @@ public class PGSetVar extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VoidResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); @@ -112,5 +113,6 @@ public class PGSetVar extends AbstractNiFiCommand { pgClient.deleteVariableRegistryUpdateRequest(pgId, updateRequestId); } + return VoidResult.getInstance(); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStart.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStart.java index 938d603dc5..b5ed664bd8 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStart.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStart.java @@ -24,6 +24,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import org.apache.nifi.web.api.entity.ScheduleComponentsEntity; import java.io.IOException; @@ -32,10 +33,10 @@ import java.util.Properties; /** * Command to start the components of a process group. */ -public class PGStart extends AbstractNiFiCommand { +public class PGStart extends AbstractNiFiCommand { public PGStart() { - super("pg-start"); + super("pg-start", VoidResult.class); } @Override @@ -49,7 +50,7 @@ public class PGStart extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VoidResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); @@ -60,6 +61,7 @@ public class PGStart extends AbstractNiFiCommand { final FlowClient flowClient = client.getFlowClient(); final ScheduleComponentsEntity resultEntity = flowClient.scheduleProcessGroupComponents(pgId, entity); + return VoidResult.getInstance(); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStop.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStop.java index cd34a247f3..23c304b6e8 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStop.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/pg/PGStop.java @@ -17,13 +17,13 @@ package org.apache.nifi.toolkit.cli.impl.command.nifi.pg; import org.apache.commons.cli.MissingOptionException; -import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.client.nifi.FlowClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import org.apache.nifi.web.api.entity.ScheduleComponentsEntity; import java.io.IOException; @@ -32,10 +32,10 @@ import java.util.Properties; /** * Command to stop the components of a process group. */ -public class PGStop extends AbstractNiFiCommand { +public class PGStop extends AbstractNiFiCommand { public PGStop() { - super("pg-stop"); + super("pg-stop", VoidResult.class); } @Override @@ -49,8 +49,8 @@ public class PGStop extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) - throws NiFiClientException, IOException, MissingOptionException, CommandException { + public VoidResult doExecute(final NiFiClient client, final Properties properties) + throws NiFiClientException, IOException, MissingOptionException { final String pgId = getRequiredArg(properties, CommandOption.PG_ID); @@ -60,6 +60,7 @@ public class PGStop extends AbstractNiFiCommand { final FlowClient flowClient = client.getFlowClient(); final ScheduleComponentsEntity resultEntity = flowClient.scheduleProcessGroupComponents(pgId, entity); + return VoidResult.getInstance(); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/CreateRegistryClient.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/CreateRegistryClient.java index ae520d635a..ddbc325295 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/CreateRegistryClient.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/CreateRegistryClient.java @@ -22,6 +22,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import org.apache.nifi.web.api.dto.RegistryDTO; import org.apache.nifi.web.api.entity.RegistryClientEntity; @@ -31,10 +32,10 @@ import java.util.Properties; /** * Command for creating a registry client in NiFi. */ -public class CreateRegistryClient extends AbstractNiFiCommand { +public class CreateRegistryClient extends AbstractNiFiCommand { public CreateRegistryClient() { - super("create-reg-client"); + super("create-reg-client", StringResult.class); } @Override @@ -50,7 +51,7 @@ public class CreateRegistryClient extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public StringResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException { final String name = getRequiredArg(properties, CommandOption.REGISTRY_CLIENT_NAME); @@ -67,6 +68,6 @@ public class CreateRegistryClient extends AbstractNiFiCommand { clientEntity.setRevision(getInitialRevisionDTO()); final RegistryClientEntity createdEntity = client.getControllerClient().createRegistryClient(clientEntity); - println(createdEntity.getId()); + return new StringResult(createdEntity.getId()); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/GetRegistryClientId.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/GetRegistryClientId.java index f2f0685d25..c2dd7a1c90 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/GetRegistryClientId.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/GetRegistryClientId.java @@ -23,6 +23,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.RegistryClientIDResult; import org.apache.nifi.web.api.dto.RegistryDTO; import org.apache.nifi.web.api.entity.RegistryClientsEntity; @@ -32,10 +33,10 @@ import java.util.Properties; /** * Command to get the id of a registry client by name or url. */ -public class GetRegistryClientId extends AbstractNiFiCommand { +public class GetRegistryClientId extends AbstractNiFiCommand { public GetRegistryClientId() { - super("get-reg-client-id"); + super("get-reg-client-id", RegistryClientIDResult.class); } @Override @@ -51,7 +52,7 @@ public class GetRegistryClientId extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public RegistryClientIDResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, CommandException { final String regClientName = getArg(properties, CommandOption.REGISTRY_CLIENT_NAME); final String regClientUrl = getArg(properties, CommandOption.REGISTRY_CLIENT_URL); @@ -85,16 +86,8 @@ public class GetRegistryClientId extends AbstractNiFiCommand { if (registry == null) { throw new NiFiClientException("No registry client exists with the name '" + regClientName + "'"); } else { - println(registry.getId()); + return new RegistryClientIDResult(getResultType(properties), registry); } } - private RegistryDTO getByName(final RegistryClientsEntity registries, final String regClientName) { - return registries.getRegistries().stream() - .map(r -> r.getComponent()) - .filter(r -> r.getName().equalsIgnoreCase(regClientName)) - .findFirst() - .orElse(null); - - } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/ListRegistryClients.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/ListRegistryClients.java index 4cf498fd7e..96264c51c5 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/ListRegistryClients.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/ListRegistryClients.java @@ -16,10 +16,10 @@ */ package org.apache.nifi.toolkit.cli.impl.command.nifi.registry; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.RegistryClientsResult; import org.apache.nifi.web.api.entity.RegistryClientsEntity; import java.io.IOException; @@ -28,10 +28,10 @@ import java.util.Properties; /** * Lists the registry clients defined in the given NiFi instance. */ -public class ListRegistryClients extends AbstractNiFiCommand { +public class ListRegistryClients extends AbstractNiFiCommand { public ListRegistryClients() { - super("list-reg-clients"); + super("list-reg-clients", RegistryClientsResult.class); } @Override @@ -40,11 +40,10 @@ public class ListRegistryClients extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException { + public RegistryClientsResult doExecute(final NiFiClient client, final Properties properties) + throws NiFiClientException, IOException { final RegistryClientsEntity registries = client.getControllerClient().getRegistryClients(); - - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeRegistryClients(registries, getContext().getOutput()); + return new RegistryClientsResult(getResultType(properties), registries); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/UpdateRegistryClient.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/UpdateRegistryClient.java index 94825b4798..b574411366 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/UpdateRegistryClient.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/nifi/registry/UpdateRegistryClient.java @@ -25,6 +25,7 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClientException; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import org.apache.nifi.web.api.entity.RegistryClientEntity; import java.io.IOException; @@ -33,10 +34,10 @@ import java.util.Properties; /** * Command to update a registry client in NiFi. */ -public class UpdateRegistryClient extends AbstractNiFiCommand { +public class UpdateRegistryClient extends AbstractNiFiCommand { public UpdateRegistryClient() { - super("update-reg-client"); + super("update-reg-client", VoidResult.class); } @Override @@ -53,7 +54,7 @@ public class UpdateRegistryClient extends AbstractNiFiCommand { } @Override - protected void doExecute(final NiFiClient client, final Properties properties) + public VoidResult doExecute(final NiFiClient client, final Properties properties) throws NiFiClientException, IOException, MissingOptionException, CommandException { final ControllerClient controllerClient = client.getControllerClient(); @@ -89,5 +90,6 @@ public class UpdateRegistryClient extends AbstractNiFiCommand { existingRegClient.getRevision().setClientId(clientId); controllerClient.updateRegistryClient(existingRegClient); + return VoidResult.getInstance(); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/AbstractNiFiRegistryCommand.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/AbstractNiFiRegistryCommand.java index 9753d8d8ba..9a3a72af82 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/AbstractNiFiRegistryCommand.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/AbstractNiFiRegistryCommand.java @@ -22,8 +22,9 @@ import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.registry.client.NiFiRegistryException; import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.CommandException; +import org.apache.nifi.toolkit.cli.api.Result; import org.apache.nifi.toolkit.cli.impl.command.AbstractPropertyCommand; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; import java.io.IOException; import java.util.List; @@ -33,22 +34,22 @@ import java.util.Properties; /** * Base class for all NiFi Reg commands. */ -public abstract class AbstractNiFiRegistryCommand extends AbstractPropertyCommand { +public abstract class AbstractNiFiRegistryCommand extends AbstractPropertyCommand { - public AbstractNiFiRegistryCommand(final String name) { - super(name); + public AbstractNiFiRegistryCommand(final String name, final Class resultClass) { + super(name, resultClass); } @Override - protected SessionVariables getPropertiesSessionVariable() { - return SessionVariables.NIFI_REGISTRY_CLIENT_PROPS; + protected SessionVariable getPropertiesSessionVariable() { + return SessionVariable.NIFI_REGISTRY_CLIENT_PROPS; } @Override - protected void doExecute(final Properties properties) throws CommandException { + public final R doExecute(final Properties properties) throws CommandException { final ClientFactory clientFactory = getContext().getNiFiRegistryClientFactory(); try (final NiFiRegistryClient client = clientFactory.createClient(properties)) { - doExecute(client, properties); + return doExecute(client, properties); } catch (Exception e) { throw new CommandException("Error executing command '" + getName() + "' : " + e.getMessage(), e); } @@ -59,8 +60,9 @@ public abstract class AbstractNiFiRegistryCommand extends AbstractPropertyComman * * @param client the NiFiRegistryClient to use for performing the action * @param properties the properties for the command + * @return the Result of executing the command */ - protected abstract void doExecute(final NiFiRegistryClient client, final Properties properties) + public abstract R doExecute(final NiFiRegistryClient client, final Properties properties) throws IOException, NiFiRegistryException, ParseException; /* diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/CreateBucket.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/CreateBucket.java index 6f71c2f8d7..bd3260de4e 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/CreateBucket.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/CreateBucket.java @@ -24,6 +24,7 @@ import org.apache.nifi.registry.client.NiFiRegistryException; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import java.io.IOException; import java.util.Properties; @@ -31,10 +32,10 @@ import java.util.Properties; /** * Creates a new bucket in the registry. */ -public class CreateBucket extends AbstractNiFiRegistryCommand { +public class CreateBucket extends AbstractNiFiRegistryCommand { public CreateBucket() { - super("create-bucket"); + super("create-bucket", StringResult.class); } @Override @@ -49,7 +50,7 @@ public class CreateBucket extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public StringResult doExecute(final NiFiRegistryClient client, final Properties properties) throws IOException, NiFiRegistryException, MissingOptionException { final String bucketName = getRequiredArg(properties, CommandOption.BUCKET_NAME); @@ -61,7 +62,6 @@ public class CreateBucket extends AbstractNiFiRegistryCommand { final BucketClient bucketClient = client.getBucketClient(); final Bucket createdBucket = bucketClient.create(bucket); - - println(createdBucket.getIdentifier()); + return new StringResult(createdBucket.getIdentifier()); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/DeleteBucket.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/DeleteBucket.java index 8dc4630b3f..754dfae67a 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/DeleteBucket.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/DeleteBucket.java @@ -25,6 +25,7 @@ import org.apache.nifi.registry.flow.VersionedFlow; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import java.io.IOException; import java.util.List; @@ -33,10 +34,10 @@ import java.util.Properties; /** * Deletes a bucket from the given registry. */ -public class DeleteBucket extends AbstractNiFiRegistryCommand { +public class DeleteBucket extends AbstractNiFiRegistryCommand { public DeleteBucket() { - super("delete-bucket"); + super("delete-bucket", VoidResult.class); } @Override @@ -51,7 +52,7 @@ public class DeleteBucket extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public VoidResult doExecute(final NiFiRegistryClient client, final Properties properties) throws IOException, NiFiRegistryException, ParseException { final String bucketId = getRequiredArg(properties, CommandOption.BUCKET_ID); @@ -65,6 +66,7 @@ public class DeleteBucket extends AbstractNiFiRegistryCommand { } else { final BucketClient bucketClient = client.getBucketClient(); bucketClient.delete(bucketId); + return VoidResult.getInstance(); } } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/ListBuckets.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/ListBuckets.java index e833d3942e..7454cf17e2 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/ListBuckets.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/bucket/ListBuckets.java @@ -16,12 +16,11 @@ */ package org.apache.nifi.toolkit.cli.impl.command.registry.bucket; -import org.apache.commons.cli.MissingOptionException; import org.apache.nifi.registry.bucket.Bucket; import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.registry.client.NiFiRegistryException; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.BucketsResult; import java.io.IOException; import java.util.List; @@ -30,10 +29,10 @@ import java.util.Properties; /** * Command to list all buckets in the registry instance. */ -public class ListBuckets extends AbstractNiFiRegistryCommand { +public class ListBuckets extends AbstractNiFiRegistryCommand { public ListBuckets() { - super("list-buckets"); + super("list-buckets", BucketsResult.class); } @Override @@ -42,10 +41,10 @@ public class ListBuckets extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) - throws IOException, NiFiRegistryException, MissingOptionException { + public BucketsResult doExecute(final NiFiRegistryClient client, final Properties properties) + throws IOException, NiFiRegistryException { final List buckets = client.getBucketClient().getAll(); - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeBuckets(buckets, getContext().getOutput()); + return new BucketsResult(getResultType(properties), buckets); } + } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/CreateFlow.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/CreateFlow.java index d62af16180..075bc15345 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/CreateFlow.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/CreateFlow.java @@ -24,6 +24,7 @@ import org.apache.nifi.registry.flow.VersionedFlow; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import java.io.IOException; import java.util.Properties; @@ -31,10 +32,10 @@ import java.util.Properties; /** * Creates a flow in the registry */ -public class CreateFlow extends AbstractNiFiRegistryCommand { +public class CreateFlow extends AbstractNiFiRegistryCommand { public CreateFlow() { - super("create-flow"); + super("create-flow", StringResult.class); } @Override @@ -50,7 +51,7 @@ public class CreateFlow extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public StringResult doExecute(final NiFiRegistryClient client, final Properties properties) throws ParseException, IOException, NiFiRegistryException { final String bucketId = getRequiredArg(properties, CommandOption.BUCKET_ID); final String flowName = getRequiredArg(properties, CommandOption.FLOW_NAME); @@ -63,7 +64,6 @@ public class CreateFlow extends AbstractNiFiRegistryCommand { final FlowClient flowClient = client.getFlowClient(); final VersionedFlow createdFlow = flowClient.create(flow); - - println(createdFlow.getIdentifier()); + return new StringResult(createdFlow.getIdentifier()); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/DeleteFlow.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/DeleteFlow.java index 8dbc9195bd..48257d39b5 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/DeleteFlow.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/DeleteFlow.java @@ -25,6 +25,7 @@ import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import java.io.IOException; import java.util.List; @@ -33,10 +34,10 @@ import java.util.Properties; /** * Deletes a flow from the given registry. */ -public class DeleteFlow extends AbstractNiFiRegistryCommand { +public class DeleteFlow extends AbstractNiFiRegistryCommand { public DeleteFlow() { - super("delete-flow"); + super("delete-flow", VoidResult.class); } @Override @@ -51,7 +52,7 @@ public class DeleteFlow extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public VoidResult doExecute(final NiFiRegistryClient client, final Properties properties) throws IOException, NiFiRegistryException, ParseException { final String flowId = getRequiredArg(properties, CommandOption.FLOW_ID); @@ -67,6 +68,7 @@ public class DeleteFlow extends AbstractNiFiRegistryCommand { } else { final FlowClient flowClient = client.getFlowClient(); flowClient.delete(bucketId, flowId); + return VoidResult.getInstance(); } } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportFlowVersion.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportFlowVersion.java index cb0e187bac..ef40bed616 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportFlowVersion.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportFlowVersion.java @@ -23,17 +23,15 @@ import org.apache.nifi.registry.flow.VersionedFlowSnapshot; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; -import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils; +import org.apache.nifi.toolkit.cli.impl.result.VersionedFlowSnapshotResult; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; import java.util.Properties; -public class ExportFlowVersion extends AbstractNiFiRegistryCommand { +public class ExportFlowVersion extends AbstractNiFiRegistryCommand { public ExportFlowVersion() { - super("export-flow-version"); + super("export-flow-version", VersionedFlowSnapshotResult.class); } @Override @@ -50,7 +48,7 @@ public class ExportFlowVersion extends AbstractNiFiRegistryCommand { } @Override - public void doExecute(final NiFiRegistryClient client, final Properties properties) + public VersionedFlowSnapshotResult doExecute(final NiFiRegistryClient client, final Properties properties) throws ParseException, IOException, NiFiRegistryException { final String flowId = getRequiredArg(properties, CommandOption.FLOW_ID); final Integer version = getIntArg(properties, CommandOption.FLOW_VERSION); @@ -74,15 +72,14 @@ public class ExportFlowVersion extends AbstractNiFiRegistryCommand { // currently export doesn't use the ResultWriter concept, it always writes JSON // destination will be a file if outputFile is specified, otherwise it will be the output stream of the CLI + final String outputFile; if (properties.containsKey(CommandOption.OUTPUT_FILE.getLongName())) { - final String outputFile = properties.getProperty(CommandOption.OUTPUT_FILE.getLongName()); - try (final OutputStream resultOut = new FileOutputStream(outputFile)) { - JacksonUtils.write(versionedFlowSnapshot, resultOut); - } + outputFile = properties.getProperty(CommandOption.OUTPUT_FILE.getLongName()); } else { - final OutputStream output = getContext().getOutput(); - JacksonUtils.write(versionedFlowSnapshot, output); + outputFile = null; } + + return new VersionedFlowSnapshotResult(versionedFlowSnapshot, outputFile); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportFlowVersion.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportFlowVersion.java index fe2539e1fa..ca5384bddd 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportFlowVersion.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportFlowVersion.java @@ -27,6 +27,7 @@ import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; import org.apache.nifi.toolkit.cli.api.Context; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils; import java.io.IOException; @@ -40,16 +41,16 @@ import java.util.Properties; /** * Imports a version of a flow to specific bucket and flow in a given registry. */ -public class ImportFlowVersion extends AbstractNiFiRegistryCommand { +public class ImportFlowVersion extends AbstractNiFiRegistryCommand { public ImportFlowVersion() { - super("import-flow-version"); + super("import-flow-version", StringResult.class); } @Override public String getDescription() { - return "Imports a version of a flow from a local file, or a URL. The imported version automatically becomes " + - "the next version of the given flow."; + return "Imports a version of a flow from a local file, or a public URL. " + + "The imported version automatically becomes the next version of the given flow."; } @Override @@ -59,7 +60,7 @@ public class ImportFlowVersion extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public StringResult doExecute(final NiFiRegistryClient client, final Properties properties) throws ParseException, IOException, NiFiRegistryException { final String flowId = getRequiredArg(properties, CommandOption.FLOW_ID); final String inputFile = getRequiredArg(properties, CommandOption.INPUT_SOURCE); @@ -112,7 +113,7 @@ public class ImportFlowVersion extends AbstractNiFiRegistryCommand { final VersionedFlowSnapshot createdSnapshot = snapshotClient.create(snapshot); final VersionedFlowSnapshotMetadata createdMetadata = createdSnapshot.getSnapshotMetadata(); - println(String.valueOf(createdMetadata.getVersion())); -} + return new StringResult(String.valueOf(createdMetadata.getVersion())); + } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlowVersions.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlowVersions.java index 7968d9cbb7..5e64205bcb 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlowVersions.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlowVersions.java @@ -22,9 +22,9 @@ import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.registry.client.NiFiRegistryException; import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.VersionedFlowSnapshotMetadataResult; import java.io.IOException; import java.util.List; @@ -33,10 +33,10 @@ import java.util.Properties; /** * Lists the metadata for the versions of a specific flow in a specific bucket. */ -public class ListFlowVersions extends AbstractNiFiRegistryCommand { +public class ListFlowVersions extends AbstractNiFiRegistryCommand { public ListFlowVersions() { - super("list-flow-versions"); + super("list-flow-versions", VersionedFlowSnapshotMetadataResult.class); } @Override @@ -50,15 +50,14 @@ public class ListFlowVersions extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public VersionedFlowSnapshotMetadataResult doExecute(final NiFiRegistryClient client, final Properties properties) throws ParseException, IOException, NiFiRegistryException { final String flow = getRequiredArg(properties, CommandOption.FLOW_ID); final String bucket = getBucketId(client, flow); final FlowSnapshotClient snapshotClient = client.getFlowSnapshotClient(); final List snapshotMetadata = snapshotClient.getSnapshotMetadata(bucket, flow); - - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeSnapshotMetadata(snapshotMetadata, getContext().getOutput()); + return new VersionedFlowSnapshotMetadataResult(getResultType(properties), snapshotMetadata); } + } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlows.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlows.java index c8156cdd18..22db2ffc62 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlows.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ListFlows.java @@ -22,9 +22,9 @@ import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.registry.client.NiFiRegistryException; import org.apache.nifi.registry.flow.VersionedFlow; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.VersionedFlowsResult; import java.io.IOException; import java.util.List; @@ -33,10 +33,10 @@ import java.util.Properties; /** * Lists all flows in the registry. */ -public class ListFlows extends AbstractNiFiRegistryCommand { +public class ListFlows extends AbstractNiFiRegistryCommand { public ListFlows() { - super("list-flows"); + super("list-flows", VersionedFlowsResult.class); } @Override @@ -50,15 +50,13 @@ public class ListFlows extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) + public VersionedFlowsResult doExecute(final NiFiRegistryClient client, final Properties properties) throws ParseException, IOException, NiFiRegistryException { final String bucketId = getRequiredArg(properties, CommandOption.BUCKET_ID); final FlowClient flowClient = client.getFlowClient(); final List flows = flowClient.getByBucket(bucketId); - - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeFlows(flows, getContext().getOutput()); + return new VersionedFlowsResult(getResultType(properties), flows); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/user/CurrentUser.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/user/CurrentUser.java index 0c1ef237b6..6b7896e4af 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/user/CurrentUser.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/user/CurrentUser.java @@ -16,12 +16,11 @@ */ package org.apache.nifi.toolkit.cli.impl.command.registry.user; -import org.apache.commons.cli.ParseException; import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.registry.client.NiFiRegistryException; import org.apache.nifi.registry.client.UserClient; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand; +import org.apache.nifi.toolkit.cli.impl.result.CurrentUserResult; import java.io.IOException; import java.util.Properties; @@ -29,10 +28,10 @@ import java.util.Properties; /** * Command to get info about the current user access NiFi Registry. */ -public class CurrentUser extends AbstractNiFiRegistryCommand { +public class CurrentUser extends AbstractNiFiRegistryCommand { public CurrentUser() { - super("current-user"); + super("current-user", CurrentUserResult.class); } @Override @@ -42,10 +41,10 @@ public class CurrentUser extends AbstractNiFiRegistryCommand { } @Override - protected void doExecute(final NiFiRegistryClient client, final Properties properties) - throws IOException, NiFiRegistryException, ParseException { + public CurrentUserResult doExecute(final NiFiRegistryClient client, final Properties properties) + throws IOException, NiFiRegistryException { final UserClient userClient = client.getUserClient(); - final ResultWriter resultWriter = getResultWriter(properties); - resultWriter.writeCurrentUser(userClient.getAccessStatus(), getContext().getOutput()); + final org.apache.nifi.registry.authorization.CurrentUser currentUser = userClient.getAccessStatus(); + return new CurrentUserResult(getResultType(properties), currentUser); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ClearSession.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ClearSession.java index 89fc5921cb..7eec6035c6 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ClearSession.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ClearSession.java @@ -20,11 +20,12 @@ import org.apache.commons.cli.CommandLine; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.SessionException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; -public class ClearSession extends AbstractCommand { +public class ClearSession extends AbstractCommand { public ClearSession() { - super("clear"); + super("clear", VoidResult.class); } @Override @@ -33,9 +34,10 @@ public class ClearSession extends AbstractCommand { } @Override - public void execute(final CommandLine cli) throws CommandException { + public VoidResult execute(final CommandLine cli) throws CommandException { try { getContext().getSession().clear(); + return VoidResult.getInstance(); } catch (SessionException se) { throw new CommandException(se.getMessage(), se); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/GetVariable.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/GetVariable.java index c7b2311d8d..60ccb60402 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/GetVariable.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/GetVariable.java @@ -22,14 +22,15 @@ import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.api.SessionException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.result.StringResult; /** * Gets a the value of a variable from the session. */ -public class GetVariable extends AbstractCommand { +public class GetVariable extends AbstractCommand { public GetVariable() { - super("get"); + super("get", StringResult.class); } @Override @@ -38,7 +39,7 @@ public class GetVariable extends AbstractCommand { } @Override - public void execute(final CommandLine commandLine) throws CommandException { + public StringResult execute(final CommandLine commandLine) throws CommandException { final String[] args = commandLine.getArgs(); if (args == null || args.length != 1 || StringUtils.isBlank(args[0])) { @@ -49,9 +50,9 @@ public class GetVariable extends AbstractCommand { try { final String value = session.get(args[0]); if (value == null) { - println(); + return new StringResult(""); } else { - println(value); + return new StringResult(value); } } catch (SessionException se) { throw new CommandException(se.getMessage(), se); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/RemoveVariable.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/RemoveVariable.java index ae37eea5d1..d1b951c490 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/RemoveVariable.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/RemoveVariable.java @@ -21,14 +21,15 @@ import org.apache.commons.lang3.StringUtils; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.SessionException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; /** * Removes a variable from the session. */ -public class RemoveVariable extends AbstractCommand { +public class RemoveVariable extends AbstractCommand { public RemoveVariable() { - super("remove"); + super("remove", VoidResult.class); } @Override @@ -37,7 +38,7 @@ public class RemoveVariable extends AbstractCommand { } @Override - public void execute(final CommandLine commandLine) throws CommandException { + public VoidResult execute(final CommandLine commandLine) throws CommandException { final String[] args = commandLine.getArgs(); if (args == null || args.length != 1 || StringUtils.isBlank(args[0])) { @@ -46,6 +47,7 @@ public class RemoveVariable extends AbstractCommand { try { getContext().getSession().remove(args[0]); + return VoidResult.getInstance(); } catch (SessionException se) { throw new CommandException(se.getMessage(), se); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/SetVariable.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/SetVariable.java index f98ee054e9..38e2ccf199 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/SetVariable.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/SetVariable.java @@ -21,16 +21,17 @@ import org.apache.commons.lang3.StringUtils; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.SessionException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; /** * Sets a variable in the session. */ -public class SetVariable extends AbstractCommand { +public class SetVariable extends AbstractCommand { public static final String NAME = "set"; public SetVariable() { - super(NAME); + super(NAME, VoidResult.class); } @Override @@ -40,7 +41,7 @@ public class SetVariable extends AbstractCommand { } @Override - public void execute(final CommandLine commandLine) throws CommandException { + public VoidResult execute(final CommandLine commandLine) throws CommandException { final String[] args = commandLine.getArgs(); if (args == null || args.length < 2 || StringUtils.isBlank(args[0]) || StringUtils.isBlank(args[1])) { @@ -49,6 +50,7 @@ public class SetVariable extends AbstractCommand { try { getContext().getSession().set(args[0], args[1]); + return VoidResult.getInstance(); } catch (SessionException se) { throw new CommandException(se.getMessage(), se); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowKeys.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowKeys.java index 8825e8312b..f941767f00 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowKeys.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowKeys.java @@ -19,15 +19,16 @@ package org.apache.nifi.toolkit.cli.impl.command.session; import org.apache.commons.cli.CommandLine; import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; /** * Command for listing available variables. */ -public class ShowKeys extends AbstractCommand { +public class ShowKeys extends AbstractCommand { public ShowKeys() { - super("keys"); + super("keys", VoidResult.class); } @Override @@ -36,11 +37,13 @@ public class ShowKeys extends AbstractCommand { } @Override - public void execute(CommandLine cli) throws CommandException { + public VoidResult execute(CommandLine cli) throws CommandException { println(); - for (final SessionVariables variable : SessionVariables.values()) { + for (final SessionVariable variable : SessionVariable.values()) { println("\t" + variable.getVariableName()); } println(); + + return VoidResult.getInstance(); } } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowSession.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowSession.java index 49c506076b..04c878f2c7 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowSession.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/session/ShowSession.java @@ -21,16 +21,17 @@ import org.apache.nifi.toolkit.cli.api.CommandException; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.api.SessionException; import org.apache.nifi.toolkit.cli.impl.command.AbstractCommand; +import org.apache.nifi.toolkit.cli.impl.result.VoidResult; import java.io.PrintStream; /** * Command to list all variables and their values. */ -public class ShowSession extends AbstractCommand { +public class ShowSession extends AbstractCommand { public ShowSession() { - super("show"); + super("show", VoidResult.class); } @Override @@ -39,11 +40,12 @@ public class ShowSession extends AbstractCommand { } @Override - public void execute(final CommandLine cli) throws CommandException { + public VoidResult execute(final CommandLine cli) throws CommandException { try { final Session session = getContext().getSession(); final PrintStream printStream = getContext().getOutput(); session.printVariables(printStream); + return VoidResult.getInstance(); } catch (SessionException se) { throw new CommandException(se.getMessage(), se); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/context/StandardContext.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/context/StandardContext.java index ef4d6aedc8..07aa7d8183 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/context/StandardContext.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/context/StandardContext.java @@ -20,15 +20,10 @@ import org.apache.commons.lang3.Validate; import org.apache.nifi.registry.client.NiFiRegistryClient; import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultType; -import org.apache.nifi.toolkit.cli.api.ResultWriter; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import java.io.PrintStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; /** * Context for the CLI which will be passed to each command. @@ -40,7 +35,6 @@ public class StandardContext implements Context { private final Session session; private final PrintStream output; private final boolean isInteractive; - private final Map resultWriters; private StandardContext(final Builder builder) { this.niFiClientFactory = builder.niFiClientFactory; @@ -48,21 +42,11 @@ public class StandardContext implements Context { this.session = builder.session; this.output = builder.output; this.isInteractive = builder.isInteractive; - this.resultWriters = Collections.unmodifiableMap( - builder.resultWriters == null ? Collections.emptyMap() : new HashMap<>(builder.resultWriters)); Validate.notNull(this.niFiClientFactory); Validate.notNull(this.niFiRegistryClientFactory); Validate.notNull(this.session); Validate.notNull(this.output); - Validate.notNull(this.resultWriters); - - // ensure every ResultType has a provided writer - for (final ResultType resultType : ResultType.values()) { - if (!resultWriters.containsKey(resultType)) { - throw new IllegalStateException("ResultWriter not found for " + resultType.name()); - } - } } @Override @@ -90,18 +74,6 @@ public class StandardContext implements Context { return isInteractive; } - @Override - public ResultWriter getResultWriter(final ResultType resultType) { - if (resultType == null) { - if (isInteractive()) { - return resultWriters.get(ResultType.SIMPLE); - } else { - return resultWriters.get(ResultType.JSON); - } - } else { - return resultWriters.get(resultType); - } - } public static class Builder { private ClientFactory niFiClientFactory; @@ -109,7 +81,6 @@ public class StandardContext implements Context { private Session session; private PrintStream output; private boolean isInteractive; - private Map resultWriters = new HashMap<>(); public Builder nifiClientFactory(final ClientFactory niFiClientFactory) { this.niFiClientFactory = niFiClientFactory; @@ -136,11 +107,6 @@ public class StandardContext implements Context { return this; } - public Builder resultWriter(final ResultType resultType, final ResultWriter writer) { - resultWriters.put(resultType, writer); - return this; - } - public StandardContext build() { return new StandardContext(this); } diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/AbstractWritableResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/AbstractWritableResult.java new file mode 100644 index 0000000000..e7da22dc4d --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/AbstractWritableResult.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.api.WritableResult; +import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils; + +import java.io.IOException; +import java.io.PrintStream; + +/** + * Base class for writable results that have either JSON or simple output. + * + * @param the type of results + */ +public abstract class AbstractWritableResult implements WritableResult { + + protected final ResultType resultType; + + public AbstractWritableResult(final ResultType resultType) { + this.resultType = resultType; + Validate.notNull(resultType); + } + + @Override + public void write(final PrintStream output) throws IOException { + if (resultType == ResultType.JSON) { + writeJsonResult(output); + } else { + writeSimpleResult(output); + } + } + + protected abstract void writeSimpleResult(PrintStream output) + throws IOException; + + protected void writeJsonResult(PrintStream output) throws IOException { + JacksonUtils.write(getResult(), output); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/BucketsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/BucketsResult.java new file mode 100644 index 0000000000..034889ceb7 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/BucketsResult.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.bucket.Bucket; +import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.api.ReferenceResolver; +import org.apache.nifi.toolkit.cli.api.Referenceable; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter; +import org.apache.nifi.toolkit.cli.impl.result.writer.Table; +import org.apache.nifi.toolkit.cli.impl.result.writer.TableWriter; + +import java.io.PrintStream; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Result for a list of buckets. + */ +public class BucketsResult extends AbstractWritableResult> implements Referenceable { + + private final List buckets; + + public BucketsResult(final ResultType resultType, final List buckets) { + super(resultType); + this.buckets = buckets; + Validate.notNull(buckets); + + // NOTE: it is important that the order the buckets are printed is the same order for the ReferenceResolver + this.buckets.sort(Comparator.comparing(Bucket::getName)); + } + + @Override + public List getResult() { + return buckets; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + if (buckets.isEmpty()) { + return; + } + + final Table table = new Table.Builder() + .column("#", 3, 3, false) + .column("Name", 20, 36, true) + .column("Id", 36, 36, false) + .column("Description", 11, 40, true) + .build(); + + for (int i = 0; i < buckets.size(); ++i) { + final Bucket bucket = buckets.get(i); + table.addRow(String.valueOf(i + 1), bucket.getName(), bucket.getIdentifier(), bucket.getDescription()); + } + + final TableWriter tableWriter = new DynamicTableWriter(); + tableWriter.write(table, output); + } + + @Override + public ReferenceResolver createReferenceResolver(final Context context) { + final Map backRefs = new HashMap<>(); + final AtomicInteger position = new AtomicInteger(0); + buckets.forEach(b -> backRefs.put(position.incrementAndGet(), b)); + + return new ReferenceResolver() { + @Override + public String resolve(final Integer position) { + final Bucket bucket = backRefs.get(position); + if (bucket != null) { + if (context.isInteractive()) { + context.getOutput().printf("Using a positional back-reference for '%s'%n", bucket.getName()); + } + return bucket.getIdentifier(); + } else { + return null; + } + } + + @Override + public boolean isEmpty() { + return backRefs.isEmpty(); + } + }; + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserEntityResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserEntityResult.java new file mode 100644 index 0000000000..853535f6ee --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserEntityResult.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.entity.CurrentUserEntity; + +import java.io.PrintStream; + +/** + * Result for CurrentUserEntity from NiFi. + */ +public class CurrentUserEntityResult extends AbstractWritableResult { + + private final CurrentUserEntity currentUserEntity; + + public CurrentUserEntityResult(final ResultType resultType, final CurrentUserEntity currentUserEntity) { + super(resultType); + this.currentUserEntity = currentUserEntity; + Validate.notNull(this.currentUserEntity); + } + + @Override + public CurrentUserEntity getResult() { + return currentUserEntity; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + output.println(currentUserEntity.getIdentity()); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserResult.java new file mode 100644 index 0000000000..11100ffad7 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/CurrentUserResult.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.authorization.CurrentUser; +import org.apache.nifi.toolkit.cli.api.ResultType; + +import java.io.PrintStream; + +/** + * Result for CurrentUser from registry. + */ +public class CurrentUserResult extends AbstractWritableResult { + + private final CurrentUser currentUser; + + public CurrentUserResult(final ResultType resultType, final CurrentUser currentUser) { + super(resultType); + this.currentUser = currentUser; + Validate.notNull(this.currentUser); + } + + @Override + public CurrentUser getResult() { + return currentUser; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + output.println(currentUser.getIdentity()); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/JsonResultWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/JsonResultWriter.java deleted file mode 100644 index 04097fc1c5..0000000000 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/JsonResultWriter.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package org.apache.nifi.toolkit.cli.impl.result; - -import org.apache.nifi.registry.authorization.CurrentUser; -import org.apache.nifi.registry.bucket.Bucket; -import org.apache.nifi.registry.flow.VersionedFlow; -import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; -import org.apache.nifi.toolkit.cli.api.ResultWriter; -import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils; -import org.apache.nifi.web.api.entity.CurrentUserEntity; -import org.apache.nifi.web.api.entity.ProcessGroupEntity; -import org.apache.nifi.web.api.entity.RegistryClientsEntity; -import org.apache.nifi.web.api.entity.VariableRegistryEntity; -import org.apache.nifi.web.api.entity.VersionControlInformationEntity; -import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataSetEntity; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.List; - -/** - * ResultWriter implementation that uses Jackson to serialize to JSON. - */ -public class JsonResultWriter implements ResultWriter { - - @Override - public void writeBuckets(List buckets, PrintStream output) throws IOException { - write(buckets, output); - } - - @Override - public void writeBucket(Bucket bucket, PrintStream output) throws IOException { - write(bucket, output); - } - - @Override - public void writeFlows(List versionedFlows, PrintStream output) throws IOException { - write(versionedFlows, output); - } - - @Override - public void writeFlow(VersionedFlow versionedFlow, PrintStream output) throws IOException { - write(versionedFlow, output); - } - - @Override - public void writeSnapshotMetadata(List versions, PrintStream output) throws IOException { - write(versions, output); - } - - @Override - public void writeSnapshotMetadata(VersionedFlowSnapshotMetadata version, PrintStream output) throws IOException { - write(version, output); - } - - @Override - public void writeRegistryClients(RegistryClientsEntity clientsEntity, PrintStream output) throws IOException { - write(clientsEntity, output); - } - - @Override - public void writeVariables(VariableRegistryEntity variableRegistryEntity, PrintStream output) throws IOException { - write(variableRegistryEntity, output); - } - - @Override - public void writeSnapshotMetadata(VersionedFlowSnapshotMetadataSetEntity versionedFlowSnapshotMetadataSetEntity, PrintStream output) throws IOException { - write(versionedFlowSnapshotMetadataSetEntity, output); - } - - @Override - public void writeVersionControlInfo(VersionControlInformationEntity versionControlInformationEntity, PrintStream output) throws IOException { - write(versionControlInformationEntity, output); - } - - @Override - public void writeProcessGroups(List processGroupEntities, PrintStream output) throws IOException { - write(processGroupEntities, output); - } - - @Override - public void writeCurrentUser(CurrentUserEntity currentUserEntity, PrintStream output) throws IOException { - write(currentUserEntity, output); - } - - @Override - public void writeCurrentUser(CurrentUser currentUser, PrintStream output) throws IOException { - write(currentUser, output); - } - - private void write(final Object result, final OutputStream output) throws IOException { - JacksonUtils.write(result, output); - } - -} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/ProcessGroupsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/ProcessGroupsResult.java new file mode 100644 index 0000000000..41cf62ede4 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/ProcessGroupsResult.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.dto.ProcessGroupDTO; +import org.apache.nifi.web.api.entity.ProcessGroupEntity; + +import java.io.PrintStream; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Result for a list of ProcessGroupEntities. + */ +public class ProcessGroupsResult extends AbstractWritableResult> { + + private final List processGroupEntities; + + public ProcessGroupsResult(final ResultType resultType, final List processGroupEntities) { + super(resultType); + this.processGroupEntities = processGroupEntities; + Validate.notNull(this.processGroupEntities); + } + + @Override + public List getResult() { + return processGroupEntities; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + final List dtos = processGroupEntities.stream() + .map(e -> e.getComponent()).collect(Collectors.toList()); + + Collections.sort(dtos, Comparator.comparing(ProcessGroupDTO::getName)); + + dtos.stream().forEach(dto -> output.println(dto.getName() + " - " + dto.getId())); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientIDResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientIDResult.java new file mode 100644 index 0000000000..e221318cc9 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientIDResult.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.dto.RegistryDTO; + +import java.io.PrintStream; + +public class RegistryClientIDResult extends AbstractWritableResult { + + private final RegistryDTO registryDTO; + + public RegistryClientIDResult(final ResultType resultType, final RegistryDTO registryDTO) { + super(resultType); + this.registryDTO = registryDTO; + Validate.notNull(this.registryDTO); + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + output.println(registryDTO.getId()); + } + + @Override + public RegistryDTO getResult() { + return registryDTO; + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientsResult.java new file mode 100644 index 0000000000..7ca912227f --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/RegistryClientsResult.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter; +import org.apache.nifi.toolkit.cli.impl.result.writer.Table; +import org.apache.nifi.toolkit.cli.impl.result.writer.TableWriter; +import org.apache.nifi.web.api.dto.RegistryDTO; +import org.apache.nifi.web.api.entity.RegistryClientEntity; +import org.apache.nifi.web.api.entity.RegistryClientsEntity; + +import java.io.PrintStream; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Result for a RegistryClientsEntity. + */ +public class RegistryClientsResult extends AbstractWritableResult { + + final RegistryClientsEntity registryClients; + + public RegistryClientsResult(final ResultType resultType, final RegistryClientsEntity registryClients) { + super(resultType); + this.registryClients = registryClients; + Validate.notNull(this.registryClients); + } + + @Override + public RegistryClientsEntity getResult() { + return this.registryClients; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + final Set clients = registryClients.getRegistries(); + if (clients == null || clients.isEmpty()) { + return; + } + + final List registries = clients.stream().map(RegistryClientEntity::getComponent) + .sorted(Comparator.comparing(RegistryDTO::getName)) + .collect(Collectors.toList()); + + final Table table = new Table.Builder() + .column("#", 3, 3, false) + .column("Name", 20, 36, true) + .column("Id", 36, 36, false) + .column("Uri", 3, Integer.MAX_VALUE, false) + .build(); + + for (int i = 0; i < registries.size(); i++) { + RegistryDTO r = registries.get(i); + table.addRow("" + (i+1), r.getName(), r.getId(), r.getUri()); + } + + final TableWriter tableWriter = new DynamicTableWriter(); + tableWriter.write(table, output); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/SimpleResultWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/SimpleResultWriter.java deleted file mode 100644 index ea4f5514ab..0000000000 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/SimpleResultWriter.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package org.apache.nifi.toolkit.cli.impl.result; - -import org.apache.nifi.registry.authorization.CurrentUser; -import org.apache.nifi.registry.bucket.Bucket; -import org.apache.nifi.registry.flow.VersionedFlow; -import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; -import org.apache.nifi.toolkit.cli.api.ResultWriter; -import org.apache.nifi.web.api.dto.ProcessGroupDTO; -import org.apache.nifi.web.api.dto.RegistryDTO; -import org.apache.nifi.web.api.dto.VariableDTO; -import org.apache.nifi.web.api.dto.VariableRegistryDTO; -import org.apache.nifi.web.api.dto.VersionControlInformationDTO; -import org.apache.nifi.web.api.entity.CurrentUserEntity; -import org.apache.nifi.web.api.entity.ProcessGroupEntity; -import org.apache.nifi.web.api.entity.RegistryClientEntity; -import org.apache.nifi.web.api.entity.RegistryClientsEntity; -import org.apache.nifi.web.api.entity.VariableRegistryEntity; -import org.apache.nifi.web.api.entity.VersionControlInformationEntity; -import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataEntity; -import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataSetEntity; - -import java.io.IOException; -import java.io.PrintStream; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * ResultWriter implementation that writes simple human-readable output, primarily for use in the interactive CLI. - */ -public class SimpleResultWriter implements ResultWriter { - - public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss (EEE)"; - - @Override - public void writeBuckets(List buckets, PrintStream output) { - if (buckets == null || buckets.isEmpty()) { - return; - } - - buckets.sort(Comparator.comparing(Bucket::getName)); - - output.println(); - - final int nameLength = buckets.stream().mapToInt(b -> b.getName().length()).max().orElse(20); - final int idLength = buckets.stream().mapToInt(b -> b.getIdentifier().length()).max().orElse(36); - // description can be empty - int descLength = buckets.stream().map(b -> Optional.ofNullable(b.getDescription())) - .filter(b -> b.isPresent()) - .mapToInt(b -> b.get().length()) - .max() - .orElse(40); - descLength = descLength < 40 ? 40 : descLength; - - String headerPattern = String.format("# %%-%ds %%-%ds %%-%ds", nameLength, idLength, descLength); - final String header = String.format(headerPattern, "Name", "Id", "Description"); - output.println(header); - - // a little clunky way to dynamically create a nice header line, but at least no external dependency - final String headerLinePattern = String.format("--- %%-%ds %%-%ds %%-%ds", - nameLength, idLength, descLength); - final String headerLine = String.format(headerLinePattern, - String.join("", Collections.nCopies(nameLength, "-")), - String.join("", Collections.nCopies(idLength, "-")), - String.join("", Collections.nCopies(descLength, "-"))); - output.println(headerLine); - - String rowPattern = String.format("%%-3d %%-%ds %%-%ds %%-%ds", nameLength, idLength, descLength); - - for (int i = 0; i < buckets.size(); ++i) { - Bucket bucket = buckets.get(i); - String s = String.format(rowPattern, - i + 1, - bucket.getName(), - bucket.getIdentifier(), - Optional.ofNullable(bucket.getDescription()).orElse("(empty)")); - output.println(s); - - } - - output.println(); - } - - @Override - public void writeBucket(Bucket bucket, PrintStream output) { - // this method is not used really, need context of List - if (bucket == null) { - return; - } - output.println(bucket.getName() + " - " + bucket.getIdentifier()); - } - - @Override - public void writeFlows(List versionedFlows, PrintStream output) { - if (versionedFlows == null || versionedFlows.isEmpty()) { - return; - } - - versionedFlows.sort(Comparator.comparing(VersionedFlow::getName)); - - output.println(); - - final int nameLength = versionedFlows.stream().mapToInt(f -> f.getName().length()).max().orElse(20); - final int idLength = versionedFlows.stream().mapToInt(f -> f.getIdentifier().length()).max().orElse(36); - // description can be empty - int descLength = versionedFlows.stream().map(b -> Optional.ofNullable(b.getDescription())) - .filter(b -> b.isPresent()) - .mapToInt(b -> b.get().length()) - .max() - .orElse(40); - descLength = descLength < 40 ? 40 : descLength; - - String headerPattern = String.format("# %%-%ds %%-%ds %%-%ds", nameLength, idLength, descLength); - final String header = String.format(headerPattern, "Name", "Id", "Description"); - output.println(header); - - // a little clunky way to dynamically create a nice header line, but at least no external dependency - final String headerLinePattern = String.format("--- %%-%ds %%-%ds %%-%ds", - nameLength, idLength, descLength); - final String headerLine = String.format(headerLinePattern, - String.join("", Collections.nCopies(nameLength, "-")), - String.join("", Collections.nCopies(idLength, "-")), - String.join("", Collections.nCopies(descLength, "-"))); - output.println(headerLine); - - String rowPattern = String.format("%%-3d %%-%ds %%-%ds %%-%ds", nameLength, idLength, descLength); - - for (int i = 0; i < versionedFlows.size(); ++i) { - VersionedFlow flow = versionedFlows.get(i); - String s = String.format(rowPattern, - i + 1, - flow.getName(), - flow.getIdentifier(), - Optional.ofNullable(flow.getDescription()).orElse("(empty)")); - output.println(s); - - } - - output.println(); - - } - - @Override - // TODO drop as unused? - public void writeFlow(VersionedFlow versionedFlow, PrintStream output) { - if (versionedFlow == null) { - return; - } - output.println(versionedFlow.getName() + " - " + versionedFlow.getIdentifier()); - } - - @Override - public void writeSnapshotMetadata(List versions, PrintStream output) { - if (versions == null || versions.isEmpty()) { - return; - } - - versions.sort(Comparator.comparing(VersionedFlowSnapshotMetadata::getVersion)); - - output.println(); - - // The following section will construct a table output with dynamic column width, based on the actual data. - // We dynamically create a pattern with item width, as Java's formatter won't process nested declarations. - - // date length, with locale specifics - final String datePattern = "%1$ta, % v.getAuthor().length()).max().orElse(20); - - // truncate comments if too long - int commentsLength = versions.stream().mapToInt(v -> v.getComments().length()).max().orElse(60); - commentsLength = commentsLength < 40 ? 40 : commentsLength; - - String headerPattern = String.format("Ver %%-%ds %%-%ds %%-%ds", dateLength, authorLength, commentsLength); - final String header = String.format(headerPattern, "Date", "Author", "Message"); - output.println(header); - - // a little clunky way to dynamically create a nice header line, but at least no external dependency - final String headerLinePattern = String.format("--- %%-%ds %%-%ds %%-%ds", dateLength, authorLength, commentsLength); - final String headerLine = String.format(headerLinePattern, - String.join("", Collections.nCopies(dateLength, "-")), - String.join("", Collections.nCopies(authorLength, "-")), - String.join("", Collections.nCopies(commentsLength, "-"))); - output.println(headerLine); - - String rowPattern = String.format("%%3d %%-%ds %%-%ds %%-%ds", dateLength, authorLength, commentsLength); - versions.forEach(vfs -> { - String row = String.format(rowPattern, - vfs.getVersion(), - String.format(datePattern, new Date(vfs.getTimestamp())), - vfs.getAuthor(), - Optional.ofNullable(vfs.getComments()).orElse("(empty)")); - output.println(row); - }); - output.println(); - } - - @Override - // TODO drop as unused? - public void writeSnapshotMetadata(VersionedFlowSnapshotMetadata version, PrintStream output) { - if (version == null) { - return; - } - - final Date date = new Date(version.getTimestamp()); - final SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT); - output.println(version.getVersion() + " - " + dateFormatter.format(date) + " - " + version.getAuthor()); - } - - @Override - public void writeRegistryClients(RegistryClientsEntity clientsEntity, PrintStream output) { - if (clientsEntity == null) { - return; - } - - final Set clients = clientsEntity.getRegistries(); - if (clients == null || clients.isEmpty()) { - return; - } - - output.println(); - - final List registries = clients.stream().map(RegistryClientEntity::getComponent) - .sorted(Comparator.comparing(RegistryDTO::getName)) - .collect(Collectors.toList()); - - final int nameLength = registries.stream().mapToInt(r -> r.getName().length()).max().orElse(20); - final int idLength = registries.stream().mapToInt(r -> r.getId().length()).max().orElse(36); - final int uriLength = registries.stream().mapToInt(r -> r.getUri().length()).max().orElse(36); - - String headerPattern = String.format("# %%-%ds %%-%ds %%-%ds", nameLength, idLength, uriLength); - final String header = String.format(headerPattern, "Name", "Id", "Uri"); - output.println(header); - - // a little clunky way to dynamically create a nice header line, but at least no external dependency - final String headerLinePattern = String.format("--- %%-%ds %%-%ds %%-%ds", nameLength, idLength, uriLength); - final String headerLine = String.format(headerLinePattern, - String.join("", Collections.nCopies(nameLength, "-")), - String.join("", Collections.nCopies(idLength, "-")), - String.join("", Collections.nCopies(uriLength, "-"))); - output.println(headerLine); - - String rowPattern = String.format("%%3d %%-%ds %%-%ds %%-%ds", nameLength, idLength, uriLength); - for (int i = 0; i < registries.size(); i++) { - RegistryDTO r = registries.get(i); - String row = String.format(rowPattern, - i + 1, - r.getName(), - r.getId(), - r.getUri()); - output.println(row); - } - - output.println(); - } - - @Override - public void writeVariables(VariableRegistryEntity variableRegistryEntity, PrintStream output) { - if (variableRegistryEntity == null) { - return; - } - - final VariableRegistryDTO variableRegistryDTO = variableRegistryEntity.getVariableRegistry(); - if (variableRegistryDTO == null || variableRegistryDTO.getVariables() == null) { - return; - } - - final List variables = variableRegistryDTO.getVariables().stream().map(v -> v.getVariable()).collect(Collectors.toList()); - Collections.sort(variables, Comparator.comparing(VariableDTO::getName)); - variables.stream().forEach(v -> output.println(v.getName() + " - " + v.getValue())); - } - - @Override - public void writeSnapshotMetadata(VersionedFlowSnapshotMetadataSetEntity versionedFlowSnapshotMetadataSetEntity, PrintStream output) { - if (versionedFlowSnapshotMetadataSetEntity == null) { - return; - } - - final Set entities = versionedFlowSnapshotMetadataSetEntity.getVersionedFlowSnapshotMetadataSet(); - if (entities == null || entities.isEmpty()) { - return; - } - - final List snapshots = entities.stream().map(v -> v.getVersionedFlowSnapshotMetadata()).collect(Collectors.toList()); - writeSnapshotMetadata(snapshots, output); - } - - @Override - public void writeVersionControlInfo(VersionControlInformationEntity versionControlInformationEntity, PrintStream output) { - if (versionControlInformationEntity == null) { - return; - } - - final VersionControlInformationDTO dto = versionControlInformationEntity.getVersionControlInformation(); - if (dto == null) { - return; - } - - output.println(dto.getRegistryName() + " - " + dto.getBucketName() + " - " + dto.getFlowName() + " - " + dto.getVersion()); - } - - @Override - public void writeProcessGroups(List processGroupEntities, PrintStream output) throws IOException { - if (processGroupEntities == null) { - return; - } - - final List dtos = processGroupEntities.stream().map(e -> e.getComponent()).collect(Collectors.toList()); - Collections.sort(dtos, Comparator.comparing(ProcessGroupDTO::getName)); - - dtos.stream().forEach(dto -> output.println(dto.getName() + " - " + dto.getId())); - } - - @Override - public void writeCurrentUser(CurrentUserEntity currentUserEntity, PrintStream output) { - if (currentUserEntity == null) { - return; - } - - output.println(currentUserEntity.getIdentity()); - } - - @Override - public void writeCurrentUser(CurrentUser currentUser, PrintStream output) { - if (currentUser == null) { - return; - } - - output.println(currentUser.getIdentity()); - } -} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/StringResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/StringResult.java new file mode 100644 index 0000000000..1d82f65ecb --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/StringResult.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.WritableResult; + +import java.io.PrintStream; + +/** + * Result for a single string value. + */ +public class StringResult implements WritableResult { + + private final String value; + + public StringResult(final String value) { + this.value = value; + Validate.notNull(this.value); + } + + @Override + public String getResult() { + return value; + } + + @Override + public void write(final PrintStream output) { + output.println(value); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VariableRegistryResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VariableRegistryResult.java new file mode 100644 index 0000000000..0791fa5581 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VariableRegistryResult.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.dto.VariableDTO; +import org.apache.nifi.web.api.dto.VariableRegistryDTO; +import org.apache.nifi.web.api.entity.VariableRegistryEntity; + +import java.io.PrintStream; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Result for a VariableRegistryEntity. + */ +public class VariableRegistryResult extends AbstractWritableResult { + + final VariableRegistryEntity variableRegistryEntity; + + public VariableRegistryResult(final ResultType resultType, final VariableRegistryEntity variableRegistryEntity) { + super(resultType); + this.variableRegistryEntity = variableRegistryEntity; + Validate.notNull(this.variableRegistryEntity); + } + + @Override + public VariableRegistryEntity getResult() { + return variableRegistryEntity; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + final VariableRegistryDTO variableRegistryDTO = variableRegistryEntity.getVariableRegistry(); + if (variableRegistryDTO == null || variableRegistryDTO.getVariables() == null) { + return; + } + + final List variables = variableRegistryDTO.getVariables().stream().map(v -> v.getVariable()).collect(Collectors.toList()); + Collections.sort(variables, Comparator.comparing(VariableDTO::getName)); + variables.stream().forEach(v -> output.println(v.getName() + " - " + v.getValue())); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionControlInfoResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionControlInfoResult.java new file mode 100644 index 0000000000..ad0d17dc01 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionControlInfoResult.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.dto.VersionControlInformationDTO; +import org.apache.nifi.web.api.entity.VersionControlInformationEntity; + +import java.io.PrintStream; + +/** + * Result for VersionControlInformationEntity. + */ +public class VersionControlInfoResult extends AbstractWritableResult { + + private final VersionControlInformationEntity versionControlInformationEntity; + + public VersionControlInfoResult(final ResultType resultType, + final VersionControlInformationEntity versionControlInformationEntity) { + super(resultType); + this.versionControlInformationEntity = versionControlInformationEntity; + Validate.notNull(this.versionControlInformationEntity); + } + + @Override + public VersionControlInformationEntity getResult() { + return versionControlInformationEntity; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + final VersionControlInformationDTO dto = versionControlInformationEntity.getVersionControlInformation(); + if (dto == null) { + return; + } + + output.println(dto.getRegistryName() + " - " + dto.getBucketName() + " - " + dto.getFlowName() + " - " + dto.getVersion()); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataResult.java new file mode 100644 index 0000000000..554097a2a8 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataResult.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter; +import org.apache.nifi.toolkit.cli.impl.result.writer.Table; +import org.apache.nifi.toolkit.cli.impl.result.writer.TableWriter; + +import java.io.PrintStream; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +/** + * Result for a list of VersionedFlowSnapshotMetadata. + */ +public class VersionedFlowSnapshotMetadataResult extends AbstractWritableResult> { + + private final List versions; + + public VersionedFlowSnapshotMetadataResult(final ResultType resultType, final List versions) { + super(resultType); + this.versions = versions; + Validate.notNull(this.versions); + this.versions.sort(Comparator.comparing(VersionedFlowSnapshotMetadata::getVersion)); + } + + @Override + public List getResult() { + return this.versions; + } + + @Override + protected void writeSimpleResult(final PrintStream output) { + if (versions == null || versions.isEmpty()) { + return; + } + + // date length, with locale specifics + final String datePattern = "%1$ta, % { + table.addRow( + String.valueOf(vfs.getVersion()), + String.format(datePattern, new Date(vfs.getTimestamp())), + vfs.getAuthor(), + vfs.getComments() + ); + }); + + final TableWriter tableWriter = new DynamicTableWriter(); + tableWriter.write(table, output); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataSetResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataSetResult.java new file mode 100644 index 0000000000..d8c1abcd98 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotMetadataSetResult.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.api.WritableResult; +import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataEntity; +import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataSetEntity; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Result for VersionedFlowSnapshotMetadataSetEntity. + */ +public class VersionedFlowSnapshotMetadataSetResult extends AbstractWritableResult { + + private final VersionedFlowSnapshotMetadataSetEntity versionedFlowSnapshotMetadataSetEntity; + + public VersionedFlowSnapshotMetadataSetResult(final ResultType resultType, + final VersionedFlowSnapshotMetadataSetEntity versionedFlowSnapshotMetadataSetEntity) { + super(resultType); + this.versionedFlowSnapshotMetadataSetEntity = versionedFlowSnapshotMetadataSetEntity; + Validate.notNull(this.versionedFlowSnapshotMetadataSetEntity); + } + + @Override + public VersionedFlowSnapshotMetadataSetEntity getResult() { + return versionedFlowSnapshotMetadataSetEntity; + } + + @Override + protected void writeSimpleResult(final PrintStream output) throws IOException { + final Set entities = versionedFlowSnapshotMetadataSetEntity.getVersionedFlowSnapshotMetadataSet(); + if (entities == null || entities.isEmpty()) { + return; + } + + final List snapshots = entities.stream() + .map(v -> v.getVersionedFlowSnapshotMetadata()).collect(Collectors.toList()); + + final WritableResult> result = new VersionedFlowSnapshotMetadataResult(resultType, snapshots); + result.write(output); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotResult.java new file mode 100644 index 0000000000..f8c74536a0 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowSnapshotResult.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.flow.VersionedFlowSnapshot; +import org.apache.nifi.toolkit.cli.api.WritableResult; +import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; + +/** + * Result for a VersionedFlowSnapshot. + * + * If this result was created with a non-null exportFileName, then the write method will ignore + * the passed in PrintStream, and will write the serialized snapshot to the give file. + * + * If this result was created with a null exportFileName, then the write method will write the + * serialized snapshot to the given PrintStream. + */ +public class VersionedFlowSnapshotResult implements WritableResult { + + private final VersionedFlowSnapshot versionedFlowSnapshot; + + private final String exportFileName; + + public VersionedFlowSnapshotResult(final VersionedFlowSnapshot versionedFlowSnapshot, final String exportFileName) { + this.versionedFlowSnapshot = versionedFlowSnapshot; + this.exportFileName = exportFileName; + Validate.notNull(this.versionedFlowSnapshot); + } + + @Override + public VersionedFlowSnapshot getResult() { + return versionedFlowSnapshot; + } + + @Override + public void write(final PrintStream output) throws IOException { + if (exportFileName != null) { + try (final OutputStream resultOut = new FileOutputStream(exportFileName)) { + JacksonUtils.write(versionedFlowSnapshot, resultOut); + } + } else { + JacksonUtils.write(versionedFlowSnapshot, output); + } + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowsResult.java new file mode 100644 index 0000000000..5f6cc18832 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VersionedFlowsResult.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.commons.lang3.Validate; +import org.apache.nifi.registry.flow.VersionedFlow; +import org.apache.nifi.toolkit.cli.api.Context; +import org.apache.nifi.toolkit.cli.api.ReferenceResolver; +import org.apache.nifi.toolkit.cli.api.Referenceable; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter; +import org.apache.nifi.toolkit.cli.impl.result.writer.Table; +import org.apache.nifi.toolkit.cli.impl.result.writer.TableWriter; + +import java.io.PrintStream; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Result for a list of VersionedFlows. + */ +public class VersionedFlowsResult extends AbstractWritableResult> implements Referenceable { + + private final List versionedFlows; + + public VersionedFlowsResult(final ResultType resultType, final List flows) { + super(resultType); + this.versionedFlows = flows; + Validate.notNull(this.versionedFlows); + + // NOTE: it is important that the order the flows are printed is the same order for the ReferenceResolver + this.versionedFlows.sort(Comparator.comparing(VersionedFlow::getName)); + } + + @Override + public List getResult() { + return versionedFlows; + } + + @Override + protected void writeSimpleResult(PrintStream output) { + if (versionedFlows.isEmpty()) { + return; + } + + final Table table = new Table.Builder() + .column("#", 3, 3, false) + .column("Name", 20, 36, true) + .column("Id", 36, 36, false) + .column("Description", 11, 40, true) + .build(); + + for (int i = 0; i < versionedFlows.size(); ++i) { + final VersionedFlow flow = versionedFlows.get(i); + table.addRow(String.valueOf(i + 1), flow.getName(), flow.getIdentifier(), flow.getDescription()); + } + + final TableWriter tableWriter = new DynamicTableWriter(); + tableWriter.write(table, output); + } + + @Override + public ReferenceResolver createReferenceResolver(final Context context) { + final Map backRefs = new HashMap<>(); + final AtomicInteger position = new AtomicInteger(0); + versionedFlows.forEach(f -> backRefs.put(position.incrementAndGet(), f)); + + return new ReferenceResolver() { + @Override + public String resolve(final Integer position) { + final VersionedFlow versionedFlow = backRefs.get(position); + if (versionedFlow != null) { + if (context.isInteractive()) { + context.getOutput().printf("Using a positional backreference for '%s'%n", versionedFlow.getName()); + } + return versionedFlow.getIdentifier(); + } else { + return null; + } + } + + @Override + public boolean isEmpty() { + return backRefs.isEmpty(); + } + }; + + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/Void.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/Void.java new file mode 100644 index 0000000000..03b5726954 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/Void.java @@ -0,0 +1,20 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +public final class Void { +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VoidResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VoidResult.java new file mode 100644 index 0000000000..9653dd6bc0 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/VoidResult.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.nifi.toolkit.cli.api.Result; + +/** + * Represents a result that has no real results. + */ +public class VoidResult implements Result { + + private static final Void VOID = new Void(); + + private static final VoidResult INSTANCE = new VoidResult(); + + public static VoidResult getInstance() { + return INSTANCE; + } + + @Override + public Void getResult() { + return VOID; + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/DynamicTableWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/DynamicTableWriter.java new file mode 100644 index 0000000000..6b1aadd0bb --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/DynamicTableWriter.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result.writer; + +import org.apache.commons.lang3.StringUtils; + +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class DynamicTableWriter implements TableWriter { + + @Override + public void write(final Table table, final PrintStream output) { + if (table == null) { + throw new IllegalArgumentException("Table cannot be null"); + } + + if (output == null) { + throw new IllegalArgumentException("Output cannot be null"); + } + + if (table.getColumns().isEmpty()) { + throw new IllegalArgumentException("Table has no columns to write"); + } + + output.println(); + + final List columns = table.getColumns(); + final List rows = table.getRows(); + + final int numColumns = columns.size(); + final Integer[] columnLengths = determineColumnLengths(columns, rows); + final List columnNames = columns.stream().map(c -> c.getName()).collect(Collectors.toList()); + + final Object[] columnLengthsObj = Arrays.copyOf(columnLengths, numColumns, Object[].class); + final Object[] columnNamesObj = columnNames.toArray(new Object[numColumns]); + + final String columnsPatternFormat = String.join("", Collections.nCopies(numColumns, "%%-%ds ")); + final String columnsPattern = String.format(columnsPatternFormat, columnLengthsObj); + + // format the header line which will include the column names + final String header = String.format(columnsPattern, columnNamesObj); + output.println(header); + + // a little clunky way to dynamically create a nice header line, but at least no external dependency + final Object[] headerLineValues = new Object[numColumns]; + for (int i=0; i < numColumns; i++) { + int length = columnLengths[i]; + headerLineValues[i] = String.join("", Collections.nCopies(length, "-")); + } + + final String headerLine = String.format(columnsPattern, headerLineValues); + output.println(headerLine); + + // format the rows and print them + for (String[] row : rows) { + // convert the row to an Object[] for the String.format and also abbreviate any values + final Object[] rowValues = new Object[row.length]; + for (int i=0; i < row.length; i++) { + final TableColumn column = columns.get(i); + if (column.isAbbreviated()) { + rowValues[i] = StringUtils.abbreviate(row[i], columnLengths[i]); + } else { + rowValues[i] = row[i]; + } + } + + final String rowString = String.format(columnsPattern, rowValues); + output.println(rowString); + } + + output.println(); + output.flush(); + } + + private Integer[] determineColumnLengths(final List columns, final List rows) { + final Integer[] columnLengths = new Integer[columns.size()]; + + for (int i=0; i < columns.size(); i++) { + final TableColumn column = columns.get(i); + + int maxLengthInColumn = -1; + + // find the max length of the values in the column + for (String[] row : rows) { + final String colVal = row[i]; + if (colVal != null && colVal.length() > maxLengthInColumn) { + maxLengthInColumn = colVal.length(); + } + } + + // if there were values for the column, then start with the min length of the column + if (maxLengthInColumn < 0) { + maxLengthInColumn = column.getMinLength(); + } + + // make sure the column length is at least as long as the column name + maxLengthInColumn = Math.max(maxLengthInColumn, column.getName().length()); + + // make sure the column length is not longer than the max length + columnLengths[i] = Math.min(maxLengthInColumn, column.getMaxLength()); + } + + return columnLengths; + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/Table.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/Table.java new file mode 100644 index 0000000000..b4941ecf12 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/Table.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result.writer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Table { + + public static String EMPTY_VALUE = "(empty)"; + + private final List columns; + private final List rows = new ArrayList<>(); + + private Table(final Builder builder) { + this.columns = Collections.unmodifiableList( + builder.columns == null ? Collections.emptyList() : new ArrayList<>(builder.columns)); + + if (this.columns.isEmpty()) { + throw new IllegalStateException("Cannot create a table with no columns"); + } + } + + public void addRow(String ... values) { + if (values == null) { + throw new IllegalArgumentException("Values cannot be null"); + } + + if (values.length != columns.size()) { + throw new IllegalArgumentException("Row has " + values.length + + " columns, but table has " + columns.size() + " columns"); + } + + // fill in any null values in the row with the empty value + for (int i=0; i < values.length; i++) { + if (values[i] == null) { + values[i] = EMPTY_VALUE; + } + } + + this.rows.add(values); + } + + public List getColumns() { + return columns; + } + + public List getRows() { + return rows; + } + + /** + * Builder for a Table. + */ + public static class Builder { + + private final List columns = new ArrayList<>(); + + public Builder column(final TableColumn column) { + if (column == null) { + throw new IllegalArgumentException("TableColumn cannot be null"); + } + this.columns.add(column); + return this; + } + + public Builder column(final String name, int minLength, int maxLength, boolean abbreviate) { + final TableColumn column = new TableColumn(name, minLength, maxLength, abbreviate); + return column(column); + } + + public Table build() { + return new Table(this); + } + + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableColumn.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableColumn.java new file mode 100644 index 0000000000..e686aefc0d --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableColumn.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result.writer; + +import org.apache.commons.lang3.Validate; + +public class TableColumn { + + private final String name; + private final int minLength; + private final int maxLength; + private final boolean abbreviate; + + public TableColumn(final String name, final int minLength, final int maxLength) { + this(name, minLength, maxLength, false); + } + + public TableColumn(final String name, final int minLength, final int maxLength, final boolean abbreviate) { + this.name = name; + this.minLength = minLength; + this.maxLength = maxLength; + this.abbreviate = abbreviate; + Validate.notBlank(this.name); + Validate.isTrue(this.minLength > 0); + Validate.isTrue(this.maxLength > 0); + Validate.isTrue(this.maxLength >= this.minLength); + } + + public String getName() { + return name; + } + + public int getMinLength() { + return minLength; + } + + public int getMaxLength() { + return maxLength; + } + + public boolean isAbbreviated() { + return abbreviate; + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableWriter.java new file mode 100644 index 0000000000..7ca90ffa77 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/writer/TableWriter.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result.writer; + +import java.io.PrintStream; + +/** + * A writer capable of printing a table to a stream. + */ +public interface TableWriter { + + /** + * Writes the given table to the given PrintStream. + * + * @param table a table to write + * @param output the stream to write to + */ + void write(Table table, PrintStream output); + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariables.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariable.java similarity index 85% rename from nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariables.java rename to nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariable.java index 747588f2dd..4c293b0a7d 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariables.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/session/SessionVariable.java @@ -22,14 +22,14 @@ import java.util.List; /** * Possible variables that can be set in the session. */ -public enum SessionVariables { +public enum SessionVariable { NIFI_CLIENT_PROPS("nifi.props"), NIFI_REGISTRY_CLIENT_PROPS("nifi.reg.props"); private final String variableName; - SessionVariables(final String variableName) { + SessionVariable(final String variableName) { this.variableName = variableName; } @@ -37,8 +37,8 @@ public enum SessionVariables { return this.variableName; } - public static SessionVariables fromVariableName(final String variableName) { - for (final SessionVariables variable : values()) { + public static SessionVariable fromVariableName(final String variableName) { + for (final SessionVariable variable : values()) { if (variable.getVariableName().equals(variableName)) { return variable; } @@ -49,7 +49,7 @@ public enum SessionVariables { public static List getAllVariableNames() { final List names = new ArrayList<>(); - for (SessionVariables variable : values()) { + for (SessionVariable variable : values()) { names.add(variable.getVariableName()); } return names; diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/NiFiCLIMainRunner.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/NiFiCLIMainRunner.java index 9a78588186..500207f15c 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/NiFiCLIMainRunner.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/NiFiCLIMainRunner.java @@ -21,7 +21,6 @@ import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultType; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.impl.client.NiFiClientFactory; import org.apache.nifi.toolkit.cli.impl.client.NiFiRegistryClientFactory; @@ -29,8 +28,6 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.command.CommandFactory; import org.apache.nifi.toolkit.cli.impl.command.CommandProcessor; import org.apache.nifi.toolkit.cli.impl.context.StandardContext; -import org.apache.nifi.toolkit.cli.impl.result.JsonResultWriter; -import org.apache.nifi.toolkit.cli.impl.result.SimpleResultWriter; import org.apache.nifi.toolkit.cli.impl.session.InMemorySession; import java.util.Map; @@ -38,7 +35,7 @@ import java.util.Map; public class NiFiCLIMainRunner { public static void main(String[] args) { - final String[] cmdArgs = ("nifi-reg create-bucket -bn FOO -p src/test/resources/test.properties " + + final String[] cmdArgs = ("registry list-buckets help " + "").split("[ ]"); final Session session = new InMemorySession(); @@ -50,8 +47,6 @@ public class NiFiCLIMainRunner { .session(session) .nifiClientFactory(niFiClientFactory) .nifiRegistryClientFactory(nifiRegClientFactory) - .resultWriter(ResultType.SIMPLE, new SimpleResultWriter()) - .resultWriter(ResultType.JSON, new JsonResultWriter()) .build(); final Map commands = CommandFactory.createTopLevelCommands(context); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/TestCLICompleter.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/TestCLICompleter.java index 10c2db0b30..3e2e2a351b 100644 --- a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/TestCLICompleter.java +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/TestCLICompleter.java @@ -21,7 +21,6 @@ import org.apache.nifi.toolkit.cli.api.ClientFactory; import org.apache.nifi.toolkit.cli.api.Command; import org.apache.nifi.toolkit.cli.api.CommandGroup; import org.apache.nifi.toolkit.cli.api.Context; -import org.apache.nifi.toolkit.cli.api.ResultType; import org.apache.nifi.toolkit.cli.api.Session; import org.apache.nifi.toolkit.cli.impl.client.NiFiClientFactory; import org.apache.nifi.toolkit.cli.impl.client.NiFiRegistryClientFactory; @@ -29,10 +28,8 @@ import org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient; import org.apache.nifi.toolkit.cli.impl.command.CommandFactory; import org.apache.nifi.toolkit.cli.impl.command.registry.NiFiRegistryCommandGroup; import org.apache.nifi.toolkit.cli.impl.context.StandardContext; -import org.apache.nifi.toolkit.cli.impl.result.JsonResultWriter; -import org.apache.nifi.toolkit.cli.impl.result.SimpleResultWriter; import org.apache.nifi.toolkit.cli.impl.session.InMemorySession; -import org.apache.nifi.toolkit.cli.impl.session.SessionVariables; +import org.apache.nifi.toolkit.cli.impl.session.SessionVariable; import org.jline.reader.Candidate; import org.jline.reader.LineReader; import org.jline.reader.impl.DefaultParser; @@ -65,8 +62,6 @@ public class TestCLICompleter { .session(session) .nifiClientFactory(niFiClientFactory) .nifiRegistryClientFactory(nifiRegClientFactory) - .resultWriter(ResultType.SIMPLE, new SimpleResultWriter()) - .resultWriter(ResultType.JSON, new JsonResultWriter()) .build(); final Map commands = CommandFactory.createTopLevelCommands(context); @@ -195,7 +190,7 @@ public class TestCLICompleter { final List candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); - assertEquals(SessionVariables.values().length, candidates.size()); + assertEquals(SessionVariable.values().length, candidates.size()); } @Test @@ -207,7 +202,7 @@ public class TestCLICompleter { Arrays.asList( topCommand, subCommand, - SessionVariables.NIFI_CLIENT_PROPS.getVariableName(), + SessionVariable.NIFI_CLIENT_PROPS.getVariableName(), "src/test/resources/"), 3, -1, -1); diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestBucketsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestBucketsResult.java new file mode 100644 index 0000000000..1bb958210a --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestBucketsResult.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.nifi.registry.bucket.Bucket; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class TestBucketsResult { + + private ByteArrayOutputStream outputStream; + private PrintStream printStream; + + @Before + public void setup() { + this.outputStream = new ByteArrayOutputStream(); + this.printStream = new PrintStream(outputStream, true); + } + + @Test + public void testWritingSimpleBucketsResult() throws IOException { + final Bucket b1 = new Bucket(); + b1.setName("Bucket 1"); + b1.setDescription("This is bucket 1"); + b1.setIdentifier(UUID.fromString("ea752054-22c6-4fc0-b851-967d9a3837cb").toString()); + + final Bucket b2 = new Bucket(); + b2.setName("Bucket 2"); + b2.setDescription(null); + b2.setIdentifier(UUID.fromString("ddf5f289-7502-46df-9798-4b0457c1816b").toString()); + + final List buckets = new ArrayList<>(); + buckets.add(b1); + buckets.add(b2); + + final BucketsResult result = new BucketsResult(ResultType.SIMPLE, buckets); + result.write(printStream); + + final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(resultOut); + + final String expected = "\n" + + "# Name Id Description \n" + + "- -------- ------------------------------------ ---------------- \n" + + "1 Bucket 1 ea752054-22c6-4fc0-b851-967d9a3837cb This is bucket 1 \n" + + "2 Bucket 2 ddf5f289-7502-46df-9798-4b0457c1816b (empty) \n" + + "\n"; + + Assert.assertEquals(expected, resultOut); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestRegistryClientResult.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestRegistryClientResult.java new file mode 100644 index 0000000000..17acacdbbc --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestRegistryClientResult.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.apache.nifi.web.api.dto.RegistryDTO; +import org.apache.nifi.web.api.entity.RegistryClientEntity; +import org.apache.nifi.web.api.entity.RegistryClientsEntity; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class TestRegistryClientResult { + + private ByteArrayOutputStream outputStream; + private PrintStream printStream; + + @Before + public void setup() { + this.outputStream = new ByteArrayOutputStream(); + this.printStream = new PrintStream(outputStream, true); + } + + @Test + public void testWriteSimpleRegistryClientsResult() throws IOException { + final RegistryDTO r1 = new RegistryDTO(); + r1.setName("Registry 1"); + r1.setUri("http://thisisalonglonglonglonglonglonglonglonglonguri.com:18080"); + r1.setId(UUID.fromString("ea752054-22c6-4fc0-b851-967d9a3837cb").toString()); + + final RegistryDTO r2 = new RegistryDTO(); + r2.setName("Registry 2 with a longer than usual name"); + r2.setUri("http://localhost:18080"); + r2.setId(UUID.fromString("ddf5f289-7502-46df-9798-4b0457c1816b").toString()); + + final RegistryClientEntity clientEntity1 = new RegistryClientEntity(); + clientEntity1.setId(r1.getId()); + clientEntity1.setComponent(r1); + + final RegistryClientEntity clientEntity2 = new RegistryClientEntity(); + clientEntity2.setId(r2.getId()); + clientEntity2.setComponent(r2); + + final Set clientEntities = new HashSet<>(); + clientEntities.add(clientEntity1); + clientEntities.add(clientEntity2); + + final RegistryClientsEntity registryClientsEntity = new RegistryClientsEntity(); + registryClientsEntity.setRegistries(clientEntities); + + final RegistryClientsResult result = new RegistryClientsResult(ResultType.SIMPLE, registryClientsEntity); + result.write(printStream); + + final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(resultOut); + + final String expected = "\n" + + "# Name Id Uri \n" + + "- ------------------------------------ ------------------------------------ --------------------------------------------------------------- \n" + + "1 Registry 1 ea752054-22c6-4fc0-b851-967d9a3837cb http://thisisalonglonglonglonglonglonglonglonglonguri.com:18080 \n" + + "2 Registry 2 with a longer than usu... ddf5f289-7502-46df-9798-4b0457c1816b http://localhost:18080 \n" + + "\n"; + + Assert.assertEquals(expected, resultOut); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowSnapshotMetadataResult.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowSnapshotMetadataResult.java new file mode 100644 index 0000000000..48e1604690 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowSnapshotMetadataResult.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; + +public class TestVersionedFlowSnapshotMetadataResult { + + private ByteArrayOutputStream outputStream; + private PrintStream printStream; + + @Before + public void setup() { + this.outputStream = new ByteArrayOutputStream(); + this.printStream = new PrintStream(outputStream, true); + } + + @Test + public void testWriteSimpleVersionedFlowSnapshotResult() throws ParseException, IOException { + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + final VersionedFlowSnapshotMetadata vfs1 = new VersionedFlowSnapshotMetadata(); + vfs1.setVersion(1); + vfs1.setAuthor("user1"); + vfs1.setTimestamp(dateFormat.parse("2018-02-14T12:00:00").getTime()); + vfs1.setComments("This is a long comment, longer than the display limit for comments"); + + final VersionedFlowSnapshotMetadata vfs2 = new VersionedFlowSnapshotMetadata(); + vfs2.setVersion(2); + vfs2.setAuthor("user2"); + vfs2.setTimestamp(dateFormat.parse("2018-02-14T12:30:00").getTime()); + vfs2.setComments("This is v2"); + + final List versions = new ArrayList<>(); + versions.add(vfs1); + versions.add(vfs2); + + final VersionedFlowSnapshotMetadataResult result = new VersionedFlowSnapshotMetadataResult(ResultType.SIMPLE, versions); + result.write(printStream); + + final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(resultOut); + + final String expected = "\n" + + "Ver Date Author Message \n" + + "--- -------------------------- ------ ---------------------------------------- \n" + + "1 Wed, Feb 14 2018 12:00 EST user1 This is a long comment, longer than t... \n" + + "2 Wed, Feb 14 2018 12:30 EST user2 This is v2 \n" + + "\n"; + + Assert.assertEquals(expected, resultOut); + } +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowsResult.java new file mode 100644 index 0000000000..bc0bd060cf --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/TestVersionedFlowsResult.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result; + +import org.apache.nifi.registry.flow.VersionedFlow; +import org.apache.nifi.toolkit.cli.api.ResultType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class TestVersionedFlowsResult { + + private ByteArrayOutputStream outputStream; + private PrintStream printStream; + + @Before + public void setup() { + this.outputStream = new ByteArrayOutputStream(); + this.printStream = new PrintStream(outputStream, true); + } + + @Test + public void testWriteSimpleVersionedFlowsResult() throws IOException { + final VersionedFlow f1 = new VersionedFlow(); + f1.setName("Flow 1"); + f1.setDescription("This is flow 1"); + f1.setIdentifier(UUID.fromString("ea752054-22c6-4fc0-b851-967d9a3837cb").toString()); + + final VersionedFlow f2 = new VersionedFlow(); + f2.setName("Flow 2"); + f2.setDescription(null); + f2.setIdentifier(UUID.fromString("ddf5f289-7502-46df-9798-4b0457c1816b").toString()); + + final List flows = new ArrayList<>(); + flows.add(f1); + flows.add(f2); + + final VersionedFlowsResult result = new VersionedFlowsResult(ResultType.SIMPLE, flows); + result.write(printStream); + + final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(resultOut); + + final String expected = "\n" + + "# Name Id Description \n" + + "- ------ ------------------------------------ -------------- \n" + + "1 Flow 1 ea752054-22c6-4fc0-b851-967d9a3837cb This is flow 1 \n" + + "2 Flow 2 ddf5f289-7502-46df-9798-4b0457c1816b (empty) \n" + + "\n"; + + Assert.assertEquals(expected, resultOut); + } + +} diff --git a/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/writer/TestDynamicTableWriter.java b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/writer/TestDynamicTableWriter.java new file mode 100644 index 0000000000..49e9a64e70 --- /dev/null +++ b/nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/result/writer/TestDynamicTableWriter.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.nifi.toolkit.cli.impl.result.writer; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +public class TestDynamicTableWriter { + + private Table table; + private TableWriter tableWriter; + + private ByteArrayOutputStream outputStream; + private PrintStream printStream; + + @Before + public void setup() { + this.table = new Table.Builder() + .column("#", 3, 3, false) + .column("Name", 20, 36, true) + .column("Id", 36, 36, false) + .column("Description", 11, 40, true) + .build(); + + this.tableWriter = new DynamicTableWriter(); + + this.outputStream = new ByteArrayOutputStream(); + this.printStream = new PrintStream(outputStream, true); + } + + @Test + public void testWriteEmptyTable() { + tableWriter.write(table, printStream); + + final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(result); + + final String expected = "\n" + + "# Name Id Description \n" + + "--- -------------------- ------------------------------------ ----------- \n" + + "\n"; + + Assert.assertEquals(expected, result); + } + + @Test + public void testDynamicTableWriter() { + table.addRow( + "1", + "Bucket 1", + "12345-12345-12345-12345-12345-12345", + "" + ); + + table.addRow( + "2", + "Bucket 2 - This is a really really really long name", + "12345-12345-12345-12345-12345-12345", + "This is a really really really really really really really really really really long description" + ); + + table.addRow( + "3", + "Bucket 3", + "12345-12345-12345-12345-12345-12345", + null + ); + + tableWriter.write(table, printStream); + + final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(result); + + final String expected = "\n" + + "# Name Id Description \n" + + "- ------------------------------------ ----------------------------------- ---------------------------------------- \n" + + "1 Bucket 1 12345-12345-12345-12345-12345-12345 \n" + + "2 Bucket 2 - This is a really reall... 12345-12345-12345-12345-12345-12345 This is a really really really really... \n" + + "3 Bucket 3 12345-12345-12345-12345-12345-12345 (empty) \n" + + "\n"; + + Assert.assertEquals(expected, result); + } + + @Test + public void testWhenAllDescriptionsAreEmpty() { + table.addRow("1", "Bucket 1", "12345-12345-12345-12345-12345-12345", null); + table.addRow("2", "Bucket 2", "12345-12345-12345-12345-12345-12345", null); + tableWriter.write(table, printStream); + + final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + //System.out.println(result); + + final String expected ="\n" + + "# Name Id Description \n" + + "- -------- ----------------------------------- ----------- \n" + + "1 Bucket 1 12345-12345-12345-12345-12345-12345 (empty) \n" + + "2 Bucket 2 12345-12345-12345-12345-12345-12345 (empty) \n" + + "\n"; + + Assert.assertEquals(expected, result); + } + +} \ No newline at end of file