All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.unix4j.unix.tail.TailArguments Maven / Gradle / Ivy

There is a newer version: 0.6
Show newest version
package org.unix4j.unix.tail;

import java.util.List;
import java.util.Map;
import java.util.Arrays;

import org.unix4j.command.Arguments;
import org.unix4j.context.ExecutionContext;
import org.unix4j.convert.ValueConverter;
import org.unix4j.option.DefaultOptionSet;
import org.unix4j.util.ArgsUtil;
import org.unix4j.util.ArrayUtil;
import org.unix4j.variable.Arg;
import org.unix4j.variable.VariableContext;

import org.unix4j.unix.Tail;

/**
 * Arguments and options for the {@link Tail tail} command.
 */
public final class TailArguments implements Arguments {
	
	private final TailOptions options;

	
	// operand: 
	private long count;
	private boolean countIsSet = false;
	
	// operand: 
	private String[] paths;
	private boolean pathsIsSet = false;
	
	// operand: 
	private java.io.File[] files;
	private boolean filesIsSet = false;
	
	// operand: 
	private String[] args;
	private boolean argsIsSet = false;
	
	/**
	 * Constructor to use if no options are specified.
	 */
	public TailArguments() {
		this.options = TailOptions.EMPTY;
	}

	/**
	 * Constructor with option set containing the selected command options.
	 * 
	 * @param options the selected options
	 * @throws NullPointerException if the argument is null
	 */
	public TailArguments(TailOptions options) {
		if (options == null) {
			throw new NullPointerException("options argument cannot be null");
		}
		this.options = options;
	}
	
	/**
	 * Returns the options set containing the selected command options. Returns
	 * an empty options set if no option has been selected.
	 * 
	 * @return set with the selected options
	 */
	public TailOptions getOptions() {
		return options;
	}

	/**
	 * Constructor string arguments encoding options and arguments, possibly
	 * also containing variable expressions. 
	 * 
	 * @param args string arguments for the command
	 * @throws NullPointerException if args is null
	 */
	public TailArguments(String... args) {
		this();
		this.args = args;
		this.argsIsSet = true;
	}
	private Object[] resolveVariables(VariableContext context, String... unresolved) {
		final Object[] resolved = new Object[unresolved.length];
		for (int i = 0; i < resolved.length; i++) {
			final String expression = unresolved[i];
			if (Arg.isVariable(expression)) {
				resolved[i] = resolveVariable(context, expression);
			} else {
				resolved[i] = expression;
			}
		}
		return resolved;
	}
	private  V convertList(ExecutionContext context, String operandName, Class operandType, List values) {
		if (values.size() == 1) {
			final Object value = values.get(0);
			return convert(context, operandName, operandType, value);
		}
		return convert(context, operandName, operandType, values);
	}

	private Object resolveVariable(VariableContext context, String variable) {
		final Object value = context.getValue(variable);
		if (value != null) {
			return value;
		}
		throw new IllegalArgumentException("cannot resolve variable " + variable + 
				" in command: tail " + this);
	}
	private  V convert(ExecutionContext context, String operandName, Class operandType, Object value) {
		final ValueConverter converter = context.getValueConverterFor(operandType);
		final V convertedValue;
		if (converter != null) {
			convertedValue = converter.convert(value);
		} else {
			if (TailOptions.class.equals(operandType)) {
				convertedValue = operandType.cast(TailOptions.CONVERTER.convert(value));
			} else {
				convertedValue = null;
			}
		}
		if (convertedValue != null) {
			return convertedValue;
		}
		throw new IllegalArgumentException("cannot convert --" + operandName + 
				" value '" + value + "' into the type " + operandType.getName() + 
				" for tail command");
	}
	
