8 Developing Mobile and Social Services Applications with the Java Client SDK

This chapter describes how to use the Java Client SDK to build desktop applications. The Java Client SDK does not provide support for building applications on mobile devices.

This chapter includes the following topics.

8.1 Before You Begin

The Mobile and Social Java Client SDK for Mobile and Social Services is included in the Oracle Access Management distribution package. It can also be downloaded from the Oracle Technical Network (OTN) website.

In addition to this Developer's Guide, API documentation generated by the Javadoc tool is available. Refer to the Java API documentation for descriptions of API classes, interfaces, constructors, methods, and fields. This documentation is provided as HTML in the SDK, and can also be downloaded from the Oracle Access Management product library in PDF and HTML formats as the Oracle Fusion Middleware Java API Reference for Mobile and Social.

8.2 Invoking Authentication Services With the Java Client SDK

This section provides sample code that illustrates how to request a Client Token, a User Token, and an Access Token. A token contains attributes related to the item, as well as encrypted information that establishes the authority, validity, or identity of the token bearer. A Client Token contains credential information, a User Token encapsulate the Client Token, and an Access Token contains the security information needed to access a protected resource.

The sample code in this section supports the "JWTAuthentication" (JSON Web Token Authentication) service type. Refer to "Configuring Mobile and Social Services" in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management for information about configuring a service provider. The code samples are organized into the following sections.

8.2.1 Import the Java Client SDK Classes

Import the following Java client SDK classes from the oic_clientsdk.jar file:

import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig;
import oracle.security.idaas.rest.jaxrs.client.sdk.Headers;
import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.AuthenticationClient;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.AuthenticationResult;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenCreateRequest;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenCreateRequestImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenDeleteRequest;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenDeleteRequestImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenExchangeRequest;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenExchangeRequestImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenReadRequest;
import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenReadRequestImpl;

8.2.2 Initialize Objects and Define Endpoints

Initialize the ClientSDKConfig object, then define the endpoints for various actions using the service provider jwtauthentication. Then initialize the AuthenticationClient object.

