Pages

Friday, March 7, 2014

Box.com User CRUD API Example

Box.com User CRUD API Example

The Box REST API end point Usage examples are Create User, Update User, Add Email Alias to the User, Get Email Aliases for the User, Update Primary Email Account, Remove the Existing Primary email Account  as an Alias, and Remove the User from the box.com

Pre-Requisite

1. Download and Install Gradle

Creating Eclipse Project Using Gradle

1. Set the Java Home Environment Variable

export JAVA_HOME=/usr/lib/jvm/java

2. Set the Gradle Home Environment Variable

export GRADLE_HOME=/home/gradle/gradle-1.10

3. Create the eclipse Project, and source Directory

    mkdir box-api-usage
    mkdir box-api-usage/src
    mkdir box-api-usage/src/main
    mkdir box-api-usage/src/main/java
    mkdir box-api-usage/src/main/resources

4. Create the build.gradle file in the box-api-usage directory

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'

repositories{
                mavenCentral()
        }

dependencies{
        compile 'org.apache.httpcomponents:httpclient:4.2.2'
        compile 'org.slf4j:slf4j-api:1.7.5','org.slf4j:slf4j-log4j12:1.7.5'
        compile 'com.google.code.gson:gson:2.2.2'

}
mainClassName='box.api.usage.client.BoxAPIUsage'

5. Create the Eclipse Project
  gradle cleanEclipse eclipse

6. Import the Project into the Eclipse

File --> Import --> Existing Project Into Workspace --> Next -->Select box-api-usage directory and click finish. It will create the eclipse project directory.

Get the Access Token from Box.com



Convert the Access Token to Map Object

        GenerateBoxCode accessCode= new GenerateBoxCode();
        String accessToken=accessCode.getAccessToken();
        Map<String, Object> tokenMap= null;
        Gson gson= new Gson();
        tokenMap=gson.fromJson(accessToken, Map.class);
        String accessToken= tokenMap.get("access_token");
        System.out.println(tokenMap);


Create User in Box.com


1. Build Create Request Attributes

  String emailId="<Replace With Your Email Id>";
  String displayName="<Replace With Your Display Name>";
  String role="<Replace With your Role>";
  String id="";
  Gson gson= new Gson();

  Map<String, String> createRequest= new HashMap<String,String>();
  createRequest.put("login", emailId);
  createRequest.put("name", displayName);
  createRequest.put("role", role);

2. Convert Map object to Json Object
      
  String jsonCreateRequest= gson.toJson(createRequest);

3. Send the Post Request to create the User in Box.com
  
  HttpClient client= new DefaultHttpClient();
  HttpPost post= new HttpPost(provisionEndPoint);
  post.addHeader("Authorization", "Bearer " + accessToken);
  try
  {
     post.setEntity(new StringEntity(jsonCreateRequest));
     HttpResponse response= client.execute(post);
     int statusCode=response.getStatusLine().getStatusCode();

     System.out.println(String.format("Response Status Code : %d" , statusCode));
     if( statusCode == 200 || statusCode == 201)
     {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
     }
      else
      {
         System.out.println("User Creation Error");
      }
   } catch (UnsupportedEncodingException e)
   {
      e.printStackTrace();
   }
   finally
   {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
     }
  

Update User in Box.com


1. Build Update Request Attributes

  displayName="<Replace With Your Display Name>";



  Map<String, String> updateRequest= new HashMap<String,String>();

  updateRequest.put("name", displayName);



2. Convert Map object to Json Object

      
  String jsonUpdateRequest= gson.toJson(updateRequest);

3. Send the PUT Request to create the User in Box.com

        HttpClient client= new DefaultHttpClient();
       
        HttpPut put= new HttpPut(provisionEndPoint+"/"+id);
        put.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            put.setEntity(new StringEntity(jsonUpdateRequest));
            HttpResponse response= client.execute(put);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Update Failed Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }


Add Aliases for the User in Box.com


String aliasName="<Replace With your Alias Name>";
String aliasId="";
1. Build Add Alias Request Attributes

  Map<String, String> addEmailAlias= new HashMap<String,String>();  addEmailAlias.put("email", aliasName);

2. Convert Map object to Json Object
      
  String jsonEmailAliasRequest= gson.toJson(addEmailAlias);

3. Send the POST Request to create the User in Box.com

        HttpClient client= new DefaultHttpClient();
       
        HttpPost post= new HttpPost(provisionEndPoint+"/"+id+"/email_aliases");
        post.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            post.setEntity(new StringEntity(jsonEmailAliasRequest));
            HttpResponse response= client.execute(post);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    aliasId=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Add Alias Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }

