com.weaverplatform.protocol.SortedWriteOperationParser Maven / Gradle / Ivy
package com.weaverplatform.protocol;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.weaverplatform.protocol.model.*;
import java.io.*;
import java.util.Set;
import java.util.TreeSet;
import static com.weaverplatform.util.SortUtil.*;
/**
* @author bastbijl
*/
public class SortedWriteOperationParser extends WriteOperationParser {
public SortedWriteOperationParser(Reader reader) {
super(reader);
}
public SortedWriteOperationParser(InputStream stream) throws UnsupportedEncodingException {
super(stream);
}
public static Character sortChar(String id) {
if(id == null || id.trim().isEmpty()) {
return Character.MIN_VALUE;
}
return id.charAt(id.length()-1); // use last character
}
public static Set startChars(InputStream stream) throws IOException {
TreeSet set = new TreeSet<>(charComparator);
JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
reader.beginArray();
while(reader.hasNext()) {
String id = sortKey(gson.fromJson(reader, new TypeToken(){}.getType()));
Character sc = sortChar(id);
set.add(sc);
}
return set;
}
public TreeSet parseNextSorted(int chunkSize, Character filter) throws IOException {
if(jsonReader == null) {
jsonReader = new JsonReader(sourceReader);
jsonReader.beginArray();
}
TreeSet set = new TreeSet<>(writeOperationComparator);
while(jsonReader.hasNext() && (chunkSize == -1 || set.size() < chunkSize)) {
WriteOperation operation;
if(includePayload) {
JsonObject source = JsonParser.parseReader(jsonReader).getAsJsonObject();
operation = gson.fromJson(source, new TypeToken() {}.getType());
operation.setPayload(source.toString());
} else {
operation = gson.fromJson(jsonReader, new TypeToken() {}.getType());
}
if (filter == null || filter.equals(sortChar(sortKey(operation)))) {
if(defaultCreator != null) {
operation.setUser(defaultCreator);
}
set.add(operation);
}
}
return set;
}
}