shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package com.walker.web.agent.impl;
 
import com.univocity.parsers.common.record.Record;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import com.walker.web.agent.BrowsCapField;
import com.walker.web.agent.Capabilities;
import com.walker.web.agent.ParseException;
import com.walker.web.agent.UserAgentParser;
 
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import static com.walker.web.agent.Capabilities.UNKNOWN_BROWSCAP_VALUE;
import static java.util.Collections.singleton;
 
public class UserAgentFileParser {
 
    // Mapping substrings to unique literal for caching of lookups
    private final Map<String, Literal> myUniqueLiterals = new HashMap<>();
 
    private final Map<Capabilities, Capabilities> myCache = new HashMap<>();
 
    private final Map<String, String> myStrings = new HashMap<>();
 
    private final Mapper myMapper;
 
    private final Set<BrowsCapField> myFields;
 
    private final LiteralDomain myDomain = new LiteralDomain();
 
    UserAgentFileParser(final Collection<BrowsCapField> fields) {
        myFields = new HashSet<>(fields);
        myMapper = new Mapper(myFields);
    }
 
    /**
     * Parses a csv stream of rules.
     * @param input The input stream
     * @param fields The fields that should be stored during parsing
     * @return a UserAgentParser based on the read rules
     * @throws IOException If reading the stream failed.
     * @throws ParseException
     */
    public static UserAgentParser parse(final Reader input, final Collection<BrowsCapField> fields)
            throws IOException, ParseException {
        return new UserAgentFileParser(fields).parse(input);
    }
 
    private UserAgentParser parse(final Reader input) throws ParseException {
        final List<Rule> rules = new ArrayList<>();
 
        final CsvParserSettings settings = new CsvParserSettings();
        final CsvParser csvParser = new CsvParser(settings);
        csvParser.beginParsing(input);
        Record record;
        while ((record = csvParser.parseNextRecord()) != null) {
            final Rule rule = getRule(record);
            if (rule != null) {
                rules.add(rule);
            }
        }
        return new UserAgentParserImpl(rules.toArray(new Rule[0]), myDomain, getDefaultCapabilities());
    }
 
    Capabilities getDefaultCapabilities() {
        final Map<BrowsCapField, String> result = new EnumMap<>(BrowsCapField.class);
        for (final BrowsCapField field : myFields) {
            result.put(field, UNKNOWN_BROWSCAP_VALUE);
        }
        return getCapabilities(result);
    }
 
    private Rule getRule(final Record record) throws ParseException {
        if (record.getValues().length <= 47) {
            return null;
        }
 
        // Normalize: lowercase and remove duplicate wildcards
        final String pattern = normalizePattern(record.getString(0));
        try {
            final Map<BrowsCapField, String> values = getBrowsCapFields(record);
            final Capabilities capabilities = getCapabilities(values);
            final Rule rule = createRule(pattern, capabilities);
 
            // Check reconstructing the pattern
            if (!pattern.equals(rule.getPattern())) {
                throw new ParseException("Unable to parse " + pattern);
            }
            return rule;
 
        } catch (final IllegalStateException e) {
            throw new ParseException("Unable to parse " + pattern);
        }
    }
 
    private static String normalizePattern(final String pattern) {
 
        final String lowerCase = pattern.toLowerCase();
        if (lowerCase.contains("**")) {
            return lowerCase.replaceAll("\\*+", "*");
        }
        return lowerCase;
    }
 
    private Map<BrowsCapField, String> getBrowsCapFields(final Record record) {
        final Map<BrowsCapField, String> values = new EnumMap<>(BrowsCapField.class);
        for (final BrowsCapField field : myFields) {
            values.put(field, getValue(record.getString(field.getIndex())));
        }
        return values;
    }
 
    String getValue(final String value) {
        if (value == null) {
            return UNKNOWN_BROWSCAP_VALUE;
        }
 
        final String trimmed = value.trim();
        if (trimmed.isEmpty()) {
            return UNKNOWN_BROWSCAP_VALUE;
        }
 
        final String cached = myStrings.get(trimmed);
        if (cached != null) {
            return cached;
        }
        myStrings.put(trimmed, trimmed);
        return trimmed;
    }
 
    Capabilities getCapabilities(final Map<BrowsCapField, String> values) {
 
        final CapabilitiesImpl result = new CapabilitiesImpl(myMapper.getValues(values), myMapper);
        final Capabilities fromCache = myCache.get(result);
        if (fromCache != null) {
            return fromCache;
        }
 
        myCache.put(result, result);
        return result;
    }
 
    Literal getLiteral(final String value) {
        return myUniqueLiterals.computeIfAbsent(value, myDomain::createLiteral);
    }
 
    LiteralDomain getDomain() {
        return myDomain;
    }
 
    Rule createRule(final String pattern, final Capabilities capabilities) {
 
        final List<String> parts = getParts(pattern);
        if (parts.isEmpty()) {
            throw new IllegalStateException();
        }
 
        final String first = parts.get(0);
        if (parts.size() == 1) {
            if ("*".equals(first)) {
                return getWildCardRule();
            }
            return new Rule(getLiteral(first), null, null, pattern, capabilities);
        }
 
        final LinkedList<String> suffixes = new LinkedList<>(parts);
 
        Literal prefix = null;
        if (!"*".equals(first)) {
            prefix = getLiteral(first);
            suffixes.remove(0);
        }
 
        final String last = parts.get(parts.size() - 1);
        Literal postfix = null;
        if (!"*".equals(last)) {
            postfix = getLiteral(last);
            suffixes.removeLast();
        }
        suffixes.removeAll(singleton("*"));
        final Literal[] suffixArray = new Literal[suffixes.size()];
        for (int i = 0; i < suffixArray.length; i++) {
            suffixArray[i] = getLiteral(suffixes.get(i));
        }
 
        return new Rule(prefix, suffixArray, postfix, pattern, capabilities);
    }
 
    private Rule getWildCardRule() {
        // The default match all pattern
        final Map<BrowsCapField, String> fieldValues = new EnumMap<>(BrowsCapField.class);
        for (final BrowsCapField field : myFields) {
            if (!field.isDefault()) {
                fieldValues.put(field, UNKNOWN_BROWSCAP_VALUE);
            }
        }
        final Capabilities capabilities = getCapabilities(fieldValues);
        return new Rule(null, new Literal[0], null, "*", capabilities);
    }
 
    static List<String> getParts(final String pattern) {
 
        final List<String> parts = new ArrayList<>();
 
        final StringBuilder literal = new StringBuilder();
        for (final char c : pattern.toCharArray()) {
            if (c == '*') {
                if (literal.length() != 0) {
                    parts.add(literal.toString());
                    literal.setLength(0);
                }
                parts.add(String.valueOf(c));
 
            } else {
                literal.append(c);
            }
        }
        if (literal.length() != 0) {
            parts.add(literal.toString());
            literal.setLength(0);
        }
 
        return parts;
    }
}