Update Primary Email User in Box.com



1. Build Update Request Attributes

  Map<String, String> updateEmail= new HashMap<String,String>();  updateEmail.put("login", aliasName);

2. Convert Map object to Json Object
      
  String jsonEmailUpdateRequest= gson.toJson(updateEmail);

3. Send the PUT Request to update the User in Box.com

        HttpClient client= new DefaultHttpClient();
       
        HttpPut put= new HttpPut(provisionEndPoint+"/"+id);
        put.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            put.setEntity(new StringEntity(jsonEmailUpdateRequest));
            HttpResponse response= client.execute(put);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Update Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }



Get All Email Aliases for the User in Box.com


1. Send the Get Request to Get All Email Aliases for the User in Box.com
        Map<String, List<Map<String, String>>> data=null;
        HttpClient client= new DefaultHttpClient();
        HttpGet get= new HttpGet(provisionEndPoint+"/"+id+"/email_aliases");
        get.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(get);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    data= gson.fromJson(strresponse, Map.class);
                    System.out.println(String.format("Raw Jason Data : %s" , data));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Get Alias Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }


Remove Aliases for the User in Box.com

 1. Send the Delete Request to Delete the Email Alias for the User in Box.com

        HttpClient client= new DefaultHttpClient();
        HttpDelete delete= new HttpDelete(provisionEndPoint+"/"+id+"/email_aliases/"+aliasId);
        delete.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(delete);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 204)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    System.out.println(strresponse);
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Alias Deletion Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
 

Remove the User from Box.com

 1. Send the Delete Request to Delete the User in Box.com

        HttpClient client= new DefaultHttpClient();
        HttpDelete delete= new HttpDelete(provisionEndPoint+"/"+id);
        delete.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(delete);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 204)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    System.out.println(strresponse);
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Deletion Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
 

Sample Code 

package box.api.usage.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;


public class BoxAPIUsage {

    public BoxAPIUsage() {
       
    }

    private static String emailId="<Replace Your BoxUser Login Email>";
    private static String displayName="<Replace Your Display Name>";
    private static String role="user";
    private static String accessToken="";
    private static String provisionEndPoint = "https://api.box.com/2.0/users";
    private static String emailAlias="<Replacing Your Alias to modify the Primary Email Account>";
    private static Gson gson= new Gson();
   
    public static void main(String[] args) {
       
        GenerateBoxCode accessCode= new GenerateBoxCode();
        String accessToken=accessCode.getAccessToken();
        Map<String, Object> tokenMap= null;
        tokenMap=gson.fromJson(accessToken, Map.class);
       
        accessToken=tokenMap.get("access_token").toString();
        System.out.println(accessToken);
        // Creating User
        String id=createUser(accessToken);
        System.out.println("Created ID :"+id);
        // Updating user DsiplayName
        id=updateUser(accessToken, id);
        // Adding alias to the user to modify the primary email account
        String aliasId=addAlias(accessToken, id);
        System.out.println("Alias id :"+aliasId);
        //Updating Email Account
        id=updateEmailUser(accessToken, id);
        // Getting the Email Aliases to remove the existing email
        Map<String, List<Map<String, String>>> aliases= getAliases(accessToken, id);
        if(aliases != null)
        {
            List<Map<String, String>> entries= aliases.get("entries");
            for (Map<String, String> map : entries)
            {
                aliasId=map.get("id");
                // removing the Email Alias
                removeAlias(accessToken, id, aliasId);
            }
        }
        // Removing the User
        removeUser(accessToken, id);
    }
   
