1 package org.sapia.ubik.net.nio.util; 2 3 import java.io.EOFException ; 4 import java.io.IOException ; 5 import java.nio.ByteBuffer ; 6 7 import org.sapia.ubik.net.nio.ChannelManager; 8 import org.sapia.ubik.net.nio.Cycle; 9 10 26 public class ReadHelper { 27 28 public static final int DEFAULT_READ_ATTEMPTS = 2; 29 public static final int DEFAULT_READ_THRESHOLD = 1; 30 31 private int _readAttempts = DEFAULT_READ_ATTEMPTS; 32 private int _readThreshold = DEFAULT_READ_THRESHOLD; 33 34 35 40 public void setReadAttempts(int attempts){ 41 _readAttempts = attempts; 42 } 43 44 48 public void setReadThreshHold(int threshHold){ 49 _readAttempts = threshHold; 50 } 51 52 56 public void read(Cycle cycle) throws IOException { 57 ByteBuffer input = cycle.getByteBuffer(); 58 boolean finished = false; 59 int read; 60 ChannelManager manager = cycle.getChannelManager(); 61 while(!finished){ 62 read = manager.read(cycle.getChannel(), input); 63 if(read < 0){ 64 throw new EOFException ("Other endpoint probably disconnected"); 65 } 66 if(read <= _readThreshold){ 67 int attempt = 0; 68 int readTotal = read; 69 do{ 70 readTotal = readTotal + manager.read(cycle.getChannel(), input); 71 attempt++; 72 }while(attempt < _readAttempts && readTotal <= _readThreshold); 73 if(readTotal <= _readThreshold){ 74 return; 75 } 76 } 77 input.flip(); 78 finished = cycle.getHandler().read(cycle); 79 while(!finished && input.hasRemaining()){ 80 finished = cycle.getHandler().read(cycle); 81 } 82 if(!input.hasRemaining()){ 83 input.clear(); 84 } 85 } 86 } 87 } 88 | Popular Tags |