/*                          
 * mBench: The Open Source Micro Benchmark Tool 
 *                                             
 * Distributable under GPL license. 
 * See terms of license at gnu.org.                 
 *
 * Copyright (C) 2005 Sumisho Computer Systems Corp.
 */
package test.jp.co.scs.mbench.stub;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


/**
 *      The stub behave as secondary node.
 * 
 *      @author Tetsuro Ikeda
 */
public class StubBenchmarkManagerSecondaryNode extends Thread{

    protected int port;

    protected List messageList = new ArrayList();

    public StubBenchmarkManagerSecondaryNode(int port) {
        this.port = port;
    }

    public String[] getMessages() {
        return (String[]) this.messageList.toArray(
            new String[this.messageList.size()]);
    }

    public void run() {
        try {
            ServerSocket server = new ServerSocket(this.port);
            server.setSoTimeout(50000);
            Socket socket = server.accept();
            socket.setSoTimeout(50000);
            byte[] buffer = new byte[20];
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            is.read(buffer);
            buffer = trimBlankByte(buffer);
            String message = new String(buffer);
            this.messageList.add(message);

            os.write(new String("doInit OK").getBytes());
            byte[] buffer2 = new byte[20];
            is.read(buffer2);
            buffer2 = trimBlankByte(buffer2);
            String message2 = new String(buffer2);
            this.messageList.add(message2);
            
        } catch (IOException ex) {
            this.messageList.add(ex.getMessage());
            ex.printStackTrace();
        }
    }
    
    protected byte[] trimBlankByte(byte[] buffer) {
        int count = 0;
        for (int i = 0; i < buffer.length; i++) {
            if (buffer[i] == 0) {
                break;
            } else {
                count++;
            }
        }
        byte[] newBuffer = new byte[count];
        for (int i = 0; i < count; i++) {
            newBuffer[i] = buffer[i];
        }
        return newBuffer;
    }
}
