001/* 002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Thomas Roger 016 */ 017 018package org.nuxeo.ecm.automation.client.rest.api; 019 020import java.io.IOException; 021import java.util.HashMap; 022import java.util.Map; 023 024import org.codehaus.jackson.JsonNode; 025import org.codehaus.jackson.map.ObjectMapper; 026import org.codehaus.jackson.type.TypeReference; 027import org.nuxeo.ecm.automation.client.AutomationException; 028 029import com.sun.jersey.api.client.ClientResponse; 030 031/** 032 * A Rest response from Nuxeo REST API. 033 * <p> 034 * Wraps a {@link ClientResponse} response and provides utility methods to get back the result as a {@link Map} or as a 035 * {@link JsonNode}. 036 * 037 * @since 5.8 038 */ 039public class RestResponse { 040 041 protected final ClientResponse clientResponse; 042 043 protected ObjectMapper objectMapper = new ObjectMapper(); 044 045 protected JsonNode responseAsJson; 046 047 public RestResponse(ClientResponse clientResponse) { 048 this.clientResponse = clientResponse; 049 } 050 051 public ClientResponse getClientResponse() { 052 return clientResponse; 053 } 054 055 public int getStatus() { 056 return clientResponse.getStatus(); 057 } 058 059 public JsonNode asJson() { 060 computeResponseAsJson(); 061 return responseAsJson; 062 } 063 064 protected void computeResponseAsJson() { 065 if (responseAsJson == null) { 066 try { 067 responseAsJson = objectMapper.readTree(clientResponse.getEntityInputStream()); 068 } catch (IOException e) { 069 throw new AutomationException(e); 070 } 071 } 072 } 073 074 public Map<String, Object> asMap() { 075 computeResponseAsJson(); 076 TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { 077 }; 078 try { 079 return objectMapper.readValue(responseAsJson, typeRef); 080 } catch (IOException e) { 081 throw new AutomationException(e); 082 } 083 } 084 085}