NIFI-4839 - Added abbreviation in simple output for name, description, and comments

- Refactored so that commands produce a result which can then be written or used
- Added support for back-referencing results, initially prototyped by Andrew Grande
- Fixed dynamic table layout when writing simple results
- Added a new command group called 'demo' with a new 'quick-import' command
- Fixes/improvements after previous refactoring
- Created a reusable TableWriter and updating a few result classes to use it
This commit is contained in:
Bryan Bende 2018-02-12 14:19:12 -05:00 committed by Pierre Villard
parent cc3c1b1714
commit b68eebd429
85 changed files with 2681 additions and 858 deletions

View File

@ -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<String> FILE_COMPLETION_VARS;
static {
final Set<String> 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);

View File

@ -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();
}

View File

@ -22,7 +22,7 @@ import org.apache.commons.cli.Options;
/**
* Represents a command to execute.
*/
public interface Command {
public interface Command<R extends Result> {
/**
* 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<R> getResultImplType();
/**
* @return true if the type of result produced is considered Referenceable
*/
default boolean isReferencable() {
return Referenceable.class.isAssignableFrom(getResultImplType());
}
}

View File

@ -36,6 +36,4 @@ public interface Context {
boolean isInteractive();
ResultWriter getResultWriter(ResultType resultType);
}

View File

@ -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();
}

View File

@ -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);
}

View File

@ -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 <T> the type of result
*/
public interface Result<T> {
/**
* @return the result of a command
*/
T getResult();
}

View File

@ -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<Bucket> buckets, PrintStream output) throws IOException;
void writeBucket(Bucket bucket, PrintStream output) throws IOException;
void writeFlows(List<VersionedFlow> versionedFlows, PrintStream output) throws IOException;
void writeFlow(VersionedFlow versionedFlow, PrintStream output) throws IOException;
void writeSnapshotMetadata(List<VersionedFlowSnapshotMetadata> 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<ProcessGroupEntity> processGroupEntities, PrintStream output) throws IOException;
void writeCurrentUser(CurrentUserEntity currentUserEntity, PrintStream output) throws IOException;
void writeCurrentUser(CurrentUser currentUser, PrintStream output) throws IOException;
}

View File

@ -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 <T> the type of result
*/
public interface WritableResult<T> extends Result<T> {
/**
* 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;
}

View File

@ -97,7 +97,6 @@ public class NiFiRegistryClientFactory implements ClientFactory<NiFiRegistryClie
// if a proxied entity was specified then return a wrapped client, otherwise return the regular client
if (!StringUtils.isBlank(proxiedEntity)) {
System.out.println("Creating client for proxied entity: " + proxiedEntity);
return new ProxiedNiFiRegistryClient(client, proxiedEntity);
} else {
return client;

View File

@ -24,8 +24,8 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.nifi.toolkit.cli.api.Command;
import org.apache.nifi.toolkit.cli.api.Context;
import org.apache.nifi.toolkit.cli.api.Result;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.api.ResultWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
@ -34,37 +34,47 @@ import java.util.Properties;
/**
* Base class for all commands.
*/
public abstract class AbstractCommand implements Command {
public abstract class AbstractCommand<R extends Result> implements Command<R> {
private final String name;
private final Class<R> resultClass;
private final Options options;
private Context context;
private PrintStream output;
public AbstractCommand(final String name) {
public AbstractCommand(final String name, final Class<R> 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<R> 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())) {

View File

@ -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();

View File

@ -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<R extends Result> extends AbstractCommand<R> {
public AbstractPropertyCommand(String name) {
super(name);
public AbstractPropertyCommand(final String name, final Class<R> 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;
}

View File

@ -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<CommandGroup> groups = new ArrayList<>();
groups.add(new NiFiRegistryCommandGroup());
groups.add(new NiFiCommandGroup());
groups.add(new DemoCommandGroup());
groups.add(new SessionCommandGroup());
final Map<String,CommandGroup> groupMap = new TreeMap<>();

View File

@ -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),

View File

@ -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<String,Command> topLevelCommands;
private final Map<String,CommandGroup> commandGroups;
private final Context context;
private final PrintStream out;
private final AtomicReference<ReferenceResolver> backReferenceHolder = new AtomicReference<>(null);
public CommandProcessor(final Map<String,Command> topLevelCommands, final Map<String,CommandGroup> 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();
}
}
}
}

View File

@ -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<R extends Result> extends AbstractCommand<R> {
public AbstractCompositeCommand(final String name, final Class<R> 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<NiFiClient> 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<NiFiRegistryClient> 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;
}

View File

@ -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<Command> createCommands() {
final List<Command> commands = new ArrayList<>();
commands.add(new QuickImport());
return commands;
}
}

View File

@ -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<StringResult> {
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;
}
}

View File

@ -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<VoidResult> {
@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<VoidResult> getResultImplType() {
return VoidResult.class;
}
}

View File

@ -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<VoidResult> {
@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<VoidResult> getResultImplType() {
return VoidResult.class;
}
}

View File

@ -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<R extends Result> extends AbstractPropertyCommand<R> {
public AbstractNiFiCommand(final String name) {
super(name);
public AbstractNiFiCommand(final String name, final Class<R> 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<NiFiClient> 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;

View File

@ -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<CurrentUserEntityResult> {
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);
}
}

View File

@ -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<StringResult> {
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());
}
}

