001package org.unix4j.unix.echo;
002
003import org.unix4j.command.AbstractCommand;
004import org.unix4j.context.ExecutionContext;
005import org.unix4j.line.Line;
006import org.unix4j.line.SimpleLine;
007import org.unix4j.processor.LineProcessor;
008import org.unix4j.unix.Echo;
009
010/**
011 * Implementation of the {@link Echo echo} command.
012 */
013class EchoCommand extends AbstractCommand<EchoArguments> {
014        public EchoCommand(EchoArguments arguments) {
015                super(Echo.NAME, arguments);
016        }
017
018        @Override
019        public LineProcessor execute(ExecutionContext context, final LineProcessor output) {
020                final EchoArguments args = getArguments(context);
021                return new LineProcessor() {
022                        @Override
023                        public boolean processLine(Line line) {
024                                return false;//we want no input lines
025                        }
026                        
027                        @Override
028                        public void finish() {
029                                final String message = getMessage();
030                                if (args.isNoNewline()) {
031                                        output.processLine(new SimpleLine(message, ""));
032                                } else {
033                                        output.processLine(new SimpleLine(message));
034                                }
035                                output.finish();
036                        }
037
038                        private String getMessage() {
039                                if (args.isStringSet()) {
040                                        return args.getString();
041                                } else if (args.isStringsSet()) {
042                                        final StringBuilder sb = new StringBuilder();
043                                        for (final String string : args.getStrings()) {
044                                                if (sb.length() > 0) sb.append(' ');
045                                                sb.append(string);
046                                        }
047                                        return sb.toString();
048                                }
049                                return "";
050                        }
051                };
052        }
053}