HttpUtils.java

1
package fr.sii.ogham.sms.util;
2
3
import java.io.IOException;
4
import java.util.ArrayList;
5
import java.util.Arrays;
6
import java.util.HashMap;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.Map.Entry;
10
import java.util.Set;
11
12
import org.apache.http.HttpResponse;
13
import org.apache.http.NameValuePair;
14
import org.apache.http.client.HttpClient;
15
import org.apache.http.client.methods.HttpGet;
16
import org.apache.http.client.utils.URLEncodedUtils;
17
import org.apache.http.impl.client.CloseableHttpClient;
18
import org.apache.http.impl.client.HttpClientBuilder;
19
import org.apache.http.message.BasicNameValuePair;
20
import org.slf4j.Logger;
21
import org.slf4j.LoggerFactory;
22
23
import fr.sii.ogham.core.exception.util.HttpException;
24
import fr.sii.ogham.core.util.BeanUtils;
25
import fr.sii.ogham.core.util.IOUtils;
26
import fr.sii.ogham.sms.util.http.Parameter;
27
import fr.sii.ogham.sms.util.http.Response;
28
29
/**
30
 * Utility class that helps to send HTTP requests.
31
 *
32
 * @author Aurélien Baudet
33
 *
34
 */
35
public final class HttpUtils {
36
    private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
37
38
    /**
39
     * Do a GET request on the provided URL and construct the Query String part
40
     * with the provided list of parameters. If the URL already contains
41
     * parameters (already contains a '?' character), then the parameters are
42
     * added to the existing parameters. The parameters are converted into
43
     * <code>application/x-www-form-urlencoded</code>. For example:
44
     * <code>field1=value1&amp;field1=value2&amp;field2=value3</code>. The special
45
     * characters are encoded. If there is a space, it is encoded into '%20'.
46
     *
47
     * @param url
48
     *            the base url
49
     * @param params
50
     *            the list of parameters to append to the query string
51
     * @return the response
52
     * @throws HttpException
53
     *             when the request has failed
54
     */
55
    public static Response get(String url, List<Parameter> params) throws HttpException {
56
        String fullUrl = url;
57
        String paramsStr = URLEncodedUtils.format(convert(params), "UTF-8");
58 1 1. get : negated conditional → NO_COVERAGE
        fullUrl += (fullUrl.contains("?") ? "&" : "?") + paramsStr;
59
        // spaces are replaced by '+' but some servers doesn't handle it
60
        // correctly
61
        // => convert space to '%20'
62
        fullUrl = fullUrl.replace("+", "%20");
63
        try (CloseableHttpClient client = getHttpClient()) {
64
            LOG.debug("Sending HTTP GET request to {}", fullUrl);
65
            HttpGet request = new HttpGet(fullUrl);
66
            HttpResponse response = client.execute(request);
67
            int statusCode = response.getStatusLine().getStatusCode();
68
            LOG.debug("HTTP GET request successfully sent to {}. Status code: {}", fullUrl, statusCode);
69
            return new Response(statusCode, IOUtils.toString(response.getEntity().getContent()));
70
        } catch (IOException e) {
71
            throw new HttpException("Failed to send GET request to " + fullUrl, e);
72
        }
73
    }
74
75
    /**
76
     * Do a GET request on the provided URL and construct the Query String part
77
     * with the provided list of parameters. If the URL already contains
78
     * parameters (already contains a '?' character), then the parameters are
79
     * added to the existing parameters. The parameters are converted into
80
     * <code>application/x-www-form-urlencoded</code>. For example:
81
     * <code>field1=value1&amp;field1=value2&amp;field2=value3</code>. The special
82
     * characters are encoded. If there is a space, it is encoded into '%20'.
83
     *
84
     * @param url
85
     *            the base url
86
     * @param params
87
     *            none, one or several parameters to append to the query string
88
     * @return the response
89
     * @throws HttpException
90
     *             when the request has failed
91
     */
92
    public static Response get(String url, Parameter... params) throws HttpException {
93 1 1. get : replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE
        return get(url, Arrays.asList(params));
94
    }
95
96
    /**
97
     * <p>
98
     * Do a GET request on the provided URL and construct the Query String part
99
     * with the provided list of parameters. If the URL already contains
100
     * parameters (already contains a '?' character), then the parameters are
101
     * added to the existing parameters. The parameters are converted into
102
     * <code>application/x-www-form-urlencoded</code>. For example:
103
     * <code>field1=value1&amp;field1=value2&amp;field2=value3</code>. The special
104
     * characters are encoded. If there is a space, it is encoded into '%20'.
105
     * </p>
106
     * The parameters can be anything:
107
     * <ul>
108
     * <li>{@link Parameter}: see {@link #get(String, Parameter...)}</li>
109
     * <li>{@link Map}: each entry is used as a parameter (see
110
     * {@link #get(String, Map)}). The key of the entry is the name of the
111
     * parameter, the value of the entry is the value of the parameter</li>
112
     * <li>A bean (any object): each property of the bean is used as parameter
113
     * (see {@link BeanUtils}). The name of the property is the name of the
114
     * parameter, the value of the property is the value of the parameter</li>
115
     * </ul>
116
     *
117
     * @param url
118
     *            the base url
119
     * @param params
120
     *            none, one or several parameters to append to the query string
121
     * @return the response
122
     * @throws HttpException
123
     *             when the request has failed
124
     */
125
    @SuppressWarnings("unchecked")
126
    public static Response get(String url, Object... params) throws HttpException {
127
        Map<String, Object> map = new HashMap<>();
128
        for (Object bean : params) {
129 1 1. get : negated conditional → NO_COVERAGE
            if (bean instanceof Parameter) {
130
                Parameter p = (Parameter) bean;
131
                map.put(p.getName(), p.getValue());
132 1 1. get : negated conditional → NO_COVERAGE
            } else if (bean instanceof Map) {
133 1 1. get : removed call to java/util/Map::putAll → NO_COVERAGE
                map.putAll((Map<String, Object>) bean);
134
            } else {
135 1 1. get : removed call to java/util/Map::putAll → NO_COVERAGE
                map.putAll(BeanUtils.convert(bean));
136
            }
137
        }
138 1 1. get : replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE
        return get(url, map);
139
    }
140
141
    /**
142
     * Do a GET request on the provided URL and construct the Query String part
143
     * with the provided list of parameters. If the URL already contains
144
     * parameters (already contains a '?' character), then the parameters are
145
     * added to the existing parameters. The parameters are converted into
146
     * <code>application/x-www-form-urlencoded</code>. For example:
147
     * <code>field1=value1&amp;field1=value2&amp;field2=value3</code>. The special
148
     * characters are encoded. If there is a space, it is encoded into '%20'.
149
     * <p>
150
     * Each entry of the map is used as a parameter. The key of the entry is the
151
     * name of the parameter, the value of the entry is the value of the
152
     * parameter
153
     * </p>
154
     *
155
     * @param url
156
     *            the base url
157
     * @param params
158
     *            none, one or several parameters to append to the query string
159
     * @return the response
160
     * @throws HttpException
161
     *             when the request has failed
162
     */
163
    public static Response get(String url, Map<String, Object> params) throws HttpException {
164 1 1. get : replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE
        return get(url, convert(params));
165
    }
166
167
    /**
168
     * Convert the map into a list of parameters
169
     *
170
     * @param map
171
     *            the map to convert
172
     * @return the list of parameters
173
     */
174
    private static List<Parameter> convert(Map<String, Object> map) {
175
        Set<Entry<String, Object>> entries = map.entrySet();
176
        List<Parameter> parameters = new ArrayList<>(entries.size());
177
        for (Entry<String, Object> entry : entries) {
178 1 1. convert : negated conditional → NO_COVERAGE
            if (entry.getValue() != null) {
179
                parameters.add(new Parameter(entry.getKey(), entry.getValue().toString()));
180
            }
181
        }
182 1 1. convert : replaced return value with Collections.emptyList for fr/sii/ogham/sms/util/HttpUtils::convert → NO_COVERAGE
        return parameters;
183
    }
184
185
    /**
186
     * Convert a list of parameters to a list of {@link NameValuePair}.
187
     *
188
     * @param params
189
     *            the parameters abstraction used in the library
190
     * @return the parameters used by the real implementation (Apache Commons
191
     *         HTTP)
192
     */
193
    private static List<NameValuePair> convert(List<Parameter> params) {
194
        List<NameValuePair> pairs = new ArrayList<>(params.size());
195
        for (Parameter param : params) {
196 1 1. convert : negated conditional → NO_COVERAGE
            if (param.getValue() != null) {
197
                pairs.add(new BasicNameValuePair(param.getName(), param.getValue()));
198
            }
199
        }
200 1 1. convert : replaced return value with Collections.emptyList for fr/sii/ogham/sms/util/HttpUtils::convert → NO_COVERAGE
        return pairs;
201
    }
202
203
    private static CloseableHttpClient getHttpClient() {
204 1 1. getHttpClient : replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::getHttpClient → NO_COVERAGE
        return HttpClientBuilder.create().useSystemProperties().build();
205
    }
206
207
    private HttpUtils() {
208
        super();
209
    }
210
}

Mutations

58

1.1
Location : get
Killed by :
negated conditional → NO_COVERAGE

93

1.1
Location : get
Killed by :
replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE

129

1.1
Location : get
Killed by :
negated conditional → NO_COVERAGE

132

1.1
Location : get
Killed by :
negated conditional → NO_COVERAGE

133

1.1
Location : get
Killed by :
removed call to java/util/Map::putAll → NO_COVERAGE

135

1.1
Location : get
Killed by :
removed call to java/util/Map::putAll → NO_COVERAGE

138

1.1
Location : get
Killed by :
replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE

164

1.1
Location : get
Killed by :
replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::get → NO_COVERAGE

178

1.1
Location : convert
Killed by :
negated conditional → NO_COVERAGE

182

1.1
Location : convert
Killed by :
replaced return value with Collections.emptyList for fr/sii/ogham/sms/util/HttpUtils::convert → NO_COVERAGE

196

1.1
Location : convert
Killed by :
negated conditional → NO_COVERAGE

200

1.1
Location : convert
Killed by :
replaced return value with Collections.emptyList for fr/sii/ogham/sms/util/HttpUtils::convert → NO_COVERAGE

204

1.1
Location : getHttpClient
Killed by :
replaced return value with null for fr/sii/ogham/sms/util/HttpUtils::getHttpClient → NO_COVERAGE

Active mutators

Tests examined


Report generated by PIT 1.13.1