AuthenticationClientSDKConfig cc = new AuthenticationClientSDKConfig();
cc.setRegisterationServiceURI("http://hostcomputer.example.com:18001/
oic_rest/rest/jwtauthentication/register");
 
cc.setAuthenticationServiceURI("http://hostcomputer.example.com:18001/
oic_rest/rest/jwtauthentication/authenticate");
 
cc.setAccessTokenServiceURI("http://hostcomputer.example.com:18001/
oic_rest/rest/jwtauthentication/access");
 
cc.setTokenInfoServiceURI("http://hostcomputer.example.com:18001/
oic_rest/rest/jwtauthentication/tokens/info");

AuthenticationClient tc = new AuthenticationClient(cc);

8.2.3 Create a Client Token

Define the required parameters for the Client Token request and then request to create the token. Save the result of the token request in a variable named savedClientToken:

String subjectType = "USERCREDENTIAL";
String uname = "profileid1";
String password = "secret12";
String tokenTypeToCreate = "CLIENTTOKEN";
TokenCreateRequest tcrd = new TokenCreateRequestImpl(subjectType, uname, password, tokenTypeToCreate);
Headers headers = new HeadersDefaultImpl();
AuthenticationResult savedClientToken = tc.createToken(tcrd, headers);

8.2.4 Create a User Token

Define the required parameters for the User Token request and request to create the token. Add the Client Token from the previous step to the REST authorization header and save the result of the User Token request in a variable named savedUserToken:

String subjectType = "USERCREDENTIAL";
String uname = "sean";
String password = "secret12";
String tokenTypeToCreate = "USERTOKEN";
TokenCreateRequest tcrd = new TokenCreateRequestImpl(subjectType, uname, password, tokenTypeToCreate);
Headers headers = new HeadersDefaultImpl();

//Value expects certain format including type...
String tokenHeaderValue = "TOKEN" + " " + savedClientToken.getValue();
headers.setIdaasRestAuthZHeader(tokenHeaderValue);
AuthenticationResult savedUserToken = tc.createToken(tcrd, headers);

8.2.5 Create an Access Token

Define the required parameters for the Access Token request and request to create the token. Save the result of the token request in a variable named savedAccessToken.

String resource = "http:myserver.com:8080/index.html";
String context = "QaZdhh77randomstuff";
String tokenSubjectValue = savedClientToken.getValue();
String credentialSubjectType = "TOKEN";
String newTokenTypeToCreate = "ACCESSTOKEN";
TokenExchangeRequest tcberd = new TokenExchangeRequestImpl(credentialSubjectType, tokenSubjectValue, resource, context, newTokenTypeToCreate);
AuthenticationResult savedAccessToken = tc.createToken(tcberd, headers);

8.2.6 Validate a Client Token

String tokenValueToVerify = savedClientToken.getValue();
String tokenSubjectTypeToVerify = "TOKEN";

headers = new HeadersDefaultImpl();
headers.setIdaasRestAuthZHeader("TOKEN " + tokenValueToVerify);

TokenReadRequest tokenToRead = new TokenReadRequestImpl();
tokenToRead.setSubjectValue(tokenValueToVerify);
tokenToRead.setSubjectType(tokenSubjectTypeToVerify);

AuthenticationResult retrievedToken = tc.readToken(tokenToRead, headers);
System.out.println("Token returned from readToken() =" + retrievedToken.getValue());
if (null != savedClientToken && null != retrievedToken) {
  System.out.println("Does value in savedClientToken == retrievedToken?" +
  savedClientToken.getValue().equals(retrievedToken.getValue()));
}

8.2.7 Validate a User Token

Headers headers = new HeadersDefaultImpl();
headers.setIdaasRestAuthZHeader("TOKEN " + savedClientToken.getValue());

TokenReadRequest tokenToRead = new TokenReadRequestImpl();
tokenToRead.setSubjectValue(savedUserToken.getValue());
tokenToRead.setSubjectType("TOKEN");
AuthenticationResult retrievedToken = tc.readToken(tokenToRead, headers);
System.out.println("Token returned from readToken() =" + retrievedToken.getValue());
if (null != savedUserToken && null != retrievedToken) {
  System.out.println("Does value in savedUserToken == retrievedToken?" +
  savedUserToken.getValue().equals(retrievedToken.getValue()));
}

8.2.8 Perform a User Lookup Using the User Token

In this step, User is a protected resource that is protected by the authentication provider.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos";
final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize";
String pageSizeValue = "1";  //Just get one user for this test.
String pageSizePosition = "0";

//Now do a search and fetch first page o results.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue);
queryParameters.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition);

// Set Header to include the User Token for authetication.
Headers headers = new HeadersDefaultImpl();
headers.setAuthZHeader(savedUserToken);

//Perform search operation.
JSONCollection searchResults = pc.searchUsers(queryParameters, headers);

8.2.9 Delete the Client Token

String deleteSubjectValue = savedClientToken.getValue(); //use first token value
String deleteTokenType = "TOKEN";
TokenDeleteRequest tokenToDelete = new TokenDeleteRequestImpl();
tokenToDelete.setSubjectValue(deleteSubjectValue);
tokenToDelete.setTokenType(deleteTokenType);
boolean result = false;
result = tc.deleteToken(tokenToDelete, headers);

8.3 Invoking User Profile Services with the Java Client SDK

Before working with the code samples in this section, see "Introduction to Building Applications With User Profile Services" for notes and information that are not specific to this SDK.

The code samples in this section are organized into the following categories:

8.3.1 Working with People

The following code samples demonstrate how to interact with User records located in a Directory store that User Profile Services can access and update. This section covers the following basic scenarios:

8.3.1.1 Importing Java Classes and Declaring People

First import the following Java classes from the oic_clientsdk.jar file, then declare the "people" Service URI global variable.

import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig;
import oracle.security.idaas.rest.jaxrs.client.sdk.Headers;
import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException;
import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.JSONCollection;
import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.PeopleClient;
 
private static String serviceURI = "http://hostcomputer.example.com:18001/oic_rest/rest/userprofile/people";

8.3.1.2 Creating a User

The following sample creates a User record with uid peopletestuser123.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
//Just generate some fake user info.
String uid = "peopletestuser123";
String userpassword = "secret123";
String sn = uid;
String cn = uid;
String mail = uid + "@example.com";
 
//Now put these values into the resourceAttrs map, and pass to helper.
Map<String, Object> resourceAttrs = new HashMap<String, Object>();
resourceAttrs.put("uid", uid);
resourceAttrs.put("password", userpassword);
resourceAttrs.put("lastname", sn);
resourceAttrs.put("commonname", cn);
resourceAttrs.put("mail", mail);
List<String> phoneNums = new ArrayList<String>();
phoneNums.add("408-123-5555");
phoneNums.add("408-123-9999");
resourceAttrs.put("telephone", phoneNums);
String personJson = pc.createUser(resourceAttrs, new HeadersDefaultImpl());

8.3.1.3 Reading a User

The following sample retrieves the User record with uid peopletestuser123.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
String uidForExistingUser = "peopletestuser123";
 
//now GET that user just to check
Map<String, String> queryParameters = new HashMap<String, String>();//none yet
String existingUser = pc.readUser(uidForExistingUser, queryParameters, new HeadersDefaultImpl());
boolean found = false;
JSONObject jo = new JSONObject(existingUser);
String s = jo.getString("uid");
found = s.equalsIgnoreCase(uid);

8.3.1.4 Updating a User

The following sample updates the User record with uid peopletestuser123.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);

//Just generate some fake user info.
final String CN_VALUE = "UPDATED CN";
 
String uidForExistingUser = "peopletestuser123"; //From class-defined uid.

//now make some attributes with new values to update
Map<String, Object> attrsToUpdate = new HashMap<String, Object>();
attrsToUpdate.put("commonname", CN_VALUE);
String result = pc.updateUser(uidForExistingUser, attrsToUpdate,new HeadersDefaultImpl());

8.3.1.5 Deleting a User

The following sample deletes the User record with uid peopletestuser123.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
boolean deleteResult = pc.deleteUser("peopletestuser123", new HeadersDefaultImpl());

8.3.1.6 Searching for a User

The following sample searches for the User record with uid peopletestuser123.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
//now do a search on uid attribute
Map<String, String> queryParameters = new HashMap<String, String>();
String queryValue = "peopletestuser"+ "*";
queryParameters.put("searchparam.uid", queryValue);

//Set query parameters and empty headers.
JSONCollection searchResult = pc.searchUsers(queryParameters, new HeadersDefaultImpl());
 
//Get raw JSON array value in "elements" attribute.
String elementJSONString = searchResult.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);
 
//Now try to match the result to the expected User with uid.
JSONObject elem = null;
boolean found = false;
for(int i=0; i<ja.length() && found==false; i++) {
  elem = ja.getJSONObject(i);  //Get item from array
  String u = elem.getString("uid");
  
  //Check if attr is present AND matches some value.
  if(u.equalsIgnoreCase("peopletestuser123")) {
    found = true;
  }
}

8.3.1.7 Retrieving User Attributes and Validating the Results

The following sample retrieves the user attribute commonname and checks that the attribute description is not present.

final String ATTRIBUTES_TO_FETCH_QUERY_PARAM_NAME = "attrsToFetch";
String attributeToFetchName = "commonname";  //fetch this attribute
String attributeShouldNotBePresent = "description";
ClientSDKConfig cc = new ClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);

