package at.jku.pervasive.ecg;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import org.apache.commons.io.IOUtils;

public class FileHeartManMock extends HeartManMock {

  private final File dataFile;

  public FileHeartManMock(File dataFile) {
    super();
    this.dataFile = dataFile;
  }

  @Override
  public void run() {
    InputStream in = null;
    OutputStream dos = null;
    try {
      StreamConnectionNotifier service = null;

      String url = "btspp://localhost:"
          + HeartManDiscovery.HEARTMAN_SERVICE_UUID
          + ";authenticate=false;encrypt=false";

      service = (StreamConnectionNotifier) Connector.open(url);
      System.out.println("Waiting for incoming connection...");
      StreamConnection connection = service.acceptAndOpen();

      RemoteDevice client = RemoteDevice.getRemoteDevice(connection);
      String clientFriendlyName = client.getFriendlyName(true);
      System.out.println("connected to " + clientFriendlyName);

      dos = connection.openOutputStream();

      in = new BufferedInputStream(new FileInputStream(dataFile));

      byte[] buffer = new byte[2];
      int len = -1;
      while ((len = in.read(buffer)) != -1) {
        dos.write(buffer, 0, len);
        dos.flush();
      }

      dos.close();
      connection.close();
    } catch (IOException io) {
      // silent
      System.err.println(io.getMessage());
    } catch (Exception e) {
      System.out.println("uweeh");
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(in);
      IOUtils.closeQuietly(dos);
    }
  }

}

@@ -1385,17 +1385,46 @@
 File));%0A
-%0A
+      while (in != null) %7B%0A%0A  
       by
@@ -1456,16 +1456,18 @@
 ;%0A      
+ 
+ 
 int len 
@@ -1472,16 +1472,18 @@
 n = -1;%0A
+  
       wh
@@ -1524,24 +1524,26 @@
 ) %7B%0A        
+ 
+ 
 dos.write(bu
@@ -1561,24 +1561,26 @@
 n);%0A        
+  
 dos.flush();
@@ -1576,24 +1576,104 @@
 os.flush();%0A
+        %7D%0A%0A        in = new BufferedInputStream(new FileInputStream(dataFile));%0A
       %7D%0A%0A   
@@ -1985,11 +1985,10 @@
   %7D%0A  %7D%0A
-%0A
 %7D%0A

add infinite loop to FileHeartManMock