001package jmri.jmris.srcp;
002
003import jmri.InstanceManager;
004
005import java.io.IOException;
006import java.io.OutputStream;
007import java.util.Date;
008
009/*
010 * The SRCP protocol requires that response messages include a timestamp based
011 * on the fast clock.  This class is a utility class to generate timestamp
012 * and send it on to the stream with the output.
013 *
014 * @author Paul Bender Copyright 2014,2020
015 */
016public class TimeStampedOutput extends OutputStream {
017
018    private final OutputStream outputStream;
019
020    public TimeStampedOutput(OutputStream outputStream){
021        super();
022        this.outputStream = outputStream;
023    }
024
025    @Override
026    public void write(byte[] bytes, int i, int i1) throws IOException {
027       outputStream.write(bytes,i,i1);
028    }
029
030    @Override
031    public synchronized void write(byte[] bytes) throws IOException {
032        Date currentTime = InstanceManager.getDefault(jmri.Timebase.class).getTime();
033        long time = currentTime.getTime();
034        String timeString = String.format("%s.%s ",time/1000,time%1000);
035        byte[] outputBytes = new byte[timeString.length() + bytes.length];
036        System.arraycopy(timeString.getBytes(),0,outputBytes,0,timeString.length());
037        System.arraycopy(bytes,0, outputBytes,timeString.length(),bytes.length);
038        outputStream.write(outputBytes);
039    }
040
041    @Override
042    public void write(int i) throws IOException {
043        outputStream.write(i);
044    }
045
046    @Override
047    public void flush() throws IOException {
048        outputStream.flush();
049    }
050
051    @Override
052    public void close() throws IOException {
053        outputStream.close();
054    }
055
056}