HTTPClient and JSON Parse
Recently, I get a request to monitor a SOLR cluster status, we can easily get the content from this URL
http://alljobs.us-east-1.elasticbeanstalk.com/solr/admin/collections?action=CLUSTERSTATUS
The JSON response will be similar to this:
{
"responseHeader":{
"status":0,
"QTime":6},
"cluster":{
"collections":{
"allJobs":{
"pullReplicas":"0",
"replicationFactor":"1",
"shards":{"shard1":{
"range":"80000000-7fffffff",
"state":"active",
"replicas":{
"core_node-690563414":{
"core":"allJobs_shard1_replica_n-673720407",
"base_url":"http://172.23.2.92:8983/solr",
"node_name":"172.23.2.92:8983_solr",
"state":"active",
"type":"NRT",
"leader":"true"},
"core_node-741092435":{
"core":"allJobs_shard1_replica_n-724249428",
"base_url":"http://172.23.2.66:8983/solr",
"node_name":"172.23.2.66:8983_solr",
"state":"active",
"type":"NRT"}}}},
"router":{"name":"compositeId"},
"maxShardsPerNode":"1",
"autoAddReplicas":"false",
"nrtReplicas":"1",
"tlogReplicas":"0",
"znodeVersion":7088,
"configName":"allJobs"}},
"live_nodes":["172.23.2.66:8983_solr",
"172.23.2.92:8983_solr"]}}
First of all, my colleague shows me the HTTPClient Fluent API, it really much easier and nice.
https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html
Then I found I may only need to parse parts of the JSON. Some people may use this library to do that.
https://github.com/json-path/JsonPath
But we may still want to keep using the jackson mapper. Here is the UNIT tests and Implement class for that.
package com.sillycat.jobssolrconsumer.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
static ObjectMapper mapper = new ObjectMapper();
public static void readPartOfInfo(String json) {
JsonNode root;
try {
root = mapper.readTree(json);
JsonNode nodes = root.findPath("replicas");
for(JsonNode node : nodes){
String url = node.get("base_url").asText();
String status = node.get("state").asText();
System.out.println("---------" + url + " " + status);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map convertJson2HashMap(String json) {
Map result = null;
try {
result = mapper.readValue(json, new TypeReference