How to search for groups calling the Prot-On Rest API with JAVA

See API Groups Demo in action

Groups.java

In order to get the groups of an user, first of all you will need a service (class) that configures the request to the REST API. In this example, the Groups class allows you to configure a Basic or Bearer authentication and uses Client.java as a class attribute to set that authentication and make the request.


package com.proton.developers;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.client.http.HttpHeaders;

public class Groups {
	
	public static String BASIC = "Basic";
	public static String BEARER = "Bearer";
	public static String BASE_SERVICE_URL = "https://dnd.prot-on.com/rest-api/api/groups/";
	
	private Client client = new Client();
	
	/**
	 * Get user groups
	 */
	public String getGroups(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String auth_type = BEARER;
		String output = null;
		
		String auth_string = getAuthentication(request, response, auth_type);
		
		if(response.containsHeader("Location")){
			return null;
		}
		
		HttpHeaders headers = new HttpHeaders();
		headers.setAuthorization(auth_string);
		
		output = callService(request, headers);

		return output;
	}
	
	/**
	 * This method allows to get the OAuth authentication (access token),
	 * assuming that the necessary credentials are submitted as request
	 * parameters.
	 */
	private String getAuthentication(HttpServletRequest request,
			HttpServletResponse response, String auth_type) throws IOException {
		
		String client_id = request.getParameter("client_id");
		String client_secret = request.getParameter("client_secret");
		
		String auth_string = null;
		if(auth_type.equals(BASIC)) {
			auth_string = client.getBasicAuth(request, response);
		} else if (auth_type.equals(BEARER)) {
			request.setAttribute("redirect_url", CODE_REDIRECT_URL);
			auth_string = client.getBearerAuth(request, response);
		}
		return auth_string;
	}
	
	/**
	 * This method calls the service specified as a class constant
	 */
	private String callService(HttpServletRequest request,
			HttpHeaders headers) {
		String output = null;
		String user_id = request.getParameter("user_id");
		String serviceURL = BASE_SERVICE_URL + user_id + "/";
		try {
			output = client.get(serviceURL, headers);
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (CertificateException e) {
			e.printStackTrace();
		}
		return output;
	}

}
			

Client.java

The Client is a class that allows to configure the OAuth authentication method (Basic, Password, Bearer...) and to make the request. When attempting the authentication it will make a static call to the "attempAuthentication" of the "OAuth" class. You can see that implementation in the OAuth example section. Once you have the authentication, you can pass it as HttpHeaders to the get method, as you can see in the Groups service (callService method).


package com.proton.developers;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;

import com.google.api.client.http.HttpHeaders;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;

public class Client {
	
	public static final String TRUSTSTORE_PATH = "The path of the truststore";
	public static final String TRUSTSTORE_PASS = "The password of the truststore";
	
	public String get(String serviceURL, HttpHeaders headers)
			throws KeyManagementException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException {
		String output = null;
		try {

			URL url = new URL(serviceURL);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Authorization", headers.getAuthorization());
			conn.setSSLSocketFactory(getSSLFactory());

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			System.out.println("Output from Server .... \n");
			String line;
			while ((line = br.readLine()) != null) {
				output += line;
				System.out.println(line);
			}

			conn.disconnect();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return output;

	}

	public static SSLSocketFactory getSSLFactory() throws KeyStoreException,
			NoSuchAlgorithmException, KeyManagementException,
			CertificateException, IOException {
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		InputStream ins = new FileInputStream(TRUSTSTORE_PATH);
		char[] truststorePwd = new String(TRUSTSTORE_PASS).toCharArray();
		keyStore.load(ins, truststorePwd);
		ins.close();

		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(keyStore);
		SSLContext ctx = SSLContext.getInstance("TLS");
		ctx.init(null, tmf.getTrustManagers(), null);
		SSLSocketFactory sslFactory = ctx.getSocketFactory();

		return sslFactory;
	}
	
	public String getBasicAuth(HttpServletRequest request,
			HttpServletResponse response) {
		
		String auth = null;
		
		String cred = request.getParameter("username") + ":" + request.getParameter("password");
		auth = "Basic " + Base64.encodeBase64String(cred.getBytes());
		
		return auth;
		
	}
	
	public String getBearerAuth(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String access_token = null;
		
		String authentication = OAuth.attemptAuthentication(request, response);
		if(authentication!=null){
			JsonFactory jsonFactory = new JsonFactory();
			JsonParser jsonParser = jsonFactory.createJsonParser(authentication);
			while(jsonParser.nextValue()!=null){
				if(jsonParser.getCurrentName()!=null &&
						jsonParser.getCurrentName().equals("access_token")){
					access_token = jsonParser.getText();
					break;
				}
			}
		}
		
		return "Bearer " + access_token;
	}
	
}
			

See API Groups Demo in action