//Now GET that User just to check.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(ATTRIBUTES_TO_FETCH_QUERY_PARAM_NAME, attributeToFetchName);
String existingUser = pc.readUser("peopletestuser123", queryParameters, new HeadersDefaultImpl());
boolean found = false;
try {
  JSONObject jo = new JSONObject(existingUser);
  //Throws exception if attribute not present
  String s = jo.getString(attributeToFetchName);
  found = true;
} catch (JSONException je) {
  found = false;
}
 
//Now verify that a certain attribute is NOT present.
found = false;
try {
  JSONObject jo = new JSONObject(existingUser);

  //throws exception if attribute not present
  for(Iterator it = jo.keys(); it.hasNext() && found==false; ) {
    String key = (String) it.next();
      if(key.equalsIgnoreCase(attributeShouldNotBePresent)) {
        found = true; //Bad if present because it should not be.
      }
  }
} catch (JSONException je) {}

8.3.2 Working With Groups

A group is a set of Users.

This section presents code samples that cover the following basic scenarios:

8.3.2.1 Importing Java Classes and Declaring Groups

First import the following Java classes, then declare the "groups" Service URI global variable.

import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig;
import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException;
import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.GroupsClient;
import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.JSONCollection;
 
private static GroupsClient gc = null;
private static PeopleClient pc = null;

private static String roleServiceURI = 'http://hostcomputer.example.com:18001/oic_rest/
rest/userprofile/groups";

private static String peopleServiceURI = "http://hostcomputer.example.com:18001/oic_rest/
rest/userprofile/people";
Map<String, String> accessURIMap = Util.createAccessURIMap("manager", "reports", "memberOf",
"members", "groupMemberOf", "groupMembers", "ownerOf", "personOwner", "groupOwner",
"groupOwnerOf");
 
Map<String, String> entityURIMap = Util.createEntityURIMap("report-uri", "manager-uri",
"person-uri", "group-uri", "member-uri", "group-uri", "owner-uri", "group-uri", "group-uri",
"owner-uri");
 
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(roleServiceURI);
cc.setAccessURIMap(accessURIMap);
cc.setEntityURIMap(entityURIMap);
gc = new GroupsClient(cc);
 
UserProfileClientSDKConfig cc2 = new UserProfileClientSDKConfig(peopleServiceURI);
cc2.setAccessURIMap(accessURIMap);
cc2.setEntityURIMap(entityURIMap);
pc = new PeopleClient(cc2);

8.3.2.2 Creating a Group

Map<String, Object> resourceAttrs = new HashMap<String, Object>();
resourceAttrs.put("commonname", "testGroup");
resourceAttrs.put("description", "testGroupDescription");
String creategroup = gc.createGroup(resourceAttrs, new HeadersDefaultImpl());

8.3.2.3 Reading a Group

String readgroup = gc.readGroup("testGroup", new HashMap<String, String>(), new HeadersDefaultImpl());

8.3.2.4 Updating a Group

Map<String, Object> resourceAttrs2 = new HashMap<String, Object>();
resourceAttrs2.put("description", "new description");
String udpatedgroup = gc.updateGroup("testGroup", resourceAttrs2, new HeadersDefaultImpl());

8.3.2.5 Deleting a Group

boolean deletedgroup = gc.deleteGroup("testGroup", new HeadersDefaultImpl());

8.3.2.6 Searching a Group

//search with searchOperator = OR, commonname and description
Map<String, String> queryParams = new HashMap<String,String>();
String commonname = "testGroup" + 1;
String description = "testGroup" + "Description";
queryParams.put("searchparam.commonname", commonname);
queryParams.put("searchparam.description", description);
queryParams.put("searchFilter","SimpleOR");

