Code Samples

Login

APIClient.sharedInstance().login("your email here", "your password here", null, false, new ObjectFaultCallback<Account>() {
            @Override
            public void call(Account account, Fault fault) {
                if(account != null) {
                    //logged in
                }
            }
        });
APIClient.sharedInstance().login("your email here", "your password here", null, false) { account, fault ->
            if (account != null) {
                //logged in
            }
        }

Logout

APIClient.sharedInstance().logout(new FaultCallback() {
            @Override
            public void call(Fault fault) {
                //logged out
            }
        });
override fun logout() {
        APIClient.sharedInstance().logout {
            //logged out
        }
    }

You can listen to login or logout notifications just like this:

NotificationCenter.defaultCenter().registerObserver(this, kMDNotificationUserDidLogin, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //your logged in code
            }
        });

        NotificationCenter.defaultCenter().registerObserver(this, kMDNotificationUserDidLogout, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //your logged out code
            }
        });
NotificationCenter.defaultCenter().registerObserver(this, kMDNotificationUserDidLogin, object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                //your logged in code
            }
        })

        NotificationCenter.defaultCenter().registerObserver(this, kMDNotificationUserDidLogout, object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                //your logged out code
            }
        })

Register User

AccountInfo info = AccountInfo.Builder.infoType(AccountInfoType.Registration)
                            .firstName("Charles")
                            .lastName("Best")
                            .email("[email protected]")
                            .mobile("16505555555")
                            .password("somePassword")
                            .gender(Gender.Male)
                            .dob(Utils.dateFromString("1899-02-27", DateParseFormat.YYYY_MM_DD))
                            .build();

        APIClient.sharedInstance().registerAccount(info, null, null, new ObjectFaultCallback<Account>() {
            @Override
            public void call(Account account, Fault fault) {
                if (account != null) {
                    // Check whether activation is required before authentication
                    boolean requiresActivation = account.getActivationRequired();
                    // Handle the case when requiresActivation == YES here
                }
            }
        });
val info = AccountInfo.Builder.infoType(AccountInfoType.Registration)
                .firstName("Charles")
                .lastName("Best")
                .email("[email protected]")
                .mobile("16505555555")
                .password("somePassword")
                .gender(Gender.Male)
                .dob(Utils.dateFromString("1899-02-27", DateParseFormat.YYYY_MM_DD))
                .build()

        APIClient.sharedInstance().registerAccount(info, null, null) { account, fault ->
            if (account != null) {
                // Check whether activation is required before authentication
                val requiresActivation = account.activationRequired!!
                // Handle the case when requiresActivation == YES here
            }
        }

Create Object

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.

Now, we want to create instances of those objects using Cortex from the client side.

Create object using jSon + FastBodyProperty

JsonObject prescription = new JsonObject();

prescription.addProperty("c_date",Utils.stringFromDate(new Date(), DateParseFormat.YYYY_MM_DD));
prescription.addProperty("c_rx", "Prescription details");
prescription.addProperty("c_patient", "some patient Id reference");
prescription.addProperty("c_provider", "some provider Id reference");
prescription.addProperty("c_dispense", 3);
prescription.addProperty("c_refills", 3);

Body prescriptionBody = new Body();
prescriptionBody.addProperty(new FastBodyProperty(prescription));

APIClient.sharedInstance().createObject("c_prescription", prescriptionBody, new ObjectFaultCallback<ObjectInstance>() {
            @Override
            public void call(ObjectInstance object, Fault fault) {

            }
        });
val prescription = JsonObject()

prescription.addProperty("c_date", Utils.stringFromDate(Date(), DateParseFormat.YYYY_MM_DD))
prescription.addProperty("c_rx", "Prescription details")
prescription.addProperty("c_patient", "some patient Id reference")
prescription.addProperty("c_provider", "some provider Id reference")
prescription.addProperty("c_dispense", 3)
prescription.addProperty("c_refills", 3)

val prescriptionBody = Body()
prescriptionBody.addProperty(FastBodyProperty(prescription))

APIClient.sharedInstance().createObject("c_prescription", prescriptionBody) { `object`, fault -> 
  //
                                                                              }

Create object using just Body + ObjectDefinition

