01: package org.xcache;
02:
03: import java.io.IOException;
04: import java.net.InetAddress;
05: import java.util.ArrayList;
06: import java.util.List;
07:
08: import org.xsocket.stream.IBlockingConnection;
09:
10: import net.sf.jsr107cache.Cache;
11:
12: public final class StaticCacheClientManager implements
13: ICacheClientManager {
14:
15: private final ICacheServerLocator locator = new CacheServerLocator();
16: private final List<Address> addresses = new ArrayList<Address>();
17:
18: public void addCacheServer(InetAddress addr, int port)
19: throws IOException {
20: Address address = new Address(addr, port);
21: addresses.add(address);
22:
23: addSegment(new Address(addr, port), addresses.size() - 1);
24: }
25:
26: private void addSegment(Address serviceAddress, int segment)
27: throws IOException {
28:
29: IBlockingConnection connection = null;
30: try {
31: connection = ConnectionPool.getInstance().getConnection(
32: serviceAddress);
33: connection.markWritePosition();
34: connection.write((int) 0); // emtpy length field
35: int length = 0;
36:
37: length += connection.write(CacheServer.CMD_ADD_SEGMENT);
38: length += connection.write(segment);
39:
40: connection.resetToWriteMark();
41: connection.write(length);
42:
43: connection.flush();
44:
45: connection.readInt(); // first position is length
46: byte response = connection.readByte();
47: if (response != CacheServer.RESULT_OK_WITHOUT_RETURNVALUE) {
48: throw new IOException("couldn't add segment");
49: }
50:
51: connection.close();
52: } catch (IOException e) {
53: if (connection != null) {
54: try {
55: ConnectionPool.getInstance().destroyConnection(
56: connection);
57: } catch (Exception ignore) {
58: }
59: }
60:
61: throw e;
62: }
63: }
64:
65: public Cache getCache() {
66: return new CacheClient(locator);
67: }
68:
69: private final class CacheServerLocator implements
70: ICacheServerLocator {
71:
72: public int computeSegement(Object key) {
73: int hc = key.hashCode();
74: if (hc < 0) {
75: hc = 0 - hc;
76: }
77:
78: int segement = hc % addresses.size();
79: return segement;
80: }
81:
82: public Address getServiceAddress(int segment)
83: throws IOException {
84: return addresses.get(segment);
85: }
86: }
87: }
|