View File

@ -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<VoidResult> {
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)

View File

@ -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<VersionedFlowSnapshotMetadataSetResult> {
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);
}
}

View File

@ -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<VariableRegistryResult> {
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);
}
}

View File

@ -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<VersionControlInfoResult> {
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);
}
}

View File

@ -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<StringResult> {
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());
}
}

View File

@ -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<ProcessGroupsResult> {
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);
}
}

View File

@ -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<VoidResult> {
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();
}
}

View File

@ -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<VoidResult> {
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();
}
}

View File

@ -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<VoidResult> {
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();
}
}

View File

@ -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<StringResult> {
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());
}
}

View File

@ -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<RegistryClientIDResult> {
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);
}
}

View File

@ -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<RegistryClientsResult> {
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);
}
}

View File

@ -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<VoidResult> {
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();
}
}

View File

@ -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<R extends Result> extends AbstractPropertyCommand<R> {
public AbstractNiFiRegistryCommand(final String name) {
super(name);
public AbstractNiFiRegistryCommand(final String name, final Class<R> 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<NiFiRegistryClient> 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;
/*

View File

@ -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<StringResult> {
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());
}
}

View File

@ -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<VoidResult> {
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();
}
}
}

View File

@ -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<BucketsResult> {
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<Bucket> buckets = client.getBucketClient().getAll();
final ResultWriter resultWriter = getResultWriter(properties);
resultWriter.writeBuckets(buckets, getContext().getOutput());
return new BucketsResult(getResultType(properties), buckets);
}
}

View File

@ -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<StringResult> {
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());
}
}

View File

@ -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<VoidResult> {
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();
}
}
}

View File

@ -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<VersionedFlowSnapshotResult> {
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);
}
}

View File

@ -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<StringResult> {
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()));
}
}

View File

@ -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<VersionedFlowSnapshotMetadataResult> {
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<VersionedFlowSnapshotMetadata> snapshotMetadata = snapshotClient.getSnapshotMetadata(bucket, flow);
final ResultWriter resultWriter = getResultWriter(properties);
resultWriter.writeSnapshotMetadata(snapshotMetadata, getContext().getOutput());
return new VersionedFlowSnapshotMetadataResult(getResultType(properties), snapshotMetadata);
}
}

View File

@ -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<VersionedFlowsResult> {
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<VersionedFlow> flows = flowClient.getByBucket(bucketId);
final ResultWriter resultWriter = getResultWriter(properties);
resultWriter.writeFlows(flows, getContext().getOutput());
return new VersionedFlowsResult(getResultType(properties), flows);
}
}

View File

@ -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<CurrentUserResult> {
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);
}
}

View File

@ -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<VoidResult> {
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);
}

View File

@ -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<StringResult> {
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);

View File

@ -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<VoidResult> {
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);
}

View File

@ -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<VoidResult> {
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);
}

View File

@ -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<VoidResult> {
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();
}
}

View File

@ -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<VoidResult> {
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);
}

View File

@ -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<ResultType,ResultWriter> 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<NiFiClient> niFiClientFactory;
@ -109,7 +81,6 @@ public class StandardContext implements Context {
private Session session;
private PrintStream output;
private boolean isInteractive;
private Map<ResultType,ResultWriter> resultWriters = new HashMap<>();
public Builder nifiClientFactory(final ClientFactory<NiFiClient> 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);
}

View File

@ -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 <T> the type of results
*/
public abstract class AbstractWritableResult<T> implements WritableResult<T> {
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);
}
}

View File

@ -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<List<Bucket>> implements Referenceable {
private final List<Bucket> buckets;
public BucketsResult(final ResultType resultType, final List<Bucket> 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<Bucket> 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<Integer,Bucket> 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();
}
};
}
}

View File

@ -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<CurrentUserEntity> {
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());
}
}

View File

@ -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<CurrentUser> {
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());
}
}

View File

@ -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<Bucket> 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<VersionedFlow> 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<VersionedFlowSnapshotMetadata> 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<ProcessGroupEntity> 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);
}
}

View File

@ -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<List<ProcessGroupEntity>> {
private final List<ProcessGroupEntity> processGroupEntities;
public ProcessGroupsResult(final ResultType resultType, final List<ProcessGroupEntity> processGroupEntities) {
super(resultType);
this.processGroupEntities = processGroupEntities;
Validate.notNull(this.processGroupEntities);
}
@Override
public List<ProcessGroupEntity> getResult() {
return processGroupEntities;
}
@Override
protected void writeSimpleResult(final PrintStream output) {
final List<ProcessGroupDTO> 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()));
}
}

View File

@ -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<RegistryDTO> {
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;
}
}

