package com.walker.web.agent.impl; import static com.walker.web.agent.BrowsCapField.BROWSER; import static com.walker.web.agent.BrowsCapField.BROWSER_MAJOR_VERSION; import static com.walker.web.agent.BrowsCapField.BROWSER_TYPE; import static com.walker.web.agent.BrowsCapField.DEVICE_TYPE; import static com.walker.web.agent.BrowsCapField.PLATFORM; import static com.walker.web.agent.BrowsCapField.PLATFORM_VERSION; import static com.walker.web.agent.Capabilities.UNKNOWN_BROWSCAP_VALUE; import com.walker.web.agent.BrowsCapField; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Mapper { private final Map myIndices; Mapper(final Collection fields) { // Get all fields final Set all = new HashSet<>(fields); for (final BrowsCapField field : BrowsCapField.values()) { if (field.isDefault()) { all.add(field); } } // Get all unique values and keep a fixed order myIndices = new EnumMap<>(BrowsCapField.class); final List ordered = new ArrayList<>(all); for (int i = 0; i < ordered.size(); i++) { myIndices.put(ordered.get(i), i); } } String[] getValues(final Map values) { final String[] result = new String[myIndices.size()]; // default values first, for backwards compatibility put(result, BROWSER, "Default Browser"); put(result, BROWSER_TYPE, "Default Browser"); put(result, BROWSER_MAJOR_VERSION, UNKNOWN_BROWSCAP_VALUE); put(result, DEVICE_TYPE, UNKNOWN_BROWSCAP_VALUE); put(result, PLATFORM, UNKNOWN_BROWSCAP_VALUE); put(result, PLATFORM_VERSION, UNKNOWN_BROWSCAP_VALUE); for (final Map.Entry entry : values.entrySet()) { put(result, entry.getKey(), entry.getValue()); } return result; } public Map getAll(final String[] values) { final Map result = new EnumMap<>(BrowsCapField.class); for (final BrowsCapField field : myIndices.keySet()) { result.put(field, getValue(values, field)); } return result; } String getValue(final String[] values, final BrowsCapField field) { final Integer index = myIndices.get(field); if (index != null) { return values[index]; } return null; } private void put(final String[] values, final BrowsCapField field, final String value) { final Integer index = myIndices.get(field); if (index != null) { values[index] = value; } } }