1 | package net.spy.memcached.protocol.ascii; |
2 | |
3 | import java.nio.ByteBuffer; |
4 | import java.util.Collection; |
5 | import java.util.Collections; |
6 | |
7 | import net.spy.memcached.KeyUtil; |
8 | import net.spy.memcached.ops.OperationCallback; |
9 | import net.spy.memcached.ops.OperationState; |
10 | import net.spy.memcached.ops.OperationStatus; |
11 | |
12 | /** |
13 | * Base class for ascii store operations (add, set, replace, append, prepend). |
14 | */ |
15 | abstract class BaseStoreOperationImpl extends OperationImpl { |
16 | |
17 | private static final int OVERHEAD = 32; |
18 | private static final OperationStatus STORED = |
19 | new OperationStatus(true, "STORED"); |
20 | protected final String type; |
21 | protected final String key; |
22 | protected final int flags; |
23 | protected final int exp; |
24 | protected final byte[] data; |
25 | |
26 | public BaseStoreOperationImpl(String t, String k, int f, int e, |
27 | byte[] d, OperationCallback cb) { |
28 | super(cb); |
29 | type=t; |
30 | key=k; |
31 | flags=f; |
32 | exp=e; |
33 | data=d; |
34 | } |
35 | |
36 | @Override |
37 | public void handleLine(String line) { |
38 | assert getState() == OperationState.READING |
39 | : "Read ``" + line + "'' when in " + getState() + " state"; |
40 | getCallback().receivedStatus(matchStatus(line, STORED)); |
41 | transitionState(OperationState.COMPLETE); |
42 | } |
43 | |
44 | @Override |
45 | public void initialize() { |
46 | ByteBuffer bb=ByteBuffer.allocate(data.length |
47 | + KeyUtil.getKeyBytes(key).length + OVERHEAD); |
48 | setArguments(bb, type, key, flags, exp, data.length); |
49 | assert bb.remaining() >= data.length + 2 |
50 | : "Not enough room in buffer, need another " |
51 | + (2 + data.length - bb.remaining()); |
52 | bb.put(data); |
53 | bb.put(CRLF); |
54 | bb.flip(); |
55 | setBuffer(bb); |
56 | } |
57 | |
58 | @Override |
59 | protected void wasCancelled() { |
60 | // XXX: Replace this comment with why I did this |
61 | getCallback().receivedStatus(CANCELLED); |
62 | } |
63 | |
64 | public Collection<String> getKeys() { |
65 | return Collections.singleton(key); |
66 | } |
67 | |
68 | public int getFlags() { |
69 | return flags; |
70 | } |
71 | |
72 | public int getExpiration() { |
73 | return exp; |
74 | } |
75 | |
76 | public byte[] getData() { |
77 | return data; |
78 | } |
79 | } |