Intercom Java SDK

intercom-java

Java bindings for the Intercom API

πŸ“˜

Installation and Configuration Steps

For information on how to install and configure the Intercom Java SDK please see the intercom-java github page. For general code examples please see below.

Authroization

Intercom.setToken("da39a3ee5e6b4b0d3255bfef95601890afd80709");

Users

Create, update or delete a user

User user = new User()
    .setEmail("[email protected]")
    .setUserId("1")
    .addCustomAttribute(CustomAttribute.newStringAttribute("role", "sergeant"))
    .addCustomAttribute(CustomAttribute.newBooleanAttribute("browncoat", true));
User created = User.create(user);
user.addCustomAttribute(CustomAttribute.newStringAttribute("role", "captain"));
User.update(user);
User user = User.find("541a144b201ebf2ec5000001");
User.delete(user.getId());

Find and iterate over users

params = Maps.newHashMap();
params.put("user_id", "1");
user = User.find(params);
Map<String, String> params = Maps.newHashMap();
params.put("email", "[email protected]");
user = User.find(params);
user = User.find("541a144b201ebf2ec5000001");
UserCollection users = User.list();
while(users.hasNext()) {
    System.out.println(users.next().getUserId());
}

Retrieve large list of users (> 10, 000)

// Retrieve users via Scroll API
ScrollableUserCollection usersScroll = User.scroll();
List<User> users = usersScroll.getPage();
usersScroll = usersScroll.scroll();

Contacts

πŸ“˜

Contacts were added in version 1.1 of the client

Create, update and remove contacts

Contact contact = new Contact()
    .setEmail("[email protected]")
    .addCustomAttribute(newStringAttribute("role", "fence"));
Contact created = Contact.create(contact);
contact.setName("Stitch Hessian");
Contact updated = Contact.update(contact);
Contact.delete(contact);

Find and iterate over contacts

//Find by id
contact = Contact.findByID("541a144b201ebf2ec5000002");
//Or user_id
contact = Contact.findByUserID("e1a7d875-d83a-46f7-86f4-73be98a98584");
ContactCollection contacts = Contact.listByEmail("[email protected]");
while(contacts.hasNext()) {
    System.out.println(contacts.next());
}
ContactCollection allContacts = Contact.list();
while(allContacts.hasNext()) {
    System.out.println(allContacts.next());
}

Convert a contact into a user

User converted = Contact.convert(contact, user);

Retrieve large list of contacts (> 10, 000)

// Retrieve contacts via Scroll API
ScrollableContactCollection contactsScroll = Contact.scroll();
List<Contact> contacts = contactsScroll.getPage();
contactsScroll = contactsScroll.scroll();

Companies

Create, update and add users to companies

Company company = new Company();
    company.setName("Blue Sun");
    company.setCompanyID("1");
    company.setPlan(new Company.Plan("premium"));
    company.addCustomAttribute(CustomAttribute.newIntegerAttribute("foddstuff-items", 246));
    company.addCustomAttribute(CustomAttribute.newStringAttribute("bestseller", "fruity oaty bar"));
Company.create(company);
company.setName("Blue Sun Corporation");
Company.update(company);
User user = User.find("541a144b201ebf2ec5000001");
user.addCompany(company);
User.update(user);

Find and iterate over companies

map = Maps.newHashMap();
map.put("company_id", "1");
Company company = Company.find(map);
map = Maps.newHashMap();
map.put("name", "Blue Sun");
Company company = Company.find(map);
Company company = Company.find("541a144b201ebf2ec5000001");
CompanyCollection companies = Company.list();
while(companies.hasNext()) {
    System.out.println(companies.next().getName());
}

List users in a company

map = Maps.newHashMap();
map.put("company_id", "6");
UserCollection users = Company.listUsers(map);

Admins

Iterate over admins

AdminCollection admins = Admin.list();
while(admins.hasNext()) {
    System.out.println(admins.next().getName());
}

Events

Create events

Event event = new Event().setEventName("bought-hat")
    .setUserID("1")
    .putMetadata("invitee_email", "[email protected]")
    .putMetadata("found_date", System.currentTimeMillis())
    .putMetadata("new_signup", true);
Event.create(event);

Tags

Create, update, delete and iterate over tags

Tag tag = new Tag().setName("alliance");
tag = Tag.create(tag);
tag.setName("independent");
tag = Tag.update(tag);
final TagCollection tags = Tag.list();
while (tags.hasNext()) {
    System.out.println(tags.next().getId());
}
Tag.delete(tag);

Tag and untag users and companies

User one = new User().setEmail("[email protected]");
User two = new User().setEmail("[email protected]").untag();
User.create(one);
User.create(two);
Tag.tag(tag, one, two);
Company c1 = new Company().setCompanyID("1");
Company c2 = new Company().setCompanyID("2").untag();
Company.create(c1);
Company.create(c2);
Tag.tag(tag, c1, c2);

Segments

Find, update and iterate over segments

