Check out the latest documentation.

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 the 51Degrees Hash Trie library
    											
    											
          res = FiftyOneDegreesTrieV3.class.getResource("/FiftyOneDegreesTrieV3.so");
          System.load(res.getPath());
      
    											
    										
  2. How to instantiate 51Degrees detection provider
    											
    											
          provider = new Provider("path/to/51Degrees/data/file.trie");
      
    											
    										
  3. Matching a User-Agent header value
    1. By creating a match and using it repeatedly (for efficiency)
      													
      													
                Match match;
            
      													
      												
      													
      													
                match = provider.getMatch(userAgentString);
            
      													
      												
    2. By having the provider create a new Match for each detection
      													
      													
                Match match = provider.getMatch(userAgentString);
            
      													
      												
  4. Getting the values for some properties of the matched User-Agent header
    											
    											
          VectorString isMobile = match.getValues("IsMobile");
      
    											
    										

The 51 Degrees Property Dictionary contains a description of each of the properties and the editions in which they are available.

main assumes it is being run with a working directory at root of project or of this module.

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;

    /**
     * Loads the 51Degrees Hash Trie library and initialises the device
     * detection Provider with the Lite data file. For more data see:
     * <a href="https://51degrees.com/compare-data-options">compare data options
     * </a>
     *
     * @throws IOException can be thrown if there is a problem reading from the
     * provided data file.
     */
    public OfflineProcessingExample() throws IOException {
        // Load the C/C++ native library. Uncomment dll line for windows and so line in linux.
        LibLoader.load("/FiftyOneDegreesTrieV3.dll");
        // LibLoader.load("/FiftyOneDegreesTrieV3.so");

        // Create a new provider.
        provider = new Provider("../../data/51Degrees-LiteV3.4.trie");
    }

    /**
     * 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;
                // 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
                    match = provider.getMatch(userAgentString);

                    // get some property values from the match
                    VectorString isMobile = match.getValues("IsMobile");
                    VectorString platformName = match.getValues("PlatformName");
                    VectorString 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(VectorString values) {
        return values == null ? "N/A": values.get(0);
    } 

    public void close() throws IOException {
        provider.delete();
    }

    /**
     * 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("../../data/20000 User Agents.csv",
                    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 .