Albert Bupp

Complete Example of Accessing the OPEN API from Java

Blog Post created by Albert Bupp on Jul 18, 2015

Greetings Akamai Developer Community,

 

I have recently been developing an interface to the OPEN API for use in my company's software distribution library which is distributed through the Akamai network. Our existing application front-end is written in Java, as is our integration with the file repository that is the origin point for our the Akamai cloud. Therefore, it was natural to choose Java to integrate to the OPEN API. While the REST interface is simple and straight-forward, the OPEN API's token-based authentication offers much greater security, which comes at the price of some additional complexity.

 

However, the only complete example of this integration is in Python, and while the Java library for Akamai OPEN EdgeGrid Client Authentication does contain a snippet of code demonstrating the Java library's use, it is not complete. After spending time on a testable interface, which included timely and helpful support from Akamai Customer Care (this is a shout out to you, Abhishek!) I was able to get a working baseline example. In the course of doing this, I did notice that there have been a number of questions posted to the forum on this topic, which the responses to have all pointed to either the EdgeGrid library's code snippet or the Python example.


So, in the spirit of community, I'd like to post my complete JUnit test which demonstrates calling the purge API via the OPEN API's token-based authentication approach in Java. In order to make it work for a given connection, set the client & access tokens, client secret and host variables with values created for your account.

 

import java.io.InputStream;

import java.net.URI;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

 

import junit.framework.TestCase;

 

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.akamai.edgegrid.auth.ClientCredential;

import com.akamai.edgegrid.auth.DefaultCredential;

import com.akamai.edgegrid.auth.EdgeGridV1Signer;

import com.akamai.edgegrid.auth.RequestSigner;

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

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

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

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

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

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

import com.google.api.client.http.apache.ApacheHttpTransport;

 

public class AkamaiTest extends TestCase {

  private static Logger log = LoggerFactory.getLogger(AkamaiTest.class);

 

  @Before

  public void setUp() throws Exception {

    super.setUp();

  }

 

    @After

  public void tearDown() throws Exception {

    super.tearDown();

  }

 

   @Test

  public void testDirectOpenPurgeRequest() throws Exception {

    // replace the following values w/ specifics for your org

    String clientToken = "akab-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx";

    String accessToken = "akab-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx";

    String clientSecret = "******************************************";

    String ccuHost = "akab-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx.purge.akamaiapis.net";

 

        @SuppressWarnings("unchecked")

    RequestSigner signer = new EdgeGridV1Signer(Collections.EMPTY_LIST, 1024 * 2);

    URI uri = new URI("https", ccuHost, "/ccu/v2/queues/default", null, null);

    HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();

    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));

    HttpHeaders headers = request.getHeaders();

    headers.set("Host", ccuHost);

    List<String> cTypes = new ArrayList<String>(1);

    cTypes.add("application/json");

    headers.set("Content-Type", cTypes);

    String json = getPurgeJson("http://www.somewhere.com/aresource");

    log.info("calling OPEN purge interface, using JSON: {}", json);

    headers.set("", json);

    ClientCredential credential = new DefaultCredential(clientToken, accessToken, clientSecret);

    HttpRequest signedRequest = signer.sign(request, credential);

    HttpResponse response = signedRequest.execute();

    int status = response.getStatusCode();

    InputStream instream = null;

    String jsonResp = "";

    try {

      instream = response.getContent();

      jsonResp = RestClient.convertStreamToString(instream);

    }

      catch (Exception e) {

      log.error("Error: {}", e.getMessage());

    }

    finally {

      // Closing the input stream will trigger connection release

      if (instream != null) instream.close();

    }

    log.info("testDirectOpenPurgeRequest response status: {}", status);

    log.info("testDirectOpenPurgeRequest response: {}", jsonResp);

  }

 

  private static String getPurgeJson(String fileUri) {

    StringBuffer jsonBuff = new StringBuffer();

    jsonBuff.append("{\"objects\":[");

    jsonBuff.append("\"");

    jsonBuff.append(fileUri);

    jsonBuff.append("\"");

    jsonBuff.append("]}");

    return jsonBuff.toString();

  }

}

Outcomes