ObjectDefinition prescriptionDef = SchemaManager.sharedInstance().getDefinition("c_prescription");
        PropertyDefinition dateDef = prescriptionDef.propertyWithName("c_date", null);
        PropertyDefinition rxDef = prescriptionDef.propertyWithName("c_rx", null);
        PropertyDefinition patientDef = prescriptionDef.propertyWithName("c_patient", null);
        PropertyDefinition dispenseDef = prescriptionDef.propertyWithName("c_dispense", null);
        PropertyDefinition prescriptionType = prescriptionDef.propertyWithName("type", null );
        PropertyDefinition propADef = prescriptionDef.propertyWithName("c_prescriptiona", "c_prescription_a");

        Body prescriptionBody = new Body();
        prescriptionBody.addProperty(new SimpleBodyProperty(dateDef, Utils.stringFromDate(new Date(), DateParseFormat.YYYY_MM_DD) ));
        prescriptionBody.addProperty(new SimpleBodyProperty(dateDef, Utils.stringFromDate(new Date(), DateParseFormat.YYYY_MM_DD) ));
        prescriptionBody.addProperty(new SimpleBodyProperty(rxDef, "some rx test"));
        prescriptionBody.addProperty(new SimpleBodyProperty(patientDef, "575f58281d0c03a53ccc3ac6"));
        prescriptionBody.addProperty(new SimpleBodyProperty(dispenseDef, 5));
        prescriptionBody.addProperty(new SimpleBodyProperty(propADef, "some test string"));
        prescriptionBody.addProperty(new SimpleBodyProperty(prescriptionType, "c_prescription_a"));

        APIClient.sharedInstance().createObject("c_prescription", prescriptionBody, new ObjectFaultCallback<ObjectInstance>() {
            @Override
            public void call(ObjectInstance object, Fault fault) {

            }
        });
