Sample Java Code (OAuth)

The following examples demonstrate how to access the P6 REST API using Java. Token generation in these examples use the OAUTH token ROPC grant type. The first example sends an HTTP GET request to the /location endpoint to retrieve information about a location with a given ObjectId. The second example sends an HTTP POST request to the /location endpoint to create a location.

Sample Program to Invoke GET REST API

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.Sapache.commons.httpclient.HttpStatus;
 
public class SampleOAUTHGET {
 
	private static String userName = "<username>";
	private static String password = "<password>";
	private static String hostName = "<hostname>";
	private static String portNumber = "<portnumber>";
	private static String objectId = "<objectId>";
	private static String tokenGenerationUrl = "http://" + hostName + ":" + portNumber + "/p6ws/oauth/token";
	private static String loadActivitiesURL = "http://" + hostName + ":" + portNumber + "/p6ws/restapi/location?Fields=City,Country,CountryCode,CreateDate,CreateUser,LastUpdateDate,LastUpdateUser,Latitude,Longitude,Municipality,Name,ObjectId,PostalCode,State,StateCode&Filter=ObjectId :eq: " + objectId;
 
	public static void main(String s[]) throws Exception {
		String responseJson = callRestURL(tokenGenerationUrl, "POST");
		System.out.println("Response:- " + responseJson);
	}
 
	private static String callRestURL(String restUrl, String method) throws Exception {
		HttpURLConnection conn = null;
		try {
			trustAllCert();
			String authTokenResponse = getAuthTokenDetails();
			URL loadUrl = new URL(loadActivitiesURL);
			conn = (HttpURLConnection) loadUrl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Content-Type", "application/json");
			System.out.println("Token Generated : " + authTokenResponse);
            conn.setRequestProperty("Authorization", authTokenResponse);
			if (conn.getResponseCode() != HttpStatus.SC_OK) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: "
						+ readStreamData(conn.getErrorStream()));
			}
			return readStreamData(conn.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
		
	}
	
	@SuppressWarnings("unchecked")
    private static String getAuthTokenDetails() {
        HttpURLConnection conn = null;
        try {
            // Generating the OAuth Token
            URL tokenUrl = new URL(tokenGenerationUrl);
            conn = (HttpURLConnection) tokenUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            String userCredentials = userName + ":" + password;
            String base64Credentials = javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes());
            String basicAuth = base64Credentials;
            conn.setRequestProperty("authToken", basicAuth);
            conn.setRequestProperty("token_exp", "3600");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: " + readStreamData(conn.getErrorStream()));
            }
            return readStreamData(conn.getInputStream());
        } catch (Exception e) {
            conn.disconnect();
            throw new RuntimeException("Failed to generate OAuth Token");
        }
    }
 
	private static String readStreamData(InputStream is) throws IOException {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
			String output;
			StringBuilder buff = new StringBuilder();
			while ((output = br.readLine()) != null) {
				buff.append(output);
			}
			return buff.toString();
		}
	}
 
	private static void trustAllCert() throws NoSuchAlgorithmException, KeyManagementException {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
 
			@Override
			public void checkClientTrusted(X509Certificate[] certs, String authType) {
			}
 
			@Override
			public void checkServerTrusted(X509Certificate[] certs, String authType) {
			}
		} };
		// Install the all-trusting trust manager
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	}
 
}

Sample Program to Invoke POST REST API

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.commons.httpclient.HttpStatus;
 
public class SampleOAUTHPOST {
 
	private static String userName = "<username>";
	private static String password = "<password>";
	private static String hostName = "<hostname>";
	private static String portNumber = "<portnumber>";
	private static String tokenGenerationUrl = "http://" + hostName + ":" + portNumber + "/p6ws/oauth/token";
	private static String postLocationsURL = "http://" + hostName + ":" + portNumber + "/p6ws/restapi/location";
 
	public static void main(String s[]) throws Exception {
		String responseJson = callRestURL(tokenGenerationUrl, "POST");
		System.out.println("Response:- " + responseJson);
	}
 
	private static String callRestURL(String restUrl, String method) throws Exception {
		HttpURLConnection conn = null;
		try {
			trustAllCert();
			String authTokenResponse = getAuthTokenDetails();
			URL loadUrl = new URL(postLocationsURL);
			conn = (HttpURLConnection) loadUrl.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Content-Type", "application/json");
			System.out.println("Token Generated : " + authTokenResponse);
            conn.setRequestProperty("Authorization", authTokenResponse);
            String input = "[{\"addressLine1\":\"MyAddress1\", \"AddressLine2\":\"MyAddress2\", \"City\":\"Chicago\", \"Country\":\"United States\",\"CountryCode\":\"1\", \"Municipality\":\"IL\", \"Name\":\"Chicago-2\", \"PostalCode\":\"60007\",\"State\":\"IL\",\"StateCode\":\"36\", \"Latitude\":5555555555, \"Longitude\":91}]";
			 
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes("UTF-8"));
            os.flush();
			if (conn.getResponseCode() != HttpStatus.SC_CREATED) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: "
						+ readStreamData(conn.getErrorStream()));
			}
			return readStreamData(conn.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
		
	}
	
	@SuppressWarnings("unchecked")
    private static String getAuthTokenDetails() {
        HttpURLConnection conn = null;
        try {
            // Generating the OAuth Token
            URL tokenUrl = new URL(tokenGenerationUrl);
            conn = (HttpURLConnection) tokenUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            String userCredentials = userName + ":" + password;
            String base64Credentials = javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes());
            String basicAuth = base64Credentials;
            conn.setRequestProperty("authToken", basicAuth);
            conn.setRequestProperty("token_exp", "3600");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: " + readStreamData(conn.getErrorStream()));
            }
            return readStreamData(conn.getInputStream());
        } catch (Exception e) {
            conn.disconnect();
            throw new RuntimeException("Failed to generate OAuth Token");
        }
    }
 
	private static String readStreamData(InputStream is) throws IOException {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
			String output;
			StringBuilder buff = new StringBuilder();
			while ((output = br.readLine()) != null) {
				buff.append(output);
			}
			return buff.toString();
		}
	}
 
	private static void trustAllCert() throws NoSuchAlgorithmException, KeyManagementException {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
 
			@Override
			public void checkClientTrusted(X509Certificate[] certs, String authType) {
			}
 
			@Override
			public void checkServerTrusted(X509Certificate[] certs, String authType) {
			}
		} };
		// Install the all-trusting trust manager
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	}
 
}