JSONCollection searchResult = gc.searchGroups(queryParams, new HeadersDefaultImpl());

//get raw JSON array value in "elements" attribute
String elementJSONString = searchResult.getJsonArrayElements();
JSONArray ja = new JSONArray(elementJSONString);

8.3.2.7 Searching Groups With Paging Support

The following sample searches for a group and returns the results one page at a time.

final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos";
final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize";
String pageSizeValue = "1"; //just get one group for this test
String pageSizePosition = "0";

//now do a search and fetch first page o results
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue);
queryParams.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition);
JSONCollection searchResults = gc.searchGroups(queryParams, new HeadersDefaultImpl());
 
//get raw JSON array value in "elements" attribute
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);
boolean justOneFound = false;


//the search returns a set with just one user
if (ja.length() == Integer.parseInt(pageSizeValue)) {
  justOneFound = true;
}

8.3.2.8 Adding a User to a Group

The following sample uses the addPersonMember method. Also see Adding a Group (or a User) to a Group Using addMemberOf.

String resultRoleMembership = gc.addPersonMember("testGroup", "testuser123", new HeadersDefaultImpl());

8.3.2.9 Getting Group Membership Info

The following sample uses the getPersonMember method. Also see Getting the Membership of a Group Using getMemberOf.

Map<String, String> queryParameters = new HashMap<String, String>(); //none yet
String membershipId ="testuser123";
String result = gc.getPersonMember("testGroup",membershipId,queryParameters, new HeadersDefaultImpl());
  

8.3.2.10 Searching for a Member Within a Group

The following sample uses the searchGroupMembers method. Also see Searching a Group Using searchMemberOf.

String queryFilter = "(uid=" +"*)";
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("nativequery", queryFilter);

//need to use membership uri such as ...doctors/members
JSONCollection searchResults = gc.searchPersonMembers("testGroup", queryParams, new HeadersDefaultImpl());

//get raw JSON array value in "elements" attribute
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);

//Sample of how to get the members' URIs. A client could call GET on each of these 
// persons' URIs using the person client API to get details about each member.Set<String> userUriSet = new HashSet<String>();
final String PERSON_URI_FIELD_NAME = "person-uri";
for (int i=0; i<ja.length(); i++) {
   JSONObject jo = ja.getJSONObject(i);
   
   //Get the URI field of this user.   String uri = jo.getString(PERSON_URI_FIELD_NAME);
   if (uri != null && !uri.isEmpty()) {
      userUriSet.add(uri);
   }
}

// Get Group members in the group.
searchResults = gc.searchGroupMembers("testGroup", queryParams, new HeadersDefaultImpl());

8.3.2.11 Removing a Member From a Group

The following sample uses the deletePersonMember method. Also see Removing a Group (or a User) from a Group Using deleteMemberOf.

boolean result = gc.deletePersonMember("testGroup", "testuser123", new HeadersDefaultImpl());

8.3.2.12 Assigning Group Ownership

The following sample demonstrates how to assign ownership of a group to a user or a group.

// Add user testuser123 to group testGroup as group owner.
String resultRoleOwnership = gc.addPersonOwner("testGroup", "testuser123", 
new HeadersDefaultImpl());

// Add group testSubGroup to group testGroup as group owner.
String resultRoleOwnership2 = gc.addGroupOwner("testGroup", "testSubGroup", 
new HeadersDefaultImpl());

8.3.2.13 Getting Group Ownership Info

Map<String, String> queryParameters = new HashMap<String, String>();//none yet
String ownershipId="testuser123";
String result = gc.getPersonOwner("testGroup", ownershipId, queryParameters, 
new HeadersDefaultImpl());
ownershipId ="testSubGroup";
result = gc.getGroupOwner("testGroup", ownershipId, queryParameters, 
new HeadersDefaultImpl());

8.3.2.14 Searching for the Owner of a Group

String queryFilter = "(uid=" +"*)";
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("nativequery", queryFilter);

// Get Person owners in the group.
JSONCollection searchResults = gc.searchPersonOwners("testGroup", queryParams, 
new HeadersDefaultImpl());

// Get raw JSON array value in the "elements" attribute.
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);

// Sample of how to get the members' URIs.  A client could call GET on each of these 
// person URIs using the person client API and get details on each member.
Set<String> userUriSet = new HashSet<String>();
final String OWNER_URI_FIELD_NAME = "owner-uri";
for(int i=0; i<ja.length(); i++) {
  JSONObject jo = ja.getJSONObject(i);

  //Get URI field of this user.
  String uri = jo.getString(OWNER_URI_FIELD_NAME);
  if (uri != null && !uri.isEmpty()) {
    userUriSet.add(uri);
  }
}

// Get Group owners in the group.
searchResults = gc.searchGroupOwners("testGroup", queryParams, new HeadersDefaultImpl());

8.3.2.15 Removing a Group Owner