val prescriptionDef = SchemaManager.sharedInstance().getDefinition("c_prescription")
        val dateDef = prescriptionDef!!.propertyWithName("c_date", null)
        val rxDef = prescriptionDef.propertyWithName("c_rx", null)
        val patientDef = prescriptionDef.propertyWithName("c_patient", null)
        val dispenseDef = prescriptionDef.propertyWithName("c_dispense", null)
        val prescriptionType = prescriptionDef.propertyWithName("type", null)
        val propADef = prescriptionDef.propertyWithName("c_prescriptiona", "c_prescription_a")

        val prescriptionBody = Body()
        prescriptionBody.addProperty(SimpleBodyProperty(dateDef!!, Utils.stringFromDate(Date(), DateParseFormat.YYYY_MM_DD)))
        prescriptionBody.addProperty(SimpleBodyProperty(dateDef, Utils.stringFromDate(Date(), DateParseFormat.YYYY_MM_DD)))
        prescriptionBody.addProperty(SimpleBodyProperty(rxDef!!, "some rx test"))
        prescriptionBody.addProperty(SimpleBodyProperty(patientDef!!, "575f58281d0c03a53ccc3ac6"))
        prescriptionBody.addProperty(SimpleBodyProperty(dispenseDef!!, 5))
        prescriptionBody.addProperty(SimpleBodyProperty(propADef!!, "some test string"))
        prescriptionBody.addProperty(SimpleBodyProperty(prescriptionType!!, "c_prescription_a"))

        APIClient.sharedInstance().createObject("c_prescription", prescriptionBody) { `object`, fault -> //your code}

Edit Object

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.

Now, we want to edit an existing instance of that type of object using Cortex from the client side.

JsonObject propertiesToUpdate = new JsonObject();

propertiesToUpdate.addProperty("c_dispense",7);
propertiesToUpdate.addProperty("c_refills", 9);
propertiesToUpdate.addProperty("c_rx", "Updated prescription details");

Body propertiesToUpdateBody = new Body();
propertiesToUpdateBody.addProperty(new FastBodyProperty(propertiesToUpdate));

APIClient.sharedInstance().updateObject("c_prescription", new ObjectId("5c8a3b1fe8355a01009073b9"), propertiesToUpdateBody, new ObjectFaultCallback<ObjectInstance>() {
            @Override
            public void call(ObjectInstance object, Fault fault) {
                //edited instance
            }
        });
val propertiesToUpdate = JsonObject()

propertiesToUpdate.addProperty("c_dispense", 7)
propertiesToUpdate.addProperty("c_refills", 9)
propertiesToUpdate.addProperty("c_rx", "Updated prescription details")

val propertiesToUpdateBody = Body()
propertiesToUpdateBody.addProperty(FastBodyProperty(propertiesToUpdate))

APIClient.sharedInstance().updateObject("c_prescription", ObjectId("5c8a3b1fe8355a01009073b9"), propertiesToUpdateBody) { `object`, fault ->
            //edited instance
        }

List Objects

Let's suppose we are using a custom Prescription object definition that was created using the Data Model Setup guide.

Now, we want to list existing instances of that type of object using Cortex from the client side.

📘

Note

For paginated listing take a look the Pagination Helpers guide.

APIClient.sharedInstance().listObjects("c_prescriptions", null, new ObjectsListCallback<ObjectInstance>() {
            @Override
            public void call(List<ObjectInstance> results, boolean hasMore, Fault fault) {
                if (fault != null) {
                    // handle fault
                }
                else
                {
                    // hasMore is true if there are more objects to load --there's a limit in the amount of returned objects.
                    // objects contains the returned object instances
                }
            }
        });
APIClient.sharedInstance().listObjects("c_prescriptions", null) { results, hasMore, fault ->
            if (fault != null) {
                // handle fault
            } else {
                // hasMore is true if there are more objects to load --there's a limit in the amount of returned objects.
                // objects contains the returned object instances
            }
        }
📘

Note

If you need to use a custom class instead of ObjectInstance and want Cortex to return instances of your class instead, follow the Cortex Objects guide.

Delete Object

APIClient.sharedInstance().deleteObject("c_prescription", new ObjectId("the object's id"), null, new FaultCallback() {
            @Override
            public void call(Fault fault) {
                if (fault != null)
     						{	
         				// handle fault
     						}
            }
        });
APIClient.sharedInstance().deleteObject("c_prescription", ObjectId("the object's id"), null) { fault ->
            if (fault != null) {
                // handle fault
            }
        }

File Download

Files Api can be downloaded using one of two methods.

Using a download path:

String path = APIClient.routeFromComponents("path","to","file");

APIClient.sharedInstance().downloadFileAtPath(path, new ObjectFaultCallback<InputStream>() {
            @Override
            public void call(InputStream stream, Fault fault) {
                if (fault != null) {
                	//handle fault
                } else if (object != null) {
                	//process stream
                }
            }
        });
val path = APIClient.routeFromComponents("path", "to", "file")

  APIClient.sharedInstance().downloadFileAtPath(path) { `object`, fault ->
  	if (fault != null) {
  		//handle fault
		} else if (`object` != null) {
  		//process stream
		}
}
                                                      }

Or using a Facet of the File.

Facet aFileFacet = ...;

//sending a bitmap as data type
aFileFacet.getFileData(new DataWithSourceOrFaultCallback<Bitmap>() {
  @Override
    public void call(Bitmap data, DataSource source, Fault fault) {
			//use the bitmap is no fault present
  }
});
val aFacetFile = ..

//not sending any specific return type here
aFacetFile.getFileData { data, source, fault ->
	// process the data if not fault find
}
📘

If you want to play with facets, you can get an object that has a property file, with some upload file in there (for instance property c_image) and you can get the facets from that property file:
yourObject.getImage().getFacets()

File Upload

File uploads are a two step process as described in the File Uploads documentation.

  1. In the first step, a file property name and the file name is sent to the server. This could happen when creating an object and also when editing an object.

  2. In the response of the first step, that is, in the callback of whichever method was used in step 1 --create or update; is when the actual file upload takes place using upload information sent by the Cortex API.

For this sample, let's suppose we are creating an instance of a c_anObject object type that, has a c_image File property. We want to upload an image to the content facet of that File.

// STEP 1 - Create/Update the object and send a file property key/value pairs
UIImage *fileToUpload = ...;
// Note: fileToUpload can be an instance of NSData too.

// File values are always key = facet name, value = file name.
NSDictionary *filePropValue = @{ @"content": fileToUpload };