    public static String createUser(String accessToken)
    {
        String id="";
        Map<String, String> createRequest= new HashMap<String,String>();
        createRequest.put("login", emailId);
        createRequest.put("name", displayName);
        createRequest.put("role", role);

       
        String jsonCreateRequest= gson.toJson(createRequest);
       
        HttpClient client= new DefaultHttpClient();
       
        HttpPost post= new HttpPost(provisionEndPoint);
        post.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            post.setEntity(new StringEntity(jsonCreateRequest));
            HttpResponse response= client.execute(post);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Creation Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }

       
        return id;
    }
    public static String updateUser(String accessToken,String boxid)
    {
        String id="";
        displayName=displayName+ "M";
        Map<String, String> updateRequest= new HashMap<String,String>();
        updateRequest.put("name", displayName);
       
        String jsonUpdateRequest= gson.toJson(updateRequest);
       
        HttpClient client= new DefaultHttpClient();
       
        HttpPut put= new HttpPut(provisionEndPoint+"/"+boxid);
        put.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            put.setEntity(new StringEntity(jsonUpdateRequest));
            HttpResponse response= client.execute(put);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Creation Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
       
        return id;
    }

    public static String addAlias(String accessToken,String boxid)
    {
        String aliasId="";
        displayName=displayName+ "M";
        Map<String, String> addEmailAlias= new HashMap<String,String>();
        addEmailAlias.put("email", emailAlias);
       
       
        String jsonEmailAliasRequest= gson.toJson(addEmailAlias);
       
        HttpClient client= new DefaultHttpClient();
       
        HttpPost post= new HttpPost(provisionEndPoint+"/"+boxid+"/email_aliases");
        post.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            post.setEntity(new StringEntity(jsonEmailAliasRequest));
            HttpResponse response= client.execute(post);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    aliasId=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Update Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
       
        return aliasId;
    }

    public static Map<String, List<Map<String, String>>> getAliases(String accessToken,String boxid)
    {
        Map<String, List<Map<String, String>>> data=null;
        HttpClient client= new DefaultHttpClient();
        HttpGet get= new HttpGet(provisionEndPoint+"/"+boxid+"/email_aliases");
        get.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(get);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    data= gson.fromJson(strresponse, Map.class);
                    System.out.println(String.format("Raw Jason Data : %s" , data));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Get Aliases Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
       
        return data;
    }

   
    public static void removeAlias(String accessToken,String boxid,String aliasId)
    {
        HttpClient client= new DefaultHttpClient();
        HttpDelete delete= new HttpDelete(provisionEndPoint+"/"+boxid+"/email_aliases/"+aliasId);
        delete.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(delete);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 204)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    System.out.println(strresponse);
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Remove Alias Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
    }

   
    public static String updateEmailUser(String accessToken,String boxid)
    {
        String id="";
        displayName=displayName+ "M";
        Map<String, String> updateEmail= new HashMap<String,String>();
        updateEmail.put("login", emailAlias);
       
        String jsonEmailUpdateRequest= gson.toJson(updateEmail);
       
        HttpClient client= new DefaultHttpClient();
       
        HttpPut put= new HttpPut(provisionEndPoint+"/"+boxid);
        put.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            put.setEntity(new StringEntity(jsonEmailUpdateRequest));
            HttpResponse response= client.execute(put);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 200 || statusCode == 201)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    Map<String, Object> data= gson.fromJson(strresponse, Map.class);
                    id=data.get("id").toString();
                    System.out.println(String.format("Raw Jason Data : %s" , strresponse));
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Update Email Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
       
        return id;
    }

    public static void removeUser(String accessToken,String boxid)
    {
        HttpClient client= new DefaultHttpClient();
        HttpDelete delete= new HttpDelete(provisionEndPoint+"/"+boxid);
        delete.addHeader("Authorization", "Bearer " + accessToken);
        try
        {
            HttpResponse response= client.execute(delete);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(String.format("Response Status Code : %d" , statusCode));
            if( statusCode == 204)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null) {
                   
                    BasicResponseHandler handler= new BasicResponseHandler();
                    String strresponse =handler.handleResponse(response);
                    System.out.println(strresponse);
                    EntityUtils.consume(entity);
                }
            }
            else
            {
                System.out.println("User Deletion Error");
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            if(client != null)
            {
                client.getConnectionManager().shutdown();   
            }
        }
    }


}


Wednesday, February 26, 2014

Box.com Oauth2 Test Client

Getting the Access Token from the Box.COM as follows

1. Get the Authorization code from the Box.COM

2. Get the Access Token Based on the Authorization Code granted by Box.COM


Pre-Requisite


1. Http Client 4.1 jar files in the Class Path.
2. Generate the Client_ID and Client_Secret in the Box.COM .

1. Get the Authorization code from the Box.COM

Get the Authorization code from the Box.COM as three step process.

Stept 1. Send the Post Request to the Box.com with client id, redirect_uri, and response_type.

In the Sample code, invoking the sendPostRequestAuthorization() method to initial the post Authentication request process.

Stept 2. Authenticate the user against Box.com with Admin Credentials

In the Sample Code, Invoking the sendPostAuthorize() method to authenticate the user against the Box.COM

Step 3. Grant Access to the User to access the Box.com and it generate the Authorization Code.

In the Sample Code, Invoking the sendPostAuthorize() method to grant to access to box.com and  generate the Authorization Code


2. Get the Access Token Based on the Authorization Code granted by Box.COM


The following parameters are required in the request to get the access token using the REST API. They are

