001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
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 *      Thibaud Arguillere <targuillere@nuxeo.com>
016 *      Vladimir Pasquier <vpasquier@nuxeo.com>
017 */
018package org.nuxeo.ecm.automation.features;
019
020import java.io.IOException;
021import java.util.Map;
022
023import javax.ws.rs.core.MediaType;
024import javax.ws.rs.core.MultivaluedMap;
025
026import org.codehaus.jackson.map.ObjectMapper;
027import org.nuxeo.ecm.automation.context.ContextHelper;
028import org.nuxeo.ecm.core.api.Blob;
029import org.nuxeo.ecm.core.api.Blobs;
030import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
031
032import com.sun.jersey.api.client.Client;
033import com.sun.jersey.api.client.ClientResponse;
034import com.sun.jersey.api.client.WebResource;
035import com.sun.jersey.api.client.config.ClientConfig;
036import com.sun.jersey.api.client.config.DefaultClientConfig;
037import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
038import com.sun.jersey.multipart.MultiPart;
039import com.sun.jersey.multipart.impl.MultiPartWriter;
040
041/**
042 * @since 7.3
043 */
044public class HTTPHelper implements ContextHelper {
045
046    protected static volatile ObjectMapper mapper = new ObjectMapper();
047
048    private static final Integer TIMEOUT = 1000 * 60 * 5; // 5min
049
050    public Blob call(String username, String password, String requestType, String path) throws IOException {
051        return call(username, password, requestType, path, null, null, null, null);
052    }
053
054    public Blob call(String username, String password, String requestType, String path,
055            Map<String, String> headers) throws IOException {
056        return call(username, password, requestType, path, null, null, null, headers);
057    }
058
059    public Blob call(String username, String password, String requestType, String path, MultiPart mp)
060            throws IOException {
061        return call(username, password, requestType, path, null, null, mp, null);
062    }
063
064    public Blob call(String username, String password, String requestType, String path, MultiPart mp,
065            Map<String, String> headers) throws IOException {
066        return call(username, password, requestType, path, null, null, mp, headers);
067    }
068
069    public Blob call(String username, String password, String requestType, String path,
070            MultivaluedMap<String, String> queryParams) throws IOException {
071        return call(username, password, requestType, path, null, queryParams, null, null);
072    }
073
074    public Blob call(String username, String password, String requestType, String path, Object data)
075            throws IOException {
076        return call(username, password, requestType, path, data, null, null, null);
077    }
078
079    public Blob call(String username, String password, String requestType, String path, Object data,
080            Map<String, String> headers) throws IOException {
081        return call(username, password, requestType, path, data, null, null, headers);
082    }
083
084    public Blob call(String username, String password, String requestType, String url, Object data,
085            MultivaluedMap<String, String> queryParams, MultiPart mp, Map<String, String> headers) throws IOException {
086        ClientConfig config = new DefaultClientConfig();
087        config.getClasses().add(MultiPartWriter.class);
088        Client client = Client.create(config);
089        client.setConnectTimeout(TIMEOUT);
090        client.setReadTimeout(TIMEOUT);
091        if (username != null && password != null) {
092            client.addFilter(new HTTPBasicAuthFilter(username, password));
093        }
094
095        WebResource wr = client.resource(url);
096
097        if (queryParams != null && !queryParams.isEmpty()) {
098            wr = wr.queryParams(queryParams);
099        }
100        WebResource.Builder builder;
101        builder = wr.accept(MediaType.APPLICATION_JSON);
102        if (mp != null) {
103            builder = wr.type(MediaType.MULTIPART_FORM_DATA_TYPE);
104        }
105
106        // Adding some headers if needed
107        if (headers != null && !headers.isEmpty()) {
108            for (String headerKey : headers.keySet()) {
109                builder.header(headerKey, headers.get(headerKey));
110            }
111        }
112        ClientResponse response = null;
113        try {
114            switch (requestType) {
115            case "HEAD":
116            case "GET":
117                response = builder.get(ClientResponse.class);
118                break;
119            case "POST":
120                if (mp != null) {
121                    response = builder.post(ClientResponse.class, mp);
122                } else {
123                    response = builder.post(ClientResponse.class, data);
124                }
125                break;
126            case "PUT":
127                if (mp != null) {
128                    response = builder.put(ClientResponse.class, mp);
129                } else {
130                    response = builder.put(ClientResponse.class, data);
131                }
132                break;
133            case "DELETE":
134                response = builder.delete(ClientResponse.class, data);
135                break;
136            default:
137                break;
138            }
139        } catch (Exception e) {
140            throw new RuntimeException(e);
141        }
142        if (response != null && response.getStatus() >= 200 && response.getStatus() < 300) {
143            return Blobs.createBlob(response.getEntityInputStream());
144        } else {
145            return new StringBlob(response.getStatusInfo() != null ? response.getStatusInfo().toString() : "error");
146        }
147    }
148
149}