Christian Pino Tossi

OPEN API Fast Purge and Java

Blog Post created by Christian Pino Tossi Employee on Sep 28, 2016

OPEN API Purge V3 (Fast Purge) and Java

Fast Purge / Purge V3 java example

Introduction

On ul 22, 2016 Kirsten Hunter did blogged Post about the new OPEN V3 API - Featuring 5-second purge.

 

The following article will demonstrate how to use the Akamai OPEN API for CCU V3, aka Fast Purge..

A general introduction to the Akamai OPEN API can be found here and is not part of the Article:

https://developer.akamai.com/introduction/

 

A general introduction, specific to the OPEN API Purge Interfaces can be found here:

(https://developer.akamai.com/api/#

 

In general OPEN API Purge, also called Content Control Utility allows to either remove or invalidate content which is stored on the Akamai Edge Servers.

Purge currently exist in 4 different flavours:

 

  1. Content Control Utility V3 (Fast Purge) The Content Control Utility (CCU) API allows you to purge edge content using Akamai's new Fast Purge capability. At this time, you can invalidate or delete by URL only. This API enters Limited Availability on September 30, 2016.
  2. Content Control Utility (v2) Purge Edge content by request.
  3. CCU Rest API Purge Edge content by request. Provided as reference. (Deprecated)
  4. PublishECCU Manage ECCU files for purging Edge content. A SOAP API.

 

 

 

OPEN API EdgeGrid Request Signing and Java

 

During this example we will use the Java Library OPEN-edgegrid-Java.(com.akamai.edgegrid.auth). The edgegrid-auth-java is a Java library for signing requests to APIs that are carried on the Akamai EdgeGrid network in general. It builds on the Google HTTP Client Library for Java and adds the EdgeGrid signature to a normal HttpRequest.

 

You can find the Java Class file on the corresponding Github Project:

https://github.com/akamai-open/AkamaiOPEN-edgegrid-java

Goal

We will purge, or to be more precise, we will invalidate the following two URLs, and therefore the corresponding content, from all Akamai Edge Servers:

We will invalidate this content only on the Akamai Staging Network.

 

We will need to use the following URL to talk to the corresponding OPEN API Purge Interface:

 

POST http://<Hostname>/ccu/v3/invalidate/url/<Environment>

 

NOTE: ‘<Hostname>’ and ‘<Environment>’ are Placeholder. They will need to be replaced by the corresponding values.

In our case, we are going to replace ‘<Environment>’ by ‘staging’ because we like to invalidate things on the Akamai Edge Staging Network.

How to get the ‘<Hostname>’ has been documented here:

https://developer.akamai.com/introduction/

 

We will need to ensure to send the following HTTP Request Header as part of the API Call:

 

Content-Type:application/json

 

We will need to send the list of URLs which needs to be purged as a JSON Object inside the HTTP POST Body:

 

{

 "hostname": "www.sample.com",

 "objects": [

    "/product1.png",

    "/product2.png"

 ]

}

 

See also https://developer.akamai.com/api/purge/ccu/reference.html for further details.

The Class OpenAPIPurge

We will create a class called cpinotos.openapi.purge.OpenAPIPurge.

Header Section of the Java Class File

 

Ensure that the following Java Libraries are included in the corresponding Class Path:

package cpinotos.openapi.purge;


import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.URI;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.Collections;

import java.util.List;

import java.util.Properties;


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.ByteArrayContent;

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;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

 

EdgeGrid Credentials

You will need the following 4 Parameter

  • Hostname: the Hostname to be used when sending the HTTP POST Request.
  • clientToken: for specifying the client token obtained from the client provisioning process
  • accessToken: for specifying the access token obtained from the client authorization process
  • clientSecret: for specifying the client secret that is associated with the client token

 

A more detailed introduction about how to get this parameters can be found here:

https://developer.akamai.com/introduction/

 

Because this parameter could vary based on the used OPEN API User and also because we would like to avoidkeeping sensitive information inside the Java Source code, we do provide this Information to the Java Class OpenAPIPurge via an external Property File, which looks as follow:

 

host: akab************************.purge.akamaiapis.net

access_token: akab-*******************

client_token: akab-************************

client_secret: *********************

File: /Users/cpinotos/workspace/cpinotos.openapi.purge/openapi.client.property

 

NOTE: Part of the values have been replaced by ‘*’.

 

To read the File we created the getPropValues Method, which is part of the Class OpenAPIPurge:

 

/**

    * @param propFileName, file path to the propery file

    * @return

    * @throws IOException

    * Does read a property file from disk

    */

   public Properties getPropValues(String propFileName) throws IOException {

      Properties prop = new Properties();

      File file = new File(propFileName);

      InputStream input = null;


      try {


          input = new FileInputStream(file);

          // load a properties file

          prop.load(input);

      } catch (IOException ex) {

          ex.printStackTrace();

      } finally {

          if (input != null) {

              try {

                  input.close();

              } catch (IOException e) {

                  e.printStackTrace();

              }

          }

      }

      return prop;

   }

}

 

