// joi/10/juno/GetfileCommand.java                         
//                                                            
//                                                            
// Copyright 2003, Bill Campbell and Ethan Bolker                         
                                                            
import java.util.*;
import java.io.*;

/**
 * The Juno shell command to get a text file from the underlying
 * operating system and copy it to a Juno text file.
 * Usage:
 * <pre>
 *     getfile native-filename juno-filename
 * </pre>

 * <pre>
 *
 * @version 10
 */

class GetfileCommand extends ShellCommand 
{
    GetfileCommand() 
    {
        super( "download a file to Juno",
               "native-filename juno-filename" );
    }

    /**
     * Use the getfile command to copy the content of a real
     * file to a Juno TextFile.
     * <p>
     * The command has the form:
     * <pre>
     * get nativeFile textfile <&>
     *
     * @param args: the reminder of the command line.
     * @param sh: the current shell
     *
     * @exception JunoException for reporting errors
     */

    public void doIt( StringTokenizer args, Shell sh )
         throws JunoException 
    {
        if ( sh.getConsole().isRemote() ) {
            throw( new JunoException(
                "Get not implemented for remote consoles." ) );
        }
        String src;
        String dst;
        try {
            src = args.nextToken();
            dst = args.nextToken();
        }
        catch (NoSuchElementException e) {
            throw new BadShellCommandException( this );
        }
        BufferedReader inStream  = null;
        Writer         outStream = null;
        try {
            inStream  = new BufferedReader( new FileReader( src ) );
            outStream = new StringWriter();
            String line;

            while ((line = inStream.readLine()) != null) {
                outStream.write( line );
                outStream.write( '\n' );
            }
            new TextFile( dst, sh.getUser(),
                          sh.getDot(), outStream.toString() );
        }
        catch (IOException e) {
            throw new JunoException( "IO problem in get" );
        }
        finally {
            try {
                inStream.close();
                outStream.close();
            }
            catch (IOException e) {};
        }
    }
}