View File

@ -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<RegistryClientsEntity> {
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<RegistryClientEntity> clients = registryClients.getRegistries();
if (clients == null || clients.isEmpty()) {
return;
}
final List<RegistryDTO> 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);
}
}

View File

@ -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<Bucket> 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<Bucket>
if (bucket == null) {
return;
}
output.println(bucket.getName() + " - " + bucket.getIdentifier());
}
@Override
public void writeFlows(List<VersionedFlow> 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<VersionedFlowSnapshotMetadata> 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, %<tb %<td %<tY %<tR %<tZ";
final int dateLength = String.format(datePattern, new Date()).length();
// anticipating LDAP long entries
final int authorLength = versions.stream().mapToInt(v -> 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<RegistryClientEntity> clients = clientsEntity.getRegistries();
if (clients == null || clients.isEmpty()) {
return;
}
output.println();
final List<RegistryDTO> 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<VariableDTO> 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<VersionedFlowSnapshotMetadataEntity> entities = versionedFlowSnapshotMetadataSetEntity.getVersionedFlowSnapshotMetadataSet();
if (entities == null || entities.isEmpty()) {
return;
}
final List<VersionedFlowSnapshotMetadata> 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<ProcessGroupEntity> processGroupEntities, PrintStream output) throws IOException {
if (processGroupEntities == null) {
return;
}
final List<ProcessGroupDTO> 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());
}
}

View File

@ -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<String> {
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);
}
}

View File

@ -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<VariableRegistryEntity> {
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<VariableDTO> 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()));
}
}

View File

@ -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<VersionControlInformationEntity> {
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());
}
}

View File

@ -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<List<VersionedFlowSnapshotMetadata>> {
private final List<VersionedFlowSnapshotMetadata> versions;
public VersionedFlowSnapshotMetadataResult(final ResultType resultType, final List<VersionedFlowSnapshotMetadata> versions) {
super(resultType);
this.versions = versions;
Validate.notNull(this.versions);
this.versions.sort(Comparator.comparing(VersionedFlowSnapshotMetadata::getVersion));
}
@Override
public List<VersionedFlowSnapshotMetadata> 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, %<tb %<td %<tY %<tR %<tZ";
final int dateLength = String.format(datePattern, new Date()).length();
final Table table = new Table.Builder()
.column("Ver", 3, 3, false)
.column("Date", dateLength, dateLength, false)
.column("Author", 20, 200, true)
.column("Message", 8, 40, true)
.build();
versions.forEach(vfs -> {
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);
}
}

View File

@ -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<VersionedFlowSnapshotMetadataSetEntity> {
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<VersionedFlowSnapshotMetadataEntity> entities = versionedFlowSnapshotMetadataSetEntity.getVersionedFlowSnapshotMetadataSet();
if (entities == null || entities.isEmpty()) {
return;
}
final List<VersionedFlowSnapshotMetadata> snapshots = entities.stream()
.map(v -> v.getVersionedFlowSnapshotMetadata()).collect(Collectors.toList());
final WritableResult<List<VersionedFlowSnapshotMetadata>> result = new VersionedFlowSnapshotMetadataResult(resultType, snapshots);
result.write(output);
}
}

View File

@ -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<VersionedFlowSnapshot> {
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);
}
}
}

View File

@ -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<List<VersionedFlow>> implements Referenceable {
private final List<VersionedFlow> versionedFlows;
public VersionedFlowsResult(final ResultType resultType, final List<VersionedFlow> 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<VersionedFlow> 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<Integer,VersionedFlow> 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();
}
};
}
}

View File

@ -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 {
}

View File

@ -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<Void> {
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;
}
}

View File

@ -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<TableColumn> columns = table.getColumns();
final List<String[]> rows = table.getRows();
final int numColumns = columns.size();
final Integer[] columnLengths = determineColumnLengths(columns, rows);
final List<String> 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<TableColumn> columns, final List<String[]> 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;
}
}

View File

@ -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<TableColumn> columns;
private final List<String[]> 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<TableColumn> getColumns() {
return columns;
}
public List<String[]> getRows() {
return rows;
}
/**
* Builder for a Table.
*/
public static class Builder {
private final List<TableColumn> 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);
}
}
}

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -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<String> getAllVariableNames() {
final List<String> names = new ArrayList<>();
for (SessionVariables variable : values()) {
for (SessionVariable variable : values()) {
names.add(variable.getVariableName());
}
return names;

View File

@ -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<String,Command> commands = CommandFactory.createTopLevelCommands(context);

View File

@ -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<String,Command> commands = CommandFactory.createTopLevelCommands(context);
@ -195,7 +190,7 @@ public class TestCLICompleter {
final List<Candidate> 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);

View File

@ -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<Bucket> 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);
}
}

View File

@ -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<RegistryClientEntity> 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);
}
}

View File

@ -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<VersionedFlowSnapshotMetadata> 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);
}
}

View File

@ -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<VersionedFlow> 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);
}
}

View File

@ -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);
}
}