Creating and searching a user with API call in Java

To search and create a user with an API call in Java, you will need to create separate Java Classes. The steps for doing that are given below for both examples.

Creating a user

Step 1. Create a new Java Class called CreateUser and make sure to replace the URL with your OpenIAM instance.

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import static org.example.FetchToken.getToken;
public class CreateUser {
public static void main(String[] args) {
try {
String url = "http://your-openiam-instance/webconsole/rest/api/prov/saveUser";
// [1] Create the JSON payload
JSONObject payload = new JSONObject();
payload.put("firstName", "user");
payload.put("lastName", "example");
payload.put("metadataTypeId", "DEFAULT_USER");
payload.put("notifyUserViaEmail", true);
// [2] Create the email addresses array
JSONObject email = new JSONObject();
email.put("email", "exampleemail@openiam.com");
email.put("typeId", "HOME_EMAIL");
email.put("published", true);
payload.put("emailAddresses", new JSONArray().put(email));
// [3] Create the phones array
JSONObject phone = new JSONObject();
phone.put("areaCd", "1");
phone.put("phoneNbr", "1");
phone.put("phoneExt", "");
phone.put("typeId", "CELL_PHONE");
phone.put("countryCd", "1");
phone.put("isForSMS", true);
phone.put("published", true);
payload.put("phones", new JSONArray().put(phone));
// [4] Create the connection
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + getToken());
con.setDoOutput(true);
// [5] Send the request
OutputStream os = con.getOutputStream();
os.write(payload.toString().getBytes("UTF-8"));
os.close();
// [6] Read the response
Scanner in = new Scanner(con.getInputStream());
StringBuilder response = new StringBuilder();
while (in.hasNext()) {
response.append(in.nextLine());
}
in.close();
// [7] Print the response
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 2. Run the program and make sure the correct results have been output. The example of output is given below.

{"primaryKey":null,"status":200,"errorList":null,"redirectURL":"editUser?id=ff808081913ac77001913af5dd5a0013","successToken":{"message":"USER_INFO_SAVED","params":null},"successMessage":"User information was saved successfully<br/>Provisioning:","contextValues":{"checkStatusInProgress":true,"userId":"ff808081913ac77001913af5dd5a0013"},"stackTrace":null,"possibleErrors":null,"error":false}

Optional step. After running, go back to the webconsole, go to User Admin > User Search then search for your user.

Searching a user

Step 1. Create a new Java Class called SearchUser, make sure to replace the URL with your OpenIAM instance and search for the user that you just created.

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;
import org.json.JSONArray;
import static org.example.FetchToken.getToken;
public class SearchUser {
public static void main(String[] args) {
try {
String url = "http://your-openiam-instance/webconsole/rest/api/users/search";
// [1] Create the JSON payload
JSONObject payload = new JSONObject();
payload.put("from", 0);
payload.put("size", 20);
payload.put("lastName", "example");
payload.put("firstName", JSONObject.NULL);
payload.put("principal", "");
payload.put("email", "");
payload.put("roleIds", new JSONArray());
payload.put("groupIds", new JSONArray());
payload.put("organizationIds", new JSONArray());
payload.put("employeeId", "");
payload.put("fromDirectoryLookup", false);
payload.put("sortBy", "name");
payload.put("orderBy", "ASC");
// [2] Create the connection
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + getToken());
con.setDoOutput(true);
// [3] Send the request
OutputStream os = con.getOutputStream();
os.write(payload.toString().getBytes("UTF-8"));
os.close();
// [4] Read the response
Scanner in = new Scanner(con.getInputStream());
StringBuilder response = new StringBuilder();
while (in.hasNext()) {
response.append(in.nextLine());
}
in.close();
// [5] Print the response
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 2. Run the program and make sure the correct results have been output. The example of output is given below.

{"error":null,"page":0,"from":0,"size":1,"pageSize":1,"beans":[{"id":"ff808081910c2cb801910c32380e0006","beanType":"UserBean","operation":"NO_CHANGE","classification":null,"middleInit":null,"accessRightIds":null,"name":"user example","phone":"1 (1) 1 ","email":"exampleemail@openiam.com","userStatus":"PENDING_INITIAL_LOGIN","accountStatus":null,"principal":"user.example","organization":null,"department":null,"division":null,"title":"","employeeId":"12345","startDate":"","accessRightStartDate":null,"accessRightEndDate":null,"organizations":null,"location":null,"firstName":"user","lastName":"example","nickname":null,"birthdate":null,"birthdateAsStr":null,"maidenName":null,"suffix":null,"sex":null,"gender":null,"jobCodeId":null,"prefix":null,"prefixLastName":null,"partnerName":null,"locationCd":null,"userTypeInd":null,"employeeTypeId":null,"employeeTypeName":null,"costCenter":null,"alternateContactId":null,"alternativeStartDate":null,"alternativeEndDate":null,"certificationDelegateId":null,"certificationDelegateEndDate":null,"certificationDelegateStartDate":null,"supervisorMdTypeName":"DEFAULT_USER","supervisorsNameList":null,"accountTypeName":null,"visible":false,"hasRelatedAccounts":false,"relationship":null,"mdTypeId":"DEFAULT_USER","applicationNames":null,"accessRightStartDateStr":null,"accessRightEndDateStr":null}],"emptySearchBean":false,"beansMap":null}