Created
January 7, 2016 00:42
-
-
Save dileeph/74ab0d0ee80c9211059b to your computer and use it in GitHub Desktop.
authenticated-rest-call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dh.ts.repo; | |
import java.net.URI; | |
import java.nio.charset.Charset; | |
import org.apache.commons.codec.binary.Base64; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.http.HttpEntity; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.http.HttpMethod; | |
import org.springframework.stereotype.Repository; | |
import org.springframework.web.client.RestTemplate; | |
import org.springframework.web.util.UriComponentsBuilder; | |
@Repository | |
public class JenkinsRepository { | |
@Value("${jenkins.host}") | |
private String remoteAddress; | |
@Value("${jenkins.port}") | |
private String port; | |
@Value("${jenkins.username}") | |
private String username; | |
@Value("${jenkins.password}") | |
private String password; | |
private HttpHeaders createHeaders(final String username, final String password) { | |
return new HttpHeaders() { | |
private static final long serialVersionUID = 1L; | |
{ | |
String auth = username + ":" + password; | |
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII"))); | |
String authHeader = "Basic " + new String(encodedAuth); | |
set("Authorization", authHeader); | |
} | |
}; | |
} | |
public void invokeJob(String jobName) { | |
URI uri = UriComponentsBuilder. | |
newInstance().scheme("http").host(remoteAddress).port(port) | |
.pathSegment(new String[]{"/job/", jobName, "/build"}).build().toUri(); | |
RestTemplate restTemplate = new RestTemplate(); | |
HttpHeaders headers = createHeaders(username, password); | |
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); | |
restTemplate.exchange(uri, HttpMethod.POST, entity, | |
String.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment