Analytics for Java

Maven Central

Our Java library lets you record analytics data from your Java code. The requests hit our servers, and then we route your data to any analytics service you enable on your integrations page.

This library is open-source, so you can check it out on Github.

All of our server-side libraries are built for high-performance, so you can use them in your web server controller code. This library uses an internal queue to make all calls non-blocking and fast. It also batches messages and flushes asynchronously to our servers.

Want to stay updated on releases? Subscribe to the release feed.

Getting Started

Javadocs

Install the library

The recommended way to install the library for Java is with a build system like Gradle or Maven. This makes it dead simple to upgrade and swap out integrations. The library is distributed via Maven Central as a jar dependency.

Here’s what it would look like with Maven:

Add to pom.xml:

<dependency>
  <groupId>com.segment.analytics.java</groupId>
  <artifactId>analytics</artifactId>
  <version>LATEST</version>
</dependency>

or if you’re using Gradle:

compile 'com.segment.analytics.java:analytics:+'

Initialize the SDK

Before you can send us events, you need to initialize an instance of the Analytics class. To do so, you must use the Analytics.Builder class.

Analytics analytics = Analytics.builder(writeKey).build();

Of course, you’ll want to replace writeKey with your actual Write Key which you can find in Segment under your source settings.

The Builder can also be used to customize behaviour of the Analytics instance.

Note: There is an internal AnalyticsClient class. Do not confuse this class with the public Analytics class and do not use this class directly.

The Analytics class has a method called enqueue that takes a MessageBuilder. Each message class has a corresponding builder that is used to construct instances of a message.

Although not enforced at compile time, make sure you provide either of userId or anonymousId for each message. Failing to do so will raise an exception at runtime.

The following examples use Guava’s immutable maps, but feel free to use plain old Java maps instead.

Identify

identify lets you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about them.

We recommend calling identify a single time when the user’s account is first created, and only identifying again later when their traits change.

Example identify call:

analytics.enqueue(IdentifyMessage.builder()
    .userId("f4ca124298")
    .traits(ImmutableMap.builder()
        .put("name", "Michael Bolton")
        .put("email", "mbolton@initech.com")
        .build()
    )
);

This call is identifying Michael by his unique User ID (the one you know him by in your database) and labeling him with name and email traits.

The identify call has the following fields:

userId StringThe ID for this user in your database.
traits Traits, optionalA dictionary of traits you know about the user. Things like: email, name or friends.

Note: The enqueue method takes a MessageBuilder instance and not a Message instance directly. This is to allow you to use a MessageTransformer that applies to all incoming messages and transform or add data. Read more in our transformer reference section.

Find details on the identify method payload in our Spec.

Track

track lets you record the actions your users perform. Every action triggers what we call an “event”, which can also have associated properties.

You’ll want to track events that you’re interested in, such as Signed Up, Item Purchased or Article Bookmarked.

To get started, we recommend tracking just a few important events. You can always add more later!

Example track call:

analytics.enqueue(TrackMessage.builder("Item Purchased")
    .userId("f4ca124298")
    .properties(ImmutableMap.builder()
        .put("revenue", 39.95)
        .put("shipping", "2-day")
        .build()
    )
);

This example track call tells us that your user just triggered the Item Purchased event with a revenue of $39.95 and chose your hypothetical ‘2-day’ shipping.

track event properties can be anything you want to record. In this case, revenue and shipping.

The track call has the following fields:

userId StringThe ID for this user in your database.
event StringThe name of the event you’re tracking. We recommend human-readable names like Song Played or Status Updated.
properties Properties, optionalA dictionary of properties for the event. If the event was Product Added, it might have properties like price or product.

Find details on best practices in event naming as well as the track method payload in our Spec.

Screen

The screen method lets you record whenever a user sees a screen of your mobile app, along with optional extra information about the page being viewed.

You’ll want to record a screen event an event whenever the user opens a screen in your app. This could be a view, fragment, dialog or activity depending on your app.

Not all services support screen, so when it’s not supported explicitly, the screen method tracks as an event with the same parameters.

Example screen call:

analytics.enqueue(ScreenMessage.builder("Schedule")
    .userId("f4ca124298")
    .properties(ImmutableMap.builder()
        .put("category", "Sports")
        .put("path", "/sports/schedule")
        .build()
    )
);

The screen call has the following fields:

userId StringThe ID for this user in your database.
name StringThe webpage name you’re tracking. We recommend human-readable names like Login or Register.
properties Properties, optionalA dictionary of properties for the webpage visit. If the event was Login, it might have properties like path or title.

Find details on the screen payload in our Spec.

Group

group lets you associate an identified user user with a group. A group could be a company, organization, account, project or team! It also lets you record custom traits about the group, like industry or number of employees.

This is useful for tools like Intercom, Preact and Totango, as it ties the user to a group of other users.

Example group call:

analytics.enqueue(GroupMessage.builder("some-group-id")
    .userId("f4ca124298")
    .traits(ImmutableMap.builder()
        .put("name", "Segment")
        .put("size", 50)
        .build()
    )
);

The group call has the following fields:

userId StringThe ID for this user in your database.
groupId StringThe ID for this group in your database.
traits Traits, optionalA dictionary of traits you know about the group. Things like: name or website.

