1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package org.apache.zookeeper.server.admin; 20 21 import com.fasterxml.jackson.core.JsonGenerationException; 22 import com.fasterxml.jackson.databind.JsonMappingException; 23 import com.fasterxml.jackson.databind.ObjectMapper; 24 import com.fasterxml.jackson.databind.PropertyNamingStrategy; 25 import com.fasterxml.jackson.databind.SerializationFeature; 26 import java.io.IOException; 27 import java.io.PrintWriter; 28 import org.slf4j.Logger; 29 import org.slf4j.LoggerFactory; 30 31 public class JsonOutputter implements CommandOutputter { 32 33 static final Logger LOG = LoggerFactory.getLogger(JsonOutputter.class); 34 35 public static final String ERROR_RESPONSE = "{\"error\": \"Exception writing command response to JSON\"}"; 36 37 private ObjectMapper mapper; 38 JsonOutputter()39 public JsonOutputter() { 40 mapper = new ObjectMapper(); 41 mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); 42 mapper.configure(SerializationFeature.INDENT_OUTPUT, true); 43 mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); 44 } 45 46 @Override getContentType()47 public String getContentType() { 48 return "application/json"; 49 } 50 51 @Override output(CommandResponse response, PrintWriter pw)52 public void output(CommandResponse response, PrintWriter pw) { 53 try { 54 mapper.writeValue(pw, response.toMap()); 55 } catch (JsonGenerationException e) { 56 LOG.warn("Exception writing command response to JSON:", e); 57 pw.write(ERROR_RESPONSE); 58 } catch (JsonMappingException e) { 59 LOG.warn("Exception writing command response to JSON:", e); 60 pw.write(ERROR_RESPONSE); 61 } catch (IOException e) { 62 LOG.warn("Exception writing command response to JSON:", e); 63 pw.write(ERROR_RESPONSE); 64 } 65 } 66 67 } 68