View Javadoc
1   package civitas.common.ballotdesign;
2   
3   import java.util.Map;
4   
5   import org.springframework.beans.factory.annotation.Autowired;
6   import org.springframework.stereotype.Controller;
7   
8   import civitas.common.CommonConstants;
9   import civitas.common.VoteChoice;
10  import civitas.common.tallystate.RecordBeat;
11  import civitas.common.tallystate.TallyState;
12  import civitas.crypto.CryptoException;
13  import civitas.crypto.msg.ElGamalMsg;
14  import civitas.crypto.parameters.DecodeChoice;
15  import civitas.util.CivitasBigInteger;
16  
17  @Controller
18  public class TallyVote implements CommonConstants {
19  
20  	@Autowired
21  	RecordBeat recordBeat;
22  
23  	@Autowired
24  	DecodeChoice decodeChoice;
25  
26  	public void apply(
27  			final String additionalcontext,
28  			final ElGamalMsg msg,
29  			final String currentcontext,
30  			final TallyState state,
31  			final Map<CivitasBigInteger, VoteChoice> decodeMap) {
32  
33  		String desiredContext = additionalcontext + KIND;
34  		if (currentcontext == null || !currentcontext.startsWith(desiredContext)) {
35  			throw new IllegalArgumentException("Incorrect context");
36  		}
37  
38  		if (msg == null) {
39  			throw new IllegalArgumentException("Null message");
40  		}
41  
42  		try {
43  			VoteChoice choice = decodeChoice.apply(decodeMap, msg.m());
44  			String suffix = currentcontext.substring(desiredContext.length());
45  			int ind = suffix.indexOf(':');
46  			try {
47  				int i = Integer.parseInt(suffix.substring(0, ind));
48  				int j = Integer.parseInt(suffix.substring(ind + 1));
49  				if (choice == VoteChoice.I_BEATS_J) {
50  					recordBeat.apply(state, i, j);
51  				}
52  				if (choice == VoteChoice.J_BEATS_I) {
53  					recordBeat.apply(state, j, i);
54  				}
55  
56  			} catch (NumberFormatException e) {
57  				throw new IllegalArgumentException("Invalid context: " + suffix);
58  			}
59  
60  		} catch (CryptoException e) {
61  			throw new IllegalArgumentException("Invalid vote value", e);
62  		} catch (IndexOutOfBoundsException e) {
63  			throw new IllegalArgumentException("Invalid index", e);
64  		}
65  	}
66  }