You can call the REST APIs from Script and Java to query and run pipelines programmatically. The Script and Java codes do not have any dependencies.

REST API from Script

The following example is script code that you call from the vRealize Code Stream API.

#!/bin/bash

echo "#### Sample script to query and trigger a pipeline execution ####"
#Server host address refers to the host on which Code Stream server is setup. Eg: codestream.abc.com
read -p "vRealize Code Stream Server Host: " server_host

#user name and password with which you login on Code Stream server Eg: jane.doe@abc.com
read -p "Username: " username
read -p "Password: " password

#tenant name can be obtained from your system administrator if not known already
read -p "Tenant: " tenant
echo "-------------------------------------------------------"

#fetch the pipeline details and subsequently trigger an execution
#enter the pipeline name for which you want to trigger an execution
read -p "Release pipeline name:" pipeline_name

#pipeline param JSON is the input required for the pipeline execution. for a single pipeline parameter 'token', the JSON input would look like:
# Eg: {"description":"test run","pipelineParams":[{"name":"token","type":"STRING","value":"4321"}]}
read -p "Enter the pipeline param JSON:" pipeline_params

#A SSO token is required to make any calls to the Code Stream server. Token can be obtained easily by passing the credentials as follows
host_url="https://$server_host/identity/api/tokens"
response=$(curl -s -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' --insecure -d '{"username": "'"$username"'", "password": "'"$password"'", "tenant": "'"$tenant"'"}' $host_url)
#token can be extracted from the JSON response as follows
token=`echo $response | sed -n 's/.*"id":"\([^}]*\)",.*}/\1/p'`

#with the token obtained, subsequent calls can be made to the code stream server (a token has an expiry so renewal might be required if the same token is reused beyond expiry)
pipeline_fetch_url="https://$server_host/release-management-service/api/release-pipelines?name=$pipeline_name"
response=$(curl -s -X GET -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $token" -k $pipeline_fetch_url)
pipeline_id=`echo $response | sed -n 's/.*"id":"\([^"]*\)",.*stages.*/\1/p'`
#echo "pipeline id: $pipeline_id"

#with the pipeline id, an execution can be triggered as follows
execute_pipeline_url="https://$server_host/release-management-service/api/release-pipelines/$pipeline_id/executions"
echo "executing pipeline:$pipeline_name :[$pipeline_id]"
response=$(curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $token" -k -d "$pipeline_params" $execute_pipeline_url)
echo "Response to execute pipeline => $response"

REST API from Java

The following example is Java code called from the vRealize Code Stream API. The Java code must be packaged with open source dependencies.

package samples;

import com.google.gson.Gson;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
* Sample Java class to invoke REST APIs on Release pipeline
*
*/
public class PipelineApiHelper {

private String username;
private String password;
private String tenant;
private String serverHost;

private Gson gson = new Gson();

private static String FETCH_TOKEN_URL_TEMPLATE = "https://%s/identity/api/tokens";
private static String TRIGGER_EXECUTION_URL_TEMPLATE = "https://%s/release-management-service/api/release-pipelines/%s/executions";
private static String FETCH_PIPELINE_INFO_URL_TEMPLATE = "https://%s/release-management-service/api/release-pipelines?name=%s";

private static ClientConnectionManager connectionManager;

/**
* Sample helper class to fetch pipeline info and trigger an execution
*
* @param serverhost Code Stream server host name
* @param username login credentials
* @param password login credentials
* @param tenant tenant id for the user
*/
public PipelineApiHelper(String serverhost, String username, String password, String tenant) {
this.username = username;
this.password = password;
this.tenant = tenant;
this.serverHost = serverhost;
}

/**
* Trigger a pipeline execution
*
* @param pipelineName name of the pipeline to execute
* @param pipelineParamsJson JSON string for the pipeline execution
* pipeline param JSON is the input required for the pipeline execution.
* for a single pipeline parameter 'token', the JSON input would look like:
* Eg: {"description":"test run","pipelineParams":[{"name":"token","type":"STRING","value":"4321"}]}
*/
public void triggerPipelineExecution(String pipelineName, String pipelineParamsJson) {
//A SSO token is required to make any calls to the Code Stream server. Token can be obtained easily by passing the credentials as follows
final String token = fetchToken();
List<Header> headers = getCommonHeaders();
headers.add( new BasicHeader("Authorization", "Bearer " + token));
try {
//fetch the pipeline id
InputStream pipelineRespStream = getRequest(String.format(FETCH_PIPELINE_INFO_URL_TEMPLATE, serverHost, pipelineName),
headers);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pipelineRespStream));
//response contains the pipeline info (containing the id)
PipelineInfoWrapper pInfo = gson.fromJson(bufferedReader, PipelineInfoWrapper.class);

//trigger the pipeline execution with the pipeline id and pipeline params
InputStream is = postRequest(String.format(TRIGGER_EXECUTION_URL_TEMPLATE, serverHost, pInfo.getContent().get(0).getId()),
headers,
pipelineParamsJson);
bufferedReader.close();
bufferedReader = new BufferedReader(new InputStreamReader(is));

String response;
System.out.println("Response:");
while ((response = bufferedReader.readLine()) != null) {
System.out.print(response);
}
System.out.println("===============================================================");
} catch (Exception ex) {
System.out.println("Error triggering pipeline: " + ex.getMessage());
}
System.out.println("Pipeline execution triggered !");
}

/**
* Fetch SSO Token from Identity server
* @return token
*/
private String fetchToken() {
//POST username,password,tenant to fetch token API
TokenRequest tokenRequest = new TokenRequest();
tokenRequest.setUsername(username);
tokenRequest.setPassword(password);
tokenRequest.setTenant(tenant);
String token = null;

try {
InputStream is = postRequest(String.format(FETCH_TOKEN_URL_TEMPLATE, serverHost),
getCommonHeaders(),
gson.toJson(tokenRequest));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
TokenResponse tokenResponse = gson.fromJson(bufferedReader, TokenResponse.class);
if (tokenResponse != null) {
token = tokenResponse.getId();
}

} catch (Exception ex) {
System.out.println("Error fetching token: " + ex.getMessage());
}
return token;
}

/**
* Construct the common headers required for the API calls
*
* @return
*/
private List<Header> getCommonHeaders() {
List<Header> headers = new ArrayList<Header>(){{
add(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
add(new BasicHeader("Accept", "application/json"));
}};

return headers;
}

/**
* Helper method for Http POST request
* @param url
* @param headers
* @param requestBody
* @return
* @throws Exception
*/
private InputStream postRequest(String url, List<Header> headers, String requestBody) throws Exception {
HttpClient httpClient = new DefaultHttpClient(getConnManager());
HttpPost post = new HttpPost(url);

post.setEntity(new StringEntity(requestBody));
Header[] headersArray = headers.toArray(new Header[headers.size()]);
post.setHeaders(headersArray);
HttpResponse response = httpClient.execute(post);
if (null != response && response.getStatusLine().getStatusCode()/100 == 2) {
return response.getEntity().getContent();
} else {
return null;
}
}

/**
* Helper method for http GET request
* @param url
* @param headers
* @return
* @throws Exception
*/
private InputStream getRequest(String url, List<Header> headers) throws Exception {
HttpClient httpClient = new DefaultHttpClient(getConnManager());
HttpGet get = new HttpGet(url);

Header[] headersArray = headers.toArray(new Header[headers.size()]);
get.setHeaders(headersArray);
HttpResponse response = httpClient.execute(get);
if (null != response && response.getStatusLine().getStatusCode()/100 == 2) {
return response.getEntity().getContent();
} else {
return null;
}
}

/**
* Construct a connection manager
* Note: This sample method ignores the SSL certificates. Ignoring them may not be something that you intend.
* @return
* @throws Exception
*/
private static ClientConnectionManager getConnManager() throws Exception {
if (connectionManager == null) {
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
public boolean isTrusted(
final X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
Scheme httpsScheme = new Scheme("https", 443, sslSocketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

connectionManager = new BasicClientConnectionManager(schemeRegistry);
}
return connectionManager;
}

public static void main(String[] args) {
PipelineApiHelper helper = new PipelineApiHelper("test.com", "test@test.com", "password", "sample");
helper.triggerPipelineExecution("PipelineName", "{\"id\":\"\",\"description\":\"test run\",\"pipelineParams\":[{\"name\":\"token\",\"type\":\"STRING\",\"value\":\"4321\"}]}");
}
}

class TokenResponse {
String expires;
String id;
String tenant;

public String getId() {
return id;
}

public String getExpires() {
return expires;
}

public String getTenant() {
return tenant;
}

public void setExpires(String expires) {
this.expires = expires;
}

public void setId(String id) {
this.id = id;
}

public void setTenant(String tenant) {
this.tenant = tenant;
}
}

class TokenRequest {
String username;
String password;
String tenant;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getTenant() {
return tenant;
}

public void setTenant(String tenant) {
this.tenant = tenant;
}
}

class PipelineInfoWrapper {
List<PipelineInfo> content;

public List<PipelineInfo> getContent() {
return content;
}

public void setContent(List<PipelineInfo> content) {
this.content = content;
}
}

class PipelineInfo {
String id;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}