Skip to content

Commit 128ee7c

Browse files
Christoffer-CortesAnders Breid
authored and
Anders Breid
committed
Add setBasicAuth method that sets Authorization header. (#26)
* Add setBasicAuth method that sets Authorization header.
1 parent 1ace436 commit 128ee7c

File tree

3 files changed

+74
-41
lines changed

3 files changed

+74
-41
lines changed

src/main/java/com/ericsson/eiffelcommons/JenkinsManager.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ public boolean createJob(String jobName, String jobXmlData) throws Exception {
108108
.addHeader("Authorization", "Basic " + encoding)
109109
.addHeader("Content-type", MediaType.APPLICATION_XML)
110110
.addHeader("Jenkins-Crumb", crumb)
111-
.addParam("name", jobName)
111+
.addParameter("name", jobName)
112112
.setBody(jobXmlData)
113113
.setEndpoint("/createItem");
114114

@@ -306,8 +306,8 @@ public boolean pluginExists(String plugin) throws Exception {
306306
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET);
307307
httpRequest.setBaseUrl(jenkinsBaseUrl)
308308
.addHeader("Authorization", "Basic " + encoding)
309-
.addParam("depth", "1")
310-
.addParam("wrapper", "plugins")
309+
.addParameter("depth", "1")
310+
.addParameter("wrapper", "plugins")
311311
.setEndpoint("/pluginManager/api/json");
312312

313313
ResponseEntity response = httpRequest.performRequest();
@@ -438,7 +438,7 @@ private boolean executeJobTriggering(String jobName, String jobToken, String bui
438438
httpRequest.setBaseUrl(jenkinsBaseUrl)
439439
.addHeader("Authorization", "Basic " + encoding)
440440
.addHeader("Content-type", mediatype)
441-
.addParam("token", jobToken)
441+
.addParameter("token", jobToken)
442442
.setEndpoint(endpoint);
443443

444444
ResponseEntity response = httpRequest.performRequest();

src/main/java/com/ericsson/eiffelcommons/utils/HttpRequest.java

Lines changed: 46 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@
1818

1919
import java.io.File;
2020
import java.io.IOException;
21+
import java.io.UnsupportedEncodingException;
2122
import java.net.URI;
2223
import java.net.URISyntaxException;
2324
import java.util.HashMap;
2425
import java.util.Map;
2526

27+
import org.apache.commons.codec.binary.Base64;
2628
import org.apache.commons.io.FileUtils;
2729
import org.apache.http.Header;
30+
import org.apache.http.HttpHeaders;
2831
import org.apache.http.client.ClientProtocolException;
2932
import org.apache.http.client.methods.HttpDelete;
3033
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
@@ -81,7 +84,7 @@ public HttpRequest(HttpMethod method, boolean persistentClient) {
8184
}
8285

8386
private void initExecutor(boolean persistentClient) {
84-
if(persistentClient) {
87+
if (persistentClient) {
8588
executor = HttpExecutor.getInstance();
8689
} else {
8790
executor = new HttpExecutor();
@@ -90,6 +93,7 @@ private void initExecutor(boolean persistentClient) {
9093

9194
/**
9295
* Sets the http method for this request object
96+
*
9397
* @param method
9498
*/
9599
public HttpRequest setHttpMethod(HttpMethod method) {
@@ -113,6 +117,7 @@ public HttpRequest setHttpMethod(HttpMethod method) {
113117

114118
/**
115119
* Gets the base url(not including endpoint) for example: http://localhost:8080
120+
*
116121
* @return String
117122
*/
118123
public String getBaseUrl() {
@@ -121,6 +126,7 @@ public String getBaseUrl() {
121126

122127
/**
123128
* Sets the base url(not including endpoint) for example: http://localhost:8080
129+
*
124130
* @param baseUrl
125131
*/
126132
public HttpRequest setBaseUrl(String baseUrl) {
@@ -147,18 +153,18 @@ public void resetHttpRequestObject() {
147153
/**
148154
* Function the adds a header to the http request.
149155
*
150-
* @param key
151-
* :: the key of the header
152-
* @param value
153-
* :: the value of the header
156+
* @param key :: the key of the header
157+
* @param value :: the value of the header
154158
* @return HttpRequest
155159
*/
156160
public HttpRequest addHeader(String key, String value) {
157161
request.addHeader(key, value);
158162
return this;
159163
}
164+
160165
/**
161-
* Function that overwrites the first header with the same name. The new header will be appended to the end of the list, if no header with the given name can be found.
166+
* Function that overwrites the first header with the same name. The new header will be appended
167+
* to the end of the list, if no header with the given name can be found.
162168
*
163169
* @param key
164170
* @param value
@@ -173,8 +179,7 @@ public HttpRequest setHeader(String key, String value) {
173179
/**
174180
* Takes a header key as input and removes that key and value from the list of headers.
175181
*
176-
* @param headerKey
177-
* :: the header to remove
182+
* @param headerKey :: the header to remove
178183
*/
179184
public void removeHeader(String headerKey) {
180185
request.removeHeaders(headerKey);
@@ -183,34 +188,30 @@ public void removeHeader(String headerKey) {
183188
/**
184189
* Function that adds multiple parameters to the http request.
185190
*
186-
* @param parameters
187-
* :: List<NameValuePair>
191+
* @param parameters :: List<NameValuePair>
188192
*/
189193
public void addParameters(Map<String, String> parameters) {
190194
for (Map.Entry<String, String> entry : parameters.entrySet()) {
191-
addParam(entry.getKey(), entry.getValue());
195+
addParameter(entry.getKey(), entry.getValue());
192196
}
193197
}
194198

195199
/**
196200
* Function that adds a parameter to the http request.
197201
*
198-
* @param key
199-
* :: the key of the parameter
200-
* @param value
201-
* :: the value of the parameter
202+
* @param key :: the key of the parameter
203+
* @param value :: the value of the parameter
202204
* @return HttpRequest
203205
*/
204-
public HttpRequest addParam(String key, String value) {
206+
public HttpRequest addParameter(String key, String value) {
205207
params.put(key, value);
206208
return this;
207209
}
208210

209211
/**
210212
* Function that sets the body of the http request with a chosen content type.
211213
*
212-
* @param body
213-
* :: String input
214+
* @param body :: String input
214215
* @return HTTPRequest
215216
*/
216217
public HttpRequest setBody(String body, ContentType contentType) {
@@ -221,8 +222,7 @@ public HttpRequest setBody(String body, ContentType contentType) {
221222
/**
222223
* Function that sets the body of the http request with default content type(text/plain).
223224
*
224-
* @param body
225-
* :: String input
225+
* @param body :: String input
226226
* @return HTTPRequest
227227
*/
228228
public HttpRequest setBody(String body) {
@@ -231,10 +231,10 @@ public HttpRequest setBody(String body) {
231231
}
232232

233233
/**
234-
* Function that sets the body of the http request with default value of content type (text/plain).
234+
* Function that sets the body of the http request with default value of content type
235+
* (text/plain).
235236
*
236-
* @param file
237-
* :: File input
237+
* @param file :: File input
238238
* @return HTTPRequest
239239
* @throws IOException
240240
*/
@@ -246,8 +246,7 @@ public HttpRequest setBody(File file) throws IOException {
246246
/**
247247
* Function that sets the body of the http request with a chosen content type.
248248
*
249-
* @param file
250-
* :: File input
249+
* @param file :: File input
251250
* @param type
252251
* @return HTTPRequest
253252
* @throws IOException
@@ -257,13 +256,30 @@ public HttpRequest setBody(File file, ContentType contentType) throws IOExceptio
257256
try {
258257
fileContent = FileUtils.readFileToString(file, "UTF-8");
259258
} catch (IOException e) {
260-
final String message = "Failed to read the Request body file:" + file.getPath() + ". Message: "
259+
final String message = "Failed to read the Request body file:" + file.getPath()
260+
+ ". Message: "
261261
+ e.getMessage();
262262
throw new IOException(message);
263263
}
264264
return setBody(fileContent, contentType);
265265
}
266266

267+
/**
268+
* Function that sets the Authorization header of the http request.
269+
*
270+
* @param username
271+
* @param password
272+
* @return
273+
* @throws UnsupportedEncodingException
274+
*/
275+
public HttpRequest setBasicAuth(String username, String password)
276+
throws UnsupportedEncodingException {
277+
String auth = String.format("%s:%s", username, password);
278+
String encodedAuth = new String(Base64.encodeBase64(auth.getBytes()), "UTF-8");
279+
params.put(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
280+
return this;
281+
}
282+
267283
/**
268284
* Function that executes the http request.
269285
*
@@ -272,7 +288,8 @@ public HttpRequest setBody(File file, ContentType contentType) throws IOExceptio
272288
* @throws IOException
273289
* @throws ClientProtocolException
274290
*/
275-
public ResponseEntity performRequest() throws URISyntaxException, ClientProtocolException, IOException {
291+
public ResponseEntity performRequest()
292+
throws URISyntaxException, ClientProtocolException, IOException {
276293
URIBuilder builder = createURIBuilder();
277294
builder = addParametersToURIBuilder(builder);
278295
request.setURI(builder.build());
@@ -314,7 +331,7 @@ private URIBuilder addParametersToURIBuilder(URIBuilder builder) {
314331
* @throws URISyntaxException
315332
*/
316333
private URIBuilder createURIBuilder() throws URISyntaxException {
317-
if(endpoint.startsWith("/")) {
334+
if (endpoint.startsWith("/")) {
318335
return new URIBuilder(baseUrl + endpoint);
319336
} else {
320337
return new URIBuilder(baseUrl + "/" + endpoint);
@@ -327,7 +344,7 @@ private URIBuilder createURIBuilder() throws URISyntaxException {
327344
* @return HttpRequest
328345
*/
329346
private String trimBaseUrl(String baseUrl) {
330-
if(baseUrl.endsWith("/")) {
347+
if (baseUrl.endsWith("/")) {
331348
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
332349
}
333350

src/test/java/com/ericsson/eiffelcommons/Utilstest/HttpRequestTest.java

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import static org.junit.Assert.assertEquals;
44

5+
import java.io.IOException;
56
import java.lang.reflect.InvocationTargetException;
67
import java.lang.reflect.Method;
8+
import java.net.URISyntaxException;
79

10+
import org.apache.http.client.ClientProtocolException;
811
import org.apache.http.client.utils.URIBuilder;
912
import org.junit.Test;
1013

@@ -13,30 +16,43 @@
1316

1417
public class HttpRequestTest {
1518
@Test
16-
public void testBuildingOfURI() throws NoSuchFieldException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
19+
public void testBuildingOfURI()
20+
throws NoSuchFieldException, SecurityException, IllegalAccessException,
21+
IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
22+
URISyntaxException, ClientProtocolException, IOException {
1723
String expectedURI = "http://something.com/testing/test/";
18-
HttpRequest request= new HttpRequest(HttpMethod.POST);
19-
Method method = request.getClass().getDeclaredMethod("createURIBuilder");
20-
method.setAccessible(true);
24+
String expectedAuthParam = "Authorization=Basic dXNlcm5hbWU6cGFzc3dvcmQ=";
25+
HttpRequest request = new HttpRequest(HttpMethod.POST);
26+
Method createURIBuilder = HttpRequest.class.getDeclaredMethod("createURIBuilder");
27+
Method addParametersToURIBuilder = HttpRequest.class.getDeclaredMethod(
28+
"addParametersToURIBuilder", URIBuilder.class);
29+
createURIBuilder.setAccessible(true);
30+
addParametersToURIBuilder.setAccessible(true);
2131

2232
request.setBaseUrl("http://something.com");
2333
request.setEndpoint("/testing/test/");
24-
URIBuilder builder = (URIBuilder) method.invoke(request);
34+
URIBuilder builder = (URIBuilder) createURIBuilder.invoke(request);
2535
assertEquals(expectedURI, builder.toString());
2636

2737
request.setBaseUrl("http://something.com/");
2838
request.setEndpoint("/testing/test/");
29-
builder = (URIBuilder) method.invoke(request);
39+
builder = (URIBuilder) createURIBuilder.invoke(request);
3040
assertEquals(expectedURI, builder.toString());
3141

3242
request.setBaseUrl("http://something.com/");
3343
request.setEndpoint("testing/test/");
34-
builder = (URIBuilder) method.invoke(request);
44+
builder = (URIBuilder) createURIBuilder.invoke(request);
3545
assertEquals(expectedURI, builder.toString());
3646

3747
request.setBaseUrl("http://something.com");
3848
request.setEndpoint("testing/test/");
39-
builder = (URIBuilder) method.invoke(request);
49+
builder = (URIBuilder) createURIBuilder.invoke(request);
4050
assertEquals(expectedURI, builder.toString());
51+
52+
request.setBasicAuth("username", "password");
53+
builder = (URIBuilder) createURIBuilder.invoke(request);
54+
builder = (URIBuilder) addParametersToURIBuilder.invoke(request, builder);
55+
String actualAuthParam = builder.getQueryParams().get(0).toString();
56+
assertEquals(expectedAuthParam, actualAuthParam);
4157
}
4258
}

0 commit comments

Comments
 (0)