</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
</project>
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
/**
- * The top level cli state that dispatches command executions
+ * The top level cli state that dispatches command executions.
*/
public class Cli implements Runnable {
private final CommandDispatcher commandRegistry;
private final ConsoleIO consoleIO;
public Cli(final ConsoleIO consoleIO, final CommandDispatcher commandRegistry,
- final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContextRegistry schemaContextRegistry) {
+ final CommandArgHandlerRegistry argumentHandlerRegistry,
+ final SchemaContextRegistry schemaContextRegistry) {
this.consoleIO = consoleIO;
this.commandRegistry = commandRegistry;
this.argumentHandlerRegistry = argumentHandlerRegistry;
// FIXME move custom writer to GenericWriter/Serializers ...
// this checks only first level
- final Optional<Class<? extends Writer<DataSchemaNode>>> customReaderClassOpt = tryGetCustomHandler(schemaNode);
+ final Optional<Class<? extends Writer<DataSchemaNode>>> customReaderClassOpt = tryGetCustomHandler(
+ schemaNode);
if (customReaderClassOpt.isPresent()) {
final Writer<DataSchemaNode> customReaderInstance = argumentHandlerRegistry
try {
final Class<?> argumentClass = Class.forName(argumentHandlerClassName);
// TODO add check before cast
- return Optional.<Class<? extends T>> of((Class<? extends T>) argumentClass);
+ return Optional.of((Class<? extends T>) argumentClass);
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Unknown custom reader class " + argumentHandlerClassName
+ " for: " + dataSchemaNode.getQName());
private final Completer completer;
- public RootConsoleContext(final CommandDispatcher commandRegistry) {
+ RootConsoleContext(final CommandDispatcher commandRegistry) {
completer = new CommandCompleter(commandRegistry);
}
private final CommandDispatcher commandRegistry;
- public CommandCompleter(final CommandDispatcher commandRegistry) {
+ CommandCompleter(final CommandDispatcher commandRegistry) {
this.commandRegistry = commandRegistry;
}
return new GenericReader(consoleIO, this, schemaContext, readConfigNode);
}
- public synchronized Writer<DataSchemaNode> getCustomWriter(final Class<? extends Writer<DataSchemaNode>> writerType) {
- return customWriters.get(writerType).provide(consoleIO, getRemoteSchema(writerType, schemaContextRegistry),
- this);
+ public synchronized Writer<DataSchemaNode> getCustomWriter(
+ final Class<? extends Writer<DataSchemaNode>> writerType) {
+ return customWriters.get(writerType).provide(
+ consoleIO, getRemoteSchema(writerType, schemaContextRegistry), this);
}
public synchronized Writer<DataSchemaNode> getGenericWriter() {
}
/**
- * Reader providers, in order to construct readers lazily
+ * Reader providers, in order to construct readers lazily.
*/
- private static interface ReaderProvider {
+ private interface ReaderProvider {
Reader<? extends DataSchemaNode> provide(ConsoleIO consoleIO,
final CommandArgHandlerRegistry commandArgHandlerRegistry,
final SchemaContextRegistry schemaContextRegistry);
}
/**
- * Writer providers, in order to construct readers lazily
+ * Writer providers, in order to construct readers lazily.
*/
- private static interface WriterProvider {
+ private interface WriterProvider {
Writer<DataSchemaNode> provide(ConsoleIO consoleIO, SchemaContext schema,
final CommandArgHandlerRegistry commandArgHandlerRegistry);
}
/**
* Parse arguments, start remote device connection and start CLI after the
- * connection is fully up
+ * connection is fully up.
*/
public class Main {
+ @SuppressWarnings("illegalCatch")
public static void main(final String[] args) {
final CliArgumentParser cliArgs = new CliArgumentParser();
try {
commandDispatcher.addLocalCommands(connectionManager, localSchema, cliArgs.getConnectionTimeoutMs());
switch (cliArgs.connectionArgsPresent()) {
- case TCP: {
- // FIXME support pure TCP
- handleRunningException(new UnsupportedOperationException("PURE TCP CONNECTIONS ARE NOT SUPPORTED YET, USE SSH INSTEAD BY PROVIDING USERNAME AND PASSWORD AS WELL"));
- return;
- }
- case SSH: {
- writeStatus(consoleIO, "Connecting to %s via SSH. Please wait.", cliArgs.getAddress());
- connectionManager.connectBlocking(cliArgs.getAddress(), cliArgs.getServerAddress(), getClientSshConfig(cliArgs));
- break;
- }
- case NONE: {/* Do not connect initially */
- writeStatus(consoleIO, "No initial connection. To connect use the connect command");
- }
+ case TCP:
+ // FIXME support pure TCP
+ handleRunningException(new UnsupportedOperationException(
+ "PURE TCP CONNECTIONS ARE NOT SUPPORTED YET, "
+ + "USE SSH INSTEAD BY PROVIDING USERNAME AND PASSWORD AS WELL"));
+ return;
+ case SSH:
+ writeStatus(consoleIO, "Connecting to %s via SSH. Please wait.", cliArgs.getAddress());
+ connectionManager.connectBlocking(cliArgs.getAddress(), cliArgs.getServerAddress(),
+ getClientSshConfig(cliArgs));
+ break;
+ case NONE:
+ /* Do not connect initially */
+ writeStatus(consoleIO, "No initial connection. To connect use the connect command");
+ break;
+ default:
+ // NOOP
+ break;
}
try {
.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
}
- private static void handleStartupException(final IOException e) {
- handleException(e, "Unable to initialize CLI");
+ private static void handleStartupException(final IOException exc) {
+ handleException(exc, "Unable to initialize CLI");
}
- private static void handleException(final Exception e, final String message) {
- System.console().writer().println(String.format("Error %s cause %s", message, getStackTraceAsString(e.fillInStackTrace())));
+ private static void handleException(final Exception exc, final String message) {
+ System.console().writer().println(
+ String.format("Error %s cause %s", message, getStackTraceAsString(exc.fillInStackTrace())));
}
private static void writeStatus(final ConsoleIO io, final String blueprint, final Object... args) {
}
}
- private static void handleRunningException(final Exception e) {
- handleException(e, "Unexpected CLI runtime exception");
+ private static void handleRunningException(final Exception exc) {
+ handleException(exc, "Unexpected CLI runtime exception");
}
private static final class CliArgumentParser {
private final ArgumentParser parser;
private Namespace parsed;
+ @SuppressWarnings("checkstyle:lineLength")
private CliArgumentParser() {
parser = ArgumentParsers.newArgumentParser("Netconf cli").defaultHelp(true)
.description("Generic cli for netconf devices")
- .usage("Submit address + port for initial TCP connection (PURE TCP CONNECTIONS ARE NOT SUPPORTED YET)\n" +
- "Submit username + password in addition to address + port for initial SSH connection\n" +
- "If no arguments(or unexpected combination) is submitted, cli will be started without initial connection\n" +
- "To use with ODL controller, run with: java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar --server localhost --port 1830 --username admin --password admin");
+ .usage("Submit address + port for initial TCP connection (PURE TCP CONNECTIONS ARE NOT SUPPORTED YET)\n"
+ + "Submit username + password in addition to address + port for initial SSH connection\n"
+ + "If no arguments(or unexpected combination) is submitted, cli will be started without initial connection\n"
+ + "To use with ODL controller, run with: java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar --server localhost --port 1830 --username admin --password admin");
final ArgumentGroup tcpGroup = parser.addArgumentGroup("TCP")
.description("Base arguments to initiate TCP connection right away");
tcpGroup.addArgument("--" + CONNECT_TIMEOUT)
.type(Integer.class)
.setDefault(DEFAULT_CONNECTION_TIMEOUT_MS)
- .help("Timeout(in ms) for connection to succeed, if the connection is not fully established by the time is up, " +
- "connection attempt is considered a failure. This attribute is not working as expected yet");
+ .help("Timeout(in ms) for connection to succeed, if the connection is not fully established by the time is up, "
+ + "connection attempt is considered a failure. This attribute is not working as expected yet");
final ArgumentGroup sshGroup = parser.addArgumentGroup("SSH")
.description("SSH credentials, if provided, initial connection will be attempted using SSH");
}
public InitialConnectionType connectionArgsPresent() {
- if(getAddress() != null && getPort() != null) {
- if(getUsername() != null && getPassword() != null) {
+ if (getAddress() != null && getPort() != null) {
+ if (getUsername() != null && getPassword() != null) {
return InitialConnectionType.SSH;
}
return InitialConnectionType.TCP;
}
/**
+ * Check if device is up.
+ *
* @return true if connection was fully established
*/
public synchronized boolean isUp() {
}
@Override
- public void onNotification(DOMNotification domNotification) {
-
- }
+ public void onNotification(DOMNotification domNotification) {}
@Override
public void close() {
import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
/**
- * Manages connect/disconnect to 1 remote device
+ * Manages connect/disconnect to 1 remote device.
*/
public class NetconfDeviceConnectionManager implements Closeable {
// TODO we receive configBuilder in order to add SessionListener, Session
// Listener should not be part of config
- public synchronized void connect(final String name, final InetSocketAddress address, final NetconfClientConfigurationBuilder configBuilder) {
+ public synchronized void connect(final String name, final InetSocketAddress address,
+ final NetconfClientConfigurationBuilder configBuilder) {
// TODO change IllegalState exceptions to custom ConnectionException
Preconditions.checkState(listener == null, "Already connected");
console, name);
final SharedSchemaRepository repository = new SharedSchemaRepository("repo");
- final SchemaContextFactory schemaContextFactory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
- final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(repository, YangTextSchemaSource.class, new File(CACHE));
+ final SchemaContextFactory schemaContextFactory = repository
+ .createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
+ final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
+ repository, YangTextSchemaSource.class, new File(CACHE));
repository.registerSchemaSourceListener(cache);
repository.registerSchemaSourceListener(TextToASTTransformer.create(repository, repository));
- final SchemaResourcesDTO schemaResourcesDTO = new SchemaResourcesDTO(repository, repository, schemaContextFactory, new NetconfStateSchemasResolverImpl());
+ final SchemaResourcesDTO schemaResourcesDTO = new SchemaResourcesDTO(
+ repository, repository, schemaContextFactory, new NetconfStateSchemasResolverImpl());
device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
}
/**
- * Blocks thread until connection is fully established
+ * Blocks thread until connection is fully established.
*/
- public synchronized Set<String> connectBlocking(final String name, final InetSocketAddress address, final NetconfClientConfigurationBuilder configBuilder) {
+ public synchronized Set<String> connectBlocking(final String name, final InetSocketAddress address,
+ final NetconfClientConfigurationBuilder configBuilder) {
this.connect(name, address, configBuilder);
synchronized (handler) {
while (handler.isUp() == false) {
/**
* Contains the local schema context (containing local commands) and remote schema context (remote commands)
*
+ * <p>
* Remote commands are set only after the connection is fully established. So classes using the remote schema context
*/
public class SchemaContextRegistry {
public abstract class AbstractCommand implements Command {
- private final QName qName;
+ private final QName qualifiedName;
private final InputDefinition args;
private final OutputDefinition output;
private final String description;
- public AbstractCommand(final QName qName, final InputDefinition args, final OutputDefinition output,
+ public AbstractCommand(final QName qualifiedName, final InputDefinition args, final OutputDefinition output,
final String description) {
- this.qName = qName;
+ this.qualifiedName = qualifiedName;
this.args = args;
this.output = output;
this.description = description;
return output != null ? OutputDefinition.fromOutput(output) : OutputDefinition.empty();
}
+ @Override
+ public OutputDefinition getOutputDefinition() {
+ return output;
+ }
+
protected static InputDefinition getInputDefinition(final RpcDefinition rpcDefinition) {
final ContainerSchemaNode input = rpcDefinition.getInput();
return InputDefinition.fromInput(input);
return args;
}
- @Override
- public OutputDefinition getOutputDefinition() {
- return output;
- }
-
@Override
public QName getCommandId() {
- return qName;
+ return qualifiedName;
}
@Override
@Override
public Optional<String> getPrompt() {
- return Optional.of(qName.getLocalName());
+ return Optional.of(qualifiedName.getLocalName());
}
};
}
// Local command ids are defined here, this links the implementation to the rpc definition in yang
// Better way needs to be found to provide this link instead of hardcoded QNames (e.g. yang extension)
- public static final QName HELP_QNAME = QName.create(URI.create("netconf:cli"), IOUtil.parseDate("2014-05-22"), "help");
+ public static final QName HELP_QNAME = QName.create(
+ URI.create("netconf:cli"), IOUtil.parseDate("2014-05-22"), "help");
public static final QName CLOSE_QNAME = QName.create(HELP_QNAME, "close");
public static final QName CONNECT_QNAME = QName.create(HELP_QNAME, "connect");
public static final QName DISCONNECT_QNAME = QName.create(CONNECT_QNAME, "disconnect");
public synchronized Optional<Command> getCommand(final String nameWithModule) {
final QName commandQName = mergeCommandIds().get(nameWithModule);
final Map<QName, Command> qNameCommandMap = mergeCommands();
- if(commandQName == null || qNameCommandMap.containsKey(commandQName) == false) {
+ if (commandQName == null || qNameCommandMap.containsKey(commandQName) == false) {
return Optional.absent();
}
return Optional.of(qNameCommandMap.get(commandQName));
}
- public synchronized Optional<Command> getCommand(final QName qName) {
- return Optional.fromNullable(mergeCommands().get(qName));
+ public synchronized Optional<Command> getCommand(final QName qualifiedName) {
+ return Optional.fromNullable(mergeCommands().get(qualifiedName));
}
- private static Optional<Command> getCommand(final Map<String, QName> commandNameMap, final Map<QName, Command> commands, final String nameWithModule) {
+ private static Optional<Command> getCommand(final Map<String, QName> commandNameMap,
+ final Map<QName, Command> commands, final String nameWithModule) {
final QName qName = commandNameMap.get(nameWithModule);
- if(qName == null)
+ if (qName == null) {
return Optional.absent();
-
+ }
final Command command = commands.get(qName);
- if(command == null) {
+ if (command == null) {
return Optional.absent();
}
return Optional.of(command);
}
- public static final Collection<String> BASE_NETCONF_SCHEMA_PATHS = Lists.newArrayList("/schema/remote/ietf-netconf.yang",
- "/schema/common/netconf-cli-ext.yang", "/schema/common/ietf-inet-types.yang");
+ public static final Collection<String> BASE_NETCONF_SCHEMA_PATHS = Lists.newArrayList(
+ "/schema/remote/ietf-netconf.yang",
+ "/schema/common/netconf-cli-ext.yang",
+ "/schema/common/ietf-inet-types.yang");
public synchronized void addRemoteCommands(final DOMRpcService rpcService, final SchemaContext remoteSchema) {
this.addRemoteCommands(rpcService, remoteSchema, parseSchema(BASE_NETCONF_SCHEMA_PATHS));
}
- public synchronized void addRemoteCommands(final DOMRpcService rpcService, final SchemaContext remoteSchema, final SchemaContext baseNetconfSchema) {
+ public synchronized void addRemoteCommands(final DOMRpcService rpcService, final SchemaContext remoteSchema,
+ final SchemaContext baseNetconfSchema) {
for (final SchemaContext context : Lists.newArrayList(remoteSchema, baseNetconfSchema)) {
for (final Module module : context.getModules()) {
for (final RpcDefinition rpcDefinition : module.getRpcs()) {
nameToQNameRemote.clear();
}
- public static final Collection<String> LOCAL_SCHEMA_PATHS = Lists.newArrayList("/schema/local/netconf-cli.yang", "/schema/common/netconf-cli-ext.yang",
- "/schema/common/ietf-inet-types.yang");
+ public static final Collection<String> LOCAL_SCHEMA_PATHS = Lists.newArrayList(
+ "/schema/local/netconf-cli.yang",
+ "/schema/common/netconf-cli-ext.yang",
+ "/schema/common/ietf-inet-types.yang");
- public synchronized void addLocalCommands(final NetconfDeviceConnectionManager connectionManager, final SchemaContext localSchema, final Integer connectionTimeout) {
+ public synchronized void addLocalCommands(final NetconfDeviceConnectionManager connectionManager,
+ final SchemaContext localSchema, final Integer connectionTimeout) {
for (final Module module : localSchema.getModules()) {
for (final RpcDefinition rpcDefinition : module.getRpcs()) {
} else if (rpcDefinition.getQName().equals(CommandConstants.DISCONNECT_QNAME)) {
localCommand = Disconnect.create(rpcDefinition, connectionManager);
} else {
- throw new IllegalStateException("No command implementation available for local command: " + rpcDefinition.getQName());
+ throw new IllegalStateException(
+ "No command implementation available for local command: " + rpcDefinition.getQName());
}
localCommands.put(localCommand.getCommandId(), localCommand);
new Function<String, InputStream>() {
@Override
public InputStream apply(final String input) {
- final InputStream resourceAsStream = NetconfDeviceConnectionHandler.class.getResourceAsStream(input);
+ final InputStream resourceAsStream = NetconfDeviceConnectionHandler.class
+ .getResourceAsStream(input);
Preconditions.checkNotNull(resourceAsStream, "File %s was null", input);
return resourceAsStream;
}
public class CommandInvocationException extends Exception {
- public CommandInvocationException(final QName qName, final Throwable cause) {
- this("Command " + qName + " invocation failed: " + cause.getMessage(), cause);
+ public CommandInvocationException(final QName qualifiedName, final Throwable cause) {
+ this("Command " + qualifiedName + " invocation failed: " + cause.getMessage(), cause);
}
protected CommandInvocationException(final String message, final Throwable cause) {
public static class CommandTimeoutException extends CommandInvocationException {
- public CommandTimeoutException(final QName qName, final Throwable e) {
- super("Command " + qName + " timed out: " + e.getMessage(), e);
+ public CommandTimeoutException(final QName qualifiedName, final Throwable throwable) {
+ super("Command " + qualifiedName + " timed out: " + throwable.getMessage(), throwable);
}
}
}
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
/**
- * Input arguments for and rpc/command execution
+ * Input arguments for and rpc/command execution.
*/
public class Input {
public Input(final List<NormalizedNode<?, ?>> args) {
// FIXME empty Input should be constructed from static factory method
- if(args.isEmpty()) {
+ if (args.isEmpty()) {
this.args = Collections.emptyList();
return;
}
final NormalizedNode<?, ?> input = args.iterator().next();
- Preconditions.checkArgument(input instanceof DataContainerChild<?, ?>, "Input container has to be of type Data Container Child.");
+ Preconditions.checkArgument(
+ input instanceof DataContainerChild<?, ?>, "Input container has to be of type Data Container Child.");
this.args = new ArrayList<>((Collection<NormalizedNode<?, ?>>) input.getValue());
for (final NormalizedNode<?, ?> arg : this.args) {
/**
* The definition of input arguments represented by schema nodes parsed from
- * yang rpc definition
+ * yang rpc definition.
*/
public class InputDefinition {
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
/**
- * Local command to shut down the cli
+ * Local command to shut down the cli.
*/
public class Close extends AbstractCommand {
- public Close(final QName qName, final InputDefinition args, final OutputDefinition output, final String description) {
- super(qName, args, output, description);
+ public Close(final QName qualifiedName, final InputDefinition args, final OutputDefinition output,
+ final String description) {
+ super(qualifiedName, args, output, description);
}
@Override
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
/**
- * Local command to connect to a remote device
+ * Local command to connect to a remote device.
*/
public class Connect extends AbstractCommand {
private final NetconfDeviceConnectionManager connectManager;
private final Integer connectionTimeout;
- private Connect(final QName qName, final InputDefinition args, final OutputDefinition output,
- final NetconfDeviceConnectionManager connectManager, final String description, final Integer connectionTimeout) {
- super(qName, args, output, description);
+ private Connect(final QName qualifiedName, final InputDefinition args, final OutputDefinition output,
+ final NetconfDeviceConnectionManager connectManager, final String description,
+ final Integer connectionTimeout) {
+ super(qualifiedName, args, output, description);
this.connectManager = connectManager;
this.connectionTimeout = connectionTimeout;
}
return invoke(config, getArgument(inputArgs, "address-name", String.class), inputArgs);
}
- private Output invoke(final NetconfClientConfigurationBuilder config, final String addressName, final Input inputArgs) {
+ private Output invoke(final NetconfClientConfigurationBuilder config,
+ final String addressName, final Input inputArgs) {
final Set<String> remoteCmds = connectManager.connectBlocking(addressName, getAdress(inputArgs), config);
final ArrayList<DataContainerChild<?, ?>> output = Lists.newArrayList();
final String address = getArgument(inputArgs, "address-name", String.class);
final InetSocketAddress inetAddress;
try {
- inetAddress = new InetSocketAddress(InetAddress.getByName(address), getArgument(inputArgs, "address-port", Integer.class));
+ inetAddress = new InetSocketAddress(
+ InetAddress.getByName(address), getArgument(inputArgs, "address-port", Integer.class));
} catch (final UnknownHostException e) {
throw new IllegalArgumentException("Unable to use address: " + address, e);
}
return new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 1000);
}
- public static Command create(final RpcDefinition rpcDefinition, final NetconfDeviceConnectionManager connectManager, final Integer connectionTimeout) {
+ public static Command create(final RpcDefinition rpcDefinition, final NetconfDeviceConnectionManager connectManager,
+ final Integer connectionTimeout) {
return new Connect(rpcDefinition.getQName(), getInputDefinition(rpcDefinition),
getOutputDefinition(rpcDefinition), connectManager, rpcDefinition.getDescription(), connectionTimeout);
}
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
/**
- * Local disconnect command
+ * Local disconnect command.
*/
public class Disconnect extends AbstractCommand {
private final NetconfDeviceConnectionManager connectionManager;
- public Disconnect(final QName qName, final InputDefinition inputDefinition,
+ public Disconnect(final QName qualifiedName, final InputDefinition inputDefinition,
final OutputDefinition outputDefinition, final NetconfDeviceConnectionManager connectionManager,
final String description) {
- super(qName, inputDefinition, outputDefinition, description);
+ super(qualifiedName, inputDefinition, outputDefinition, description);
this.connectionManager = connectionManager;
}
private final CommandDispatcher commandDispatcher;
- public Help(final QName qName, final InputDefinition argsDefinition, final OutputDefinition output, final String description, final CommandDispatcher commandDispatcher) {
- super(qName, argsDefinition, output, description);
+ public Help(final QName qualifiedName, final InputDefinition argsDefinition, final OutputDefinition output,
+ final String description, final CommandDispatcher commandDispatcher) {
+ super(qualifiedName, argsDefinition, output, description);
this.commandDispatcher = commandDispatcher;
}
ImmutableLeafNodeBuilder.create()
.withNodeIdentifier(new NodeIdentifier(QName.create(getCommandId(), "id")))
.withValue(id).build());
- if(description.isPresent()) {
+ if (description.isPresent()) {
nameAndDescription.add(
ImmutableLeafNodeBuilder.create()
.withNodeIdentifier(new NodeIdentifier(QName.create(getCommandId(), "description")))
}
public static Command create(final RpcDefinition rpcDefinition, final CommandDispatcher commandDispatcher) {
- return new Help(rpcDefinition.getQName(), getInputDefinition(rpcDefinition), getOutputDefinition(rpcDefinition), rpcDefinition.getDescription(), commandDispatcher);
+ return new Help(rpcDefinition.getQName(), getInputDefinition(rpcDefinition), getOutputDefinition(rpcDefinition),
+ rpcDefinition.getDescription(), commandDispatcher);
}
}
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
- * Output values for and rpc/command execution
+ * Output values for and rpc/command execution.
*/
public class Output {
final Map<DataSchemaNode, List<NormalizedNode<?, ?>>> mappedNodesToSchema = Maps.newHashMap();
final DataSchemaNode schemaNode = mappedSchemaNodes.get(output.getNodeType().withoutRevision());
- final List<NormalizedNode<?, ?>> list = mappedNodesToSchema.get(schemaNode) == null ? Lists.<NormalizedNode<?, ?>>newArrayList()
- : mappedNodesToSchema.get(schemaNode);
+ final List<NormalizedNode<?, ?>> list = mappedNodesToSchema.get(schemaNode) == null
+ ? Lists.newArrayList() : mappedNodesToSchema.get(schemaNode);
list.add(output);
mappedNodesToSchema.put(schemaNode, list);
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
- * The definition of output elements represented by schema nodes parsed from yang rpc definition
+ * The definition of output elements represented by schema nodes parsed from yang rpc definition.
*/
public class OutputDefinition implements Iterable<DataSchemaNode> {
/**
* Generic remote command implementation that sends the rpc xml to the remote device and waits for response
- * Waiting is limited with TIMEOUT
+ * Waiting is limited with TIMEOUT.
*/
public class RemoteCommand extends AbstractCommand {
private static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
private final DOMRpcService rpcService;
- public RemoteCommand(final QName qName, final InputDefinition args, final OutputDefinition output, final String description, final DOMRpcService rpcService) {
- super(qName, args, output, description);
+ public RemoteCommand(final QName qualifiedName, final InputDefinition args, final OutputDefinition output,
+ final String description, final DOMRpcService rpcService) {
+ super(qualifiedName, args, output, description);
this.rpcService = rpcService;
}
@Override
public Output invoke(final Input inputArgs) throws CommandInvocationException {
- final CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc =
- rpcService.invokeRpc(SchemaPath.create(Collections.singletonList(getCommandId()), true), inputArgs.wrap(getCommandId()));
+ final CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc = rpcService.invokeRpc(
+ SchemaPath.create(Collections.singletonList(getCommandId()), true), inputArgs.wrap(getCommandId()));
try {
return new Output(invokeRpc.get(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT).getResult());
import java.io.IOException;
/**
- * Definition of IO interface
+ * Definition of IO interface.
*/
public interface ConsoleIO {
import org.slf4j.LoggerFactory;
/**
- * Jline based IO implementation
+ * Jline based IO implementation.
*/
public class ConsoleIOImpl implements ConsoleIO {
newPrompt.append(promptPart.get());
}
}
- if (newPrompt.length() ==0) {
+ if (newPrompt.length() == 0) {
newPrompt.append(PATH_SEPARATOR);
}
private class QuestionMarkActionListener implements ActionListener {
@Override
- public void actionPerformed(final ActionEvent e) {
+ public void actionPerformed(final ActionEvent event) {
ConsoleIOImpl.this.complete();
}
}
package org.opendaylight.netconf.cli.io;
import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
public static final String PROMPT_SUFIX = ">";
public static final String PATH_SEPARATOR = "/";
- private IOUtil() {
- }
+ private IOUtil() {}
- public static boolean isQName(final String qName) {
- final Matcher matcher = patternNew.matcher(qName);
+ public static boolean isQName(final String qualifiedName) {
+ final Matcher matcher = PATTERN.matcher(qualifiedName);
return matcher.matches();
}
return "";
}
- public static String qNameToKeyString(final QName qName, final String moduleName) {
- return String.format("%s(%s)", qName.getLocalName(), moduleName);
+ public static String qNameToKeyString(final QName qualifiedName, final String moduleName) {
+ return String.format("%s(%s)", qualifiedName.getLocalName(), moduleName);
}
// TODO test and check regex + review format of string for QName
- final static Pattern patternNew = Pattern.compile("([^\\)]+)\\(([^\\)]+)\\)");
+ static final Pattern PATTERN = Pattern.compile("([^\\)]+)\\(([^\\)]+)\\)");
- public static QName qNameFromKeyString(final String qName, final Map<String, QName> mappedModules)
+ public static QName qNameFromKeyString(final String qualifiedName, final Map<String, QName> mappedModules)
throws ReadingException {
- final Matcher matcher = patternNew.matcher(qName);
+ final Matcher matcher = PATTERN.matcher(qualifiedName);
if (!matcher.matches()) {
- final String message = String.format("QName in wrong format: %s should be: %s", qName, patternNew);
+ final String message = String.format("QName in wrong format: %s should be: %s", qualifiedName, PATTERN);
throw new ReadingException(message);
}
final QName base = mappedModules.get(matcher.group(2));
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
- * marker interface to mark reader which can be used with GenericListReader
+ * Marker interface to mark reader which can be used with GenericListReader.
*/
public interface GenericListEntryReader<T extends DataSchemaNode> extends Reader<T> {
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
- * Generic provider(reader) of input arguments for commands
+ * Generic provider(reader) of input arguments for commands.
*/
public interface Reader<T extends DataSchemaNode> {
private static final long serialVersionUID = -298382323286156591L;
- public ReadingException(final String msg, final Exception e) {
- super(msg, e);
+ public ReadingException(final String msg, final Exception ex) {
+ super(msg, ex);
}
public ReadingException(final String msg) {
// FIXME refactor + unite common code with FilterReader
@Override
- protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+ protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode)
+ throws IOException, ReadingException {
console.writeLn("Config " + schemaNode.getQName().getLocalName());
console.writeLn("Submit path of the data to edit. Use TAB for autocomplete");
List<? extends NormalizedNode<?, ?>> previous = readInnerNode(rawValue);
- for (final QName qName : Lists.reverse(filterPartsQNames).subList(1, filterPartsQNames.size())) {
+ for (final QName qualifiedName : Lists.reverse(filterPartsQNames).subList(1, filterPartsQNames.size())) {
previous = Collections.<NormalizedNode<?, ?>>singletonList(
ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new NodeIdentifier(qName))
- .withValue(previous == null ? Collections.<DataContainerChild<?, ?>>emptyList() : (Collection) previous).build()
+ .withNodeIdentifier(new NodeIdentifier(qualifiedName))
+ .withValue(previous == null ? Collections.emptyList() : (Collection) previous).build()
);
}
return Collections.singletonList(null);
}
- final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = ImmutableContainerNodeBuilder.create();
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = ImmutableContainerNodeBuilder
+ .create();
builder.withNodeIdentifier(new NodeIdentifier(schemaNode.getQName()));
builder.withValue((Collection<DataContainerChild<?, ?>>) previous);
- return Collections.<NormalizedNode<?, ?>> singletonList(builder.build());
+ return Collections.singletonList(builder.build());
}
private List<NormalizedNode<?, ?>> readInnerNode(final String pathString) throws ReadingException {
private final SchemaContext remoteSchemaContext;
- public FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
+ FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
super(schemaNode);
this.remoteSchemaContext = remoteSchemaContext;
}
@Override
protected List<Completer> getAdditionalCompleters() {
- return Collections.<Completer> singletonList(new FilterCompleter(remoteSchemaContext));
+ return Collections.singletonList(new FilterCompleter(remoteSchemaContext));
}
}
private final SchemaContext remoteSchemaContext;
- public FilterCompleter(final SchemaContext remoteSchemaContext) {
+ FilterCompleter(final SchemaContext remoteSchemaContext) {
this.remoteSchemaContext = remoteSchemaContext;
}
// FIXME this could be removed if feature/if-feature are supported
- public EditContentReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContext schemaContext) {
+ public EditContentReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+ final SchemaContext schemaContext) {
super(console, argumentHandlerRegistry, schemaContext);
}
@Override
- public List<NormalizedNode<?, ?>> readWithContext(final ChoiceSchemaNode choiceNode) throws IOException, ReadingException {
- Preconditions.checkState(choiceNode.getQName().equals(EDIT_CONTENT_QNAME), "Unexpected choice %s, expected %s", choiceNode, EDIT_CONTENT_QNAME);
+ public List<NormalizedNode<?, ?>> readWithContext(final ChoiceSchemaNode choiceNode)
+ throws IOException, ReadingException {
+ Preconditions.checkState(choiceNode.getQName().equals(EDIT_CONTENT_QNAME),
+ "Unexpected choice %s, expected %s", choiceNode, EDIT_CONTENT_QNAME);
final ChoiceCaseNode selectedCase = choiceNode.getCaseNodeByName(CONFIG_QNAME);
- Preconditions.checkNotNull(selectedCase, "Unexpected choice %s, expected %s that contains %s", choiceNode, EDIT_CONTENT_QNAME, CONFIG_QNAME);
+ Preconditions.checkNotNull(selectedCase,
+ "Unexpected choice %s, expected %s that contains %s", choiceNode, EDIT_CONTENT_QNAME, CONFIG_QNAME);
return readSelectedCase(selectedCase);
}
public static final String FILTER_TYPE_VALUE_DEFAULT = "subtree";
@Override
- protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+ protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode)
+ throws IOException, ReadingException {
boolean redSuccessfuly = false;
DataContainerChild<?, ?> newNode = null;
do {
DataContainerChild<?, ?> previous = null;
- for (final QName qName : Lists.reverse(filterPartsQNames)) {
- previous = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(qName))
- .withValue(previous == null ? Collections.<DataContainerChild<?, ?>>emptyList()
- : Collections.<DataContainerChild<?, ?>>singletonList(previous)).build();
+ for (final QName qualifiedName : Lists.reverse(filterPartsQNames)) {
+ previous = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new NodeIdentifier(qualifiedName))
+ .withValue(previous == null ? Collections.emptyList()
+ : Collections.singletonList(previous)).build();
}
final Map<QName, String> attributes = Collections.singletonMap(FILTER_TYPE_QNAME,
console.writeLn(message);
}
} while (!redSuccessfuly);
- return Collections.<NormalizedNode<?, ?>> singletonList(newNode);
+ return Collections.singletonList(newNode);
}
@Override
private final SchemaContext remoteSchemaContext;
- public FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
+ FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
super(schemaNode);
this.remoteSchemaContext = remoteSchemaContext;
}
@Override
protected List<Completer> getAdditionalCompleters() {
- return Collections.<Completer> singletonList(new FilterCompleter(remoteSchemaContext));
+ return Collections.singletonList(new FilterCompleter(remoteSchemaContext));
}
}
// TODO add skip to filter completer, better soulution would be to add
// SKIP completer before context completer if possible
- public FilterCompleter(final SchemaContext remoteSchemaContext) {
+ FilterCompleter(final SchemaContext remoteSchemaContext) {
this.remoteSchemaContext = remoteSchemaContext;
}
return Optional.of(parent);
}
- QName qName;
+ QName qualifiedName;
try {
- qName = IOUtil.qNameFromKeyString(part, mappedModules);
+ qualifiedName = IOUtil.qNameFromKeyString(part, mappedModules);
} catch (final ReadingException e) {
return Optional.of(parent);
}
- final DataSchemaNode dataChildByName = parent.getDataChildByName(qName);
+ final DataSchemaNode dataChildByName = parent.getDataChildByName(qualifiedName);
if (dataChildByName instanceof DataNodeContainer) {
parent = (DataNodeContainer) dataChildByName;
} else {
}
@Override
- protected List<NormalizedNode<?, ?>> readWithContext(final AnyXmlSchemaNode schemaNode) throws IOException, ReadingException {
+ protected List<NormalizedNode<?, ?>> readWithContext(final AnyXmlSchemaNode schemaNode)
+ throws IOException, ReadingException {
console.writeLn(listType(schemaNode) + " " + schemaNode.getQName().getLocalName());
final String rawValue = console.read();
.withNodeIdentifier(new NodeIdentifier(schemaNode.getQName()))
.withChild(value.get()).build();
} else {
- newNode = ImmutableLeafNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(schemaNode.getQName())).withValue(rawValue).build();
+ newNode = ImmutableLeafNodeBuilder.create().withNodeIdentifier(
+ new NodeIdentifier(schemaNode.getQName())).withValue(rawValue).build();
}
}
private Optional<DataContainerChild<?, ?>> tryParse(final String rawValue, final AnyXmlSchemaNode schemaNode) {
try {
final Document dom = XmlUtil.readXmlToDocument(rawValue);
- return Optional.<DataContainerChild<?, ?>> of(
- DomToNormalizedNodeParserFactory.
- getInstance(DomUtils.defaultValueCodecProvider(), getSchemaContext()).
- getAnyXmlNodeParser().
- parse(Collections.singletonList(dom.getDocumentElement()), schemaNode)
+ return Optional.of(
+ DomToNormalizedNodeParserFactory
+ .getInstance(DomUtils.defaultValueCodecProvider(), getSchemaContext())
+ .getAnyXmlNodeParser()
+ .parse(Collections.singletonList(dom.getDocumentElement()), schemaNode)
);
} catch (SAXException | IOException e) {
// TODO log
@Override
public List<NormalizedNode<?, ?>> readWithContext(final T schemaNode) throws IOException, ReadingException {
TypeDefinition<?> type = getType(schemaNode);
- console.formatLn("Submit %s %s(%s)", listType(schemaNode), schemaNode.getQName().getLocalName(), type.getQName().getLocalName());
+ console.formatLn("Submit %s %s(%s)", listType(schemaNode), schemaNode.getQName().getLocalName(),
+ type.getQName().getLocalName());
while (baseTypeFor(type) instanceof UnionTypeDefinition) {
final Optional<TypeDefinition<?>> optionalTypeDef = new UnionTypeReader(console).read(type);
return currentCompleter;
}
- private static interface DataHolderCompleter extends Completer {
-
+ private interface DataHolderCompleter extends Completer {
Object resolveValue(String rawValue) throws ReadingException;
}
private final Optional<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> codec;
private final TypeDefinition<?> type;
- public GeneralDataHolderCompleter(final TypeDefinition<?> type) {
+ GeneralDataHolderCompleter(final TypeDefinition<?> type) {
this.type = type;
codec = getCodecForType(type);
}
private static Optional<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> getCodecForType(
final TypeDefinition<?> type) {
if (type != null) {
- return Optional
- .<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> fromNullable(TypeDefinitionAwareCodec
- .from(type));
+ return Optional.fromNullable(TypeDefinitionAwareCodec.from(type));
}
return Optional.absent();
}
+ @SuppressWarnings("illegalCatch")
@Override
public Object resolveValue(final String rawValue) throws ReadingException {
try {
return codec.isPresent() ? codec.get().deserialize(rawValue) : rawValue;
- } catch (final RuntimeException e) {
+ } catch (final Exception e) {
final String message = "It wasn't possible deserialize value " + rawValue + ".";
LOG.error(message, e);
throw new ReadingException(message, e);
private static final class EnumDataHolderCompleter extends GeneralDataHolderCompleter {
- public EnumDataHolderCompleter(final TypeDefinition<?> type) {
+ EnumDataHolderCompleter(final TypeDefinition<?> type) {
super(type);
}
private final BiMap<String, QName> identityMap;
- public IdentityRefDataHolderCompleter(final TypeDefinition<?> type, final SchemaContext schemaContext) {
+ IdentityRefDataHolderCompleter(final TypeDefinition<?> type, final SchemaContext schemaContext) {
super(type);
this.identityMap = getIdentityMap(schemaContext);
}
}
@Override
- public List<NormalizedNode<?, ?>> readWithContext(final ChoiceSchemaNode choiceNode) throws IOException, ReadingException {
+ public List<NormalizedNode<?, ?>> readWithContext(final ChoiceSchemaNode choiceNode)
+ throws IOException, ReadingException {
final Map<String, ChoiceCaseNode> availableCases = collectAllCases(choiceNode);
console.formatLn("Select case for choice %s from: %s", choiceNode.getQName().getLocalName(),
formatSet(availableCases.keySet()));
// leaf without question, since the case was selected
if (containsOnlyOneEmptyLeaf(selectedCase)) {
final NormalizedNode<?, ?> newNode = ImmutableLeafNodeBuilder.create()
- .withNodeIdentifier(new NodeIdentifier(selectedCase.getChildNodes().iterator().next().getQName())).build();
+ .withNodeIdentifier(new NodeIdentifier(selectedCase.getChildNodes().iterator().next().getQName()))
+ .build();
return Collections.<NormalizedNode<?, ?>>singletonList(newNode);
}
return new BaseConsoleContext<ChoiceSchemaNode>(schemaNode) {
@Override
public List<Completer> getAdditionalCompleters() {
- return Collections
- .<Completer> singletonList(new StringsCompleter(collectAllCases(schemaNode).keySet()));
+ return Collections.<Completer>singletonList(
+ new StringsCompleter(collectAllCases(schemaNode).keySet()));
}
};
}
}
@Override
- public List<NormalizedNode<?, ?>> readWithContext(final ContainerSchemaNode containerNode) throws IOException, ReadingException {
+ public List<NormalizedNode<?, ?>> readWithContext(final ContainerSchemaNode containerNode)
+ throws IOException, ReadingException {
console.formatLn("Submit child nodes for container: %s, %s", containerNode.getQName().getLocalName(),
Collections2.transform(containerNode.getChildNodes(), new Function<DataSchemaNode, String>() {
@Override
return input.getQName().getLocalName();
}
}));
- final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = ImmutableContainerNodeBuilder.create();
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = ImmutableContainerNodeBuilder
+ .create();
builder.withNodeIdentifier(new NodeIdentifier(containerNode.getQName()));
final ArrayList<NormalizedNode<?, ?>> nodesToAdd = new ArrayList<>();
nodesToAdd.addAll(argumentHandlerRegistry.getGenericReader(getSchemaContext(),
getReadConfigNode()).read(childNode));
}
- return Collections.<NormalizedNode<?, ?>> singletonList(builder.withValue((ArrayList) nodesToAdd).build());
+ return Collections.singletonList(builder.withValue((ArrayList) nodesToAdd).build());
}
private List<DataSchemaNode> sortChildren(final Set<DataSchemaNode> unsortedNodes) {
}
@Override
- protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+ protected List<NormalizedNode<?, ?>> readWithContext(final DataSchemaNode schemaNode)
+ throws IOException, ReadingException {
final Optional<Class<? extends Reader<DataSchemaNode>>> customReaderClassOpt = tryGetCustomHandler(schemaNode);
if (customReaderClassOpt.isPresent()) {
// TODO reuse instances
}
- private List<NormalizedNode<?, ?>> readGeneric(final DataSchemaNode schemaNode) throws ReadingException, IOException {
+ private List<NormalizedNode<?, ?>> readGeneric(final DataSchemaNode schemaNode)
+ throws ReadingException, IOException {
final List<NormalizedNode<?, ?>> newNodes = new ArrayList<>();
boolean isRedCorrectly = false;
do {
try {
final Class<?> argumentClass = Class.forName(argumentHandlerClassName);
// TODO add check before cast
- return Optional.<Class<? extends T>> of((Class<? extends T>) argumentClass);
+ return Optional.of((Class<? extends T>) argumentClass);
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Unknown custom reader class " + argumentHandlerClassName
+ " for: " + dataSchemaNode.getQName());
class LeafListEntryReader extends BasicDataHolderReader<LeafListSchemaNode> implements
GenericListEntryReader<LeafListSchemaNode> {
- public LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext) {
+ LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext) {
super(console, schemaContext);
}
- public LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext, final boolean readConfigNode) {
+ LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext, final boolean readConfigNode) {
super(console, schemaContext, readConfigNode);
}
@Override
protected List<Completer> getAdditionalCompleters() {
- return Lists.<Completer> newArrayList(getBaseCompleter(getDataSchemaNode()));
+ return Lists.newArrayList(getBaseCompleter(getDataSchemaNode()));
}
};
}
return new BaseConsoleContext<LeafSchemaNode>(schemaNode) {
@Override
public List<Completer> getAdditionalCompleters() {
- final List<Completer> completers = Lists.<Completer> newArrayList(getBaseCompleter(schemaNode));
+ final List<Completer> completers = Lists.newArrayList(getBaseCompleter(schemaNode));
final Optional<String> defaultValue = getDefaultValue(schemaNode);
if (defaultValue.isPresent()) {
completers.add(new StringsCompleter(defaultValue.get()));
private final CommandArgHandlerRegistry argumentHandlerRegistry;
- public ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+ ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
final SchemaContext schemaContext) {
super(console, schemaContext);
this.argumentHandlerRegistry = argumentHandlerRegistry;
}
- public ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
- final SchemaContext schemaContext, final boolean readConfigNode) {
+ ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+ final SchemaContext schemaContext, final boolean readConfigNode) {
super(console, schemaContext, readConfigNode);
this.argumentHandlerRegistry = argumentHandlerRegistry;
}
@Override
- public List<NormalizedNode<?, ?>> readWithContext(final ListSchemaNode listNode) throws IOException, ReadingException {
+ public List<NormalizedNode<?, ?>> readWithContext(final ListSchemaNode listNode)
+ throws IOException, ReadingException {
console.formatLn("Submit child nodes for list entry: %s, %s", listNode.getQName().getLocalName(),
Collections2.transform(listNode.getChildNodes(), new Function<DataSchemaNode, String>() {
@Override
return newNodes;
}
- private List<NormalizedNode<?, ?>> readMandatoryNotKeys(final Set<DataSchemaNode> mandatoryNotKeys) throws ReadingException,
- IOException {
+ private List<NormalizedNode<?, ?>> readMandatoryNotKeys(final Set<DataSchemaNode> mandatoryNotKeys)
+ throws ReadingException, IOException {
final List<NormalizedNode<?, ?>> newNodes = new ArrayList<>();
console.writeLn("Reading mandatory not keys nodes:");
private final Set<DataSchemaNode> mandatoryNotKey;
private final Set<DataSchemaNode> otherNodes;
- public SeparatedNodes(final Set<DataSchemaNode> keyNodes, final Set<DataSchemaNode> mandatoryNotKey,
- final Set<DataSchemaNode> otherNodes) {
+ private SeparatedNodes(final Set<DataSchemaNode> keyNodes, final Set<DataSchemaNode> mandatoryNotKey,
+ final Set<DataSchemaNode> otherNodes) {
this.keyNodes = keyNodes;
this.mandatoryNotKey = mandatoryNotKey;
this.otherNodes = otherNodes;
return separateNodes(dataNodeContainer, false);
}
- static SeparatedNodes separateNodes(final DataNodeContainer dataNodeContainer, final boolean removeConfigFalseNodes) {
+ static SeparatedNodes separateNodes(final DataNodeContainer dataNodeContainer,
+ final boolean removeConfigFalseNodes) {
final Set<DataSchemaNode> keys = new HashSet<>();
final Set<DataSchemaNode> mandatoryNotKeys = new HashSet<>();
final Set<DataSchemaNode> others = new HashSet<>();
private final ConsoleIO console;
- public UnionTypeReader(final ConsoleIO console) {
+ UnionTypeReader(final ConsoleIO console) {
this.console = console;
}
}
final TypeDefinition<?> value = mapping.get(rawValue);
if (value != null) {
- return Optional.<TypeDefinition<?>> of(value);
+ return Optional.of(value);
} else {
- final String message = String.format("Incorrect type (%s) was specified for union type definition", rawValue);
+ final String message = String.format(
+ "Incorrect type (%s) was specified for union type definition", rawValue);
LOG.error(message);
throw new ReadingException(message);
}
private final TypeDefinition<?> typeDef;
private final Map<String, TypeDefinition<?>> menuItemsToTypeDefinitions = new HashMap<>();
- public UnionConsoleContext(final TypeDefinition<?> typeDef) {
+ UnionConsoleContext(final TypeDefinition<?> typeDef) {
this.typeDef = typeDef;
}
public Completer getCompleter() {
List<TypeDefinition<?>> subtypesForMenu = resolveSubtypesFrom(typeDef);
if (subtypesForMenu.isEmpty()) {
- subtypesForMenu = Collections.<TypeDefinition<?>> singletonList(typeDef);
+ subtypesForMenu = Collections.singletonList(typeDef);
}
final Collection<String> menuItems = toMenuItem(subtypesForMenu);
return new AggregateCompleter(new StringsCompleter(menuItems), new StringsCompleter(IOUtil.SKIP));
}
/**
- *
* If union type is found in potentialEndTypeCandidate as subtype then
* it these subtypes become candidates.
*
private static final long serialVersionUID = 8401242676753560336L;
- public WriteException(final String msg, final Exception e) {
- super(msg, e);
+ public WriteException(final String msg, final Exception exc) {
+ super(msg, exc);
}
public WriteException(final String msg) {
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
- * Generic handler(writer) of output elements for commands
+ * Generic handler(writer) of output elements for commands.
*/
public interface Writer<T extends DataSchemaNode> {
}
@Override
- protected void writeInner(final DataSchemaNode dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes) throws IOException, WriteException {
+ protected void writeInner(final DataSchemaNode dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes)
+ throws IOException, WriteException {
Preconditions.checkArgument(dataNodes.size() == 1, "Expected only 1 element for data node");
final NormalizedNode<?, ?> dataNode = dataNodes.get(0);
- Preconditions.checkArgument(dataNode instanceof ContainerNode, "Unexpected node type: %s, should be %s", dataNode, ContainerNode.class);
+ Preconditions.checkArgument(dataNode instanceof ContainerNode, "Unexpected node type: %s, should be %s",
+ dataNode, ContainerNode.class);
StringBuilder output = new StringBuilder();
- out.increaseIndent().addStringWithIndent(output, dataSchemaNode.getQName().getLocalName()).openComposite(output);
+ out.increaseIndent().addStringWithIndent(
+ output, dataSchemaNode.getQName().getLocalName()).openComposite(output);
console.writeLn(output.toString());
- for (final Object oChildNode : ((DataContainerNode) dataNode).getValue()) {
- final NormalizedNode<?, ?> childNode = (NormalizedNode<?, ?>) oChildNode;
- final Optional<DataSchemaNode> schemaNode = XmlDocumentUtils.findFirstSchema(childNode.getNodeType(), remoteSchemaContext.getDataDefinitions());
- Preconditions.checkState(schemaNode.isPresent(), "Unknown data node %s, not defined in schema", childNode.getNodeType());
- new NormalizedNodeWriter(console, out).write(schemaNode.get(), Collections.<NormalizedNode<?, ?>>singletonList(childNode));
+ for (final Object childNodeObject : ((DataContainerNode) dataNode).getValue()) {
+ final NormalizedNode<?, ?> childNode = (NormalizedNode<?, ?>) childNodeObject;
+ final Optional<DataSchemaNode> schemaNode = XmlDocumentUtils.findFirstSchema(childNode.getNodeType(),
+ remoteSchemaContext.getDataDefinitions());
+ Preconditions.checkState(schemaNode.isPresent(), "Unknown data node %s, not defined in schema",
+ childNode.getNodeType());
+ new NormalizedNodeWriter(console, out).write(schemaNode.get(), Collections.singletonList(childNode));
}
output = new StringBuilder();
}
}
- protected abstract void writeInner(final T dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes) throws IOException,
- WriteException;
+ protected abstract void writeInner(final T dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes)
+ throws IOException, WriteException;
}
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AugmentationNodeBaseSerializer;
import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+
final class AugmentationNodeCliSerializer extends AugmentationNodeBaseSerializer<String> {
private final NodeSerializerDispatcher<String> dispatcher;
}
@Override
- public FromNormalizedNodeSerializer<String, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
+ public FromNormalizedNodeSerializer<
+ String, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
return leafSetEntryNodeSerializer;
}
private final OutFormatter out;
- public LeafSetEntryNodeCliSerializer(final OutFormatter out) {
+ LeafSetEntryNodeCliSerializer(final OutFormatter out) {
this.out = out;
}
return;
}
- int i = 0;
+ int index = 0;
output.append(" [");
- for (final Entry<QName, Object> qNameObjectEntry : keyValues.entrySet()) {
- output.append(qNameObjectEntry.getKey().getLocalName());
+ for (final Entry<QName, Object> keys : keyValues.entrySet()) {
+ output.append(keys.getKey().getLocalName());
output.append("=");
- output.append(qNameObjectEntry.getValue().toString());
- if (++i != keyValues.size()) {
+ output.append(keys.getValue().toString());
+ if (++index != keyValues.size()) {
output.append(", ");
}
}
this.out = out;
}
- public void writeInner(final DataSchemaNode dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes) throws WriteException,
- IOException {
+ public void writeInner(final DataSchemaNode dataSchemaNode, final List<NormalizedNode<?, ?>> dataNodes)
+ throws WriteException, IOException {
//Preconditions.checkState(dataNodes.size() == 1);
// TODO - add getDispatcher method to CnSnToNormalizedNodeParserFactory
// to be able call dispatchChildElement
private String serializeToCliOutput(final NormalizedNode<?, ?> dataContainerChild,
final DataSchemaNode childSchema) {
- final CliOutputFromNormalizedNodeSerializerFactory factorySerialization = CliOutputFromNormalizedNodeSerializerFactory
- .getInstance(out, DomUtils.defaultValueCodecProvider());
+ final CliOutputFromNormalizedNodeSerializerFactory factorySerialization =
+ CliOutputFromNormalizedNodeSerializerFactory.getInstance(out, DomUtils.defaultValueCodecProvider());
final NodeSerializerDispatcher<String> dispatcher = factorySerialization.getDispatcher();
- final Iterable<String> result = dispatcher.dispatchChildElement(childSchema, (DataContainerChild<?, ?>) dataContainerChild);
+ final Iterable<String> result = dispatcher.dispatchChildElement(childSchema,
+ (DataContainerChild<?, ?>) dataContainerChild);
if (result == null) {
return "";
String lastMessage;
private final List<ValueForMessage> valuesForMessages;
- public ConsoleIOTestImpl(final Map<String, Deque<String>> inputValues, final List<ValueForMessage> valuesForMessages)
- throws IOException {
+ public ConsoleIOTestImpl(final Map<String, Deque<String>> inputValues,
+ final List<ValueForMessage> valuesForMessages) throws IOException {
super();
this.inputValues = inputValues;
this.valuesForMessages = valuesForMessages;
List<String> messageKeyWords;
String value;
- public ValueForMessage(final String value, final String... messageKeyWords) {
+ ValueForMessage(final String value, final String... messageKeyWords) {
this.messageKeyWords = Arrays.asList(messageKeyWords);
this.value = value;
}