1 | package net.spy.memcached.ops; |
2 | |
3 | import java.util.ArrayList; |
4 | import java.util.Collection; |
5 | |
6 | import net.spy.memcached.OperationFactory; |
7 | |
8 | /** |
9 | * Base class for operation factories. |
10 | * |
11 | * <p> |
12 | * There is little common code between OperationFactory implementations, but |
13 | * some exists, and is complicated and likely to cause problems. |
14 | * </p> |
15 | */ |
16 | public abstract class BaseOperationFactory implements OperationFactory { |
17 | |
18 | private String first(Collection<String> keys) { |
19 | return keys.iterator().next(); |
20 | } |
21 | |
22 | public Collection<Operation> clone(KeyedOperation op) { |
23 | assert op.getState() == OperationState.WRITING |
24 | : "Who passed me an operation in the " + op.getState() + "state?"; |
25 | assert !op.isCancelled() : "Attempted to clone a canceled op"; |
26 | assert !op.hasErrored() : "Attempted to clone an errored op"; |
27 | |
28 | Collection<Operation> rv = new ArrayList<Operation>( |
29 | op.getKeys().size()); |
30 | if(op instanceof GetOperation) { |
31 | rv.addAll(cloneGet(op)); |
32 | } else if(op instanceof GetsOperation) { |
33 | GetsOperation.Callback callback = |
34 | (GetsOperation.Callback)op.getCallback(); |
35 | for(String k : op.getKeys()) { |
36 | rv.add(gets(k, callback)); |
37 | } |
38 | } else if(op instanceof CASOperation) { |
39 | CASOperation cop = (CASOperation)op; |
40 | rv.add(cas(cop.getStoreType(), first(op.getKeys()), |
41 | cop.getCasValue(), cop.getFlags(), cop.getExpiration(), |
42 | cop.getBytes(), cop.getCallback())); |
43 | } else if(op instanceof DeleteOperation) { |
44 | rv.add(delete(first(op.getKeys()), op.getCallback())); |
45 | } else if(op instanceof MutatorOperation) { |
46 | MutatorOperation mo = (MutatorOperation)op; |
47 | rv.add(mutate(mo.getType(), first(op.getKeys()), |
48 | mo.getBy(), mo.getDefault(), mo.getExpiration(), |
49 | op.getCallback())); |
50 | } else if(op instanceof StoreOperation) { |
51 | StoreOperation so = (StoreOperation)op; |
52 | rv.add(store(so.getStoreType(), first(op.getKeys()), so.getFlags(), |
53 | so.getExpiration(), so.getData(), op.getCallback())); |
54 | } else if(op instanceof ConcatenationOperation) { |
55 | ConcatenationOperation c = (ConcatenationOperation)op; |
56 | rv.add(cat(c.getStoreType(), c.getCasValue(), first(op.getKeys()), |
57 | c.getData(), c.getCallback())); |
58 | } else { |
59 | assert false : "Unhandled operation type: " + op.getClass(); |
60 | } |
61 | |
62 | return rv; |
63 | } |
64 | |
65 | protected abstract Collection<? extends Operation> cloneGet( |
66 | KeyedOperation op); |
67 | |
68 | } |