Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 44 Current »

This page shows examples of how to use the API in to perform simple tasks in Java, Actionscript and curl.  Any language that can send HTTP request can consume the API, these are just some examples showing some common languages.

Note that there is a "beta" Java driver in the data model JAR (github link). It is beta in the sense that it is incomplete (ie some REST calls don't have Java functions) and that it is (currently) undocumented. All functions that are present are well-tested (they have been used in our own internal applications).

Example 0: Hashing a password

If we look at the login page documentation, we see that the password needs to be SHA-256 encoded and a base-64 string.

Because logging in is a vital function, here is a Java, Actionscript, and Web example of getting your hashed password:
*If you are doing this correctly the password "12345" will hash to "WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U="

Java - Hashing a Password
//In this example we use the apache commons codec library to convert our hashed password to base 64
//the library can be found at: http://commons.apache.org/codec/download_codec.cgi
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
public class hashpword 
{
    public static void main(String[] args) throws NoSuchAlgorithmException
    {
        String password = "12345";
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashbytes = digest.digest(password.getBytes());
        String hashpassword = Base64.encodeBase64String(hashbytes);
        System.out.println(hashpassword);
    }
}

Actionscript - Hashing a Password
//The Crypto class can be found in the as3crypto library
//the library can be found at: http://code.google.com/p/as3crypto/
var password:String = "12345";
var c:Crypto = new Crypto();
var cipher:IHash = Crypto.getHash( "sha256" );
var data:ByteArray = Hex.toArray( Hex.fromString( password ) );
var hashed:String = Base64.encodeByteArray( cipher.hash( data ) );
Alert.show( hashed );

Web Browser - Hashing a Password

Example 1: Sending an HTTP request and sending a request to Login

Because our API is REST based, the most important thing to do in any language is understand how to send HTTP Requests so you are able to call our system.  Many languages may have multiple ways to do this so we will show an example of how you can send requests in Java, Actionscript, curl, and your browser. 

 

Java - HTTP Request
//set up url
String username = "sterling_archer@ikanow.com";
String hashedpassword = "WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D"; //don't forget to URLEncode your arguments
String address = "http://infinite.ikanow.com/api/auth/login/" + username + "/" + hashedpassword;
        
//send request
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("GET");
                
//read back result
BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder strBuilder = new StringBuilder();
String buffer;            
while ( (buffer = inStream.readLine()) != null )
{
    strBuilder.append(buffer);
}        
inStream.close();
        
//print out response json
System.out.println(strBuilder.toString());
Actionscript - HTTP Request
protected function button_clickHandler( event:MouseEvent ):void
{
	//set up url
    var username:String = "sterling_archer@ikanow.com";
    var hashedpassword:String = "WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D"; //don't forget to URLEncode your arguments
    var address:String = "http://infinite.ikanow.com/api/auth/login/" + username + "/" + hashedpassword;
                
	//send request
    var httpService:HTTPService = new HTTPService();
    httpService.addEventListener( ResultEvent.RESULT, httpResultHandler );
    httpService.addEventListener( FaultEvent.FAULT, httpFaultHandler );
    httpService.url = address;
    httpService.send();
}            
            
protected function httpFaultHandler( event:FaultEvent ):void
{
	Alert.show( "Http Request had an error: " + event.message );
}
            
protected function httpResultHandler( event:ResultEvent ):void
{
	//print out response json
	Alert.show( event.result.toString() );	
}
cURL - HTTP Request
curl http://infinite.ikanow.com/auth/login/sterling_archer@ikanow.com/WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D
Web Browser - HTTP Request
 1. In the url bar of your favorite web browser just type the url you want to navigate to and push go: http://infinite.ikanow.com/auth/login/sterling_archer@ikanow.com/WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D

Once you have mastered how to send http requests, you can attempt to send requests to the API.  To login to the system you simply need to send an http request to http://infinite.ikanow.com/api/auth/login with username and password.  On a successful login, you will receive a cookie that will be active for 30 minutes from your last command.  This cookie will need to be passed back anytime you want to perform an API call that needs authentication. 

In the next section we show examples of how to send requests with cookies.

Example 2: Getting a cookie, and sending the cookie in a subsequent request (Login, Get Person, Logout).

To make requests to many of our services we require you to send a cookie along with the HTTP Request so we can verify who we are getting the information for.  Below are examples of how to receive cookies from a Login call, send the cookies to another call, and log out.

Java - Login for cookie, send cookie to get/person call, logout
public static void main(String[] args) throws Exception 
{
	//don't forget to URLEncode your arguments 
    String address = "http://infinite.ikanow.com/api/auth/login/sterling_archer@ikanow.com/WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D";        
    String loginresult = sendRequest(address);
	//Our data objects can be used by importing infinit.e.data_model.jar and gson.jar
    ResponsePojo response = ResponsePojo.fromApi(loginresult, ResponsePojo.class);
    if ( response.getResponse().isSuccess())
    {
        //send next request
        String personAddress = "http://infinite.ikanow.com/api/social/person/get";
        String personresult = sendRequest(personAddress);
        //We need to convert the result object into a response with a person object in it
        response = ResponsePojo.fromApi(personresult, ResponsePojo.class, PersonPojo.class, new PersonPojoApiMap());
        if ( response.getResponse().isSuccess() )
        {                
            PersonPojo personResult = (PersonPojo)response.getData();                            
            System.out.println(personResult.getEmail());
        }
    }
    else
    {
        System.out.println("error logging in: " + response.getResponse().getMessage());
    }    
	//logout when we are done, this will deactivate our cookie
    sendRequest("http://infinite.ikanow.com/api/auth/logout");
}

private static String cookie = null;
public static String sendRequest(String urlAddress ) throws Exception
{
    URL url = new URL(urlAddress);
    URLConnection urlConnection = url.openConnection();
    if ( cookie != null ) //add cookie to request if we have one
        urlConnection.setRequestProperty("Cookie", cookie);
    ((HttpURLConnection)urlConnection).setRequestMethod("GET");
            
    //read back result
    BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder strBuilder = new StringBuilder();
    String buffer;            
    while ( (buffer = inStream.readLine()) != null )
    {
        strBuilder.append(buffer);
    }        
    inStream.close();
    
    //save cookie if cookie is null
    if ( cookie == null )
    {
        String headername;
        for ( int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++ )
        {
            if ( headername.equals("Set-Cookie") )
            {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }        
    return strBuilder.toString();
}        
Actionscript - Login for cookie, send cookie to get/person, logout
protected function button_clickHandler( event:MouseEvent ):void
{
    //set up url
    var username:String = "sterling_archer@ikanow.com";
    var hashedpassword:String = "WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D"; //don't forget to URLEncode your arguments
    var address:String = "http://infinite.ikanow.com/api/auth/login/" + username + "/" + hashedpassword;
    
	//send login request
    var httpService:HTTPService = new HTTPService();
    httpService.addEventListener( ResultEvent.RESULT, httpResultHandler );
    httpService.addEventListener( FaultEvent.FAULT, httpFaultHandler );
    httpService.url = address;
    httpService.send();
}

protected function httpResultHandler( event:ResultEvent ):void
{
    //convert result json string to an as3 object using the as3corelib library
    //available at: https://github.com/mikechambers/as3corelib
    var jsonObject:Object = JSON.decode( event.result.toString(), true );
    
    if ( jsonObject.response.success == true )
    {
        //successfully logged in, cookies are automatically stored in flash so no need to handle them
		//send request for our person object (will print out in httpPersonResultHandler)
        var httpService:HTTPService = new HTTPService();
        httpService.addEventListener( ResultEvent.RESULT, httpPersonResultHandler );
        httpService.addEventListener( FaultEvent.FAULT, httpFaultHandler );
        httpService.url = "http://infinite.ikanow.com/api/social/person/get";
        httpService.send();
    }
}

protected function httpPersonResultHandler( event:ResultEvent ):void
{
    //just print out person result json
    Alert.show( event.result.toString() );
	//logout
	var httpService:HTTPService = new HTTPService();
	httpService.url = "http://infinite.ikanow.com/api/auth/logout";
	httpService.send(); 
}

protected function httpFaultHandler( event:FaultEvent ):void
{
    Alert.show( "Http Request had an error: " + event.message );
}
cURL - Login for cookie, send cookie to get/person, logout
curl -c cookies.txt http://infinite.ikanow.com/api/auth/login/sterling_archer@ikanow.com/WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D
curl -b cookies.txt http://infinite.ikanow.com/api/social/person/get
curl -b cookies.txt http://infinite.ikanow.com/api/auth/logout
Web Browser- Login for cookie, send cookie to get/person, logout
1. In the url bar of your favorite web browser just type the url you want to navigate to and push go: http://infinite.ikanow.com/api/auth/login/sterling_archer@ikanow.com/WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U%3D
2. In the url bar of your favorite web browser just type the url you want to navigate to and push go: http://infinite.ikanow.com/api/social/person/get
3. In the url bar of your favorite web browser just type the url you want to navigate to and push go: http://infinite.ikanow.com/api/auth/logout

 

Beyond this point the examples are just showing added functionality.  As a result only a single language will be used to demonstrate each examples.  Using the above principles in example 2 you can extend any language to do the tasks below.

Example 3: Login, Get Communities, Perform a Query, Logout

Performing a query adds a final bit of complexity in which we must send a POST request with a json object in the body.

Actionscript - Login, Get Communities, Perform a Query, Logout

Example 4: Login, Create a Community, Invite User, Logout

Java - Login, Create a Community, Invite User, Logout

Note that the Java example above includes an example of how to use the Data Model library to deserialize from JSON strings into Infinit.e data store (or API) objects:

Using the ResponsePojo utility code
// Single object:
ResponsePojo response = ResponsePojo.fromApi(communityresult, ResponsePojo.class, CommunityPojo.class, new CommunityPojoApiMap()); 
	// (use null instead of "new CommunityPojoApiMap()" for objects derived from BaseApiPojo)
CommunityPojo community = (CommunityPojo)response.getData();
// Multiple objects:
ResponsePojo response = ResponsePojo.listFromApi(communityresult, ResponsePojo.class, CommunityPojo.listType(), new CommunityPojoApiMap()); 
List<CommunityPojo> communities  = (List<CommunityPojo>)response.getData();

Example 5: Login, Get Public Communities, Request to Join Community, Logout

cURL - Login, Get Public Communities, Request to Join Community, Logout

Example 6: Login, Get a Source, Edit the Source, Test the new Source, Save the new Source, Logout

Actionscript - Login, Get a Source, Edit the Source, Test the new Source, Save the new Source, Logout

Example 7: Login, share a hadoop Jar file, schedule a map reduce job with jar, Logout

Java - Login, share a hadoop Jar file, schedule a map reduce job with jar, Logout

Note that unlike example 4, this Java example uses the simpler ResponsePojo "fromApi" call for when the "data" field from the API call is just a string:

Simpler ResponsePojo usage
ResponsePojo response = ResponsePojo.fromApi(schedulejobresult, ResponsePojo.class);
String responseData = (String) response.getData();

Example 8: Login, Get Map Reduce Jobs, Get Reults of a map reduce job, Logout

cURL - Login, Get Map Reduce Jobs, Get Reults of a map reduce job, Logout

  • No labels