grant_type=authorization_code
code=clientCode
client_id=<Client ID>
client_secret=CLIENT_SECRET

 REST URL: https://www.box.com/api/oauth2/token
 Request Type: Post

In the Sample Code, Invoke the getAccessToken() method and it will get the access token from the box.com



Sample Code:



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;


public class OauthClientBox
{

    private static String BOX_AUTHORIZE_URL="https://app.box.com/api/oauth2/authorize";
    private static String BOX_OAUTH_TOKEN_URL="https://www.box.com/api/oauth2/token";
    private static String CLIENT_ID="<Replace With Your Client ID>";
    private static String CLIENT_SECRET="<Replace With your Client Secret>";
    private static String USER_NAME="<Co Admin User Name>";
    private static String PASSWORD="Co Admin Password";
    private static String REDIRECT_URL="<Redirect URL>";
   
    /**
     * This is required to carry forward the box.com cookies from each request
     */
    private static BasicCookieStore cookieStore= new BasicCookieStore();
    private static BasicHttpContext context= new BasicHttpContext();

   
   
    public OauthClientBox() {
    }

    public static void main(String args[]) throws Exception
    {
       String accessToken=getAccessToken();
    }
   
public static String getAccessToken()
{
       context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      
        // Returns the HTML Form Data
        String htmlData=sendPostRequestAuthorization();
        // Separating the Form Data. For Example <form name="login_form" action="http://localhost" method="post"><input type=hidden name=test/><input type=submit value=login></form>
        String formData=getFormRawData(htmlData);
        // Constructing the Form Data as a Key as Html Field element name , and values as a Map such as name=<Html Field name>,type=hidden or submit , value=<html field value>
        Map<String,Map<String, String>> loginFormElements= constructFormData(formData);
        if(loginFormElements != null && !loginFormElements.isEmpty())
        {
            // Setting the User Name and Password for Authentication
            loginFormElements.get("login").put("value", USER_NAME);
            loginFormElements.get("password").put("value", PASSWORD);
        }
        // Getting the Form Action and Method type as a Map. For Example. action="http://localhost" method="post"
        Map<String, String> formDataMap= getFormData(formData);
    //Sending Authentication Request to Box.com   
  String authenticatedHtmlData= sendPostAuthorize(loginFormElements,false,formDataMap.get("action"));
        
 
      formData=getFormRawData(authenticatedHtmlData);

// Constructing the Form Data as a Key as Html Field element name , and values as a Map such as name=<Html Field name>,type=hidden or submit , value=<html field value>
       
        Map<String,Map<String, String>> authFormElements= constructFormData(formData);
      // Getting the Form Action and Method type as a Map. For Example. action="http://localhost" method="post"
        formDataMap= getFormData(authenticatedHtmlData);
//Sending the Authorization Request to Box.Com to authorize and grant the access to the user and it will return the code. 
        String code=sendPostAuthorize(authFormElements,false,formDataMap.get("action"));
        System.out.println("Final Authorize Code :"+code);
        // Getting the Access Token Based on the Authorization code
        String accessToken= getAccessToken(code);
        System.out.println("Final Access Token :"+accessToken);
        return  accessToken;
}
   
