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