1. Overview
When building a web application, we often need information about the devices and browsers accessing our application so that we can deliver optimized user experiences.
A user agent is a string that identifies the client making requests to our server. It contains information about the client device, operating system, browser, and more. It’s sent to the server through the User-Agent request header.
However, parsing user agent strings can be challenging due to their complex structure and varied nature. The Yauaa (Yet Another UserAgent Analyzer) library helps simplify this process when working in the Java ecosystem.
In this tutorial, we’ll explore how to leverage Yauaa in a Spring Boot application to parse user agent strings and implement device-specific routing.
2. Setting up the Project
Before we dive into the implementation, we’ll need to include an SDK dependency and configure our application correctly.
2.1. Dependencies
Let’s start by adding the yauaa dependency to our project’s pom.xml file:
<dependency>
<groupId>nl.basjes.parse.useragent</groupId>
<artifactId>yauaa</artifactId>
<version>7.28.1</version>
</dependency>
This dependency provides us with the necessary classes to parse and analyze the user agent request header from our application.
2.2. Defining UserAgentAnalyzer Configuration Bean
Now that we’ve added the correct dependency, let’s define our UserAgentAnalyzer bean:
private static final int CACHE_SIZE = 1000;
@Bean
public UserAgentAnalyzer userAgentAnalyzer() {
return UserAgentAnalyzer
.newBuilder()
.withCache(CACHE_SIZE)
// ... other settings
.build();
}
The UserAgentAnalyzer class is the main entry point for parsing user agent strings.
The UserAgentAnalyzer, by default, uses an in-memory cache with a size of 10000, but we can update it as required using the withCache() method as we’ve done in our example. Caching helps us improve performance by avoiding repeated parsing of the same user agent strings.
3. Exploring UserAgent Fields
Once we’ve defined our UserAgentAnalyzer bean, we can use it to parse a user agent string and get information about the client.
For our demonstration, let’s take the user agent of the device that’s being used to write this tutorial:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15
Now, we’ll use our UserAgentAnalyzer bean to parse the above and extract all available fields:
UserAgent userAgent = userAgentAnalyzer.parse(USER_AGENT_STRING);
userAgent
.getAvailableFieldNamesSorted()
.forEach(fieldName -> {
log.info("{}: {}", fieldName, userAgent.getValue(fieldName));
});
Let’s take a look at the generated logs when we execute the above code:
com.baeldung.Application : DeviceClass: Desktop
com.baeldung.Application : DeviceName: Apple Macintosh
com.baeldung.Application : DeviceBrand: Apple
com.baeldung.Application : DeviceCpu: Intel
com.baeldung.Application : DeviceCpuBits: 64
com.baeldung.Application : OperatingSystemClass: Desktop
com.baeldung.Application : OperatingSystemName: Mac OS
com.baeldung.Application : OperatingSystemVersion: >=10.15.7
com.baeldung.Application : OperatingSystemVersionMajor: >=10.15
com.baeldung.Application : OperatingSystemNameVersion: Mac OS >=10.15.7
com.baeldung.Application : OperatingSystemNameVersionMajor: Mac OS >=10.15
com.baeldung.Application : LayoutEngineClass: Browser
com.baeldung.Application : LayoutEngineName: AppleWebKit
com.baeldung.Application : LayoutEngineVersion: 605.1.15
com.baeldung.Application : LayoutEngineVersionMajor: 605
com.baeldung.Application : LayoutEngineNameVersion: AppleWebKit 605.1.15
com.baeldung.Application : LayoutEngineNameVersionMajor: AppleWebKit 605
com.baeldung.Application : AgentClass: Browser
com.baeldung.Application : AgentName: Safari
com.baeldung.Application : AgentVersion: 17.6
com.baeldung.Application : AgentVersionMajor: 17
com.baeldung.Application : AgentNameVersion: Safari 17.6
com.baeldung.Application : AgentNameVersionMajor: Safari 17
com.baeldung.Application : AgentInformationEmail: Unknown
com.baeldung.Application : WebviewAppName: Unknown
com.baeldung.Application : WebviewAppVersion: ??
com.baeldung.Application : WebviewAppVersionMajor: ??
com.baeldung.Application : WebviewAppNameVersion: Unknown
com.baeldung.Application : WebviewAppNameVersionMajor: Unknown
com.baeldung.Application : NetworkType: Unknown
As we can see, the UserAgent class provides valuable information about the device, operating system, browser, and more. We can use these fields and make informed decisions as per our business requirements.
It’s also important to note that not all the fields are available for a given user agent string, which is evident by the Unknown and ?? values in the log statements. If we don’t want these unavailable values displayed, we can use the getCleanedAvailableFieldNamesSorted() method of the UserAgent class instead.
4. Implementing Device-Based Routing
Now that we’ve looked at the various fields available in the UserAgent class, let’s put this knowledge to use by implementing device-based routing in our application.
For our demonstration, we’ll assume a requirement to serve our application to mobile devices while restricting access to non-mobile devices. We can achieve this by inspecting the DeviceClass field of the user agent string.
First, let’s define a list of supported device classes that we’ll consider as mobile devices:
private static final List SUPPORTED_MOBILE_DEVICE_CLASSES = List.of("Mobile", "Tablet", "Phone");
Next, let’s create our controller method:
@GetMapping("/mobile/home")
public ModelAndView homePage(@RequestHeader(HttpHeaders.USER_AGENT) String userAgentString) {
UserAgent userAgent = userAgentAnalyzer.parse(userAgentString);
String deviceClass = userAgent.getValue(UserAgent.DEVICE_CLASS);
boolean isMobileDevice = SUPPORTED_MOBILE_DEVICE_CLASSES.contains(deviceClass);
if (isMobileDevice) {
return new ModelAndView("/mobile-home");
}
return new ModelAndView("error/open-in-mobile", HttpStatus.FORBIDDEN);
}
In our method, we use the @RequestHeader to get the value of the user agent string, which we parse using our UserAgentAnalyzer bean. Then, we extract the DEVICE_CLASS field from the parsed UserAgent instance and check if it matches any of the supported mobile device classes.
If we identify that the incoming request has been made from a mobile device, we return the /mobile-home view. Otherwise, we return an error view with an HTTP status of Forbidden, indicating that the resource is only accessible from mobile devices.
5. Testing Device-Based Routing
Now that we’ve implemented device-based routing, let’s test it to ensure it works as expected using MockMvc:
private static final String SAFARI_MAC_OS_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";
mockMvc.perform(get("/mobile/home")
.header("User-Agent", SAFARI_MAC_OS_USER_AGENT))
.andExpect(view().name("error/open-in-mobile"))
.andExpect(status().isForbidden());
We simulate a request with a Safari user agent string for macOS and invoke our /home endpoint. We verified that our error view was returned to the client with an HTTP status of 403 forbidden.
Similarly, let’s now invoke our endpoint with a mobile user agent:
private static final String SAFARI_IOS_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";
mockMvc.perform(get("/mobile/home")
.header("User-Agent", SAFARI_IOS_USER_AGENT))
.andExpect(view().name("/mobile-home"))
.andExpect(status().isOk());
Here, we use a Safari user agent string for iOS and assert that the request is successfully completed with the correct view returned to the client.
6. Reducing Memory Footprint and Speeding up Execution
By default, Yauaa parses all available fields from the user agent string. However, if we only need a subset of fields in our application, we can specify them in our UserAgentAnalyzer bean:
UserAgentAnalyzer
.newBuilder()
.withField(UserAgent.DEVICE_CLASS)
// ... other settings
.build();
Here, we configure the UserAgentAnalyzer to only parse the DEVICE_CLASS field that we used in our device-based routing implementation.
We can chain multiple withField() methods together if we need to parse multiple fields. This approach is highly recommended as it helps reduce memory usage and improves performance.
7. Conclusion
In this article, we explored using Yauaa to parse and analyze user agent strings.
We walked through the necessary configuration, looked at the different fields we have access to, and implemented device-based routing in our application.
As always, all the code examples used in this article are available over on GitHub.