Find more details about group, including the group payload, in our Spec.

Alias

alias is how you associate one identity with another. This is an advanced method, but it is required to manage user identities successfully in some of our integrations.

In Mixpanel it’s used to associate an anonymous user with an identified user once they sign up. For KISSmetrics, if your user switches IDs, you can use ‘alias’ to rename the ‘userId’.

Example alias call:

analytics.enqueue(AliasMessage.builder("previousId")
    .userId("f4ca124298")
);

Here’s a full example of how we might use the alias call:

// the anonymous user does actions ...
track("anonymous_user", "Anonymous Event");
// the anonymous user signs up and is aliased
alias("anonymous_user", "identified@gmail.com");
// the signed up user is identified
identify("identified@gmail.com", new Traits("plan", "Free"));
// the identified user does actions ...
track("identified@gmail.com", "Identified Action");

For more details about alias, including the alias call payload, check out our Spec.


Historical Import

You can import historical data by adding the timestamp argument to any of your method calls. This can be helpful if you’ve just switched to Segment.

Historical imports can only be done into integrations that can accept historical timestamp’ed data. Most analytics tools like Mixpanel, Amplitude, Kissmetrics, etc. can handle that type of data just fine. One common integration that does not accept historical data is Google Analytics since their API cannot accept historical data.

Note: If you’re tracking things that are happening right now, leave out the timestamp and our servers will timestamp the requests for you.

Date historicalDate = ...;
analytics.enqueue(TrackMessage.builder("Button Clicked")
    .userId("f4ca124298")
    .timestamp(historicalDate)
);

Selecting Integrations

The alias, group, identify, page and track calls can all be passed an object of integrations that lets you turn certain integrations on or off. By default all integrations are enabled.

Similar to timestamp, the builders take a map of integrations that control which analytics integrations you want each message to go to.

analytics.enqueue(TrackMessage.builder("Button Clicked")
    .userId("f4ca124298")
    .enableIntegration("All", false)
    .enableIntegration("Amplitude", true)
);

In this case, we’re specifying that we want this identify to only go to Amplitude. "all", false says that no integration should be enabled unless otherwise specified. { "Amplitude", true } turns on Amplitude.

Integration flags are case sensitive and match the integration’s name in the docs (i.e. “AdLearn Open Platform”, “awe.sm”, “MailChimp”, etc.).

Note:

  • Available at the business level, filtering track calls can be done right from the Segment UI on your source schema page. We recommend using the UI if possible since it’s a much simpler way of managing your filters and can be updated with no code changes on your side.

  • If you are on a grandfathered plan, events sent server-side that are filtered through the Segment dashboard will still count towards your API usage.

Context

If you’re running a web server, you might want to send context variables such as userAgent or ip with your page or screen calls. You can do so by setting the Context.

analytics.enqueue(TrackMessage.builder("Button Clicked")
    .userId("f4ca124298")
    .context(ImmutableMap.builder()
        .put("ip", "12.212.12.49")
        .put("language", "en-us")
        .build()
    )
);

Batching

Our libraries are built to support high performance environments. That means it is safe to use analytics-java on a web server that’s serving hundreds of requests per second. For more information, check out the java benchmark.

Every method you call does not result in an HTTP request, but is queued in memory instead. Messages are flushed in batch in the background, which allows for much faster operation.

There is a maximum of 500kb per batch request and 15kb per call.

How do I flush right now?!

You can also flush on demand. For example, at the end of your program, you’ll want to flush to make sure there’s nothing left in the queue. Just call the flush method:

analytics.flush()

Calling this method will notify the client to upload any events in the queue.

Multiple Clients

Different parts of your app may require different types of batching. In that case, you can initialize different Analytics instances. Simply use the builder method (you can reuse it with different parameters) to create different instances.

Analytics.Builder builder = Analytics.builder(writeKey);
Analytics first = builder.build();
Analytics second = builder.flushInterval(2, TimeUnit.SECONDS).build();

Logging

You can enable verbose logging to see what data is being sent over HTTP when debugging issues. You can enable logging by initializing the library like this:

Analytics analytics = Analytics.builder("<writeKey>")
        .log(STDOUT)
        .build();

Snapshots

To add a snapshot dependency to your builds, make sure you add the snapshot repository so your build system can look up the dependency.

Maven users can add the following to their pom.xml:

<repository>
    <id>ossrh</id>
    <name>Sonatype Snapshot Repository</name>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

Gradle users should declare this in their repositories block:

repositories {
  mavenCentral()
  maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}

Troubleshooting

If you’re having trouble we have a few tips that help common problems.

No events in my debugger

  1. Double check that you’ve followed all the steps in the Quickstart.

  2. Make sure that you’re calling one of our API methods once the library is successfully installed—identify, track, etc.

No events in my end tools

  1. Double check your credentials for that integration.

  2. Make sure that the integration you are troubleshooting can accept server-side API calls. Compatibility is shown on the integration docs pages and on the sheets on your Segment source Integrations page.

  3. Check out the integration’s documentation to see if there are other requirements for using the method and integration you’re trying to get working.


If you have any questions or see anywhere we can improve our documentation, please let us know or kick off a conversation in the Segment Community!