\r\n

51Degrees Device Detection Java  4.3

Device detection services for 51Degrees Pipeline

mvc/configuration/UACHExampleMvcConfig.java

Spring MVC User Agent Client Hints example.

In this scenario, the standard Pipeline API web integration is used. This means that several jobs that the API usually takes care of automatically For example, setting the HTTP response headers to request user-agent client hints.

The source code for this example is available in full on GitHub.

This example can be configured to use the 51Degrees cloud service or a local data file. If you don't already have data file you can obtain one from the device-detection-data GitHub repository.

To use the cloud service you will need to create a resource key. The resource key is used as short-hand to store the particular set of properties you are interested in as well as any associated license keys that entitle you to increased request limits and/or paid-for properties.

You can create a resource key using the 51Degrees Configurator.

Set up configuration options to add elements to the 51Degrees Pipeline.

1 <PipelineOptions>
2  <Elements>
3  <Element>
4  <BuildParameters>
5  <EndPoint>https://cloud.51degrees.com/api/v4</EndPoint>
6  <!-- Obtain a resource key for free at
7  https://configure.51degrees.com
8  Make sure to include the 'BrowserName','BrowserVendor',
9  'BrowserVersion','HardwareName','HardwareVendor',
10  'PlatformName','PlatformVendor','PlatformVersion'
11  properties as they are used by this example. -->
12  <ResourceKey>!!YOUR_RESOURCE_KEY!!</ResourceKey>
13  </BuildParameters>
14  <BuilderName>CloudRequestEngine</BuilderName>
15  </Element>
16  <Element>
17  <BuilderName>DeviceDetectionCloudEngine</BuilderName>
18  </Element>
19  </Elements>
20 </PipelineOptions>

Alternatively, to use the on-premise API with automatic updates enabled, replace the cloud element in the config with the new configuration.

