package geniusweb.actions; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import geniusweb.issuevalue.Bid; /** * Indicates that a party conditionally agrees with any of the {@link Vote}s * provided. */ public class Votes extends AbstractAction { private final List votes; /** * * @param id party id * @param votes the {@link Vote}s that the party can agree on, if the * condition of the Vote holds. There can be at most 1 * {@link Vote} for each bid. */ @JsonCreator public Votes(@JsonProperty("actor") PartyId id, @JsonProperty("votes") List votes) { super(id); this.votes = votes; if (votes == null) throw new NullPointerException("votes must be not null"); for (Vote vote : votes) { if (!vote.getActor().equals(id)) { throw new IllegalArgumentException("All votes must come from " + id + " but found " + vote); } } Map counts = votes.stream().map(vote -> vote.getBid()) .collect(Collectors.groupingBy(bid -> bid, Collectors.counting())); Optional> nonunique = counts.entrySet().stream() .filter(entry -> entry.getValue() > 1).findAny(); if (nonunique.isPresent()) throw new IllegalArgumentException( "Votes contains multiple Vote's for " + nonunique.get().getKey()); } /** * Test if Votes extends other votes. Extending means that for each vote on * bid B with power P in othervotes, this contains also a vote for bid B * with power at most P. * * @param otherVotes * @return true iff this extends the otherVotes. */ public boolean isExtending(Votes otherVotes) { if (!otherVotes.getActor().equals(getActor())) return false; for (Vote vote : otherVotes.getVotes()) { Vote myvote = getVote(vote.getBid()); if (myvote == null) return false; if (myvote.getMinPower() > vote.getMinPower()) return false; } return true; } /** * * @param bid the bid that we may have a vote for * @return myvote for bid, or null if no vote for that bid; */ public Vote getVote(Bid bid) { for (Vote vote : votes) { if (vote.getBid().equals(bid)) return vote; } return null; } public List getVotes() { return Collections.unmodifiableList(votes); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((votes == null) ? 0 : votes.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Votes other = (Votes) obj; if (votes == null) { if (other.votes != null) return false; } else if (!votes.equals(other.votes)) return false; return true; } @Override public String toString() { return "Votes[" + getActor() + "," + votes + "]"; } }