boolean result = gc.deletePersonOwner("testGroup", "testuser123", new HeadersDefaultImpl());boolean result2= gc.deleteGroupOwner("testGroup", "testSubGroup", new HeadersDefaultImpl());

8.3.2.16 Adding a Group (or a User) to a Group Using addMemberOf

The following sample demonstrates how to use the addMemberOf method to make a group a member of another group, or how to make a user a member of a group.

// Add group "testSubGroup" to be a member of group "testGroup"
String resultRoleMembership2= gc.addMemberOf("testGroup", "testSubGroup", 
new HeadersDefaultImpl());

// Add user "testuser123" to be a member of group "testGroup"
String resultRoleMembership = pc.addMemberOf("testuser123", "testGroup", 
new HeadersDefaultImpl());

8.3.2.17 Getting the Membership of a Group Using getMemberOf

The following sample demonstrates how to use the getMemberOf method to get relationship data about a specified group.

// Get relationship data where user "testuser123" is a member of group "testGroup"
String resultRoleMembership = pc.getMemberOf("testuser123", "testGroup", new HeadersDefaultImpl());

// Get relationship data where group "testsubGroup" is a member of group "testGroup"
String resultRoleMembership2= gc.getMemberOf("testGroup", "testSubGroup", 
new HeadersDefaultImpl());

8.3.2.18 Searching a Group Using searchMemberOf

String queryFilter = "(uid=" +"*)";
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("nativequery", queryFilter);

// Search groups of which Person "testuser123" is a member
JSONCollection searchResults = pc.searchMemberOf("testuser123", queryParams, 
new HeadersDefaultImpl());

//Get raw JSON array value in "elements" attribute
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);

// Sample of how to get the members' URIs. A client could call GET on each of these 
// person URIs using the person client API to get details about each member.Set<String> groupUriSet = new HashSet<String>();
final String GROUP_URI_FIELD_NAME = "group-uri";
for(int i=0; i<ja.length(); i++) {
  JSONObject jo = ja.getJSONObject(i);


  //Get URI field of this user.  String uri = jo.getString(GROUP_URI_FIELD_NAME);
  if (uri != null && !uri.isEmpty()) {
    groupUriSet.add(uri);
  }
}

// Search Groups of which group "testSbuGroup" is a member.
searchResults = gc.searchMemberOf("testSubGroup", queryParams, new HeadersDefaultImpl());

8.3.2.19 Removing a Group (or a User) from a Group Using deleteMemberOf

// Delete member "testuser123" from group "testGroup"
boolean result = pc.deleteMemberOf("testuser123","testGroup", new HeadersDefaultImpl());

// Delete member "testSubGroup" from group "testGroup"
boolean result2= gc.deleteMemberOf("testGroup","testSubGroup", new HeadersDefaultImpl());

8.3.2.20 Assigning Group Ownership Using addOwnerOf

// Add user "testuser123" to be an owner of group "testGroup"
String resultRoleOwnership = pc.addOwnerOf("testuser123", "testGroup", new HeadersDefaultImpl());

// Add group "testSubGroup" to be an owner of group "testGroup"
String resultRoleOwnership2 = gc.addOwnerOf("testGroup", "testSubGroup", new HeadersDefaultImpl());

8.3.2.21 Getting Group Ownership Info Using getOwnerOf

// Get relationship data where user "testuser123" is an owner of group "testGroup"
String resultRoleOwnership = pc.getOwnerOf("testuser123", "testGroup", new HeadersDefaultImpl());

// Get relationship data where group "testsubGroup" is an owner of group "testGroup"
String resultRoleOwnership2= gc.getOwnerOf("testGroup", "testSubGroup", new HeadersDefaultImpl());

8.3.2.22 Searching for the Owner of a Group Using searchOwnerOf

String queryFilter = "(uid=" +"*)";
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("nativequery", queryFilter);

// Search Groups of which Person "testuser123" is an owner.
JSONCollection searchResults = pc.searchOwnerOf("testuser123", queryParams, 
new HeadersDefaultImpl());

// Get raw JSON array value in "elements" attribute.
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);


// Sample of how to get the members' URIs. A client could call GET on each of these person URIs using the person client API to get details about each member.
Set<String> groupUriSet = new HashSet<String>();
final String GROUP_URI_FIELD_NAME = "group-uri";
for(int i=0; i<ja.length(); i++) {
  JSONObject jo = ja.getJSONObject(i);
  
  // Get URI field of this user.
  String uri = jo.getString(GROUP_URI_FIELD_NAME);
  if (uri != null && !uri.isEmpty()) {
    groupUriSet.add(uri);
  }
}

// Search Groups of which group "testSbuGroup" is an owner.
searchResults = gc.searchOwnerOf("testSubGroup", queryParams, new HeadersDefaultImpl());

8.3.2.23 Removing a Group (or a User) from a Group Using deleteOwnerOf

// Delete owner "testuser123" from group "testGroup"
boolean result = pc.deleteOwnerOf("testuser123","testGroup", new HeadersDefaultImpl());

