ResponseParser { public Response parse(final InputStream in) throws IOException { try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in, US_ASCII))) { final String response = reader.readLine().trim(); if (response.startsWith("CONFIG cluster ")) { final int configVersion = Integer.valueOf(reader.readLine()); final List<String> hosts = Splitter.on(' ').splitToList(reader.readLine()); final List<HostAndPort> result = new ArrayList<>(); for (final String host : hosts) { final List<String> tokens = Splitter.on('|').splitToList(host); if (tokens.size() != 3) { throw new IOException("Expected 3 parts for a host, but got " + host); } result.add(HostAndPort.fromParts(tokens.get(0), Integer.valueOf(tokens.get(2)))); } final String emptyLine = reader.readLine(); if (!"".equals(emptyLine)) { throw new IOException("Expected empty trailing line, invalid server response"); } final String end = reader.readLine(); if (!"END".equals(end)) { throw new IOException("Expected end of response, invalid server response"); } return new Response(configVersion, result); } else { throw new IOException("Unexpected server response: " + response); } } }  Response parse(final InputStream in);  }
@Test public void parseFull() throws IOException { final InputStream in = in("CONFIG cluster 0 140\n2\nhost1|172.31.15.57|11211 host2|172.31.8.107|11212\n\r\nEND"); final Response response = parser.parse(in); assertEquals(2, response.getConfigurationVersion()); assertEquals(asList(fromParts("host1", 11211), fromParts("host2", 11212)), response.getHosts()); }
@Test public void parseSingleNode() throws IOException { final InputStream in = in("CONFIG cluster 0 140\n2\nhost1|172.31.15.57|11211\n\r\nEND"); final Response response = parser.parse(in); assertEquals(2, response.getConfigurationVersion()); assertEquals(asList(fromParts("host1", 11211)), response.getHosts()); }
@Test public void parseNoIp() throws IOException { final InputStream in = in("CONFIG cluster 0 140\n2\nhost1||11211 host2|172.31.8.107|11212\n\r\nEND"); final Response response = parser.parse(in); assertEquals(2, response.getConfigurationVersion()); assertEquals(asList(fromParts("host1", 11211), fromParts("host2", 11212)), response.getHosts()); }
@Test(expected = IOException.class) public void parseMissingEnd() throws IOException { final InputStream in = in("CONFIG cluster 0 140\n2\nhost1|172.31.15.57|11211\n\r\n"); parser.parse(in); }
@Test(expected = IOException.class) public void parseMissingEmpty() throws IOException { final InputStream in = in("CONFIG cluster 0 140\n2\nhost1|172.31.15.57|11211\n"); parser.parse(in); }
@Test(expected = IOException.class) public void parseError() throws IOException { final InputStream in = in("END"); parser.parse(in); }