	@Override
	public TailArguments getForContext(ExecutionContext context) {
		if (context == null) {
			throw new NullPointerException("context cannot be null");
		}
		if (!argsIsSet || args.length == 0) {
			//nothing to resolve
			return this;
		}

		//check if there is at least one variable
		boolean hasVariable = false;
		for (final String arg : args) {
			if (arg != null && arg.startsWith("$")) {
				hasVariable = true;
				break;
			}
		}
		//resolve variables
		final Object[] resolvedArgs = hasVariable ? resolveVariables(context.getVariableContext(), this.args) : this.args;
		
		//convert now
		final List defaultOperands = Arrays.asList("paths");
		final Map> map = ArgsUtil.parseArgs("options", defaultOperands, resolvedArgs);
		final TailOptions.Default options = new TailOptions.Default();
		final TailArguments argsForContext = new TailArguments(options);
		for (final Map.Entry> e : map.entrySet()) {
			if ("count".equals(e.getKey())) {
					
				final long value = convertList(context, "count", long.class, e.getValue());  
				argsForContext.setCount(value);
			} else if ("paths".equals(e.getKey())) {
					
				final String[] value = convertList(context, "paths", String[].class, e.getValue());  
				argsForContext.setPaths(value);
			} else if ("files".equals(e.getKey())) {
					
				final java.io.File[] value = convertList(context, "files", java.io.File[].class, e.getValue());  
				argsForContext.setFiles(value);
			} else if ("args".equals(e.getKey())) {
				throw new IllegalStateException("invalid operand '" + e.getKey() + "' in tail command args: " + Arrays.toString(args));
			} else if ("options".equals(e.getKey())) {
					
				final TailOptions value = convertList(context, "options", TailOptions.class, e.getValue());  
				options.setAll(value);
			} else {
				throw new IllegalStateException("invalid operand '" + e.getKey() + "' in tail command args: " + Arrays.toString(args));
			}
		}
		return argsForContext;
	}
	
	/**
	 * Returns the {@code } operand value: The last {@code count} lines of each input file are
			copied to standard output, starting from 1 (characters instead of 
			lines if the {@code -c} option is specified, and offset from start  
			instead of end with {@code -s} option). Must be a non-negative 
			integer or an exception is thrown. If {@code count} is greater than 
			the number number of lines (characters) in the input, the
			application will not error and send the whole file to the output.
	 * 
	 * @return the {@code } operand value (variables are not resolved)
	 * @throws IllegalStateException if this operand has never been set
	 * 
	 */
	public long getCount() {
		if (countIsSet) {
			return count;
		}
		throw new IllegalStateException("operand has not been set: " + count);
	}