Segment segment = Segment.find("1");
segment.setName("new name");
Segment.update(segment);
SegmentCollection segments = Segment.list();
while(segments.hasNext()) {
    System.out.println(segments.next().getId());
}

Notes

Create, find and iterate over notes

User user = new User().setId("5310d8e8598c9a0b24000005");
Author author = new Author().setId("1");
Note note = new Note()
    .setUser(user)
    .setAuthor(author)
    .setBody("The note");
Note.create(note);
note = Note.find("1");
Map<String, String> params = Maps.newHashMap();
params.put("user_id", "1");
NoteCollection notes = Note.list(params);
while(notes.hasNext()) {
    System.out.println(notes.next().getBody());
}
params = Maps.newHashMap();
params.put("email", "[email protected]");
notes = Note.list(params);
while(notes.hasNext()) {
    System.out.println(notes.next().getBody());
}

Conversations

Send messages

User user = new User().setId("5310d8e8598c9a0b24000005");
Admin admin = new Admin().setId("1");
AdminMessage adminMessage = new AdminMessage()
    .setAdmin(admin)
    .setUser(user)
    .setSubject("This Land")
    .setBody("Har har har! Mine is an evil laugh!")
    .setMessageType("email")
    .setTemplate("plain");
Conversation.create(adminMessage);
UserMessage userMessage = new UserMessage()
    .setBody("Hey! Is there, is there a reward?")
    .setUser(user);
Conversation.create(userMessage);
ContactMessage contactMessage = new ContactMessage()
    .setBody("Hey! Is there, is there a reward?")
    .setUser(contact);
Conversation.create(contactMessage);

Find conversations

Map<String, String> params = Maps.newHashMap();
params.put("type", "admin");
params.put("admin_id", "1");
ConversationCollection adminConversations = Conversation.list(params);
while (adminConversations.hasNext()) {
    Conversation conversation = adminConversations.next();
}
params = Maps.newHashMap();
params.put("type", "user");
params.put("user_id", "1");
ConversationCollection userConversations = Conversation.list(params);
while (userConversations.hasNext()) {
    Conversation conversation = userConversations.next();
}
final Conversation conversation = Conversation.find("66");
ConversationMessage conversationMessage = conversation.getConversationMessage();
ConversationPartCollection parts = conversation.getConversationPartCollection();
List<ConversationPart> partList = parts.getPage();
for (ConversationPart part : partList) {
    String partType = part.getPartType();
    Author author = part.getAuthor();
    String body = part.getBody();
}
ConversationPart part = conversation.getMostRecentConversationPart();
Admin assignee = conversation.getAssignee();
User user = conversation.getUser();
params = Maps.newHashMap();
params.put("type", "admin");
params.put("admin_id", "7");
params.put("display_as", "plaintext");
ConversationCollection openForAdmin = Conversation.list(params);

Reply and close conversations

Admin admin = new Admin().setId("1");
AdminReply adminReply = new AdminReply(admin);
adminReply.setBody("These apples are healthsome");
Conversation.reply("66", adminReply);
Admin admin = new Admin().setId("1");
AdminReply adminReply = new AdminReply(admin);
adminReply.setMessageType("close");
Conversation.reply("66", adminReply);
User user1 = new User().setId("5310d8e8598c9a0b24000005");
UserReply userReply = new UserReply(user1);
userReply.setBody("Mighty fine shindig");
System.out.println(MapperSupport.objectMapper().writeValueAsString(userReply));
Conversation.reply("66", userReply);

Webhooks

Create, find and list subscriptions

Subscription subscription = new Subscription();
subscription.setUrl(new URI("https://example.org/webhooks/1"));
subscription.addTopic(Subscription.Topic.USER_CREATED);
subscription.addTopic(Subscription.Topic.USER_TAG_CREATED);
subscription.addTopic(Subscription.Topic.COMPANY);
subscription.setAppID("pi3243fa");
Subscription.create(subscription);
subscription = Subscription.find("nsub_60ca7690-4020-11e4-b789-4961958e51bd");
SubscriptionCollection list = Subscription.list();
while(list.hasNext()) {
    Subscription sub = list.next();
    String appID = sub.getAppID();
    String serviceType = sub.getServiceType();
    List<Subscription.Topic> topics = sub.getTopics();
    String hubSecret = sub.getHubSecret();
}

Webhook notifications

NotificationCollection sent = Subscription.sentFeed(subscription.getId());
while(sent.hasNext()) {
    Notification notification = sent.next();
    String id = notification.getId();
    String topic = notification.getTopic();
    NotificationData data = notification.getData();
    String type = data.getType();
    // raw map representation of the payload
    Map item = data.getItem();
}
NotificationErrorCollection errors = Subscription.errorFeed(subscription.getId());
while (errors.hasNext()) {
    NotificationError notificationError = errors.next();
    RequestResponseCapture capture = notificationError.getCapture();
    URI requestURI = capture.getRequestURI();
    String requestMethod = capture.getRequestMethod();
    Map<String, String> requestHeaders = capture.getRequestHeaders();
    String requestEntity = capture.getRequestEntity();
    int statusCode = capture.getResponseStatusCode();
    Map<String, String> responseHeaders = capture.getResponseHeaders();
    String responseEntity = capture.getResponseEntity();
}
InputStream jsonStream = ...;
final Notification notification = Notification.readJSON(jsonStream);
String jsonString = ...;
final Notification notification = Notification.readJSON(jsonString);