// Delete owner "testSubGroup" from group "testGroup"
boolean result2= gc.deleteOwnerOf("testGroup","testSubGroup", new HeadersDefaultImpl());

8.3.3 Working With Organizations

An organization is a hierarchical group of people that usually includes a manager and reports. This section presents code samples that cover the following basic scenarios:

8.3.3.1 Importing Java Classes and Declaring Groups

The following code samples import the Java classes and then declare the "groups" Service URI global variable.

import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig;
import oracle.security.idaas.rest.jaxrs.client.sdk.Headers;
import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl;
import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.PeopleClient;
 
private static String personServiceURI= "http://hostcomputer.example.com:18001/oic_rest/rest/userprofile/people";
 
private static String peopleBaseURI = "/oic_rest/rest/userprofile/people";

8.3.3.2 Creating User Data with a Helper Utility

public static String createPersonHelper(String personServiceURI, String username,String password,Map<String, String> optionalAttributes) {

ClientSDKConfig cc = new ClientSDKConfig(personServiceURI);
PeopleClient pc = new PeopleClient(cc);

//Generate some fake user info.
String uid = username;
String userpassword = password;
String sn = uid;
String cn = uid;
String mail = uid + "@example.com";
 
try {
//now put these values into the resourceAttrs map, and pass to helper
//these java string names need to match the json field names
Map<String, Object> resourceAttrs = new HashMap<String, Object>();
resourceAttrs.put("uid", uid);
resourceAttrs.put("password", userpassword);
resourceAttrs.put("lastname", sn);
resourceAttrs.put("commonname", cn);
resourceAttrs.put("mail", mail);
if (optionalAttributes != null && !optionalAttributes.isEmpty()) {
for(Map.Entry<String, String> me : optionalAttributes.entrySet()) {
resourceAttrs.put(me.getKey(), me.getValue());
}
}
 
String newUser = pc.createUser(resourceAttrs, new HeadersDefaultImpl());
 
}

8.3.3.3 Establishing Manager and Reports Relationships with a Helper Utility

private static boolean assignManagerToUser(String personServiceURI, String serviceBaseURI, String userUID, String theManagerId) {
ClientSDKConfig cc = new ClientSDKConfig(personServiceURI);
PeopleClient pc = new PeopleClient(cc);
final String MANAGER_URI_SEGMENT_NAME = "manager";
//now make payload
final String MANAGER_URI_JSON_ATTRIBUTE_NAME = "manager-uri";
final String REPORTS_URI_JSON_ATTRIBUTE_NAME = "report-uri";
Map<String, Object> resourceAttrs = new HashMap<String, Object>();
resourceAttrs = new HashMap<String, Object>();
//use base URI od people service within json values
String theManagerURIValue = serviceBaseURI + "/" + theManagerId;
resourceAttrs.put(MANAGER_URI_JSON_ATTRIBUTE_NAME, theManagerURIValue);
String theReporteeURIValue = serviceBaseURI + "/" + userUID; //user being added to list of reports
resourceAttrs.put(REPORTS_URI_JSON_ATTRIBUTE_NAME, theReporteeURIValue);
 
return pc.addUserToOrgChart(userUID, MANAGER_URI_SEGMENT_NAME, resourceAttrs, new HeadersDefaultImpl());
}

8.3.3.4 Creating Users at Different Hierarchies with a Data Preparation Utility

String theUIDofManager = null;
Map<String, String> optionalAttributes = new HashMap<String, String>();
optionalAttributes.put("manager", theUIDofManager);
//keep a map of created people in orgchart
Map<String, String> createdPeople= new HashMap<String, String>();
String userPassword = "secret123";
String userId = "ceo"+ "orgcharttestuser"+ "123"; // user is CEO
String person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes );
 
theUIDofManager = userId; //set to previously created user
userId = "director" + "orgcharttestuer" + "123"; // user id DIRECTOR
optionalAttributes = new HashMap<String, String>();//reset for each new user
person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes);
 
//now assign this newly created user DIRECTOR's manager to be CEO
assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager);
 
theUIDofManager = userId; //set to previously created user
userId = "developer111" + "orgcharttestuser" + "123"; // user is DEVELOPER111
optionalAttributes = new HashMap<String, String>();//reset for each new user
person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes);
 
//now assign this newly created user DEVELOPER111's manager to be DIRECTOR
assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager);
 
userId = "developer222"+ "orgcharttestuser"+"123"; // user is DEVELOPER222
optionalAttributes = new HashMap<String, String>();//reset for each new user
person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes);
//now assign this newly created user DEVELOPER222's manager to be DIRECOTR
assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager);

8.3.3.5 Verifying a Manager

//Set empty query parameters and empty headers.
Map<String, String> searchQueryParameters = new HashMap<String, String>();
Headers searchHeaders = new HeadersDefaultImpl();
JSONCollection resultSet = pc.searchManagers("developer222orgcharttestuser123", searchQueryParameters, searchHeaders);
 
//get raw JSON array value in "elements" attribute
String elementJSONString = resultSet.getJsonArrayElements();
 
