by Moesif, the API analytics and API monetization platform.
Base Java library to send API events, users, companies, and subscription data to Moesif API Observability service.
For logging API traffic at scale, most customers should integrate with one of Moesif's API monitoring agents that instrument your API automatically and handle batching. For more information, see the Java integration options in Server integration docs.
If you're new to Moesif, see our Getting Started resources to quickly get up and running.
Before using this library, make sure you have the following:
After you log into Moesif Portal, you can get your Moesif Application ID during the onboarding steps. You can always access the Application ID any time by following these steps from Moesif Portal after logging in:
- Select the account icon to bring up the settings menu.
- Select Installation or API Keys.
- Copy your Moesif Application ID from the Collector Application ID field.
Add this dependency to your project's POM:
<dependency>
<groupId>com.moesif.api</groupId>
<artifactId>moesifapi</artifactId>
<version>1.8.3</version>
</dependency>
Add this dependency to your project's build file:
implementation 'com.moesif.api:moesifapi:1.8.3'
See src/test/java/com/moesif/api/controllers/APIControllerTest.java
for more usage examples.
The following examples demonstrate the basic operations using this library. In these examples, replace YOUR_COLLECTOR_APPLICATION_ID
with your Moesif Application ID.
You can create an event in two ways: synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
String reqBody = "{" +
"\"items\": [" +
"{" +
"\"type\": 1," +
"\"id\": \"hello\"" +,
"}" +
"]" +
"}";
String rspBody = "{" +
"\"Error\": \"InvalidArgumentException\"," +
"\"Message\": \"Missing field field_a\"" +
"}";
// Generate the event
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Accept-Encoding", "gzip");
Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
BodyParser.BodyWrapper reqBodyWrapper = BodyParser.parseBody(reqHeaders, reqBody);
BodyParser.BodyWrapper rspBodyWrapper = BodyParser.parseBody(rspHeaders, rspBody);
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(reqBodyWrapper.body)
.transferEncoding(reqBodyWrapper.transferEncoding);
.build();
EventResponseModel eventRsp = new EventResponseBuilder()
.time(new Date(System.currentTimeMillis() + 1000))
.status(500)
.headers(rspHeaders)
.body(rspBodyWrapper.body)
.transferEncoding(rspBodyWrapper.transferEncoding);
.build();
EventModel eventModel = new EventBuilder()
.request(eventReq)
.response(eventRsp)
.userId("12345")
.companyId("67890")
.build();
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
assertEquals("Status is not 201",
201, context.getResponse().getStatusCode());
// Sent successfully!
}
public void onFailure(HttpContext context, Throwable error) {
// Log there was a failure
}
};
client.getAPI().createEventAsync(eventModel, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().createEvent(eventModel);
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.
String reqBody = "{" +
"\"items\": [" +
"{" +
"\"type\": 1," +
"\"id\": \"hello\"" +,
"}" +
"]" +
"}";
String rspBody = "{" +
"\"Error\": \"InvalidArgumentException\"," +
"\"Message\": \"Missing field field_a\"" +
"}";
// Generate the event
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Accept-Encoding", "gzip");
Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
BodyParser.BodyWrapper reqBodyWrapper = BodyParser.parseBody(reqHeaders, reqBody);
BodyParser.BodyWrapper rspBodyWrapper = BodyParser.parseBody(rspHeaders, rspBody);
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(reqBodyWrapper.body)
.transferEncoding(reqBodyWrapper.transferEncoding);
.build();
EventResponseModel eventRsp = new EventResponseBuilder()
.time(new Date(System.currentTimeMillis() + 1000))
.status(500)
.headers(rspHeaders)
.body(rspBodyWrapper.body)
.transferEncoding(rspBodyWrapper.transferEncoding);
.build();
EventModel eventModel = new EventBuilder()
.request(eventReq)
.response(eventRsp)
.userId("12345")
.companyId("67890")
.build();
// Create a batch of events
List<EventModel> events = new ArrayList<EventModel>();
events.add(eventModel);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APICallBack<Object> callBack = new APICallBack<Object>() {
public void onSuccess(HttpContext context, Object response) {
assertEquals("Status is not 201",
201, context.getResponse().getStatusCode());
// Sent successfully!
}
public void onFailure(HttpContext context, Throwable error) {
// Log there was a failure
}
};
client.getAPI().createEventsBatchAsync(events, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().createEventsBatch(events);
For a general troubleshooting guide that can help you solve common problems, see Server Troubleshooting Guide.
Other troubleshooting supports:
To create or update a user profile in Moesif, use the updateUserAsync()
function and updateUser()
functions.
// 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
.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();
The metadata
field can contain any customer demographic or other info you want to store. Moesif only requires the userId
field.
For more information, see the function documentation in Moesif Java API reference
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
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
}
};
client.getAPI().updateUserAsync(user, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateUser(user);
To update a list of users in one batch, use the updateUsersBatchAsync()
and updateUsersBatch()
functions.
You can update users synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
List<UserModel> users = new ArrayList<UserModel>();
UserModel userA = new UserBuilder()
.userId("12345")
.companyId("67890")
.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")
.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);
The metadata
field can contain any customer demographic or other info you want to store. Moesif only requires the userId
field.
For more information, see the function documentation in Moesif Java API reference
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
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
client.getAPI().updateUsersBatchAsync(users, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateUsersBatch(users, callBack);
To update a single company, use the updateCompanyAsync()
and updateCompany()
functions.
// 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
.metadata(APIHelper.deserialize("{" +
"\"org_name\": \"Acme, Inc\"," +
"\"plan_name\": \"Free\"," +
"\"deal_stage\": \"Lead\"," +
"\"mrr\": 24000," +
"\"demographics\": {" +
"\"alexa_ranking\": 500000," +
"\"employee_count\": 47" +
"}" +
"}"))
.build();
The metadata
field can contain any company demographic or other information you want to store. Moesif only requires the companyId
field.
For more information, see the function documentation in Moesif Java API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_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
}
};
client.getAPI().updateCompanyAsync(company, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateCompany(company);
To update a list of companies in one batch, use the updateCompaniesBatchAsync()
and updateCompaniesBatch()
functions.
You can update users synchronously or asynchronously on a background thread. Unless you require synchronous behavior, we recommend the async versions.
// 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
.metadata(APIHelper.deserialize("{" +
"\"org_name\": \"Acme, Inc\"," +
"\"plan_name\": \"Free\"," +
"\"deal_stage\": \"Lead\"," +
"\"mrr\": 24000," +
"\"demographics\": {" +
"\"alexa_ranking\": 500000," +
"\"employee_count\": 47" +
"}" +
"}"))
.build();
// Create a batch of companies
List<EventModel> events = new ArrayList<CompanyModel>();
events.add(company);
The metadata
field can contain any company demographic or other information you want to store. Moesif only requires the companyId
field.
For more information, see the function documentation in Moesif Java API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
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
}
};
client.getAPI().updateCompaniesBatchAsync(companies, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateCompaniesBatch(companies);
To create or update a subscription in Moesif, use the updateSubscriptionAsync()
and updateSubscription()
functions.
// 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();
Moesif requires the subscriptionId
, companyId
, and status
fields. For more information, see Moesif Java API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APICallBack<HttpResponse> callBack = new APICallBack<HttpResponse>() {
public void onSuccess(HttpContext context, HttpResponse response) {
// Handle success
}
public void onFailure(HttpContext context, Throwable error) {
// Handle failure
}
};
client.getAPI().updateSubscriptionAsync(subscription, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateSubscription(subscription);
To update a list of subscriptions in one batch, use the updateSubscriptionsBatchAsync()
and updateSubscriptionsBatch()
functions.
Moesif requires the subscriptionId
, companyId
, and status
fields. For more information, see Moesif Java API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
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
}
};
client.getAPI().updateSubscriptionsBatchAsync(subscriptions, callBack);
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().updateSubscriptionsBatch(subscriptions);
To track and log single Action in Moesif, use the createActionAsync()
and createAction()
functions. Here we create
an action to send:
ActionRequestModel requestContext = new ActionRequestModel.Builder("https://acmeinc.com/pricing")
.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
.build();
Map<String, Object> metadata = new HashMap<>();
metadata.put("button_label", "Get Started");
metadata.put("sign_up_method", "Google SSO");
ActionModel action = new ActionModel.Builder("Clicked Sign Up", requestContext)
.setUserId("12345")
.setCompanyId("67890")
.setTransactionId("a3765025-46ec-45dd-bc83-b136c8d1d257")
.setMetadata(metadata)
.build();
The metadata
object can contain any optional metadata about the Action you want to store. Moesif only requires the action name and requestContext
. For more information, see the documentation in Moesif API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APICallBack<HttpResponse> callBack = new APICallBack<HttpResponse>() {
public void onSuccess(HttpContext context, HttpResponse response) {
// Handle success
}
public void onFailure(HttpContext context, Throwable error) {
// Handle failure
}
};
client.getAPI().createActionAsync(action, callBack); // action defined previously
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().createAction(action);
To track and log a batch of Actions in Moesif, use the createActionsBatchAsync()
and createActionsBatch()
functions. Here we create
a list of actions to send:
// Create multiple ActionModels
List<ActionModel> actions = new ArrayList<>();
for (int i = 0; i < 4; i++) {
ActionRequestModel requestContext = new ActionRequestModel.Builder("https://acmeinc.com/pricing")
.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
.build();
Map<String, Object> metadata = new HashMap<>();
metadata.put("button_label", "Get Started " + i);
metadata.put("sign_up_method", "Google SSO");
ActionModel action = new ActionModel.Builder("Clicked Sign Up", requestContext)
.setUserId("user_" + i)
.setCompanyId("company_" + i)
.setTransactionId(UUID.randomUUID().toString())
.setMetadata(metadata)
.build();
actions.add(action);
}
The metadata
object can contain any optional metadata about the Action you want to store. Moesif only requires the action name and requestContext
. For more information, see the documentation in Moesif API reference.
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APICallBack<HttpResponse> callBack = new APICallBack<HttpResponse>() {
public void onSuccess(HttpContext context, HttpResponse response) {
// Handle success
}
public void onFailure(HttpContext context, Throwable error) {
// Handle failure
}
};
client.getAPI().createActionsBatchAsync(actions, callBack); // actions defined previously
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
client.getAPI().createActionsBatch(company);
- Extract the zip file to a new folder named JavaSDK.
- Open a command prompt and navigate to the JavaSDK/MoesifApi folder.
- Execute "mvn install", this will install dependencies and also add the generated JAR in your local maven repository
- The invoked process will automatically run the JUnit tests and show the results in the console
For build process do the following
- Open Eclipse and click on the "Import" option in "File" menu.
- Select "General -> Existing Projects into Workspace" option from the tree list.
- In "Select root directory", provide path to the unzipped archive for the generated code.
- 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:
- Edit
/src/test/java/com/moesif/api/controllers/ControllerTestBase.java
to change the ApplicationId to your ApplicationId obtained from Moesif. - Select the project MoesifApi from the package explorer.
- Select "Run -> Run as -> Junit Test" or use "Alt + Shift + X" followed by "T" to run the Tests.
- Data will be captured in the corresponding Moesif account of the Moesif Application ID.
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:
- Click on the "Export" option in "File" menu.
- Select "Java -> JAR file" and click on "Next".
- Check the box beside "MoesifApi" and click on "Finish".
For further details on exporting JARs follow up on the following link. Importing an application client JAR file.
For using JARs, see Importing an application client JAR file.
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
If you face any issues using this library, try the troubheshooting guidelines. For further assistance, reach out to our support team.