// --- Optinally the mime type can be set:
NSDictionary *filePropValue = @{ @"content": @{ @"mime": @"image/png", @"data": fileToUpload }};
// ---

// Create/Update bodies are always key = prop name, value = prop value or the right type.
NSDictionary *createBody = @{
                             @"c_aPropName": @"aPropValue",
                             @"c_image": filePropValue,
                             @"c_someOtherPropName": @55
                             };

[[Medable client]
 createObjectWithContext:@"c_anObject"
 body:createBody
 callback:^(MDObjectInstance * _Nullable instance, MDFault * _Nullable fault)
 {
     if (fault)
     {
         // handle fault
     }
     else if (instance)
     {
         // STEP 2 - File Upload - Performed internally by Cortex. Read "Managing File Uploads" to know how to keep track of file uploads. Files are also cached and encrypted locally by Cortex.
     }
 }];
// STEP 1 - Create/Update the object and send a file property key/value pairs
let fileToUpload: UIImage! = ...
// Note: fileToUpload can be an instance of NSData too.

// File values are always key = facet name, value = file name.
let filePropValue = [ "content": fileToUpload ]

// --- Optinally the mime type can be set:
let filePropValue = [ "content": [ "mime": "image/png", "data": fileToUpload ] ]
// ---

// Create/Update bodies are always key = prop name, value = prop value or the right type.
let createBody: [ String: Any ] = [
    "c_aPropName": "aPropValue",
    "c_image": filePropValue,
    "c_someOtherPropName": 55
]

Medable.client().createObject(
    withContext: "c_anObject",
    body: createBody) {
        (instance: MDObjectInstance?, fault: MDFault?) in
        
        if let fault = fault {
            // handle fault
        } else if let instance = instance {
            // STEP 2 - File Upload - Performed internally by Cortex. Read "Managing File Uploads" to know how to keep track of file uploads. Files are also cached and encrypted locally by Cortex.
        }
}
// STEP 1 - Create/Update the object and send a file property key/value pairs

ObjectDefinition prescriptionDefinition = SchemaManager.sharedInstance().getDefinition("c_anObject");
PropertyDefinition imagePropertyDefinition= prescriptionDefinition.propertyWithName("c_aProp", null);

Body bodyCreate = new Body();

FileBodyProperty imageProperty = new FileBodyProperty(imagePropertyDefinition);
        imageProperty.addFacetAttachment("content", "image/jpeg", bitmap );

bodyCreate.addProperty(imageProperty);

JsonObject createBodyJson = new JsonObject();
createBodyJson.addProperty("c_anotherProp", "aPropValue");
...
bodyCreate.addProperty(new FastBodyProperty(createBodyJson));


APIClient.sharedInstance().createObject("c_anObject", bodyCreate, new ObjectFaultCallback<ObjectInstance>() {
            @Override
            public void call(ObjectInstance object, Fault fault) {
                if (fault != null) {
                  // handle fault
                }
              	else if (instance != null) {
                // STEP 2 - File Upload - Performed internally by Cortex. Read "Managing File Uploads" to know how to keep track of file uploads. Files are also cached and encrypted locally by Cortex.
              	}
            }
        });
// STEP 1 - Create/Update the object and send a file property key/value pairs

val prescriptionDefinition = SchemaManager.sharedInstance().getDefinition("c_anObj")
val imagePropertyDefinition = prescriptionDefinition!!.propertyWithName("c_aProp", null)

val bodyCreate = Body()

val imageProperty = FileBodyProperty(imagePropertyDefinition!!)
imageProperty.addFacetAttachment("content", "image/jpeg", bitmap)

bodyCreate.addProperty(imageProperty)

val createBodyJson = JsonObject()
createBodyJson.addProperty("c_rx", "test")
...
bodyCreate.addProperty(FastBodyProperty(createBodyJson))

APIClient.sharedInstance().createObject("c_anObj", bodyCreate) { `object`, fault ->
            if (fault != null) {
                //handle fault
            } else {
                // STEP 2 - File Upload - Performed internally by Cortex. Read "Managing File Uploads" to know how to keep track of file uploads. Files are also cached and encrypted locally by Cortex.
            }
        }
📘

File Uploads

For a deeper management of file uploads take a look at the Managing File Uploads documentation.