Counts

Available Counts

// app totals
Counts.Totals totals = Counts.appTotals();
System.out.println("companies: " + totals.getCompany().getValue());
System.out.println("segments: :" + totals.getSegment().getValue());
System.out.println("tags: :" + totals.getTag().getValue());
System.out.println("users: :" + totals.getUser().getValue());
Counts.Conversation conversationTotals = Counts.conversationTotals();
System.out.println("assigned: " + conversationTotals.getAssigned());
System.out.println("closed: :" + conversationTotals.getClosed());
System.out.println("open: :" + conversationTotals.getOpen());
System.out.println("unassigned: :" + conversationTotals.getUnassigned());
Counts.Conversation adminCounts = Counts.conversationAdmins();
List<Admin> admins = adminCounts.getAdmins();
for (Admin admin : admins) {
    System.out.println(admin.getName() + ": " + admin.getClosed() + ", " + admin.getOpen());
}
System.out.println("tag user counts: ");
List<Counts.CountItem> tags = Counts.userTags();
for (Counts.CountItem tag : tags) {
    System.out.println(tag.getName()+": " +tag.getValue());
}
List<Counts.CountItem> segments = Counts.userSegments();
for (Counts.CountItem segment : segments) {
    System.out.println(segment.getName()+": " +segment.getValue());
}
List<Counts.CountItem> companyUsers = Counts.companyUsers();
for (Counts.CountItem company : companyUsers) {
    System.out.println(company.getName()+": " +company.getValue());
}
List<Counts.CountItem> companyTags = Counts.companyTags();
for (Counts.CountItem tag : companyTags) {
    System.out.println(tag.getName()+": " +tag.getValue());
}

Idioms

HTTP requests

To signal local versus remote methods, calls that result in HTTP requests are performed
using static methods, for example User.find(). The objects returned by static methods
are built from server responses. The exception to the static idiom is where the next(),
hasNext() and nextPage() methods on Collections are used to abstract over pagination.

##Β Pagination
Some API classes have static list() methods that correspond to paginated API responses.
These return a Collection object (eg UserCollection) which can be iterated in two
ways

  • The collection's getPage(), hasNextPage() and nextPage() methods - these are useful when you want to fetch one or just a few pages directly.

  • Java's inbuilt iterator methods next() and hasNext() - these are useful when you want to fetch data without manually handling pagination.

  • User and Contact listing only works up to 10k records. To retrieve all records use the Scroll API via scroll()

Intercom.setToken("da39a3ee5e6b4b0d3255bfef95601890afd80709");
Intercom.setToken("da39a3ee5e6b4b0d3255bfef95601890afd80709");
Intercom.setToken("da39a3ee5e6b4b0d3255bfef95601890afd80709");

Error handling

You do not need to deal with the HTTP response from an API call directly.
If there is an unsuccessful response then an IntercomException or a subclass
of IntercomException will be thrown. The exception will have Error objects
that can be examined via getErrorCollection and getFirstError for more detail.

The API throws the following runtime exceptions -

  • AuthorizationException: for a 401 or 403 response
  • InvalidException: for a 422 response or a local validation failure
  • RateLimitException: for a 429 rate limit exceeded response
  • ClientException: for a general 4xx response
  • ServerException: for a 500 or 503 response
  • IntercomException: general exception

Configuration

HTTP

The client can be configured to accept any http stack that implements
java.net.HttpURLConnection by implementing the HttpConnectorSupplier
interface.

For example, to use OkHttp as a connection
supplier, create a supplier class and hand a supplier to the Intercom object

public class OkHttpSupplier implements HttpConnectorSupplier {
    private final OkUrlFactory urlFactory;

    public OkHttpSupplier(OkUrlFactory urlFactory) {
        this.urlFactory = urlFactory;
    }

    @Override
    public HttpURLConnection connect(URI uri) throws IOException {
        return urlFactory.open(uri.toURL());
    }
}
final OkHttpClient client = new OkHttpClient();
final OkUrlFactory factory = new OkUrlFactory(client);
final OkHttpSupplier supplier = new OkHttpSupplier(factory);
Intercom.setHttpConnectorSupplier(supplier);

Timeouts

The default connection and request timeouts can be set in milliseconds using the
Intercom.setConnectionTimeout and Intercom.setRequestTimeout methods.

Target API Server

The base URI to target can be changed for testing purposes

URI baseURI = new URI("https://example.org/server");
Intercom.setApiBaseURI(baseURI);