boolean found = false;
final String MANAGER_URI_ATTRIBUTE_NAME = "manager-uri";
JSONArray ja = new JSONArray(elementJSONString);
for(int i=0; i< ja.length() && found==false; i++) {
    JSONObject elem = ja.getJSONObject(i);//get item from array
    try {
      //The "manager-uri" attribute of this item in element array is
      //expanded automatically so its value is a JSONObject.
      JSONObject managerURIObject = elem.getJSONObject(MANAGER_URI_ATTRIBUTE_NAME);

      //Check if attr is present AND matches some value.
      if(managerURIObject.getString("uri").equalsIgnoreCase("directororgcharttestuser123")) {
        found = true;
      }
    } catch (JSONException je) {
    //An exception is thrown if attribute is not found or is not a JSON object
    //found = false;
    }

//print out each user, until found
}

8.3.3.6 Verifying Direct Reports

Map<String, String> searchQueryParameters = new HashMap<String, String>();
Headers searchHeaders = new HeadersDefaultImpl();
JSONCollection resultSet = pc.searchReportees("ceoorgcharttestuser123",
searchQueryParameters, searchHeaders);

//Get raw JSON array value in "elements" attribute.
String elementJSONString = resultSet.getJsonArrayElements();

boolean found = false;
final String REPORTS_URI_ATTRIBUTE_NAME = "report-uri";

JSONArray ja = new JSONArray(elementJSONString);
for(int i=0; i< ja.length() && found==false; i++) {
  JSONObject elem = ja.getJSONObject(i); //Get item from array
  try {
    JSONObject reportURIObject = elem.getJSONObject(REPORTS_URI_ATTRIBUTE_NAME);
    
    //Check if attr is present AND matches some value.
    if(reportURIObject.getString("uri").equalsIgnoreCase("directororgcharttestuser123")) {
      found = true;
    }
  } catch (JSONException je) {
  //exception is thrown if attribute is not found or is not JSON object
  //found = false;
  }

//Print out each user, until found.
}

8.3.3.7 Retrieve All Reports Using Scope=All Feature

The following code samples verify all of the reports in an organization, including indirect reports.

ClientSDKConfig cc = new ClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);

//Now test CEO orgchart by getting reports with scope=all, which should include developer.
String orgChartIdURI = "reports";

//Now do a search and fetch first page o results.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(ClientConstants.ATTRIBUTES_TO_ORG_CHART_SCOPE_QUERY_PARAM_NAME, "all");
JSONCollection resultSet = pc.searchReportees("ceoorgcharttestuser123", queryParameters,
new HeadersDefaultImpl());

//Get raw JSON array value in "elements" attribute.
String elementJSONString = resultSet.getJsonArrayElements();
boolean found = false;
JSONArray ja = new JSONArray(elementJSONString);
for (int i=0; i<ja.length(); i++) {
  JSONObject jo = ja.getJSONObject(i);
  Object reportURIObj = jo.get("report-uri");
  if (reportURIObj.toString().indexOf( "developer111orgcharttestuser123") != -1) {
    found = true;
  }
}

8.3.3.8 Retrieve the Manager Chain Using Scope=toTop Feature

The following code samples use the toTop attribute to retrieve an array that contains the managers in a management chain.

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);

// Now do a search and fetch the first page of results.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(ClientConstants.ATTRIBUTES_TO_ORG_CHART_SCOPE_QUERY_PARAM_NAME, "toTop");
JSONCollection resultSet = pc.searchManagers("developer111orgcharttestuser123", 
queryParameters, new HeadersDefaultImpl());

// Get raw JSON array value in "elements" attribute.
String elementJSONString = resultSet.getJsonArrayElements();

8.3.3.9 Retrieve Report Details Using Pre-Fetch Feature

The following code samples retrieve manager details when the Report ID and the Manager ID are known.

ClientSDKConfig cc = new ClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
final String ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME = ClientConstants.ATTRIBUTES_TO_PRFFETCH_QUERY_PARAM_NAME;
String attributeToPrefetch = "report-uri";
final String MANAGER_URI_SEGMENT_NAME = "manager";
 
//Now read/get new user's details.
String reporteeId = "developer111orgcharttestuser123";
String managerId = "directororgcharttestuser123";
 
//Now GET that user just to check.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME, attributeToPrefetch);

//Get raw JSON representation.
String existingManagerRel = pc.getManager(reporteeId, managerId, queryParameters, new HeadersDefaultImpl());
 
//Now obtain manager details and retrieve the reports data.
JSONObject jo = new JSONObject(existingManagerRel);
Object managerAttributeValue = jo.get(attributeToPrefetch);

8.3.3.10 Retrieve Manager Data using the Pre-Fetch feature

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
final String ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME = ClientConstants.ATTRIBUTES_TO_PRFFETCH_QUERY_PARAM_NAME;
String attributeToPrefetchName = "manager(commonname)";
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME, attributeToPrefetchName);

// Get the raw JSON representation of the person.
String existingUser = pc.readUser("developer111orgcharttestuser123", queryParameters, new HeadersDefaultImpl());
 
