001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others.
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 * Contributors:
017 *     Thomas Roger
018 */
019
020package org.nuxeo.ecm.automation.client.rest.api;
021
022import java.io.IOException;
023import java.util.HashMap;
024import java.util.Map;
025
026import org.codehaus.jackson.JsonNode;
027import org.codehaus.jackson.map.ObjectMapper;
028import org.codehaus.jackson.type.TypeReference;
029import org.nuxeo.ecm.automation.client.AutomationException;
030
031import com.sun.jersey.api.client.ClientResponse;
032
033/**
034 * A Rest response from Nuxeo REST API.
035 * <p>
036 * Wraps a {@link ClientResponse} response and provides utility methods to get back the result as a {@link Map} or as a
037 * {@link JsonNode}.
038 *
039 * @since 5.8
040 */
041public class RestResponse {
042
043    protected final ClientResponse clientResponse;
044
045    protected ObjectMapper objectMapper = new ObjectMapper();
046
047    protected JsonNode responseAsJson;
048
049    public RestResponse(ClientResponse clientResponse) {
050        this.clientResponse = clientResponse;
051    }
052
053    public ClientResponse getClientResponse() {
054        return clientResponse;
055    }
056
057    public int getStatus() {
058        return clientResponse.getStatus();
059    }
060
061    public JsonNode asJson() {
062        computeResponseAsJson();
063        return responseAsJson;
064    }
065
066    protected void computeResponseAsJson() {
067        if (responseAsJson == null) {
068            try {
069                responseAsJson = objectMapper.readTree(clientResponse.getEntityInputStream());
070            } catch (IOException e) {
071                throw new AutomationException(e);
072            }
073        }
074    }
075
076    public Map<String, Object> asMap() {
077        computeResponseAsJson();
078        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
079        };
080        try {
081            return objectMapper.readValue(responseAsJson, typeRef);
082        } catch (IOException e) {
083            throw new AutomationException(e);
084        }
085    }
086
087}