    public static String getAccessToken(String clientCode)
    {
        String data=null;
        HttpClient client= new DefaultHttpClient();
        HttpPost post= new HttpPost(BOX_OAUTH_TOKEN_URL);
        List<NameValuePair> nameValueParams= new ArrayList<NameValuePair>();
        nameValueParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValueParams.add(new BasicNameValuePair("code", clientCode));
        nameValueParams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        nameValueParams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
          
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nameValueParams));
            HttpResponse response=client.execute(post);
            System.out.println(String.format("status code  %d",  response.getStatusLine().getStatusCode()));
            if(response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BasicResponseHandler handler= new BasicResponseHandler();
                    data=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return data;
    }
   
    private static String getFormRawData(String htmlData)
    {
        String result="";
        int startIndex = htmlData.indexOf("<form");
        int endIndex = htmlData.indexOf("</form>");
        if(startIndex !=-1 && endIndex !=-1)
        {
            result = htmlData.substring(startIndex,endIndex+7);  
        }
        return result;
    }

   
   
   
    // Sending Box API Initial Authorization Request
    private static String sendPostRequestAuthorization()
    {
        String result=null;
        DefaultHttpClient client= new DefaultHttpClient();
        try
        {
          
            HttpPost post= new HttpPost(BOX_AUTHORIZE_URL);
            List<NameValuePair> params= new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("response_type", "code"));
            params.add(new BasicNameValuePair("client_id", CLIENT_ID));
            params.add(new BasicNameValuePair("redirect_uri", REDIRECT_URL));
            post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response=client.execute(post,context);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode==200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    BasicResponseHandler handler= new BasicResponseHandler();
                    result=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
          
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    private static String sendPostAuthorize(Map<String, Map<String, String>> data,boolean authrize,String url)
    {
        String result=null;
        DefaultHttpClient client= new DefaultHttpClient();
        try
        {
          
            HttpPost post= new HttpPost(url);
            Set<String> inputKey= data.keySet();
            List<NameValuePair> params= new ArrayList<NameValuePair>();
            for (String string : inputKey) {
                Map<String, String> inputData= data.get(string);
                String type=inputData.get("type");
                if(type != null && !type.equalsIgnoreCase("submit"))
                {
                    params.add(new BasicNameValuePair(string, inputData.get("value")));
                }
            }
            if(authrize)
            {
                params.add(new BasicNameValuePair("consent_accept", "Grant access to Box"));
            }
            post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response=client.execute(post,context);
            int statusCode=response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if(statusCode==200)
            {
                HttpEntity entity=response.getEntity();
                if (entity != null)
                {
                    BasicResponseHandler handler= new BasicResponseHandler();
                    result=handler.handleResponse(response);
                    EntityUtils.consume(entity);
                }
            }
            else if(statusCode==302)
            {
                String redirectURL = response.getFirstHeader("Location").getValue();
                String codeStr="code=";
                int index=redirectURL.indexOf("code=");
                if(index !=-1)
                {
                    String code=redirectURL.substring(index+codeStr.length());
                    result=code;
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    private static Map<String,Map<String, String>> constructFormData(String data)
    {
        Map<String,Map<String, String>> inputElements= new HashMap<String,Map<String, String>>();
        int startIndex= data.indexOf("<input");
        int endIndex= data.indexOf(">",startIndex);
        while(startIndex != -1 && endIndex !=-1)
        {
            String inputElement= data.substring(startIndex, endIndex+1);
            Map<String, String> inputData= getInputElement(inputElement);
            inputElements.put(inputData.get("name"), inputData);
            startIndex=data.indexOf("<input", endIndex+1);
            endIndex= data.indexOf(">",startIndex);
        }
        return inputElements;
    }
   
    private static Map<String, String> getInputElement(String element)
    {
        Map<String, String> row= new HashMap<String, String>();
      
        int nameIndex=element.indexOf("name=");
        int typeIndex=element.indexOf("type=");
        int valueIndex=element.indexOf("value=");
      
        if(nameIndex != -1)
        {
            String data= element.substring("name=".length()+nameIndex);
            row.put("name", getValue(data));
        }
        if(typeIndex != -1)
        {
            String data= element.substring("type=".length()+typeIndex);
            row.put("type", getValue(data));
        }
        if(valueIndex != -1)
        {
            String data= element.substring("value=".length()+valueIndex);
            row.put("value", getValue(data));
        }
      
        return row;
    }
   
    private static String getValue(String data)
    {
        String result="";
        int startQuote=data.indexOf("\"");
        int endQuote=data.indexOf("\"",startQuote+1);
        if(startQuote != -1 && endQuote !=-1)
        {
            result=data.substring(startQuote+1,endQuote);
        }
        return result;  
    }

    public static Map<String, String> getFormData(String formData)
    {
        Map<String, String> formDataMap= new HashMap<String,String>();
        int startIndex= formData.indexOf("<form");
        int endIndex= formData.indexOf(">",startIndex);
        if(startIndex !=-1 && endIndex !=-1)
        {
            String form= formData.substring(startIndex,endIndex+1);
            String action=getValue(form,"action=");
            String method=getValue(form,"method=");
            formDataMap.put("action", action);
            formDataMap.put("method", method);
        }
        return formDataMap;
    }
    private static String getValue(String element,String query)
    {
        String result="";
        int nameIndex=element.indexOf(query);
        if(nameIndex != -1)
        {
            String data= element.substring(query.length()+nameIndex);
          
            int startQuote=data.indexOf("\"");
            int endQuote=data.indexOf("\"",startQuote+1);
            if(startQuote != -1 && endQuote !=-1)
            {
                result=data.substring(startQuote+1,endQuote);
            }
        }
        return result;
    }




   
   
}

 

Tuesday, January 21, 2014

This account doesn't have an Outlook Web App mailbox in Office 365

Problem:

You're currently signed in as <User Principal Name>. Please sign out, then sign in to Outlook Web App with the account you use to read your organization's email. Click <here> to sign out.

The problem is mailbox is created in exchange online with few missing attributes. The attributes are SKUAssigned.



Causes:

1. The target resource like Exchange Online attributes are not synchronized with Office 365 Azure AD. The synchronized attributes are SKUAssigned, and ExternalObjectID.

2. The ExchangeUserAccountControl  attribute value is AccountDisabled in the Exchange Online Office 365. The ExchangeUserAccountControl value always None.


Solution:

There are two solutions are available to resolve the issue. They are

Solution 1: The User doesn't have any data in exchange online.

1. Login to the Office 365 Portal.
2. Search the User
3. Remove the Licenses to the User
4. Usually it takes 5 minutes to replicates the changes from Azure AD  to Exchange Online.In worst case  you need to wait 24 Hours to replicate the changes from Azure AD to Exchange Online.
5. After re-assign the licenses to the user and the issue will be resolved.

Solution 2: The User have data in exchange mailbox and you need to restore the mailbox.

The Following procedure is being used to restore the Mailbox in the Exchange Online integrated with Federated environment. They are

1. Finding the PendingInput Status user in Office 365

$users = Get-MsolUser -UserPrincipalName <User Principal Name>

foreach($user in $users)
{
    $licenses = $user.Licenses[0].ServiceStatus
    foreach($license in $licenses)
    {
         if($License.ProvisioningStatus -eq "PendingInput")
         {
            Write-Host $user.UserPrincipalName " - " $License.ServicePlan.ServiceName "-"  $License.ProvisioningStatus
         }
         else
         {
            Write-Host $user.UserPrincipalName " - " $License.ServicePlan.ServiceName "-"  $License.ProvisioningStatus
         }
    }
}

2. Finding the Exchange Online SKUAssigned value for the User

Get-Mailbox <User Principal Name> | Select SKUAssigned

The SKUAssigned value should be empty because the azure ad licensing info was not replicated from azure ad to exchange online. 


3. Removing the User from the Office 365 Azure AD

The following commands needs to be executed to remove the user from Windows Azure AD.

Remove-MsolUser -UserPrincipalName <User Principal Name> -force
Remove-MsolUser -UserPrincipalName <User PrinciplaName> -force -RemoveFromRecycleBin




4. Verifying the Azure AD user replicated to exchange online removal state

Usually the replication process from azure AD to Office 365 time duration is 5 minutes to 24 hours. The following commands being used to retrieve the removal state mailbox.

$rmb=Get-RemovedMailbox <User Principal Name> | Select Guid

 The guid is required to relinking the existing mailbox in the exchange online. 

5. Linking the Existing MailBox in exchange online

New-MailBox -Name <Name> -RemovedMailbox <GUID> -FirstName <FirstName> -LastName <LastName> -DisplayName <DisplayName> -MicrosoftOnlineServicesID <UPN>  -PrimarySmtpAddress <upn> -ImmutableId <immutable Id> -FederatedIdentity <federated id> 

6. Testing the Mailbox Accepting the Messages

Test-MAPIConnectivity <User Principal Name>

This command move the mailbox disconnected state to active state.

7. Update the Country Location in Office 365 

   set-msoluser -UserPrincipalName <User Principal Name> -UsageLocation "US"

8. Assign the A2 Licenses to the user in office 365 using power shell.

 Set-MsolUserLicense -UserPrincipalName <UserPrincipalName> -AddLicenses tests:STANDARDWOFFPACK_STUDENT

9. Update the Immutable ID or Source Anchor in the Office 365

 Set-MsolUserPrincipalName -UserPrincipalName <FederatedDomainUPN> -NewUserPrincipalName <NonFederatedUPN>.

For example Federated Domain UPN is testid@testfed.com and non federated domain is testid@test.onmicrosoft.com

Set-MsolUser -UserPrincipalName <NonFederatedUPN> -ImmutableId <Unique ID> 

Set-MsolUserPrincipalName -UserPrincipalName <NonFederatedUPN>. -NewUserPrincipalName <FederatedDomainUPN>





Office 365 OverallProvisioningStatus : PendingInput

Problem:

1. After assigning the licenses to the user in office 365 and the provisioning status of the user is OverallProvisioningStatus  :  PendingInput

Cause:

The target resource like Exchange Online, Lync, Sharepoint Resource attributes are not synchronized with Office 365 Azure AD.

Solution:

1. Remove the existing licenses to the Office 365 User in office 365 portal or power shell and Wait for   24 hours to De-provision the resources in the target system.
2. Re-Assign the Licenses to the user in Office 365 portal or Power Shell.
3. After assigning the licenses to the user, the issue will be resolved.





Monday, January 13, 2014

SchedulerService API Example


The SchedulerService interface API being used to retrieve, manipulate the schedule task parameters and also execute the schedule task job pro-grammatically in OIM repository as follows:



Pre-Requisite:

Initial Setup.

Please follow the link and setup the OIM client environment to use to create the OIM Objects.


Client Code Setup

SchedulerService  API Usage:

1. Retrieving the Schedule Task Job Parameters.

2. Update the Schedule Task Parameters.

3. Executing the Schedule Task Pro-grammatically. 

4. Retrieving the Job History.

5. Retrieving the Last Job History.


Tasks Needs to be Performed:

1.    Create the OIMClient Handle


OIMClient client= new OIMClient();
client.login(username,password.toCharArray());

2.    Get SchedulerService service object

SchedulerService schedulerService = client.getService(SchedulerService.class);

3.  Retrieving the Schedule Task Job Parameters. 


String scheduleJobName="AD User Target Recon";
JobDetails jobdetails=schedulerService.getJobDetail(scheduleJobName);
HashMap<String, JobParameter> params= jobdetails.getParams();
           

4.  Updating the Schedule Task Parameter. 


String parameterName="Search Filter";
String parameterValue="(objectclass=inetorgperson)";
//Retrieving the Job Parameter Object
JobParameter jobParam= params.get(parameterName);
//Updating the Job Parameter Value in the Object
jobParam.setValue(parameterValue);
params.put(parameterName, jobParam);

//Udating the Schedule Task Parameters in OIM
schedulerService.updateJob(jobdetails);

5.  Executing the Schedule Task. 

// Invoking the Schedule Task

schedulerService.triggerNow(scheduleJobName);


6.  Retrieving the Schedule Job History

        List<JobHistory> history= schedulerService.getHistoryOfJob(jobName);
        if(history != null && !history.isEmpty())
        {
            for (JobHistory jobHistory : history)
            { // Retrieving the Error Data
                System.out.println("Error Data :"+new String(jobHistory.getErrorData() != null ? jobHistory.getErrorData() : "Success".getBytes()));
                try
                {
                   //Retrieving the Error Message
                    Exception exp=jobHistory.getExceptionObject();
                    if(exp != null)
                    {
                       System.out.println("Exception Message :"+.getMessage());
                    }
                   
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

7. Retrieving the Schedule Job Last Run History.


        JobHistory  history = schedulerService.getLastHistoryOfJob(jobName);
        if(history != null){
        // Retrieving the Error Data
        System.out.println("Error Data :"+new String(history.getErrorData() != null ? history.getErrorData() : "Success".getBytes()));
        // Exception Message
        System.out.println("Exception Message :"+history.getExceptionObject() != null ? history.getExceptionObject().getMessage() : "Empty");
                   
       }

              

Thursday, January 2, 2014

tcFormInstanceOperationsIntf API Example

The tcFormInstanceOperationsIntf inteface API being used to retrieve and manipulate the the Active Directory Process form data and also child data. In my example I have used first name to update data in the AD Process form in OIM, and also Adding, Updating, and Removing group Names in OIM using the process child form as Follows:

Retrieving the Process Parent and Child Form Data, Updating the Parent and Process Child Form Data, Adding the Process Form Child Data, Removing the Process Form Child Data, and Retrieving the Parent and Child Process Form Definition Keys, and Retrieving the Process Form Active Version  in the Oracle Identity Manager repository.

Pre-Requisite:

Initial Setup.

Please follow the link and setup the OIM client environment to use to create the OIM Objects.


Client Code Setup

tcFormInstanceOperationsIntf  API Usage:

Process Form Data Example:


1. Retrieving the Process Form Data,
2. Updating the Process Form Data,

Process Form Child Data Example:

3. Retrieving the Process Form Definition Key,
4. Retrieving the Process Form Active Version,
5. Retrieving the Process Form Child Definition Key,
6. Retrieving the Process Form Child Data,
7. Adding the Process Form Child Data,
8. Updating the Process Form Child Data,
9. Removing the Process Form Child Data.

Tasks Needs to be Performed:

1.    Create the OIMClient Handle


OIMClient client= new OIMClient();
client.login(username,password.toCharArray());

2.    Get tcFormInstanceOperationsIntf service object

tcFormInstanceOperationsIntf formInstanceIntf = client.getService(tcFormInstanceOperationsIntf.class);

Process Form Data Example:

3.  Retrieving the Process Form Data. 

// This Key is Getting from the Process Definition Task 
long processInstanceKey= 123456
tcResultSet trs = formInstanceIntf.getProcessFormData(processInstanceKey);
int count=trs.getRowCount();
for(int i=0;i<count;i++){
                trs.goToRow(i);
 
        String columnNames[] = trs.getColumnNames();
        for (String string : columnNames)
        {
            try {
                System.out.println(string + " - " + trs.getStringValue(string));
            } catch (tcAPIException | tcColumnNotFoundException e)
           {
                e.printStackTrace();
            }
        }
}

4.  Updating the Process Form Data. 


// Updating the Users First Name
String adColumnName="AD_USER_FNAME";
Map updateData=new HashMap();
updateData.put(adColumnName, "Liyaqat");
formInstanceIntf.setProcessFormData(pkey, updateData);


Process Form Child Data Example:

5.  Retrieving the Process Form Definition Key.

long processDefKey = formInstanceIntf.getProcessFormDefinitionKey(processInstanceKey);

6.  Retrieving the Process Form Active Version.

int formActiveVersion=formInstanceIntf.getActiveVersion(processDefKey);

7.  Retrieving the Process Form Child Definition Key.

String childFormName="UD_ADUSRC";
tcResultSet childTrsDef=formInstanceIntf.getChildFormDefinition(processDefKey, formActiveVersion);
int childCount=childTrsDef.getRowCount();
long childDefKey=-1;
for(int i=0;i<childCount;i++)
{
   
childTrs.goToRow(i);
    //Retreiving the Child Table Name and Child Table Definition Key
    String tableName=childTrsDef.getStringValue("Structure Utility.Table Name");
    childDefKey = childTrsDef..getLongValue("Structure Utility.Child Tables.Child Key");
    if(tableName.equalsIgnoreCase(childFormName))
    {
       break;
    }
}

8.  Retrieving the Process Form Child Data.


getProcessFormChildData
tcResultSet childTrs=formInstanceIntf.getChildFormDefinition(processDefKey, formActiveVersion);
int childCount=childTrs.getRowCount();
Map<String,Long> childData= new HashMap<String,Long>();
for(int i=0;i<childCount;i++)
{
            childTrs.goToRow(i);
            try 
           {
    String groupName=childTrs.getStringValue("UD_ADUSRC_GROUPNAME");
    long groupKey = childTrs..getLongValue("UD_ADUSRC_KEY");
    childData.put(groupName,groupKey);
            } catch (tcAPIException | tcColumnNotFoundException e)
           {
                e.printStackTrace();
            }

}

9.  Adding the Process Form Child Data.

String groupName="cn=Admin,ou=groups,dc=test,dc=com";
String childColumnName="UD_ADUSRC_GROUPNAME";
Map<String, String> childData= new HashMap<String,String>();
data.put(childColumnName, groupName);
formInstanceIntf.addProcessFormChildData(childDefKey,processInstanceKey,childData);

10.  Updating the Process Form Child Data.

// Updating AD Group Names are not supported by OIM. First you need to remove the existing group Name and add the new group Name.

Supported Option:
 
String updateGroupName="cn=Admin1,ou=groups,dc=test,dc=com";
 If(childData.ContainsKey(groupName))
{
   // Remove the Existing Group Member Ship for the user
   long adGroupKey =   childData.get(groupName);
   formInstanceIntf.removeProcessFormChildData(childDefKey, adGroupKey);

// Adding the  Group Member Ship for the user
Map<String, String> childData= new HashMap<String,String>();
data.put(childColumnName, updateGroupName);
formInstanceIntf.addProcessFormChildData(childDefKey,processInstanceKey,childData);
}
Un-Supported Option:
If using this option, it will only update in the OIM repository and not updated in the target resource. In our example is Active Directory.
 
 If(childData.ContainsKey(groupName))
{
   // Remove the Existing Group Member Ship for the user
   long adGroupKey =   childData.get(groupName);
// Updating the  Group Member Ship for the user in OIM Repository only.
Map<String, String> childData= new HashMap<String,String>();
data.put(childColumnName, updateGroupName);
formInstanceIntf.updateProcessFormChildData(childDefKey,adGroupKey,childData); 
}

11.  Removing the Process Form Child Data.

String removeGroupName="cn=Admin1,ou=groups,dc=test,dc=com";
 If(childData.ContainsKey(removeGroupName))
{
   // Remove the Existing Group Member Ship to the the user in OIM and also target resource
   long adGroupKey =   childData.get(groupName);
   formInstanceIntf.removeProcessFormChildData(childDefKey, adGroupKey);
}