org.swisspush.gateleen.player.log.ReaderRequestLog Maven / Gradle / Ivy
package org.swisspush.gateleen.player.log;
import org.swisspush.gateleen.player.exchange.Exchange;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Request log providing exchanges from a serialized JSON stream, as the one generated by the logging filter.
*
* @author https://github.com/lbovet [Laurent Bovet]
*/
public abstract class ReaderRequestLog extends RequestLog {
private String urlPrefix;
class ExchangeIterator implements Iterator {
private BufferedReader bufferedReader;
private Exchange readAhead;
ExchangeIterator() {
bufferedReader = new BufferedReader(getReader());
}
@Override
public boolean hasNext() {
if(readAhead != null) {
return true;
}
try {
readAhead = next();
return true;
} catch (NoSuchElementException e) {
return false;
}
}
@Override
public Exchange next() {
if (readAhead != null) {
Exchange result = readAhead;
readAhead = null;
return result;
} else {
try {
String line = "";
while(line != null && ( line.trim().equals("") || line.trim().startsWith("#"))) {
line = bufferedReader.readLine();
}
if (line == null) {
throw new NoSuchElementException();
}
try {
return new Exchange(urlPrefix, new JSONObject(line));
} catch (JSONException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
protected abstract Reader getReader();
public ReaderRequestLog(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
@Override
public Iterator iterator() {
return new ExchangeIterator();
}
}