public class GPSReceiverSpout implements IRichSpout {
private static final long serialVersionUID = 1L;
private SpoutOutputCollector _collector;
private BufferedReader fileReader;
//private TopologyContext context;
//private String file="/home/ghchen/2013-01-05.1/2013-01-05--11_05_48.txt";
private TupleInfo tupleInfo=new TupleInfo();
static Socket sock=null;
@Override
public void close() {
}
@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector)
{
_collector = collector;
System.out.println("This is open function in FieldSpout !");
}
@SuppressWarnings("unused")
@Override
public void nextTuple() {
int count=0;
int ch=0;
int err=0;
try {
if(sock==null){
sock=new Socket("172.20.14.XXX",portXXXX);}
while(true){
byte[] b3= new byte[3];
if(sock!=null ){
try{
sock.getInputStream().read(b3,0,3);
ch=b3[0];
}catch ( Exception e){
System.out.println("connection reset, reconnecting ...");
sock.close();
Thread.sleep(100);
sock=new Socket("172.20.14.XXX",portXXXX);;
}
}else{
sock=new Socket("172.20.14.XXX",portXXXX);;
break ;
}
int len=SocketJava.bytesToShort(b3, 1);
if(len<0) break;
byte[] bytelen= new byte[len];
sock.getInputStream().read(bytelen);
if(bytelen==null){
System.out.println("read the second part from byte from socket failed ! ");
break;
}
sock.getInputStream().markSupported();
sock.getInputStream().mark(3);
String gpsString=SocketJava.DissectOneMessage(ch,bytelen);
String[] GPSRecord=null;
if(gpsString!=null){
GPSRecord =gpsString.split(TupleInfo.getDelimiter());
_collector.emit(new Values(GPSRecord[0],GPSRecord[3],GPSRecord[7],GPSRecord[5],
GPSRecord[6] , GPSRecord[2],GPSRecord[1]));
//}
}else{
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void ack(Object id) {
System.out.println("OK:"+id);
}
@Override
public void fail(Object id) {
System.out.println("Fail:"+id);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
TupleInfo tuple = new TupleInfo();
Fields fieldsArr;
try {
fieldsArr= tuple.getFieldList();
declarer.declare(fieldsArr);
} catch (Exception e) {
throw new RuntimeException("error:fail to new Tuple object in declareOutputFields, tuple is null",e);
}
}
@Override
public void activate() {
}
@Override
public void deactivate() {
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
static int count=0;
public static void writeToFile(String fileName, Object obj){
try {
FileWriter fwriter;
fwriter= new FileWriter(fileName,true);
BufferedWriter writer= new BufferedWriter(fwriter);
writer.write(obj.toString());
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}