001package org.unix4j.unix.xargs; 002 003import org.unix4j.context.ExecutionContext; 004import org.unix4j.line.Line; 005import org.unix4j.processor.AbstractLineProcessor; 006import org.unix4j.processor.LineProcessor; 007import org.unix4j.variable.VariableContext; 008 009class XargsLineProcessor extends AbstractLineProcessor<XargsArguments> { 010 011 private final Itemizer itemizer; 012 013 private final DefaultItemStorage storage; 014 015 public XargsLineProcessor(XargsCommand command, ExecutionContext context, LineProcessor output) { 016 super(command, context, new XargsOutput(output)); 017 final XargsArguments args = getArguments(); 018 if (args.isDelimiterSet()) { 019 final String delimiter = args.getDelimiter(); 020 if (delimiter.length() == 1) { 021 itemizer = new CharDelimitedItemizer(delimiter.charAt(0)); 022 } else { 023 //FIXME support length>1 delimiters 024 throw new IllegalArgumentException("unsupported delimiter: " + delimiter); 025 } 026 } else if (args.isDelimiter0()) { 027 itemizer = new CharDelimitedItemizer(Line.ZERO); 028 } else { 029 itemizer = new WhitespaceItemizer(); 030 } 031 this.storage = new DefaultItemStorage(this); 032 getVariableContext().addVariableResolver(storage); 033 } 034 035 @Override 036 protected XargsCommand getCommand() { 037 return (XargsCommand)super.getCommand(); 038 } 039 040 @Override 041 protected XargsArguments getArguments() { 042 return super.getArguments(); 043 } 044 045 @Override 046 protected XargsOutput getOutput() { 047 return (XargsOutput)super.getOutput(); 048 } 049 050 protected VariableContext getVariableContext() { 051 return getContext().getVariableContext(); 052 } 053 054 protected void invoke() { 055 final XargsOutput output = getOutput(); 056 final LineProcessor invocation = getCommand().getInvokedCommand().execute(getContext(), output); 057 invocation.finish(); 058 } 059 060 @Override 061 public boolean processLine(Line line) { 062 itemizer.itemizeLine(line, storage); 063 return true;//we always want all the lines 064 } 065 066 @Override 067 public void finish() { 068 itemizer.finish(storage); 069 storage.flush(); 070 getVariableContext().removeVariableResolver(storage); 071 getOutput().finishAll(); 072 } 073}