/** * Establish a connection with the Leader found by findLeader. Retries 5 times before giving up. * * @param addr - the address of the Leader to connect to. * @throws IOException - if the socket connection fails on the 5th attempt * @throws ConnectException * @throws InterruptedException */ protected void connectToLeader(InetSocketAddress addr) throws IOException, ConnectException, InterruptedException { sock = new Socket(); sock.setSoTimeout(self.tickTime * self.initLimit); for (int tries = 0; tries < 5; tries++) { try { sock.connect(addr, self.tickTime * self.syncLimit); sock.setTcpNoDelay(nodelay); break; } catch (IOException e) { if (tries == 4) { LOG.error("Unexpected exception", e); throw e; } else { LOG.warn("Unexpected exception, tries=" + tries + ", connecting to " + addr, e); sock = new Socket(); sock.setSoTimeout(self.tickTime * self.initLimit); } } Thread.sleep(1000); } leaderIs = M2mBinaryInputArchive.getArchive(new BufferedInputStream(sock.getInputStream())); bufferedOutput = new BufferedOutputStream(sock.getOutputStream()); leaderOs = M2mBinaryOutputArchive.getArchive(bufferedOutput); }
public void delete(final String path) { M2mRequestHeader m2mRequestHeader = new M2mRequestHeader(); m2mRequestHeader.setType(ZooDefs.OpCode.delete); m2mRequestHeader.setKey(path); M2mDeleteRequest m2mDeleteRequest = new M2mDeleteRequest(path); M2mReplyHeader m2mReplyHeader = new M2mReplyHeader(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); M2mBinaryOutputArchive.getArchive(baos); M2mPacket m2mPacket = new M2mPacket(m2mRequestHeader, m2mReplyHeader, m2mDeleteRequest, new M2mCreateResponse()); tcpClient.write(m2mPacket); }
public String create(final String path, byte[] data) throws IOException { M2mRequestHeader m2mRequestHeader = new M2mRequestHeader(); m2mRequestHeader.setType(ZooDefs.OpCode.create); m2mRequestHeader.setKey(path); M2mCreateRequest m2mCreateRequest = new M2mCreateRequest(); M2mCreateResponse m2mCreateResponse = new M2mCreateResponse(); M2mReplyHeader m2mReplyHeader = new M2mReplyHeader(); m2mCreateRequest.setKey(path); M2mDataNode m2mDataNode = new M2mDataNode(); m2mDataNode.setId(path); m2mDataNode.setData(11); ByteArrayOutputStream baos = new ByteArrayOutputStream(); M2mBinaryOutputArchive boa = M2mBinaryOutputArchive.getArchive(baos); m2mDataNode.serialize(boa, "m2mData"); byte[] bytes = baos.toByteArray(); m2mCreateRequest.setData(bytes); M2mPacket m2mPacket = new M2mPacket(m2mRequestHeader, m2mReplyHeader, m2mCreateRequest, m2mCreateResponse); tcpClient.write(m2mPacket); return ""; }