Check out Moesif's Developer Documentation and Java API Reference to learn more
Add this dependency to your project's POM:
<dependency>
<groupId>com.moesif.api</groupId>
<artifactId>moesifapi</artifactId>
<version>1.7.7</version>
</dependency>
Add this dependency to your project's build file:
compile 'com.moesif.api:moesifapi:1.7.7'
(See src/test/java/com/moesif/api/controllers/APIControllerTest.java for more usage examples)
There are two ways to create an event: synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Accept", "*/*");
reqHeaders.put("Connection", "Keep-Alive");
reqHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 5.0.2; C6906 Build/14.5.A.0.242)");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Content-Length", "126");
reqHeaders.put("Accept-Encoding", "gzip");
Object reqBody = APIHelper.deserialize("{" +
"\"items\": [" +
"{" +
"\"type\": 1," +
"\"id\": \"fwfrf\"" +
"}," +
"{" +
"\"type\": 2," +
"\"id\": \"d43d3f\"" +
"}" +
"]" +
"}");
Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Date", "Tue, 23 Feb 2019 23:46:49 GMT");
rspHeaders.put("Vary", "Accept-Encoding");
rspHeaders.put("Pragma", "no-cache");
rspHeaders.put("Expires", "-1");
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
rspHeaders.put("Cache-Control","no-cache");
Object rspBody = APIHelper.deserialize("{" +
"\"Error\": \"InvalidArgumentException\"," +
"\"Message\": \"Missing field field_a\"" +
"}");
EventRequestModel eventReq = new EventRequestBuilder()
.time(new Date())
.uri("https://api.acmeinc.com/items/reviews/")
.verb("PATCH")
.apiVersion("1.1.0")
.ipAddress("61.48.220.123")
.headers(reqHeaders)
.body(reqBody)
.build();
EventResponseModel eventRsp = new EventResponseBuilder()
.time(new Date(System.currentTimeMillis() + 1000))
.status(500)
.headers(rspHeaders)
.body(rspBody)
.build();
EventModel eventModel = new EventBuilder()
.request(eventReq)
.response(eventRsp)
.userId("my_user_id")
.companyId("my_company_id")
.sessionToken("23jdf0owekfmcn4u3qypxg09w4d8ayrcdx8nu2ng]s98y18cx98q3yhwmnhcfx43f")
.build();
MoesifAPIClient client = new MoesifAPIClient("your_moesif_application_id");
APIController api = client.getAPI();
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
assertEquals("Status is not 201",
201, context.getResponse().getStatusCode());
lock.countDown();
}
public void onFailure(HttpContext context, Throwable error) {
fail();
}
};
api.createEventAsync(eventModel, callBack);
MoesifAPIClient client = new MoesifAPIClient("your_moesif_application_id");
APIController api = client.getAPI();
api.createEvent(eventModel, callBack);
You can also create a batch of events at once by sending a list of events. Similar to the single event API, there are two ways to create an event: synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Accept", "*/*");
reqHeaders.put("Connection", "Keep-Alive");
reqHeaders.put("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 5.0.2; C6906 Build/14.5.A.0.242)");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Content-Length", "126");
reqHeaders.put("Accept-Encoding", "gzip");
Object reqBody = APIHelper.deserialize("{" +
"\"items\": [" +
"{" +
"\"type\": 1," +
"\"id\": \"fwfrf\"" +
"}," +
"{" +
"\"type\": 2," +
"\"id\": \"d43d3f\"" +
"}" +
"]" +
"}");
Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Date", "Tue, 23 Feb 2019 23:46:49 GMT");
rspHeaders.put("Vary", "Accept-Encoding");
rspHeaders.put("Pragma", "no-cache");
rspHeaders.put("Expires", "-1");
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
rspHeaders.put("Cache-Control","no-cache");
Object rspBody = APIHelper.deserialize("{" +
"\"Error\": \"InvalidArgumentException\"," +
"\"Message\": \"Missing field field_a\"" +
"}");
EventRequestModel eventReq = new EventRequestBuilder()
.time(new Date())
.uri("https://api.acmeinc.com/items/reviews/")
.verb("PATCH")
.apiVersion("1.1.0")
.ipAddress("61.48.220.123")
.headers(reqHeaders)
.body(reqBody)
.build();
EventResponseModel eventRsp = new EventResponseBuilder()
.time(new Date(System.currentTimeMillis() + 1000))
.status(500)
.headers(rspHeaders)
.body(rspBody)
.build();
EventModel eventModel = new EventBuilder()
.request(eventReq)
.response(eventRsp)
.userId("12345")
.companyId("67890")
.sessionToken("23jdf0owekfmcn4u3qypxg09w4d8ayrcdx8nu2ng]s98y18cx98q3yhwmnhcfx43f")
.build();
List<EventModel> events = new ArrayList<EventModel>();
events.add(eventModel);
events.add(eventModel);
events.add(eventModel);
events.add(eventModel);
MoesifAPIClient client = new MoesifAPIClient("your_moesif_application_id");
APIController api = client.getAPI();
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
assertEquals("Status is not 201",
201, context.getResponse().getStatusCode());
lock.countDown();
}
public void onFailure(HttpContext context, Throwable error) {
fail();
}
};
api.createEventsBatchAsync(events, callBack);
MoesifAPIClient client = new MoesifAPIClient("your_moesif_application_id");
APIController api = getClient().getAPI();
api.createEventsBatch(events, callBack);
Create or update a user profile in Moesif.
The metadata field can be any customer demographic or other info you want to store.
Only the userId
field is required.
For details, visit the Java API Reference.
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#users for campaign schema
CampaignModel campaign = new CampaignBuilder()
.utmSource("google")
.utmCampaign("cpc")
.utmMedium("adwords")
.utmTerm("api+tooling")
.utmContent("landing")
.build();
// Only userId is required
// metadata can be any custom object
UserModel user = new UserBuilder()
.userId("12345")
.companyId("67890") // If set, associate user with a company object
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"email\": \"[email protected]\"," +
"\"first_name\": \"John\"," +
"\"last_name\": \"Doe\"," +
"\"title\": \"Software Engineer\"," +
"\"sales_info\": {" +
"\"stage\": \"Customer\"," +
"\"lifetime_value\": 24000," +
"\"account_owner\": \"[email protected]\"" +
"}" +
"}"))
.build();
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
// Do something
}
public void onFailure(HttpContext context, Throwable error) {
// Do something else
}
};
apiClient.updateUserAsync(user, callBack);
apiClient.updateUser(user);
Similar to UpdateUser, but used to update a list of users in one batch.
Only the userId
field is required.
For details, visit the Java API Reference.
You can update users synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
List<UserModel> users = new ArrayList<UserModel>();
UserModel userA = new UserBuilder()
.userId("12345")
.companyId("67890")
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"email\": \"[email protected]\"," +
"\"first_name\": \"John\"," +
"\"last_name\": \"Doe\"," +
"\"title\": \"Software Engineer\"," +
"\"sales_info\": {" +
"\"stage\": \"Customer\"," +
"\"lifetime_value\": 24000," +
"\"account_owner\": \"[email protected]\"" +
"}" +
"}"))
.build();
users.add(userA);
UserModel userB = new UserBuilder()
.userId("54321")
.companyId("67890")
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"email\": \"[email protected]\"," +
"\"first_name\": \"John\"," +
"\"last_name\": \"Doe\"," +
"\"title\": \"Software Engineer\"," +
"\"sales_info\": {" +
"\"stage\": \"Customer\"," +
"\"lifetime_value\": 24000," +
"\"account_owner\": \"[email protected]\"" +
"}" +
"}"))
.build();
users.add(userB);
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
// Do something
}
public void onFailure(HttpContext context, Throwable error) {
// Do something else
}
};
// Asynchronous call to update users
apiClient.updateUsersBatchAsync(users, callBack);
apiClient.updateUsersBatch(users, callBack);
Create or update a company profile in Moesif.
The metadata field can be any company demographic or other info you want to store.
Only the companyId
field is required.
For details, visit the Java API Reference.
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").Api;
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
CampaignModel campaign = new CampaignBuilder()
.utmSource("google")
.utmCampaign("cpc")
.utmMedium("adwords")
.utmTerm("api+tooling")
.utmContent("landing")
.build();
// Only companyId is required
// metadata can be any custom object
CompanyModel company = new CompanyBuilder()
.companyId("67890")
.companyDomain("acmeinc.com") // If set, Moesif will enrich your profiles with publicly available info
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"org_name\": \"Acme, Inc\"," +
"\"plan_name\": \"Free\"," +
"\"deal_stage\": \"Lead\"," +
"\"mrr\": 24000," +
"\"demographics\": {" +
"\"alexa_ranking\": 500000," +
"\"employee_count\": 47" +
"}" +
"}"))
.build();
MoesifAPIClient client = new MoesifAPIClient("your_moesif_application_id");
APIController api = client.getAPI();
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
// Do something
}
public void onFailure(HttpContext context, Throwable error) {
// Do something else
}
};
apiClient.updateCompanyAsync(company, callBack);
apiClient.updateCompany(company);
Similar to updateCompany, but used to update a list of companies in one batch.
Only the companyId
field is required.
For details, visit the Java API Reference.
You can update users synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").Api;
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
CampaignModel campaign = new CampaignBuilder()
.utmSource("google")
.utmCampaign("cpc")
.utmMedium("adwords")
.utmTerm("api+tooling")
.utmContent("landing")
.build();
// Only companyId is required
// metadata can be any custom object
CompanyModel company = new CompanyBuilder()
.companyId("67890")
.companyDomain("acmeinc.com") // If set, Moesif will enrich your profiles with publicly available info
.campaign(campaign)
.metadata(APIHelper.deserialize("{" +
"\"org_name\": \"Acme, Inc\"," +
"\"plan_name\": \"Free\"," +
"\"deal_stage\": \"Lead\"," +
"\"mrr\": 24000," +
"\"demographics\": {" +
"\"alexa_ranking\": 500000," +
"\"employee_count\": 47" +
"}" +
"}"))
.build();
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
// Do something
}
public void onFailure(HttpContext context, Throwable error) {
// Do something else
}
};
apiClient.updateCompaniesBatchAsync(companies, callBack);
apiClient.updateCompaniesBatch(companies);
Create or update a subscription in Moesif. The metadata field can store any subscription-related information you want to keep. The subscriptionId
, companyId
, and status
fields are required. For more details, visit the Java API Reference.
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").Api;
// Create a subscription model with required and optional fields
SubscriptionModel subscription = new SubscriptionBuilder()
.subscriptionId("sub_12345")
.companyId("67890")
.currentPeriodStart(new Date())
.currentPeriodEnd(new Date())
.status("active")
.metadata(APIHelper.deserialize("{" +
"\"email\": \"[email protected]\"," +
"\"string_field\": \"value_1\"," +
"\"number_field\": 0," +
"\"object_field\": {" +
"\"field_1\": \"value_1\"," +
"\"field_2\": \"value_2\"" +
"}" +
"}"))
.build();
APICallBack<HttpResponse> callBack = new APICallBack<HttpResponse>() {
public void onSuccess(HttpContext context, HttpResponse response) {
// Handle success
}
public void onFailure(HttpContext context, Throwable error) {
// Handle failure
}
};
apiClient.updateSubscriptionAsync(subscription, callBack);
apiClient.updateSubscription(subscription);
Similar to updating a single subscription, but used to update a list of subscriptions in one batch. The subscriptionId
, companyId
, and status
fields are required for each subscription in the list.
List<SubscriptionModel> subscriptions = new ArrayList<>();
subscriptions.add(subscription); // Assuming 'subscription' is previously defined
APICallBack<HttpResponse> callBack = new APICallBack<HttpResponse>() {
public void onSuccess(HttpContext context, HttpResponse response) {
// Handle success
}
public void onFailure(HttpContext context, Throwable error) {
// Handle failure
}
};
apiClient.updateSubscriptionsBatchAsync(subscriptions, callBack);
apiClient.updateSubscriptionsBatch(subscriptions);
1. Extract the zip file to a new folder named JavaSDK.
2. Open a command prompt and navigate to the JavaSDK/MoesifApi folder.
3. Execute "mvn install", this will install dependencies and also add the generated JAR in your local maven repository.
4. The invoked process will automatically run the JUnit tests and show the results in the console.
For build process do the following:
1. Open Eclipse and click on the "Import" option in "File" menu.
2. Select "General -> Existing Projects into Workspace" option from the tree list.
3. In "Select root directory", provide path to the unzipped archive for the generated code.
4. Click "Finish" and ensure that "Project -> Build Automatically" option is enabled in the menu.
The generated code and the server can be tested using automatically generated test cases. Junit is used as the testing framework and test runner.
For test process do the following:
1. Edit the '/src/test/java/com/moesif/api/controllers/ControllerTestBase.java' to change the ApplicationId to your ApplicationId obtained from Moesif.
2. Select the project MoesifApi from the package explorer.
3. Select "Run -> Run as -> Junit Test" or use "Alt + Shift + X" followed by "T" to run the Tests.
4. Data will be captured in the corresponding Moesif account of the ApplicationId.
Export the compiled classes as a java libray (jar). The exported jar can be used as library. See the following links for more information on this topic.
Exporting JARs: 1. Click on the "Export" option in "File" menu. 2. Select "Java -> JAR file" and click on "Next". 3. Check the box beside "MoesifApi" and click on "Finish".
For further details on exporting JARs follow up on the following link. http://help.eclipse.org/mars/topic/org.eclipse.jdt.doc.user/tasks/tasks-33.htm
Using JARs: http://help.eclipse.org/juno/topic/org.eclipse.jst.j2ee.doc.user/topics/tjimpapp.html
To execute JUnit tests using mvn
command, the environment variable MOESIF_APPLICATION_ID
needs to be set. You'll also need to set the MOESIF_BASE_URI
. Below is the URI for testing against Moesif production, if testing against a local API, change accordingly.
export MOESIF_APPLICATION_ID="<Set your Moesif Application Id here>"
export MOESIF_BASE_URI="https://api.moesif.net"
mvn test