001    /*
002     * Copyright (C) 2012 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     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    package org.crsh.command.pipeline;
020    
021    import org.crsh.command.CommandContext;
022    import org.crsh.text.Chunk;
023    
024    import java.io.IOException;
025    
026    /** @author Julien Viet */
027    public class ConvertingPipe<C, P, CONS extends CommandContext<? super P>> extends AbstractPipe<C, P, CONS> {
028    
029      /** . */
030      private final Class<C> consumedType;
031    
032      /** . */
033      private final Class<P> producedType;
034    
035      public ConvertingPipe(Class<C> consumedType, Class<P> producedType, boolean piped) {
036        super(piped);
037    
038        //
039        this.consumedType = consumedType;
040        this.producedType = producedType;
041      }
042    
043      public Class<C> getConsumedType() {
044        return consumedType;
045      }
046    
047      public Class<P> getProducedType() {
048        return producedType;
049      }
050    
051      public void write(Chunk chunk) throws IOException {
052        if (producedType.equals(Void.class)) {
053          //
054        } else if (producedType.isAssignableFrom(Chunk.class)) {
055          P p = producedType.cast(chunk);
056          consumer.provide(p);
057        } else {
058          consumer.write(chunk);
059        }
060      }
061    
062      public void provide(C element) throws IOException {
063        if (producedType.isInstance(element)) {
064          P p = producedType.cast(element);
065          consumer.provide(p);
066        } else {
067          // Discarded for now...
068        }
069      }
070    }