1 <PipelineOptions>
2  <Elements>
3  <Element>
4  <BuildParameters>
5  <AutoUpdate>true</AutoUpdate>
6  <DataFileSystemWatcher>false</DataFileSystemWatcher>
7  <CreateTempDataCopy>true</CreateTempDataCopy>
8  <!-- Obtain your own license key and enterprise data file
9  from https://51degrees.com. -->
10  <DataUpdateLicenseKey>[[Your License Key]]</DataUpdateLicenseKey>
11  <DataFile>D:\[[Path to data file]]\51Degrees-EnterpriseV4.1.hash</DataFile>
12  <PerformanceProfile>LowMemory</PerformanceProfile>
13  </BuildParameters>
14  <BuilderName>DeviceDetectionHashEngineBuilder</BuilderName>
15  </Element>
16  </Elements>
17 </PipelineOptions>
  1. Set up MVC, enable configuration, and add the Pipeline component.
    @EnableWebMvc
    @Configuration
    @ComponentScan({"fiftyone.pipeline.uach.examples.mvc.controller","fiftyone.pipeline.web.mvc"})
    public class UACHExampleMvcConfig extends WebMvcConfigurerAdapter {
    ...
  2. Configure the interceptor.
    public class UACHExampleMvcConfig extends WebMvcConfigurerAdapter {
    ...
    @Bean
    public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() {
    final FiftyOneInterceptorConfigDefault bean = new FiftyOneInterceptorConfigDefault();
    bean.setDataFilePath(servletContext.getRealPath("/WEB-INF/51Degrees-Hash.xml"));
    bean.setClientsidePropertiesEnabled(true);
    return bean;
    }
    ...
  3. Enable client-side code to improve detection accuracy on devices like iPhones.
    public class UACHExampleMvcConfig extends WebMvcConfigurerAdapter {
    ...
    @Override
    public void addViewControllers(final ViewControllerRegistry registry) {
    enableClientsideProperties(registry);
    }
    ...
  4. Add the interceptor.
    public class UACHExampleMvcConfig extends WebMvcConfigurerAdapter {
    ...
    @Autowired
    FiftyOneInterceptor fiftyOneInterceptor;
    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
    registry.addInterceptor(fiftyOneInterceptor);
    }
    ...
  5. Inject the FlowDataProvider into a controller.
    @Controller
    @RequestMapping("/")
    public class UACHExampleController {
    private FlowDataProvider flowDataProvider;
    @Autowired
    public ExampleController(FlowDataProvider flowDataProvider) {
    this.flowDataProvider = flowDataProvider;
    }
    ...
  6. Use the results contained in the flow data to display something on a page view.
    @Controller
    @RequestMapping("/")
    public class UACHExampleController {
    ...
    @RequestMapping(method = RequestMethod.GET)
    public String get(ModelMap model, HttpServletRequest request) {
    FlowData data = flowDataProvider.getFlowData(request);
    DeviceData device = data.get(DeviceData.class);
    model.addAttribute("browser", device.getBrowserVendor() + " " + device.getBrowserName() + " " + device.getBrowserVersion());
    model.addAttribute("device", device.getHardwareVendor() + " " + device.getHardwareName());
    model.addAttribute("os", device.getPlatformVendor() + " " + device.getPlatformName() + " " + device.getPlatformVersion());
    return "example";
    }
    ...

    Controller

/* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2019 51 Degrees Mobile Experts Limited, 5 Charlotte Close,
* Caversham, Reading, Berkshire, United Kingdom RG4 7BY.
*
* This Original Work is licensed under the European Union Public Licence (EUPL)
* v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* */
package fiftyone.pipeline.uach.examples.mvc.controller;
import fiftyone.devicedetection.hash.engine.onpremise.flowelements.DeviceDetectionHashEngine;
import fiftyone.devicedetection.shared.DeviceData;
import fiftyone.pipeline.core.data.FlowData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import fiftyone.pipeline.web.mvc.components.FlowDataProvider;
import javax.servlet.http.HttpServletRequest;
import static fiftyone.pipeline.uach.examples.mvc.controller.UACHExampleHelper.tryGet;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/")
public class UACHExampleController {
private FlowDataProvider flowDataProvider;
@Autowired
public UACHExampleController(FlowDataProvider flowDataProvider) {
this.flowDataProvider = flowDataProvider;
}
/*
* Controller method that takes evidences from the request
* Sets required properties in as model attributes
* And return view name.
* @param model: Model in which values will be set.
* @param request: A request parameter
* @param response: A response parameter
*/
@RequestMapping(method = RequestMethod.GET)
public String get(ModelMap model, HttpServletRequest request) throws Exception {
// A try-with-resource block MUST be used for the FlowData instance.
// This ensures that native resources created by the device
// detection engine are freed.
try (FlowData data = flowDataProvider.getFlowData(request);) {
// Get the device data from flowData
DeviceData device = data.get(DeviceData.class);
model.addAttribute("hardwareVendor",
tryGet(() -> device.getHardwareVendor()));
model.addAttribute("hardwareName",
tryGet(() -> device.getHardwareName()));
model.addAttribute("deviceType",
tryGet(() -> device.getDeviceType()));
model.addAttribute("platformVendor",
tryGet(() -> device.getPlatformVendor()));
model.addAttribute("platformName",
tryGet(() -> device.getPlatformName()));
model.addAttribute("platformVersion",
tryGet(() -> device.getPlatformVersion()));
model.addAttribute("browserVendor",
tryGet(() -> device.getBrowserVendor()));
model.addAttribute("browserName",
tryGet(() -> device.getBrowserName()));
model.addAttribute("browserVersion",
tryGet(() -> device.getBrowserVersion()));
Map<String, Object> evidenceUsed = new HashMap<>();
DeviceDetectionHashEngine engine = data.getPipeline().getElement(DeviceDetectionHashEngine.class);
for (Map.Entry<String, Object> evidence : data.getEvidence().asKeyMap().entrySet()) {
if(engine.getEvidenceKeyFilter().include(evidence.getKey())) {
evidenceUsed.put(evidence.getKey(), evidence.getValue());
}
}
model.addAttribute("evidenceUsed", evidenceUsed);
return "uachexample";
}
}
}

Config

/* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2019 51 Degrees Mobile Experts Limited, 5 Charlotte Close,
* Caversham, Reading, Berkshire, United Kingdom RG4 7BY.
*
* This Original Work is licensed under the European Union Public Licence (EUPL)
* v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* */
package fiftyone.pipeline.uach.examples.mvc.configuration;
import javax.servlet.ServletContext;
import fiftyone.pipeline.web.mvc.components.FiftyOneInterceptor;
import fiftyone.pipeline.web.mvc.configuration.FiftyOneInterceptorConfig;
import fiftyone.pipeline.web.mvc.configuration.FiftyOneInterceptorConfigDefault;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import static fiftyone.pipeline.web.mvc.components.FiftyOneInterceptor.enableClientsideProperties;
@EnableWebMvc
@Configuration
@ComponentScan({"fiftyone.pipeline.uach.examples.mvc.controller","fiftyone.pipeline.web.mvc"})
public class UACHExampleMvcConfig extends WebMvcConfigurerAdapter {
public UACHExampleMvcConfig() {
super();
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
enableClientsideProperties(registry);
}
@Autowired
ServletContext servletContext;
@Bean
public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() {
final FiftyOneInterceptorConfigDefault bean = new FiftyOneInterceptorConfigDefault();
bean.setDataFilePath(servletContext.getRealPath("/WEB-INF/51Degrees-Hash.xml"));
bean.setClientsidePropertiesEnabled(true);
return bean;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
return bean;
}
@Autowired
FiftyOneInterceptor fiftyOneInterceptor;
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(fiftyOneInterceptor);
}
}