// Get the manager attribute, which is expanded by prefetch to include one or more
// sub-attributes, so that manager is a JSON object within the person JSON.
// Now it is a JSONObject.
JSONObject jo = new JSONObject(existingUser);
Object managerAttributeValue = (Object) jo.get("manager");
System.out.println(CLASS_NAME + "." + METHOD + ": prefetch detail="
+ managerAttributeValue);

8.3.3.11 Deleting a Report From the Manager

ClientSDKConfig cc = new ClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
String uidForExistingUser = "developer111orgcharttestuser123";
String theManagerId = "directororgcharttestuser123";
final String REPORTS_URI_SEGMENT_NAME = "reports";
Map<String, String> queryParameters = new HashMap<String, String>(); //None yet.
String existingOrgChartInstanceDetails = pc.getReportee(theManagerId, uidForExistingUser, queryParameters, new HeadersDefaultImpl());
 
//Now that we verified it exists, delete this membership in the reports list.
boolean deleteResult = pc.deleteOrgChartInstance(theManagerId, REPORTS_URI_SEGMENT_NAME, uidForExistingUser, new HeadersDefaultImpl());

//Now try to get/read that user again. This time we should not find the user.
queryParameters = new HashMap<String, String>(); //None yet.
existingOrgChartInstanceDetails = null;
try {
  existingOrgChartInstanceDetails = pc.readOrgChartInstance(theManagerId, REPORTS_URI_SEGMENT_NAME, uidForExistingUser, queryParameters, new HeadersDefaultImpl());
} catch (OICClientException ce) {
  System.out.println("existingOrgChartInstanceDetails was successfully deleted so not found"
  + " on subsequent read.");
}

8.3.4 Searching With Paging Support

UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI);
PeopleClient pc = new PeopleClient(cc);
 
final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos";
final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize";
String pageSizeValue = "1"; //Just get one user for this test.
String pageSizePosition = "0";

//Now do a search and fetch first page o results.
Map<String, String> queryParameters = new HashMap<String, String>();
queryParameters.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue);
queryParameters.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition);

//Set query params and empty headers.
JSONCollection searchResults = pc.searchUsers(queryParameters, new HeadersDefaultImpl());
 
//Get raw JSON array value in "elements" attribute
String elementJSONString = searchResults.getJsonArrayElements();
JSONArray ja = null;
ja = new JSONArray(elementJSONString);
boolean justOneFound = false;

//The search returns a set with just one user.
if (ja.length() == Integer.parseInt(pageSizeValue)) {
  justOneFound = true;
}

8.4 Invoking Authorization Services With the Java Client SDK

This example demonstrates accessing the Authorization Service, which is protected by the Access Manager Authentication Service.

String clientToken = null;
String userToken = null;
ClientSDKConfig cc = null;
AuthenticationClient authNClient = null;
AuthorizationClient authZClient = null;
Headers headers = new HeadersDefaultImpl();
headers.setContractName("Default");
 
TokenCreateRequest req = null;
AuthenticationResult resultToken = null;
 
 
// Create a Client Token.
cc = new ClientSDKConfig("http://hostcomputer.example.com:18001/oic_rest/rest/oamauthentication/authenticate");
 
authNClient = new AuthenticationClient(cc);
req = new TokenCreateRequestImpl("USERCREDENTIAL", "profileid1", "secret12",
"CLIENTTOKEN");
headers = new HeadersDefaultImpl();
headers.setContractName("Default");
resultToken = authNClient.createToken(req, headers);
clientToken = resultToken.getValue();
System.out.println("ClientToken from REST Service : " + clientToken);
 
// Create a User Token.
req = new TokenCreateRequestImpl("USERCREDENTIAL", "jane", "secret12",
"USERTOKEN");
headers = new HeadersDefaultImpl();
headers.setIdaasRestAuthZHeader("TOKEN " + clientToken);
headers.setContractName("Default");
 
resultToken = authNClient.createToken(req, headers);
userToken = resultToken.getValue();
System.out.println("UserToken from REST Service : " + userToken);
 
 
// Access the Authorization Service using the User Token.
cc = new ClientSDKConfig("http://hostcomputer.example.com:18001/idaas_rest/rest/oamauthorization/authorization");
authZClient = new AuthorizationClient(cc);
 
headers = new HeadersDefaultImpl();
headers.setAuthZHeader(userToken);
headers.setContractName("Default");
 
Map<String, String> qp = new HashMap<String,String>();
qp.put("resource", "http://hostcomputer.example.com:18001/index.html");
 
qp.put("action", "get");
qp.put(ClientConstants.IDAAS_REST_SUBJECT_TYPE_QUERY_PARAM_NAME, "TOKEN");
qp.put(ClientConstants.IDAAS_REST_SUBJECT_VALUE_QUERY_PARAM_NAME, userToken);
AuthorizationDecision ad = authZClient.getAuthzDecision (qp, headers);
System.out.println("AuthZ Decision from REST Service : " + ad.getAllowed());