• About Us
  • Blog
  • Basket
  • Account
  • Sign In
  •  

Java API

What's Covered

This tutorial illustrates how to append a CSV file containing User-Agent strings with IsMobile, PlatformName and PlatformVersion properties. The following aspects of the API are covered:

  • How to perform a User-Agent match.
  • How to reuse resources to perform subsequent matching.
  • How to retrieve match results for a specific property.
  • How to append a property value to a CSV file.

Code and Explanation

Example of using 51Degrees Pattern Detection to process a file containing User-Agent header values and output a CSV file containing the same header values with various properties detected by 51Degrees.

The example illustrates:

  1. Loading a Provider from a Disk-based (Stream) Pattern Dataset
          provider = new Provider(StreamFactory.create
          (Shared.getLitePatternV32(), false));
      
  2. Matching a User-Agent header value
    1. By creating a match and using it repeatedly (for efficiency)
                Match match = provider.createMatch();
            
                provider.match(userAgentString, match);
            
    2. By having the provider create a new Match for each detection
                Match match = provider.match(userAgentString);
            
  3. Getting the values for some properties of the matched User-Agent header
          Values isMobile = match.getValues("IsMobile");
      

    A property may have multiple values. Helper methods convert the list of values into a Boolean, Double etc. For example:

          isMobile.toBool();
      
You can run MetadataExample.main(java.lang.String[]) for a listing of which properties are available in the dataset supplied with this distribution.

Full Source File
    // output file in current working directory
    public String outputFilePath = "batch-processing-example-results.csv";
    // pattern detection matching provider
    private final Provider provider;

    /**
     * Initialises the device detection Provider with the included Lite data
     * file. For more data see: 
     * <a href="https://51degrees.com/compare-data-options">compare data options
     * </a>
     * 
     * @throws IOException if there was a problem reading from the data file.
     */
    public OfflineProcessingExample() throws IOException {
        provider = new Provider(StreamFactory.create(
                Shared.getLitePatternV32(), false));
     }

    /**
     * Reads a CSV file containing User-Agents and adds the IsMobile, 
     * PlatformName and PlatformVersion information for the first 20 lines.
     * For a full list of properties and the files they are available in please 
     * see: <a href="https://51degrees.com/resources/property-dictionary">
     * Property Dictionary</a>
     * 
     * @param inputFileName the CSV file to read from.
     * @param outputFilename where to save the file with extra entries.
     * @throws IOException if there was a problem reading from the data file.
     */
    public void processCsv(String inputFileName, String outputFilename) 
            throws IOException {
        BufferedReader bufferedReader = 
                new BufferedReader(new FileReader(inputFileName));
        try {
            FileWriter fileWriter = new FileWriter(outputFilename);
            try {
                // it's more efficient over the long haul to create a match 
                // once and reuse it in multiple matches
                Match match = provider.createMatch();
                // there are 20k lines in supplied file, we'll just do a couple 
                // of them!
                for (int i = 0; i < 20; i++) {

                    // read next line
                    String userAgentString = bufferedReader.readLine();

                    // ask the provider to match the UA using match we created
                    provider.match(userAgentString, match);

                    // get some property values from the match
                    Values isMobile = match.getValues("IsMobile");
                    Values platformName = match.getValues("PlatformName");
                    Values platformVersion = match.getValues("PlatformVersion");

                    // write result to file
                    fileWriter.append("\"")
                            .append(userAgentString)
                            .append("\", ")
                            .append(getValueForDisplay(isMobile))
                            .append(", ")
                            .append(getValueForDisplay(platformName))
                            .append(", ")
                            .append(getValueForDisplay(platformVersion))
                            .append('\n')
                            .flush();
                }
            } finally {
                fileWriter.close();
            }
        } finally {
            bufferedReader.close();
        }
    }

    /**
     * Match values may be null. A helper method to get something displayable
     * @param values a Values to render
     * @return a non-null String
     */
    protected String getValueForDisplay(Values values) {
        return values == null ? "N/A": values.toString();
    } 

    /**
     * Closes the {@link fiftyone.mobile.detection.Dataset} by releasing data 
     * file readers and freeing the data file from locks. This method should 
     * only be used when the {@code Dataset} is no longer required, i.e. when 
     * device detection functionality is no longer required, or the data file 
     * needs to be freed.
     * 
     * @throws IOException if there was a problem accessing the data file.
     */
    @Override
    public void close() throws IOException {
        provider.dataSet.close();
    }

    /**
     * Instantiates this class and starts 
     * {@link #processCsv(java.lang.String, java.lang.String)} with default 
     * parameters.
     * 
     * @param args command line arguments.
     * @throws IOException if there was a problem accessing the data file.
     */
    public static void main(String[] args) throws IOException {
        System.out.println("Starting Offline Processing Example");
        OfflineProcessingExample offlineProcessingExample = 
                new OfflineProcessingExample();
        try {
            offlineProcessingExample.processCsv(Shared.getGoodUserAgentsFile(), 
                    offlineProcessingExample.outputFilePath);
            System.out.println("Output written to " + 
                    offlineProcessingExample.outputFilePath);
        } finally {
            offlineProcessingExample.close();
        }
    }

Full Source File

Summary

Offline device detection is frequently required for a variety of reasons such as generating reports. The example is based on an actual support request where several properties had to be added to the CSV file before it could be passed on for another department to use.

This tutorial covered how to use the detector offline to append the first 20 lines of a CSV file with Lite properties: IsMobile, PlatformName and PlatformVersion. Using a Premium or an Enterprise data file gives you access to a far greater number of properties including HardwareVendor, PriceBand, ScreenInchesWidth, IsCrawler and more. A full list of properties and the data file version they are present in can be viewed in the Property Dictionary.