001 /*
002 * Copyright (C) 2011 eXo Platform SAS.
003 *
004 * This is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU Lesser General Public License as
006 *
007 * published by the Free Software Foundation; either version 2.1 of
008 * the License, or (at your option) any later version.
009 *
010 * This software is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
013 * Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public
016 * License along with this software; if not, write to the Free
017 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
018 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
019 */
020
021 package org.crsh.command.impl;
022
023 import org.crsh.command.InvocationContext;
024 import org.crsh.shell.io.ShellPrinter;
025 import org.crsh.util.LineFeedWriter;
026
027 import java.io.StringWriter;
028 import java.util.Collections;
029 import java.util.LinkedList;
030 import java.util.List;
031 import java.util.Map;
032
033 /**
034 * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
035 * @version $Revision$
036 */
037 public abstract class BaseInvocationContext<C, P> extends BaseCommandContext implements InvocationContext<C, P> {
038
039 /** . */
040 protected ShellPrinter writer;
041
042 /** . */
043 protected StringWriter buffer;
044
045 /** . */
046 protected List<P> producedItems;
047
048 /** . */
049 protected Iterable<C> consumedItems;
050
051 protected BaseInvocationContext(
052 Iterable<C> consumedItems,
053 Map<String, Object> attributes) {
054 super(attributes);
055
056 //
057 this.writer = null;
058 this.buffer = null;
059 this.consumedItems = consumedItems;
060 this.producedItems = Collections.emptyList();
061 }
062
063 public List<P> getProducedItems() {
064 return producedItems;
065 }
066
067 public StringWriter getBuffer() {
068 return buffer;
069 }
070
071 public boolean isPiped() {
072 return consumedItems != null;
073 }
074
075 public Iterable<C> consume() {
076 if (consumedItems == null) {
077 throw new IllegalStateException("Cannot consume as no pipe operation is involved");
078 }
079 return consumedItems;
080 }
081
082 public void produce(P product) {
083 if (producedItems.isEmpty()) {
084 producedItems = new LinkedList<P>();
085 }
086 producedItems.add(product);
087 }
088
089 public ShellPrinter getWriter() {
090 if (writer == null) {
091 buffer = new StringWriter();
092 writer = new ShellPrinter(new LineFeedWriter(buffer, "\r\n"));
093 }
094 return writer;
095 }
096 }