	/**
	 * Returns true if the {@code } operand has been set. 
	 * 

* Note that this method returns true even if {@code null} was passed to the * {@link #setCount(long)} method. * * @return true if the setter for the {@code } operand has * been called at least once */ public boolean isCountSet() { return countIsSet; } /** * Sets {@code }: The last {@code count} lines of each input file are copied to standard output, starting from 1 (characters instead of lines if the {@code -c} option is specified, and offset from start instead of end with {@code -s} option). Must be a non-negative integer or an exception is thrown. If {@code count} is greater than the number number of lines (characters) in the input, the application will not error and send the whole file to the output. * * @param count the value for the {@code } operand */ public void setCount(long count) { this.count = count; this.countIsSet = true; } /** * Returns the {@code } operand value: Pathnames of the input files to be filtered; wildcards * and ? are supported; relative paths are resolved on the basis of the current working directory. * * @return the {@code } operand value (variables are not resolved) * @throws IllegalStateException if this operand has never been set * */ public String[] getPaths() { if (pathsIsSet) { return paths; } throw new IllegalStateException("operand has not been set: " + paths); } /** * Returns true if the {@code } operand has been set. *

* Note that this method returns true even if {@code null} was passed to the * {@link #setPaths(String[])} method. * * @return true if the setter for the {@code } operand has * been called at least once */ public boolean isPathsSet() { return pathsIsSet; } /** * Sets {@code }: Pathnames of the input files to be filtered; wildcards * and ? are supported; relative paths are resolved on the basis of the current working directory. * * @param paths the value for the {@code } operand */ public void setPaths(String... paths) { this.paths = paths; this.pathsIsSet = true; } /** * Returns the {@code } operand value: The input files to be filtered; relative paths are not resolved (use the string paths argument to enable relative path resolving based on the current working directory). * * @return the {@code } operand value (variables are not resolved) * @throws IllegalStateException if this operand has never been set * */ public java.io.File[] getFiles() { if (filesIsSet) { return files; } throw new IllegalStateException("operand has not been set: " + files); } /** * Returns true if the {@code } operand has been set. *

* Note that this method returns true even if {@code null} was passed to the * {@link #setFiles(java.io.File[])} method. * * @return true if the setter for the {@code } operand has * been called at least once */ public boolean isFilesSet() { return filesIsSet; } /** * Sets {@code }: The input files to be filtered; relative paths are not resolved (use the string paths argument to enable relative path resolving based on the current working directory). * * @param files the value for the {@code } operand */ public void setFiles(java.io.File... files) { this.files = files; this.filesIsSet = true; } /** * Returns the {@code } operand value: String arguments defining the options and operands for the command. Options can be specified by acronym (with a leading dash "-") or by long name (with two leading dashes "--"). Operands other than the default "--paths" operand have to be prefixed with the operand name (e.g. "--count" for a subsequent count operand value). * * @return the {@code } operand value (variables are not resolved) * @throws IllegalStateException if this operand has never been set * */ public String[] getArgs() { if (argsIsSet) { return args; } throw new IllegalStateException("operand has not been set: " + args); } /** * Returns true if the {@code } operand has been set. * * @return true if the setter for the {@code } operand has * been called at least once */ public boolean isArgsSet() { return argsIsSet; } /** * Returns true if the {@code --}{@link TailOption#chars chars} option * is set. The option is also known as {@code -}c option. *

* Description: The {@code count} argument is in units of characters instead of lines. Starts from 1 and includes line ending characters. * * @return true if the {@code --chars} or {@code -c} option is set */ public boolean isChars() { return getOptions().isSet(TailOption.chars); } /** * Returns true if the {@code --}{@link TailOption#suppressHeaders suppressHeaders} option * is set. The option is also known as {@code -}q option. *

* Description: Suppresses printing of headers when multiple files are being examined. * * @return true if the {@code --suppressHeaders} or {@code -q} option is set */ public boolean isSuppressHeaders() { return getOptions().isSet(TailOption.suppressHeaders); } /** * Returns true if the {@code --}{@link TailOption#countFromStart countFromStart} option * is set. The option is also known as {@code -}s option. *

* Description: The {@code count} argument is relative to the beginning of the file instead of counting from the end of the file. For instance, {@code tail -s 10} prints the lines starting from line 10; {@code tail -s 1} prints the whole file. * * @return true if the {@code --countFromStart} or {@code -s} option is set */ public boolean isCountFromStart() { return getOptions().isSet(TailOption.countFromStart); } @Override public String toString() { // ok, we have options or arguments or both final StringBuilder sb = new StringBuilder(); if (argsIsSet) { for (String arg : args) { if (sb.length() > 0) sb.append(' '); sb.append(arg); } } else { // first the options if (options.size() > 0) { sb.append(DefaultOptionSet.toString(options)); } // operand: if (countIsSet) { if (sb.length() > 0) sb.append(' '); sb.append("--").append("count"); sb.append(" ").append(toString(getCount())); } // operand: if (pathsIsSet) { if (sb.length() > 0) sb.append(' '); sb.append("--").append("paths"); sb.append(" ").append(toString(getPaths())); } // operand: if (filesIsSet) { if (sb.length() > 0) sb.append(' '); sb.append("--").append("files"); sb.append(" ").append(toString(getFiles())); } // operand: if (argsIsSet) { if (sb.length() > 0) sb.append(' '); sb.append("--").append("args"); sb.append(" ").append(toString(getArgs())); } } return sb.toString(); } private static String toString(Object value) { if (value != null && value.getClass().isArray()) { return ArrayUtil.toString(value); } return String.valueOf(value); } }