Instantiate OpenAPIPurge Object

Inside the “static void main” Method we do instantiate an OpenAPIPurge Object:

 

public static void main(String[] args) throws Exception {

      //Location of the Open API Credential Property File

      String propertyFilePath = "/Users/cpinotos/workspace/cpinotos.openapi.purge/openapi.client.property";

      //Instantiate an instance of cpinotos.openapi.purge.OpenAPIPurge

      OpenAPIPurge apt = new OpenAPIPurge(propertyFilePath);

 

Get PurgeObjects Object

In a next step we need to provide the details about the URL which needs to be purged (invalidated) in JSON Format.

 

Therefore we created a Text File which contains the URL Purge Details in JSON Format:

 

{

 "hostname": "www.sample.com",

 "objects": [

    "/product1.png",

    "/product2.png"

 ]

}

File: /Users/cpinotos/workspace/cpinotos.openapi.purge/purgeobjects.json

The Class OpenAPIPurge contains the Method “getPUrgeObjects,” which expects the File Path to the JSON Text File as an input Parameter:

 

public String getPurgeObjects(String PurgeObjectsFileName) throws IOException {

   String prugeObjectsJSON = null;

   try {

        byte[] encoded = Files.readAllBytes(Paths.get(PurgeObjectsFileName));

        prugeObjectsJSON = new String(encoded, StandardCharsets.UTF_8);


   } catch (IOException ex) {

      ex.printStackTrace();

   }

   return prugeObjectsJSON;

}

 

Inside the “static void main” Method we do define the Path to the JSON Text File as follow:

 

String purgeObjectsFilePath = "/Users/cpinotos/gdrive/workspace/cpinotos.openapi.purge/purgeobjects.json";

 

Instantiate the Google HTTPRequest Object

In a next step we need to create an HTTPRequest Object of type com.google.api.client.http.HttpRequest:

 

//We will need to send a HTTP Request to the OPEN API Interface, therefore we are going to use the com.google.api.client.http Helper Classes      

HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();

HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();


//Invalidation URL of the OPEN API Interface

String path = "/ccu/v3/invalidate/url/staging";

URI uri = new URI("https", apt.prop.getProperty("host"), path, null, null);


//It is important to send the Request with the Content-Type application/json

HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(uri),ByteArrayContent.fromString("application/json", apt.getPurgeObjects(purgeObjectsFilePath)));

 

//Set the Host Header of the OPEN API Call based on the OPEN API Credential Property File Value 'Host'

HttpHeaders headers = request.getHeaders();

headers.set("Host", apt.prop.getProperty("host"));

 

Sign and send the HTTPRequest with Java EdgeGrid

Now we reach the most important step, in which we need to sign the HTTPRequest via the Java EdgeGrid Classes, so the Request will be authorized by the Akamai OPEN API Purge Interface:

 

//Create the EdgeGrid credential opject which will be used as an input parameter to sign the request with the EdgeGrid Signer Object

ClientCredential credential = new DefaultCredential(apt.prop.getProperty("client_token"),apt.prop.getProperty("access_token"), apt.prop.getProperty("client_secret"));


//Create a new EdgeGrid Signer Object

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


//Sign the request with the credentials

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


//send the request to the OPEN API Interface via HTTP POST

HttpResponse response = signedRequest.execute();

 

RUN

We added more Logging to the Source Code above, so we can follow the Steps far better.

If you run the following Code you will see the following Output:

 

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - host: akab-******.purge.akamaiapis.net

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - access_token: akab-*******

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - client_token: *********

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - client_secret: ******

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - apt.getPurgeObjects():

{

 "hostname": "www.sample.com",

 "objects": [

    "/img/product1.png",

    "/img/product2.png"

 ]

}

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - request.getUrl():https://akab-*****************.purge.akamaiapis.net/ccu/v3/invalidate/url/staging

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - request.getRequestMethod():POST

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - response.getStatusCode():201

[main] INFO cpinotos.openapi.purge.OpenAPIPurge - response.parseAsString():{"estimatedSeconds": 5, "purgeId": "*********************", "supportId": "*******************", "httpStatus": 201, "detail": "Request accepted"}

 

The most important part here is the last line which indicates an 201 Response Code and a time estimate of 5 seconds.

Outcomes