001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.actuate.endpoint.jmx; 018 019import java.util.Collection; 020import java.util.List; 021import java.util.Map; 022 023import com.fasterxml.jackson.databind.JavaType; 024import com.fasterxml.jackson.databind.ObjectMapper; 025 026/** 027 * {@link JmxOperationResponseMapper} that delegates to a Jackson {@link ObjectMapper} to 028 * return a JSON response. 029 * 030 * @author Stephane Nicoll 031 * @since 2.0.0 032 */ 033public class JacksonJmxOperationResponseMapper implements JmxOperationResponseMapper { 034 035 private final ObjectMapper objectMapper; 036 037 private final JavaType listType; 038 039 private final JavaType mapType; 040 041 public JacksonJmxOperationResponseMapper(ObjectMapper objectMapper) { 042 this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); 043 this.listType = this.objectMapper.getTypeFactory() 044 .constructParametricType(List.class, Object.class); 045 this.mapType = this.objectMapper.getTypeFactory() 046 .constructParametricType(Map.class, String.class, Object.class); 047 } 048 049 @Override 050 public Class<?> mapResponseType(Class<?> responseType) { 051 if (CharSequence.class.isAssignableFrom(responseType)) { 052 return String.class; 053 } 054 if (responseType.isArray() || Collection.class.isAssignableFrom(responseType)) { 055 return List.class; 056 } 057 return Map.class; 058 } 059 060 @Override 061 public Object mapResponse(Object response) { 062 if (response == null) { 063 return null; 064 } 065 if (response instanceof CharSequence) { 066 return response.toString(); 067 } 068 if (response.getClass().isArray() || response instanceof Collection) { 069 return this.objectMapper.convertValue(response, this.listType); 070 } 071 return this.objectMapper.convertValue(response, this.mapType); 072 } 073 074}