meerkat-java/voter-registry/src/main/java/util/CollectionMessagesUtils.java

83 lines
3.2 KiB
Java

package util;
import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.VoterRegistryMessage;
import meerkat.protobuf.BulletinBoardAPI;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by Vladimir Eliezer Tokarev on 1/15/2016.
* adds extra functionality to Messages collections
*/
public abstract class CollectionMessagesUtils {
/**
* Converts lost of UnsignedBulletinBoardMessage to VoterRegistryMessags
* @param messages list<VoterRegistryMessage>
* @return List<VoterRegistryMessage>
*/
public static List<VoterRegistryMessage> ConvertToVoterRegistryMessages(List<BulletinBoardAPI.UnsignedBulletinBoardMessage> messages){
return messages.stream().map(VoterRegistryMessage::new).collect(Collectors.toList());
}
/**
* Gets map of GroupId to basicMessage, where the basicMessages are the last actions for those groups
* @param messages List<VoterRegistryMessage>
* @return Map{String:VoterRegistryMessage}
* @throws ParseException
*/
public static Map<String, VoterRegistryMessage> GetLatestGroupsActions(List<VoterRegistryMessage> messages) throws ParseException {
Map<String, VoterRegistryMessage> groupIdToMessage = new HashMap<>();
// iterate trough all the messages and put into the map the last updated groups actions
for (VoterRegistryMessage message : messages) {
String groupId = message.GetWantedTagFromBasicMessage(RegistryTags.GROUP_ID_TAG);
VoterRegistryMessage temp = groupIdToMessage.get(groupId);
if (temp != null) {
if (temp != message) {
if (temp.GetBasicMessageActionTimestamp().before(message.GetBasicMessageActionTimestamp())) {
groupIdToMessage.put(groupId, message);
}
}
}
}
return groupIdToMessage;
}
/**
* Gets list of groups ids of the basicMessages that carried the adding to group tag
* @param groupIdToMessage Map<String, VoterRegistryMessage>
* @return List<String>
*/
public static List<String> GetListOfGroupIds(Map<String, VoterRegistryMessage> groupIdToMessage) {
List<String> groupsIds = new ArrayList<>();
groupIdToMessage.values().stream().filter(VoterRegistryMessage::IsGroupAdding).forEach(message -> {
String groupId = message.GetWantedTagFromBasicMessage(RegistryTags.GROUP_ID_TAG);
groupsIds.add(groupId);
});
return groupsIds;
}
/**
* Gets all the basic messages from bulletin board messages
* @param listOfMessages list of bulletin board messages
* @return List<UnsignedBulletinBoardMessage>
* @throws InvalidProtocolBufferException
*/
public static List<BulletinBoardAPI.UnsignedBulletinBoardMessage> GetUnsignedBulletinBoardMessages(
List<BulletinBoardAPI.BulletinBoardMessage> listOfMessages) throws InvalidProtocolBufferException {
return listOfMessages.stream().map(BulletinBoardAPI.BulletinBoardMessage::getMsg).collect(Collectors.toList());
}
}