├── .gitignore ├── COPYING ├── COPYING.LESSER ├── LICENSE ├── README.md ├── README_MAVEN.md ├── buildfile ├── pom.xml └── src ├── main ├── java │ └── cz │ │ └── mallat │ │ └── uasparser │ │ ├── BrowserEntry.java │ │ ├── BrowserFamilyParser.java │ │ ├── CachingOnlineUpdateUASparser.java │ │ ├── DeviceEntry.java │ │ ├── MultithreadedUASparser.java │ │ ├── OnlineUpdateUASparser.java │ │ ├── OnlineUpdater.java │ │ ├── OsEntry.java │ │ ├── RobotEntry.java │ │ ├── SingleThreadedUASparser.java │ │ ├── UASparser.java │ │ ├── UserAgentInfo.java │ │ └── fileparser │ │ ├── Entry.java │ │ ├── PHPFileParser.java │ │ └── Section.java └── resources │ └── user_agent_strings.txt └── test ├── java └── cz │ └── mallat │ └── uasparser │ ├── Benchmark.java │ ├── TestOldDatabase.java │ ├── TestOnlineUpdater.java │ ├── TestParsers.java │ └── TestSuite.java └── resources └── uas-nodevice.txt.gz /.gitignore: -------------------------------------------------------------------------------- 1 | .ruby-version 2 | .rvmrc 3 | .classpath 4 | .project 5 | .settings 6 | target/ 7 | reports/ 8 | tmp/ 9 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This program is free software: you can redistribute it and/or modify 2 | it under the terms of the GNU Lesser General Public License as published by 3 | the Free Software Foundation, either version 3 of the License, or 4 | (at your option) any later version. 5 | 6 | This program is distributed in the hope that it will be useful, 7 | but WITHOUT ANY WARRANTY; without even the implied warranty of 8 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 9 | GNU General Public License for more details. 10 | 11 | You should have received a copy of the GNU Lesser General Public License 12 | along with this program. If not, see . 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UASparser 2 | 3 | A fast User Agent parser library, using data from [user-agent-string.info](http://user-agent-string.info/) 4 | 5 |
6 | **NOTE:** As of December 1, 2014, the upstream User Agent database is no longer free and the old update URL is returning *bad data*. 7 | 8 | This means that the `OnlineUpdater`, `OnlineUpdateUASparser`, and `CachingOnlineUpdateUASparser` APIs will retrieve an incorrect database and **must be disabled immediately**. If you were using any of these methods, please update your code as in the example below. 9 | 10 | You may continue to use this library with the bundled UA database, as long as updating is disabled. 11 |
12 | 13 | ## Install 14 | 15 | UASparser is available via Maven Central: 16 | 17 | * Group ID: `cz.mallat.uasparser` 18 | * Artifact ID: `uasparser` 19 | 20 | View the latest [artifact info](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22uasparser%22). 21 | 22 | ## Usage 23 | 24 | Simply use UASparser or any of its subclasses like so: 25 | 26 | ``` 27 | UASparser parser = new UASparser(OnlineUpdater.getVendoredInputStream()); 28 | UserAgentInfo info = parser.parse("Mozilla/4.0 (compatible; MSIE 7.0; 29 | Windows NT 5.1; )"); 30 | ``` 31 | 32 | This will create a new parser and initialize it with a bundled copy of the database. 33 | 34 | In addition, there are a few different parser classes available: 35 | 36 | * ``UASparser`` - Default parser, thread-safe 37 | * ``MultithreadedUASparser`` - A faster variant of UASparser, uses a bit more memory 38 | * ``SingleThreadedUASparser`` - Non-threadsafe variant, ideal for Hadoop and similar use cases 39 | * ``BrowserFamilyParser`` - UASparser subclass which _only_ returns the browser family string 40 | 41 | ## Building 42 | 43 | Building requires [Apache buildr](http://buildr.apache.org/): 44 | 45 | ``` 46 | $ [sudo] gem install buildr 47 | ``` 48 | 49 | To build UASparser: 50 | 51 | ``` 52 | $ git clone https://github.com/chetan/UASparser.git 53 | $ cd UASparser 54 | $ buildr package 55 | ``` 56 | 57 | Binaries will be placed in `target`. 58 | 59 | ## Dependencies 60 | 61 | * [JRegex](http://jregex.sourceforge.net/) 62 | 63 | 64 | ## Changelog 65 | 66 | #### 0.6.2 - 2014-12-03 67 | 68 | * Disabled online updates (for now) 69 | 70 | #### 0.6.1 - 2014-09-09 71 | 72 | * Fixed device detection logic (issue #12, #13) 73 | 74 | #### n/a - 2013-11-16 75 | 76 | * Now available via Maven Central 77 | 78 | #### 0.6.0 - 2013-10-08 79 | 80 | * added support for the [device] and [device_reg] sections 81 | 82 | #### 0.5.0 - 2013-05-29 83 | 84 | * Handle version API errors (issue #3) 85 | * Defer initial update on startup (don't block) 86 | * Apply jitter after every update 87 | 88 | #### 0.4.1 - 2013-05-21 89 | 90 | * Added UserAgentInfo#getBrowserVersionInfo() method 91 | 92 | * Documented all UserAgentInfo reader methods 93 | 94 | #### 0.4 - 2012-11-08 95 | 96 | * Added a new, fast, thread-safe MultithreadedUASparser (thanks to Michael Remme) 97 | 98 | * New OnlineUpdater class replaces the old OnlineUpdateUASparser and CachingOnlineUpdateUASparser classes which are now deprecated 99 | 100 | * OnlineUpdater will fallback to a vendored copy if no cached version exists and update fails 101 | 102 | * Minor bugfixes 103 | 104 | ## License 105 | 106 | LGPL. See LICENSE file for details. 107 | -------------------------------------------------------------------------------- /README_MAVEN.md: -------------------------------------------------------------------------------- 1 | 2 | 1. Increment version number in `pom.xml` and `buildfile` 3 | 1. Build, sign and upload to nexus staging (commands below) 4 | 1. Login to nexus at https://oss.sonatype.org/ 5 | 1. Click 'Staging Repositories' from left menu 6 | 1. Search for 'uasparser' 7 | 1. "Close" repository 8 | 1. "Release" repository 9 | 10 | ```bash 11 | # REQUIRES JDK 1.7 12 | 13 | buildr test=no clean package 14 | export VERSION="0.6.1" 15 | cp -a pom.xml target/uasparser-$VERSION.pom 16 | mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=target/uasparser-$VERSION.pom -Dfile=target/uasparser-$VERSION.jar 17 | mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=target/uasparser-$VERSION.pom -Dfile=target/uasparser-$VERSION-sources.jar -Dclassifier=sources 18 | mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=target/uasparser-$VERSION.pom -Dfile=target/uasparser-$VERSION-javadoc.jar -Dclassifier=javadoc 19 | ``` 20 | -------------------------------------------------------------------------------- /buildfile: -------------------------------------------------------------------------------- 1 | 2 | repositories.remote << 'http://www.ibiblio.org/maven2' 3 | repositories.remote << "http://mirrors.ibiblio.org/pub/mirrors/maven2" 4 | 5 | class Buildr::Artifact 6 | def <=>(other) 7 | self.id <=> other.id 8 | end 9 | end 10 | 11 | def add_artifacts(*args) 12 | artifacts( [ args ].flatten.sort.uniq ).sort 13 | end 14 | 15 | JARS = add_artifacts('net.sourceforge.jregex:jregex:jar:1.2_01') 16 | TEST_JARS = JARS + add_artifacts('commons-lang:commons-lang:jar:2.5') 17 | 18 | desc 'UASparser' 19 | define 'UASparser' do 20 | project.group = 'cz.mallat.uasparser' 21 | project.version = '0.6.2' 22 | 23 | compile.with JARS 24 | test.with TEST_JARS 25 | 26 | package :jar, :id => 'uasparser' 27 | package :sources, :id => 'uasparser' 28 | package :javadoc, :id => 'uasparser' 29 | 30 | package(:tgz).path("#{id}-#{version}").tap do |path| 31 | path.include "pom.xml" 32 | path.include "README.md" 33 | path.include "LICENSE" 34 | path.include "COPYING" 35 | path.include "COPYING.LESSER" 36 | path.include package(:jar), package(:sources) 37 | path.path("lib").include JARS 38 | end 39 | 40 | end 41 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | cz.mallat.uasparser 8 | uasparser 9 | 10 | 0.6.2 11 | jar 12 | 13 | UASparser 14 | 15 | User Agent parser library for use with the database provided by http://user-agent-string.info/ 16 | 17 | https://github.com/chetan/UASparser 18 | 19 | 20 | 21 | GNU Lesser General Public License, v3 22 | http://www.gnu.org/licenses/lgpl-3.0.txt 23 | repo 24 | 25 | 26 | 27 | 28 | git@github.com:chetan/UASparser.git 29 | scm:git:git@github.com:chetan/UASparser.git 30 | scm:git:git@github.com:chetan/UASparser.git 31 | HEAD 32 | 33 | 34 | 35 | 36 | sonatype-nexus-snapshots 37 | Sonatype Nexus snapshot repository 38 | https://oss.sonatype.org/content/repositories/snapshots 39 | 40 | 41 | sonatype-nexus-staging 42 | Sonatype Nexus release repository 43 | https://oss.sonatype.org/service/local/staging/deploy/maven2 44 | 45 | 46 | 47 | 48 | UTF-8 49 | 50 | 51 | 52 | 53 | chetan 54 | Chetan Sarva 55 | csarva@pixelcop.net 56 | http://chetanislazy.com/blog/ 57 | 58 | 59 | oli 60 | Oli Kurt 61 | 62 | 63 | fsiegrist 64 | Felix Siegrist 65 | felix.siegrist@inventage.com 66 | http://www.inventage.com 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | ${project.basedir} 76 | 77 | README* 78 | LICENSE* 79 | COPYING* 80 | 81 | 82 | 83 | src/main/resources 84 | 85 | 86 | 87 | 88 | 89 | 90 | org.apache.maven.plugins 91 | maven-compiler-plugin 92 | 3.1 93 | 94 | 1.6 95 | 1.6 96 | UTF-8 97 | 98 | 99 | 100 | 101 | org.apache.maven.plugins 102 | maven-jar-plugin 103 | 2.4 104 | 105 | 106 | 107 | true 108 | true 109 | 110 | 111 | 112 | 113 | 114 | 115 | org.apache.maven.plugins 116 | maven-source-plugin 117 | 2.2.1 118 | 119 | 120 | attach-sources 121 | verify 122 | 123 | jar-no-fork 124 | 125 | 126 | 127 | 128 | 129 | 130 | org.apache.maven.plugins 131 | maven-javadoc-plugin 132 | 2.9.1 133 | 134 | 135 | attach-javadoc 136 | verify 137 | 138 | jar 139 | 140 | 141 | 142 | 143 | 144 | 145 | org.apache.maven.plugins 146 | maven-deploy-plugin 147 | 2.8.1 148 | 149 | 150 | 151 | 152 | org.apache.maven.plugins 153 | maven-release-plugin 154 | 2.4.2 155 | 156 | forked-path 157 | 158 | 159 | 160 | 161 | 162 | org.apache.maven.plugins 163 | maven-surefire-plugin 164 | 2.16 165 | 166 | ${skipTests} 167 | 168 | TestSuite.java 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | release-sign-artifacts 181 | 182 | 183 | performRelease 184 | true 185 | 186 | 187 | 188 | 189 | 190 | org.apache.maven.plugins 191 | maven-gpg-plugin 192 | 1.4 193 | 194 | 195 | sign-artifacts 196 | verify 197 | 198 | sign 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | net.sourceforge.jregex 212 | jregex 213 | 1.2_01 214 | compile 215 | 216 | 217 | junit 218 | junit 219 | 4.13.1 220 | test 221 | 222 | 223 | commons-lang 224 | commons-lang 225 | 2.5 226 | test 227 | 228 | 229 | 230 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/BrowserEntry.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | 6 | /** 7 | * JavaBean that holds the data from the [browser] section in the data file 8 | * 9 | * @author oli 10 | * 11 | */ 12 | class BrowserEntry { 13 | 14 | private Long type; 15 | private String family; 16 | @Deprecated 17 | private String name; 18 | private String url; 19 | private String company; 20 | private String companyUrl; 21 | private String ico; 22 | private String infoUrl; 23 | 24 | public BrowserEntry(List data) { 25 | Iterator it = data.iterator(); 26 | this.type = Long.parseLong(it.next()); 27 | this.family = it.next(); 28 | this.url = it.next(); 29 | this.company = it.next(); 30 | this.companyUrl = it.next(); 31 | this.ico = it.next(); 32 | this.infoUrl = it.next(); 33 | // this.name stays empty, will be filled with family + version 34 | } 35 | 36 | public String getFamily() { 37 | return family; 38 | } 39 | 40 | public void setFamily(String family) { 41 | this.family = family; 42 | } 43 | 44 | public Long getType() { 45 | return type; 46 | } 47 | 48 | public void setType(Long type) { 49 | this.type = type; 50 | } 51 | 52 | /** 53 | * This field is never used 54 | * @return 55 | */ 56 | @Deprecated 57 | public String getName() { 58 | return name; 59 | } 60 | 61 | /** 62 | * This field is never used 63 | * @param name 64 | */ 65 | @Deprecated 66 | public void setName(String name) { 67 | this.name = name; 68 | } 69 | 70 | public String getUrl() { 71 | return url; 72 | } 73 | 74 | public void setUrl(String url) { 75 | this.url = url; 76 | } 77 | 78 | public String getCompany() { 79 | return company; 80 | } 81 | 82 | public void setCompany(String company) { 83 | this.company = company; 84 | } 85 | 86 | public String getCompanyUrl() { 87 | return companyUrl; 88 | } 89 | 90 | public void setCompanyUrl(String companyUrl) { 91 | this.companyUrl = companyUrl; 92 | } 93 | 94 | public String getIco() { 95 | return ico; 96 | } 97 | 98 | public void setIco(String ico) { 99 | this.ico = ico; 100 | } 101 | 102 | public String getInfoUrl() { 103 | return infoUrl; 104 | } 105 | 106 | public void setInfoUrl(String infoUrl) { 107 | this.infoUrl = infoUrl; 108 | } 109 | 110 | @Override 111 | public String toString() { 112 | return "Browser: \n" + 113 | " Family: " + family + "\n" + 114 | " Type: " + type + "\n" + 115 | " URL: " + url + "\n" + 116 | " Company: " + company + "\n" + 117 | " Company URL: " + companyUrl + "\n" + 118 | " ICO: " + ico + "\n" + 119 | " Info URL: " + infoUrl; 120 | } 121 | 122 | } -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/BrowserFamilyParser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.HashMap; 6 | import java.util.LinkedHashMap; 7 | import java.util.Map; 8 | 9 | import jregex.Matcher; 10 | import jregex.Pattern; 11 | 12 | /** 13 | * A {@link UASparser} which is only concerned with returning the browser 14 | * family string as quickly as possible. Uses the JRegex library for further 15 | * speedups. 16 | * 17 | * You can optionally ignore unwanted browsers by passing in a list of 18 | * browsers which you are interested in. 19 | * 20 | * @author chetan 21 | * 22 | */ 23 | public class BrowserFamilyParser extends UASparser { 24 | 25 | protected Map compiledBrowserRegMap; 26 | protected Map compiledOsRegMap; 27 | 28 | public static final String UNKNOWN = "unknown"; 29 | 30 | protected Map browsers; 31 | 32 | public BrowserFamilyParser(InputStream inputStreamToDefinitionFile) throws IOException { 33 | super(inputStreamToDefinitionFile); 34 | } 35 | 36 | public BrowserFamilyParser(InputStream inputStreamToDefinitionFile, String[] browsers) throws IOException { 37 | super(inputStreamToDefinitionFile); 38 | setBrowsers(browsers); 39 | } 40 | 41 | public BrowserFamilyParser(String localDefinitionFilename) throws IOException { 42 | super(localDefinitionFilename); 43 | } 44 | 45 | /** 46 | * Creates a parser which can directly return the Browser Family string 47 | * 48 | * @param localDefinitionFilename 49 | * @param browsers 50 | * Only the browsers included in this list will be tested for 51 | * @throws IOException 52 | */ 53 | public BrowserFamilyParser(String localDefinitionFilename, String[] browsers) 54 | throws IOException { 55 | super(localDefinitionFilename); 56 | setBrowsers(browsers); 57 | } 58 | 59 | private void setBrowsers(String[] browsers) { 60 | this.browsers = new HashMap(); 61 | for (String b : browsers) { 62 | this.browsers.put(b, 1); 63 | } 64 | preCompileRegExes(); // recompile 65 | } 66 | 67 | public String parseBrowserFamily(String userAgent) { 68 | for (Map.Entry entry : compiledBrowserRegMap.entrySet()) { 69 | Matcher matcher = entry.getKey().matcher(userAgent); 70 | if (matcher.find()) { 71 | Long idBrowser = entry.getValue(); 72 | BrowserEntry be = browserMap.get(idBrowser); 73 | if (be != null) { 74 | return be.getFamily(); 75 | } 76 | return UNKNOWN; 77 | } 78 | } 79 | return UNKNOWN; 80 | } 81 | 82 | @Override 83 | protected void preCompileRegExes() { 84 | preCompileBrowserRegMap(); 85 | preCompileOsRegMap(); 86 | } 87 | 88 | /** 89 | * Precompile browser regexes 90 | */ 91 | protected void preCompileBrowserRegMap() { 92 | compiledBrowserRegMap = new LinkedHashMap(browserRegMap.size()); 93 | for (Map.Entry entry : browserRegMap.entrySet()) { 94 | if (browsers != null 95 | && !browsers.containsKey(browserMap.get(entry.getValue()).getFamily())) { 96 | continue; 97 | } 98 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 99 | compiledBrowserRegMap.put(pattern, entry.getValue()); 100 | } 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/CachingOnlineUpdateUASparser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.net.URL; 10 | import java.util.Properties; 11 | 12 | /** 13 | * Adds a cache to the OnlineUpdateUAParser 14 | * 15 | * @author oli 16 | */ 17 | @Deprecated 18 | public class CachingOnlineUpdateUASparser extends OnlineUpdateUASparser { 19 | 20 | private static final String CACHE_FILENAME = "userAgentString.txt"; 21 | private static final String PROPERTIES_FILENAME = "userAgentString.properties"; 22 | 23 | private final Properties prop; 24 | private final String cacheDir; 25 | 26 | /** 27 | * The cache files are put into the java tmp directory 28 | * 29 | * @throws IOException 30 | */ 31 | public CachingOnlineUpdateUASparser() throws IOException { 32 | this(null); 33 | } 34 | 35 | /** 36 | * The cache files are put into the cacheDir 37 | * 38 | * @param cacheDir 39 | * @throws IOException 40 | */ 41 | public CachingOnlineUpdateUASparser(String cacheDir) throws IOException { 42 | this.cacheDir = cacheDir; 43 | this.prop = new Properties(); 44 | 45 | if (cacheDir != null && !(new File(cacheDir).canWrite())) { 46 | throw new RuntimeException("Can't write to cacheDir: " + cacheDir); 47 | } 48 | 49 | File propFile = getPropertiesFile(); 50 | if (false && propFile.exists()) { 51 | FileInputStream fis = new FileInputStream(getPropertiesFile()); 52 | try { 53 | prop.load(fis); 54 | lastUpdateCheck = Long.parseLong(prop.getProperty("lastUpdateCheck")); 55 | currentVersion = prop.getProperty("currentVersion"); 56 | } finally { 57 | fis.close(); 58 | } 59 | 60 | try { 61 | loadDataFromFile(getCacheFile()); 62 | } catch (IOException e) { 63 | e.printStackTrace(); 64 | // reset the status variables, so we'll load the data file again 65 | lastUpdateCheck = 0; 66 | currentVersion = ""; 67 | } 68 | } 69 | } 70 | 71 | /** 72 | * This implementation uses a local properties file to keep the lastUpdate time and the local data file version 73 | */ 74 | @Override 75 | protected synchronized void checkDataMaps() throws IOException { 76 | if (true) { 77 | // DISABLED - upstream db is no longer free and updates are impossible 78 | System.err.println("WARNING! Online updates have been disabled; see https://github.com/chetan/UASparser"); 79 | return; 80 | } 81 | if (lastUpdateCheck == 0 || lastUpdateCheck < System.currentTimeMillis() - UPDATE_INTERVAL) { 82 | String versionOnServer = getVersionFromServer(); 83 | if (currentVersion == null || versionOnServer.compareTo(currentVersion) > 0) { 84 | loadDataFromInternetAndSave(); 85 | loadDataFromFile(getCacheFile()); 86 | currentVersion = versionOnServer; 87 | prop.setProperty("currentVersion", currentVersion); 88 | } 89 | lastUpdateCheck = System.currentTimeMillis(); 90 | prop.setProperty("lastUpdateCheck", Long.toString(lastUpdateCheck)); 91 | saveProperties(prop); 92 | } 93 | } 94 | 95 | private File getCacheFile() { 96 | return new File(cacheDir == null ? System.getProperty("java.io.tmpdir") : cacheDir, CACHE_FILENAME); 97 | } 98 | 99 | private File getPropertiesFile() { 100 | return new File(cacheDir == null ? System.getProperty("java.io.tmpdir") : cacheDir, PROPERTIES_FILENAME); 101 | } 102 | 103 | /** 104 | * loads the data file from the server and saves it to the local file system 105 | * 106 | * @throws IOException 107 | */ 108 | private void loadDataFromInternetAndSave() throws IOException { 109 | InputStream is = null; 110 | FileOutputStream fos = null; 111 | try { 112 | URL url = new URL(DATA_RETRIVE_URL); 113 | is = url.openStream(); 114 | fos = new FileOutputStream(getCacheFile()); 115 | byte[] buff = new byte[1024 * 8]; 116 | int len = 0; 117 | while ((len = is.read(buff)) != -1) { 118 | fos.write(buff, 0, len); 119 | } 120 | } finally { 121 | if (is != null) { 122 | is.close(); 123 | } 124 | if (fos != null) { 125 | fos.close(); 126 | } 127 | } 128 | 129 | } 130 | 131 | /** 132 | * Saves the properties file to the local filesystem 133 | * 134 | * @param prop 135 | * @throws FileNotFoundException 136 | * @throws IOException 137 | */ 138 | private void saveProperties(Properties prop) throws FileNotFoundException, IOException { 139 | FileOutputStream fos = new FileOutputStream(getPropertiesFile()); 140 | try { 141 | prop.store(fos, null); 142 | } finally { 143 | fos.close(); 144 | } 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/DeviceEntry.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | 6 | /** 7 | * Java bean that holds the data from the [device] section in the data file. 8 | * 9 | * @author Felix Siegrist, Inventage AG 10 | * 11 | */ 12 | class DeviceEntry { 13 | 14 | private String type; 15 | private String ico; 16 | private String infoUrl; 17 | 18 | public DeviceEntry(List data) { 19 | Iterator it = data.iterator(); 20 | this.type = it.next(); 21 | this.ico = it.next(); 22 | this.infoUrl = it.next(); 23 | } 24 | 25 | public String getType() { 26 | return type; 27 | } 28 | 29 | public void setType(String type) { 30 | this.type = type; 31 | } 32 | 33 | public String getIco() { 34 | return ico; 35 | } 36 | 37 | public void setIco(String ico) { 38 | this.ico = ico; 39 | } 40 | 41 | public String getInfoUrl() { 42 | return infoUrl; 43 | } 44 | 45 | public void setInfoUrl(String infoUrl) { 46 | this.infoUrl = infoUrl; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "Device: \n" + 52 | " Type: " + type + "\n" + 53 | " ICO: " + ico + "\n" + 54 | " Info URL: " + infoUrl; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/MultithreadedUASparser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | import java.util.Set; 8 | 9 | import jregex.Matcher; 10 | 11 | /** 12 | * This parser creates a Matcher set per-Thread using a ThreadLocal. It is faster than 13 | * the standard {@link UASparser} at the expense of greater memory usage. 14 | * 15 | * Copyright: Copyright (c) 09.10.2012
16 | * Company: Braintags GmbH
17 | * 18 | * @author mremme 19 | */ 20 | public class MultithreadedUASparser extends SingleThreadedUASparser { 21 | 22 | private ThreadLocal> compiledBrowserMatcherMapT; 23 | private ThreadLocal> compiledOsMatcherMapT; 24 | private ThreadLocal> compiledDeviceMatcherMapT; 25 | 26 | public MultithreadedUASparser(InputStream inputStreamToDefinitionFile) throws IOException { 27 | super(inputStreamToDefinitionFile); 28 | } 29 | 30 | public MultithreadedUASparser(String localDefinitionFilename) throws IOException { 31 | super(localDefinitionFilename); 32 | } 33 | 34 | @Override 35 | protected void preCompileBrowserRegMap() { 36 | compiledBrowserMatcherMapT = new ThreadLocal>() { 37 | @Override 38 | protected Map initialValue() { 39 | return preCompileBrowserMatcherMap(); 40 | } 41 | }; 42 | } 43 | 44 | @Override 45 | protected void preCompileOsRegMap() { 46 | compiledOsMatcherMapT = new ThreadLocal>() { 47 | @Override 48 | protected Map initialValue() { 49 | return preCompileOsMatcherMap(); 50 | } 51 | }; 52 | } 53 | 54 | @Override 55 | protected void preCompileDeviceRegMap() { 56 | compiledDeviceMatcherMapT = new ThreadLocal>() { 57 | @Override 58 | protected Map initialValue() { 59 | return preCompileDeviceMatcherMap(); 60 | } 61 | }; 62 | } 63 | 64 | @Override 65 | protected Set> getOsMatcherSet() { 66 | return compiledOsMatcherMapT.get().entrySet(); 67 | } 68 | 69 | @Override 70 | protected Set> getBrowserMatcherSet() { 71 | return compiledBrowserMatcherMapT.get().entrySet(); 72 | } 73 | 74 | @Override 75 | protected Set> getDeviceMatcherSet() { 76 | Map map = compiledDeviceMatcherMapT.get(); 77 | if (map == null) { 78 | return null; 79 | } 80 | return map.entrySet(); 81 | } 82 | 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/OnlineUpdateUASparser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.net.ConnectException; 6 | import java.net.URL; 7 | 8 | import cz.mallat.uasparser.fileparser.PHPFileParser; 9 | 10 | /** 11 | * The parser will download the definition file from the internet 12 | * 13 | * @author oli 14 | */ 15 | @Deprecated 16 | public class OnlineUpdateUASparser extends UASparser { 17 | 18 | protected static final String DATA_RETRIVE_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini"; 19 | protected static final String VERSION_CHECK_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini&ver=y"; 20 | protected static final long UPDATE_INTERVAL = 1000 * 60 * 60 * 24; // 1 day 21 | 22 | protected long lastUpdateCheck; 23 | protected String currentVersion; 24 | 25 | /** 26 | * Since we've online access to the data file, we check every day for an update 27 | */ 28 | @Override 29 | protected synchronized void checkDataMaps() throws IOException { 30 | if (true) { 31 | // DISABLED - upstream db is no longer free and updates are impossible 32 | System.err.println("WARNING! Online updates have been disabled; see https://github.com/chetan/UASparser"); 33 | return; 34 | } 35 | if (lastUpdateCheck == 0 || lastUpdateCheck < System.currentTimeMillis() - UPDATE_INTERVAL) { 36 | String versionOnServer = getVersionFromServer(); 37 | if (currentVersion == null || versionOnServer.compareTo(currentVersion) > 0) { 38 | loadDataFromInternet(); 39 | currentVersion = versionOnServer; 40 | } 41 | lastUpdateCheck = System.currentTimeMillis(); 42 | } 43 | } 44 | 45 | /** 46 | * Loads the data file from user-agent-string.info 47 | * 48 | * @throws IOException 49 | */ 50 | private void loadDataFromInternet() throws IOException { 51 | URL url = new URL(DATA_RETRIVE_URL); 52 | InputStream is = url.openStream(); 53 | try { 54 | PHPFileParser fp = new PHPFileParser(is); 55 | createInternalDataStructure(fp.getSections()); 56 | } finally { 57 | is.close(); 58 | } 59 | } 60 | 61 | /** 62 | * Gets the current version from user-agent-string.info 63 | * 64 | * @return 65 | * @throws IOException 66 | */ 67 | protected String getVersionFromServer() throws IOException { 68 | URL url = new URL(VERSION_CHECK_URL); 69 | InputStream is = null; 70 | try{ 71 | is = url.openStream(); 72 | } catch (ConnectException e) { 73 | return "0"; 74 | } 75 | 76 | try { 77 | byte[] buff = new byte[4048]; 78 | int len = is.read(buff); 79 | return new String(buff, 0, len); 80 | } finally { 81 | is.close(); 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/OnlineUpdater.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.FileReader; 9 | import java.io.FileWriter; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.io.OutputStream; 14 | import java.net.URL; 15 | import java.util.List; 16 | import java.util.Random; 17 | import java.util.concurrent.TimeUnit; 18 | 19 | import cz.mallat.uasparser.fileparser.PHPFileParser; 20 | import cz.mallat.uasparser.fileparser.Section; 21 | 22 | /** 23 | * An updater which runs in a separate background thread and will update once per day. 24 | * 25 | *

The updated UA strings are cached on disk. If no cached copy is found on start, 26 | * one will be fetched immediately. If this initial update fails, it will fallback 27 | * to an included copy.

28 | * 29 | * @author chetan 30 | * 31 | */ 32 | public class OnlineUpdater extends Thread { 33 | 34 | public static final String CACHE_FILENAME = "user_agent_strings.txt"; 35 | public static final String PROPERTIES_FILENAME = "user_agent_strings-version.txt"; 36 | 37 | protected static final String DATA_RETRIVE_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini"; 38 | protected static final String VERSION_CHECK_URL = "http://user-agent-string.info/rpc/get_data.php?key=free&format=ini&ver=y"; 39 | 40 | protected final long updateInterval; 41 | protected int currentVersion; 42 | 43 | protected UASparser parser; 44 | 45 | protected File cacheFile; 46 | protected File propsFile; 47 | 48 | /** 49 | * Create a new updater with the default interval of 1 day 50 | * 51 | * @param parser Parser instance to update 52 | */ 53 | public OnlineUpdater(UASparser parser) { 54 | this(parser, null, 1, TimeUnit.DAYS); 55 | } 56 | 57 | /** 58 | * Create a new updater 59 | * 60 | * @param parser Parser instance to update 61 | * @param cacheDir directory where file should be cached. If null, uses system temp dir 62 | * @param interval number of intervals for the given units 63 | * @param units unit type 64 | */ 65 | public OnlineUpdater(UASparser parser, String cacheDir, long interval, TimeUnit units) { 66 | this.parser = parser; 67 | 68 | if (cacheDir == null) { 69 | cacheDir = System.getProperty("java.io.tmpdir"); 70 | } 71 | if (!new File(cacheDir).canWrite()) { 72 | throw new RuntimeException("Can't write to cacheDir: " + cacheDir); 73 | } 74 | this.cacheFile = new File(cacheDir, CACHE_FILENAME); 75 | this.propsFile = new File(cacheDir, PROPERTIES_FILENAME); 76 | this.currentVersion = 0; 77 | 78 | updateInterval = units.toMillis(interval); 79 | 80 | init(); 81 | 82 | if (true) { 83 | // DISABLED - upstream db is no longer free and updates are impossible 84 | System.err.println("WARNING! Online updates have been disabled; see https://github.com/chetan/UASparser"); 85 | return; 86 | } 87 | 88 | start(); 89 | } 90 | 91 | /** 92 | * Initialize the parser with cached data. Falls back to vendored copy if no cache is available. 93 | */ 94 | public void init() { 95 | 96 | if (false && this.cacheFile.exists()) { 97 | // DISABLED - upstream db is no longer free and updates are impossible and 98 | // cached db is probably bad by now, don't use it. 99 | if (true) { return; } 100 | try { 101 | parser.loadDataFromFile(cacheFile); 102 | this.currentVersion = 103 | Integer.parseInt(new BufferedReader(new FileReader(propsFile)).readLine()); 104 | return; 105 | } catch (Throwable t) { 106 | this.currentVersion = 0; 107 | } 108 | } 109 | 110 | try { 111 | // fall back to vendored copy so we don't block on startup 112 | parser.loadDataFromFile(getVendoredInputStream()); 113 | } catch (IOException e) { 114 | } 115 | } 116 | 117 | /** 118 | * Retrieve an {@link InputStream} to the vendored copy of the UA strings file. 119 | * @return {@link InputStream} 120 | */ 121 | public static InputStream getVendoredInputStream() { 122 | return OnlineUpdater.class.getClassLoader().getResourceAsStream(CACHE_FILENAME); 123 | } 124 | 125 | /** 126 | * Fetch latest UA file if a newer one is available 127 | * 128 | * @return boolean True if parser was updated. 129 | */ 130 | public boolean update() { 131 | try { 132 | int versionOnServer = getVersionFromServer(); 133 | if (currentVersion == 0 || versionOnServer > currentVersion) { 134 | parser.createInternalDataStructure(loadDataFromInternet()); 135 | 136 | // if reached this far then we loaded it correctly, store new version # 137 | currentVersion = versionOnServer; 138 | FileWriter writer = new FileWriter(propsFile); 139 | writer.write(Integer.toString(currentVersion)); 140 | writer.close(); 141 | 142 | return true; 143 | } 144 | } catch (Throwable t) { 145 | } 146 | return false; 147 | } 148 | 149 | /** 150 | * Update loop 151 | */ 152 | @Override 153 | public void run() { 154 | while (true) { 155 | update(); 156 | try { 157 | // add up to 300sec of jitter to interval 158 | Thread.sleep(updateInterval + (new Random().nextInt(300) * 1000)); 159 | } catch (InterruptedException e) { 160 | return; 161 | } 162 | } 163 | } 164 | 165 | /** 166 | * Loads the data file from user-agent-string.info and caches it on disk 167 | * @return 168 | * 169 | * @throws IOException 170 | */ 171 | protected List
loadDataFromInternet() throws IOException { 172 | 173 | File tmpFile = File.createTempFile("uas", ".txt"); 174 | 175 | try { 176 | 177 | // Download file to temp location 178 | BufferedReader reader = null; 179 | FileWriter writer = null; 180 | try { 181 | URL url = new URL(DATA_RETRIVE_URL); 182 | reader = new BufferedReader(new InputStreamReader(url.openStream())); 183 | writer = new FileWriter(tmpFile); 184 | String line = null; 185 | while ((line = reader.readLine()) != null) { 186 | writer.write(line); 187 | writer.write(System.getProperty("line.separator")); 188 | } 189 | 190 | } finally { 191 | if (reader != null) { 192 | reader.close(); 193 | } 194 | if (writer != null) { 195 | writer.close(); 196 | } 197 | } 198 | 199 | // Try to parse it 200 | try { 201 | PHPFileParser fp = new PHPFileParser(tmpFile); 202 | List
sections = fp.getSections(); 203 | 204 | // now that we've finished parsing, we can save the temp copy 205 | if (cacheFile.exists()) { 206 | cacheFile.delete(); 207 | } 208 | 209 | if (!tmpFile.renameTo(cacheFile)) { 210 | // was across filesystems or target exists, or something else. 211 | // Try other another way 212 | // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4017593 213 | copyFile(tmpFile, cacheFile); 214 | } 215 | 216 | return sections; 217 | 218 | } catch (Throwable t) { 219 | if (t instanceof IOException) { 220 | throw (IOException) t; 221 | } 222 | throw new IOException(t); 223 | } 224 | 225 | } finally { 226 | if (tmpFile.compareTo(cacheFile) != 0) { 227 | tmpFile.delete(); 228 | } 229 | } 230 | } 231 | 232 | /** 233 | * Copy source file to destination 234 | * 235 | * @param src 236 | * @param dest 237 | * 238 | * @throws FileNotFoundException 239 | * @throws IOException 240 | */ 241 | protected void copyFile(File src, File dest) throws FileNotFoundException, IOException { 242 | InputStream inStream = new FileInputStream(src); 243 | OutputStream outStream = new FileOutputStream(dest); 244 | 245 | byte[] buffer = new byte[4096]; 246 | 247 | int length; 248 | while ((length = inStream.read(buffer)) > 0) { 249 | outStream.write(buffer, 0, length); 250 | } 251 | 252 | inStream.close(); 253 | outStream.close(); 254 | } 255 | 256 | /** 257 | * Gets the current version from user-agent-string.info 258 | * 259 | * @return long version number (e.g., 2013012301) 260 | * @throws IOException 261 | * @throws {@link NumberFormatException} 262 | */ 263 | protected int getVersionFromServer() throws IOException { 264 | URL url = new URL(VERSION_CHECK_URL); 265 | BufferedReader reader = null; 266 | try { 267 | reader = new BufferedReader(new InputStreamReader(url.openStream())); 268 | String ver = reader.readLine(); 269 | if (ver == null || ver.isEmpty()) { 270 | throw new IOException("Failed to read version number"); 271 | } 272 | return Integer.parseInt(ver.replace("-", "")); 273 | 274 | } finally { 275 | if (reader != null) { 276 | reader.close(); 277 | } 278 | } 279 | } 280 | 281 | } 282 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/OsEntry.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | 6 | /** 7 | * JavaBean that holds the data from the [os] section in the data file 8 | * 9 | * @author oli 10 | * 11 | */ 12 | class OsEntry { 13 | 14 | private String family; 15 | private String name; 16 | private String url; 17 | private String company; 18 | private String companyUrl; 19 | private String ico; 20 | 21 | public OsEntry(List data) { 22 | Iterator it = data.iterator(); 23 | this.family = it.next(); 24 | this.name = it.next(); 25 | this.url = it.next(); 26 | this.company = it.next(); 27 | this.companyUrl = it.next(); 28 | this.ico = it.next(); 29 | } 30 | 31 | public String getFamily() { 32 | return family; 33 | } 34 | 35 | public void setFamily(String family) { 36 | this.family = family; 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public void setName(String name) { 44 | this.name = name; 45 | } 46 | 47 | public String getUrl() { 48 | return url; 49 | } 50 | 51 | public void setUrl(String url) { 52 | this.url = url; 53 | } 54 | 55 | public String getCompany() { 56 | return company; 57 | } 58 | 59 | public void setCompany(String company) { 60 | this.company = company; 61 | } 62 | 63 | public String getCompanyUrl() { 64 | return companyUrl; 65 | } 66 | 67 | public void setCompanyUrl(String companyUrl) { 68 | this.companyUrl = companyUrl; 69 | } 70 | 71 | public String getIco() { 72 | return ico; 73 | } 74 | 75 | public void setIco(String ico) { 76 | this.ico = ico; 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return "Operating System: \n" + 82 | " Family: " + family + "\n" + 83 | " Name: " + name + "\n" + 84 | " URL: " + url + "\n" + 85 | " Company: " + company + "\n" + 86 | " Company URL: " + companyUrl + "\n" + 87 | " ICO: " + ico; 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/RobotEntry.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | 6 | /** 7 | * JavaBean that holds the data from the [robots] section in the data file 8 | * 9 | * @author oli 10 | * 11 | */ 12 | class RobotEntry { 13 | 14 | private String userAgentString; 15 | private String family; 16 | private String name; 17 | private String url; 18 | private String company; 19 | private String companyUrl; 20 | private String ico; 21 | private String osId; 22 | private String infoUrl; 23 | 24 | public RobotEntry(List data) { 25 | Iterator it = data.iterator(); 26 | this.userAgentString = it.next(); 27 | this.family = it.next(); 28 | this.name = it.next(); 29 | this.url = it.next(); 30 | this.company = it.next(); 31 | this.companyUrl = it.next(); 32 | this.ico = it.next(); 33 | this.osId = it.next(); 34 | this.infoUrl = it.next(); 35 | } 36 | 37 | public String getUserAgentString() { 38 | return userAgentString; 39 | } 40 | 41 | public void setUserAgentString(String userAgentString) { 42 | this.userAgentString = userAgentString; 43 | } 44 | 45 | public String getFamily() { 46 | return family; 47 | } 48 | 49 | public void setFamily(String family) { 50 | this.family = family; 51 | } 52 | 53 | public String getName() { 54 | return name; 55 | } 56 | 57 | public void setName(String name) { 58 | this.name = name; 59 | } 60 | 61 | public String getUrl() { 62 | return url; 63 | } 64 | 65 | public void setUrl(String url) { 66 | this.url = url; 67 | } 68 | 69 | public String getCompany() { 70 | return company; 71 | } 72 | 73 | public void setCompany(String company) { 74 | this.company = company; 75 | } 76 | 77 | public String getCompanyUrl() { 78 | return companyUrl; 79 | } 80 | 81 | public void setCompanyUrl(String companyUrl) { 82 | this.companyUrl = companyUrl; 83 | } 84 | 85 | public String getIco() { 86 | return ico; 87 | } 88 | 89 | public void setIco(String ico) { 90 | this.ico = ico; 91 | } 92 | 93 | public String getOsId() { 94 | return osId; 95 | } 96 | 97 | public void setOsId(String osId) { 98 | this.osId = osId; 99 | } 100 | 101 | public String getInfoUrl() { 102 | return infoUrl; 103 | } 104 | 105 | public void setInfoUrl(String infoUrl) { 106 | this.infoUrl = infoUrl; 107 | } 108 | 109 | @Override 110 | public String toString() { 111 | return "Robot: \n" + 112 | " Company: " + company + "\n" + 113 | " Company URL: " + companyUrl + "\n" + 114 | " Family: " + family + "\n" + 115 | " ICO: " + ico + "\n" + 116 | " Info URL: " + infoUrl + "\n" + 117 | " OS ID: " + osId + "\n" + 118 | " URL: " + url + "\n" + 119 | " User Agent: " + userAgentString; 120 | } 121 | 122 | } -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/SingleThreadedUASparser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.Map.Entry; 8 | import java.util.Set; 9 | 10 | import jregex.Matcher; 11 | import jregex.Pattern; 12 | 13 | /** 14 | * This parser implementation is not thread-safe as it re-uses Matcher objects instead of creating 15 | * them on each call to parse() for a modest speedup. 16 | * 17 | * Recommended for single-threaded scenarios, such as Hadoop map/reduce jobs. 18 | * 19 | * @author chetan 20 | * 21 | */ 22 | public class SingleThreadedUASparser extends UASparser { 23 | 24 | protected Map compiledBrowserMatcherMap; 25 | protected Map compiledOsMatcherMap; 26 | protected Map compiledDeviceMatcherMap; 27 | 28 | public SingleThreadedUASparser(InputStream inputStreamToDefinitionFile) throws IOException { 29 | super(inputStreamToDefinitionFile); 30 | } 31 | 32 | public SingleThreadedUASparser(String localDefinitionFilename) throws IOException { 33 | super(localDefinitionFilename); 34 | } 35 | 36 | /** 37 | * Precompile browser regexes 38 | */ 39 | @Override 40 | protected void preCompileBrowserRegMap() { 41 | this.compiledBrowserMatcherMap = preCompileBrowserMatcherMap(); 42 | } 43 | 44 | protected LinkedHashMap preCompileBrowserMatcherMap() { 45 | LinkedHashMap compiledBrowserMatcherMap = 46 | new LinkedHashMap(browserRegMap.size()); 47 | 48 | for (Map.Entry entry : browserRegMap.entrySet()) { 49 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 50 | compiledBrowserMatcherMap.put(pattern.matcher(), entry.getValue()); 51 | } 52 | return compiledBrowserMatcherMap; 53 | } 54 | 55 | /** 56 | * Precompile OS regexes 57 | */ 58 | @Override 59 | protected void preCompileOsRegMap() { 60 | this.compiledOsMatcherMap = preCompileOsMatcherMap(); 61 | } 62 | 63 | protected LinkedHashMap preCompileOsMatcherMap() { 64 | LinkedHashMap compiledOsMatcherMap = 65 | new LinkedHashMap(osRegMap.size()); 66 | 67 | for (Map.Entry entry : osRegMap.entrySet()) { 68 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 69 | compiledOsMatcherMap.put(pattern.matcher(), entry.getValue()); 70 | } 71 | return compiledOsMatcherMap; 72 | } 73 | 74 | /** 75 | * Precompile device regexes 76 | */ 77 | @Override 78 | protected void preCompileDeviceRegMap() { 79 | this.compiledDeviceMatcherMap = preCompileDeviceMatcherMap(); 80 | } 81 | 82 | protected LinkedHashMap preCompileDeviceMatcherMap() { 83 | if (deviceRegMap == null) { 84 | return null; // skip for older ini files 85 | } 86 | LinkedHashMap compiledDeviceMatcherMap = 87 | new LinkedHashMap(deviceRegMap.size()); 88 | 89 | for (Map.Entry entry : deviceRegMap.entrySet()) { 90 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 91 | compiledDeviceMatcherMap.put(pattern.matcher(), entry.getValue()); 92 | } 93 | return compiledDeviceMatcherMap; 94 | } 95 | 96 | /** 97 | * Searches in the os regex table. if found a match copies the os data 98 | * 99 | * @param useragent 100 | * @param retObj 101 | */ 102 | @Override 103 | protected void processOsRegex(String useragent, UserAgentInfo retObj) { 104 | Set> osMatcherSet = getOsMatcherSet(); 105 | for (Map.Entry entry : osMatcherSet) { 106 | Matcher matcher = entry.getKey(); 107 | matcher.setTarget(useragent); 108 | if (matcher.find()) { 109 | retObj.setOsEntry(osMap.get(entry.getValue())); 110 | break; 111 | } 112 | } 113 | } 114 | 115 | /** 116 | * Searchs in the browser regex table. if found a match copies the browser data and if possible os data 117 | * 118 | * @param useragent 119 | * @param retObj 120 | */ 121 | @Override 122 | protected void processBrowserRegex(String useragent, UserAgentInfo retObj) { 123 | Set> browserMatcherSet = getBrowserMatcherSet(); 124 | for (Map.Entry entry : browserMatcherSet) { 125 | Matcher matcher = entry.getKey(); 126 | matcher.setTarget(useragent); 127 | if (matcher.find()) { 128 | Long idBrowser = entry.getValue(); 129 | BrowserEntry be = browserMap.get(idBrowser); 130 | if (be != null) { 131 | retObj.setType(browserTypeMap.get(be.getType()));; 132 | if (matcher.groupCount() > 1) { 133 | retObj.setBrowserVersionInfo(matcher.group(1)); 134 | } 135 | retObj.setBrowserEntry(be); 136 | } 137 | // check if this browser has exactly one OS mapped 138 | Long idOs = browserOsMap.get(idBrowser); 139 | if (idOs != null) { 140 | retObj.setOsEntry(osMap.get(idOs)); 141 | } 142 | return; 143 | } 144 | } 145 | } 146 | 147 | /** 148 | * Searches in the devices regex table. if found a match copies the device data 149 | * 150 | * @param useragent 151 | * @param uaInfo 152 | */ 153 | @Override 154 | protected void processDeviceRegex(String useragent, UserAgentInfo uaInfo) { 155 | Set> deviceMatcherSet = getDeviceMatcherSet(); 156 | if (deviceMatcherSet == null || deviceMap == null) { 157 | return; 158 | } 159 | for (Map.Entry entry : deviceMatcherSet) { 160 | Matcher matcher = entry.getKey(); 161 | matcher.setTarget(useragent); 162 | if (matcher.find()) { 163 | uaInfo.setDeviceEntry(deviceMap.get(entry.getValue())); 164 | return; 165 | } 166 | } 167 | } 168 | 169 | protected Set> getOsMatcherSet() { 170 | return compiledOsMatcherMap.entrySet(); 171 | } 172 | 173 | protected Set> getBrowserMatcherSet() { 174 | return compiledBrowserMatcherMap.entrySet(); 175 | } 176 | 177 | protected Set> getDeviceMatcherSet() { 178 | if (compiledDeviceMatcherMap == null) { 179 | return null; 180 | } 181 | return compiledDeviceMatcherMap.entrySet(); 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/UASparser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.util.HashMap; 7 | import java.util.Iterator; 8 | import java.util.LinkedHashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | import jregex.Matcher; 13 | import jregex.Pattern; 14 | import cz.mallat.uasparser.fileparser.Entry; 15 | import cz.mallat.uasparser.fileparser.PHPFileParser; 16 | import cz.mallat.uasparser.fileparser.Section; 17 | 18 | /** 19 | * User agent parser. 20 | * 21 | * Thread-safe, however also see the {@link MultithreadedUASparser} for a faster variant. 22 | * 23 | * @author oli 24 | * 25 | */ 26 | public class UASparser { 27 | 28 | static final String INFO_URL = "http://user-agent-string.info"; 29 | static final String ROBOT = "Robot"; 30 | static final Long DEVICE_ID_OTHER = 1L; 31 | static final Long DEVICE_ID_DESKTOP = 2L; 32 | static final Long DEVICE_ID_SMARTPHONE = 3L; 33 | 34 | protected Map robotsMap; 35 | protected Map osMap; 36 | protected Map browserMap; 37 | protected Map browserTypeMap; 38 | protected Map browserRegMap; 39 | protected Map browserOsMap; 40 | protected Map osRegMap; 41 | protected Map deviceMap; 42 | protected Map deviceRegMap; 43 | 44 | protected Map compiledBrowserRegMap; 45 | protected Map compiledOsRegMap; 46 | protected Map compiledDeviceRegMap; 47 | 48 | protected UserAgentInfo unknownAgentInfo; 49 | 50 | /** 51 | * Create a new {@link UASparser} without initializing maps. Expects an updater to be 52 | * configured and run immediately. 53 | */ 54 | public UASparser() { 55 | } 56 | 57 | /** 58 | * Use the given filename to load the definition file from the local filesystem 59 | * 60 | * @param localDefinitionFilename 61 | * @throws IOException 62 | */ 63 | public UASparser(String localDefinitionFilename) throws IOException { 64 | loadDataFromFile(new File(localDefinitionFilename)); 65 | unknownAgentInfo = new UserAgentInfo(); 66 | } 67 | 68 | /** 69 | * Use the given inputstream to load the definition file from the local filesystem 70 | * 71 | * @param inputStreamToDefinitionFile 72 | * @throws IOException 73 | */ 74 | public UASparser(InputStream inputStreamToDefinitionFile) throws IOException { 75 | loadDataFromFile(inputStreamToDefinitionFile); 76 | unknownAgentInfo = new UserAgentInfo(); 77 | } 78 | 79 | /** 80 | * When a class inherits from this class, it probably has to override this method 81 | */ 82 | @Deprecated 83 | protected void checkDataMaps() throws IOException { 84 | // empty for this base class 85 | } 86 | 87 | /** 88 | * Parse the given user agent string and returns a UserAgentInfo object with the related data 89 | * 90 | * @param useragent 91 | * @throws IOException 92 | * may happen when the retrieval of the data file fails 93 | * @return 94 | */ 95 | public UserAgentInfo parse(String useragent) throws IOException { 96 | if (useragent == null) { 97 | return unknownAgentInfo; 98 | } 99 | 100 | UserAgentInfo uaInfo = new UserAgentInfo(); 101 | useragent = useragent.trim(); 102 | 103 | // check that the data maps are up-to-date (deprecated) 104 | checkDataMaps(); 105 | 106 | // first check if it's a robot 107 | if (processRobot(useragent, uaInfo)) { 108 | return uaInfo; 109 | } 110 | 111 | // it's not a robot, so search for a browser on the browser regex patterns 112 | processBrowserRegex(useragent, uaInfo); 113 | if (!uaInfo.hasOsInfo()) { 114 | // search the OS regex patterns for the used OS 115 | processOsRegex(useragent, uaInfo); 116 | } 117 | 118 | // search the device regex patterns to set the according device 119 | processDeviceRegex(useragent, uaInfo); 120 | if (!uaInfo.hasDeviceInfo()) { 121 | guessDeviceType(uaInfo); 122 | } 123 | 124 | return uaInfo; 125 | } 126 | 127 | /** 128 | * Determine device type based on UA type field 129 | * @param uaInfo 130 | */ 131 | protected void guessDeviceType(UserAgentInfo uaInfo) { 132 | if (compiledDeviceRegMap == null || deviceMap == null) { 133 | return; 134 | } 135 | 136 | String type = uaInfo.getType(); 137 | if (type == null || type.isEmpty()) { 138 | return; 139 | } 140 | 141 | if (type.equals("Other") || type.equals("Library") || type.equals("Useragent Anonymizer")) { 142 | uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_OTHER)); 143 | } else if (type.equals("Mobile Browser") || type.equals("Wap Browser")) { 144 | uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_SMARTPHONE)); 145 | } else { 146 | uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_DESKTOP)); 147 | } 148 | } 149 | 150 | /** 151 | * Parse the given user agent string and returns a UserAgentInfo object 152 | * with only the related Browser data set. 153 | * 154 | * @param useragent 155 | * @return {@link UserAgentInfo} 156 | */ 157 | public UserAgentInfo parseBrowserOnly(String useragent) { 158 | if (useragent == null) { 159 | return unknownAgentInfo; 160 | } 161 | 162 | UserAgentInfo uaInfo = new UserAgentInfo(); 163 | processBrowserRegex(useragent, uaInfo); 164 | return uaInfo; 165 | } 166 | 167 | /** 168 | * Precompile all regular regexes 169 | */ 170 | protected void preCompileRegExes() { 171 | preCompileBrowserRegMap(); 172 | preCompileOsRegMap(); 173 | preCompileDeviceRegMap(); 174 | } 175 | 176 | /** 177 | * Precompile browser regexes 178 | */ 179 | protected void preCompileBrowserRegMap() { 180 | LinkedHashMap compiledBrowserRegMap = new LinkedHashMap(browserRegMap.size()); 181 | for (Map.Entry entry : browserRegMap.entrySet()) { 182 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 183 | compiledBrowserRegMap.put(pattern, entry.getValue()); 184 | } 185 | this.compiledBrowserRegMap = compiledBrowserRegMap; 186 | } 187 | 188 | /** 189 | * Precompile OS regexes 190 | */ 191 | protected void preCompileOsRegMap() { 192 | LinkedHashMap compiledOsRegMap = new LinkedHashMap(osRegMap.size()); 193 | for (Map.Entry entry : osRegMap.entrySet()) { 194 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 195 | compiledOsRegMap.put(pattern, entry.getValue()); 196 | } 197 | this.compiledOsRegMap = compiledOsRegMap; 198 | } 199 | 200 | /** 201 | * Precompile device regexes 202 | */ 203 | protected void preCompileDeviceRegMap() { 204 | if (deviceRegMap != null) { 205 | LinkedHashMap compiledDeviceRegMap = new LinkedHashMap(deviceRegMap.size()); 206 | for (Map.Entry entry : deviceRegMap.entrySet()) { 207 | Pattern pattern = new Pattern(entry.getKey(), Pattern.IGNORE_CASE | Pattern.DOTALL); 208 | compiledDeviceRegMap.put(pattern, entry.getValue()); 209 | } 210 | this.compiledDeviceRegMap = compiledDeviceRegMap; 211 | } 212 | } 213 | 214 | /** 215 | * Checks if the User Agent matches that of a known Robot (crawler or other automated agent) 216 | * 217 | * @param useragent 218 | * @param uaInfo 219 | */ 220 | protected boolean processRobot(String useragent, UserAgentInfo uaInfo) { 221 | // Robots UAs must match *exactly*, hence we use a simple hash lookup and not a regex match 222 | if (!robotsMap.containsKey(useragent)) { 223 | return false; 224 | } 225 | 226 | uaInfo.setType(ROBOT); 227 | RobotEntry robotEntry = robotsMap.get(useragent); 228 | uaInfo.setRobotEntry(robotEntry); 229 | if (robotEntry.getOsId() != null) { 230 | uaInfo.setOsEntry(osMap.get(robotEntry.getOsId())); 231 | } 232 | 233 | if (compiledDeviceRegMap != null && deviceMap != null) { 234 | // Set device to 'other' 235 | uaInfo.setDeviceEntry(deviceMap.get(DEVICE_ID_OTHER)); 236 | } 237 | return true; 238 | } 239 | 240 | /** 241 | * Searchs in the browser regex table. if found a match copies the browser data and if possible os data 242 | * 243 | * @param useragent 244 | * @param uaInfo 245 | */ 246 | protected void processBrowserRegex(String useragent, UserAgentInfo uaInfo) { 247 | for (Map.Entry entry : compiledBrowserRegMap.entrySet()) { 248 | Matcher matcher = entry.getKey().matcher(useragent); 249 | if (matcher.find()) { 250 | Long idBrowser = entry.getValue(); 251 | BrowserEntry be = browserMap.get(idBrowser); 252 | if (be != null) { 253 | uaInfo.setType(browserTypeMap.get(be.getType()));; 254 | if (matcher.groupCount() > 1) { 255 | uaInfo.setBrowserVersionInfo(matcher.group(1)); 256 | } 257 | uaInfo.setBrowserEntry(be); 258 | } 259 | // check if this browser has exactly one OS mapped 260 | Long idOs = browserOsMap.get(idBrowser); 261 | if (idOs != null) { 262 | uaInfo.setOsEntry(osMap.get(idOs)); 263 | } 264 | return; 265 | } 266 | } 267 | } 268 | 269 | /** 270 | * Searches in the os regex table. if found a match copies the os data 271 | * 272 | * @param useragent 273 | * @param uaInfo 274 | */ 275 | protected void processOsRegex(String useragent, UserAgentInfo uaInfo) { 276 | for (Map.Entry entry : compiledOsRegMap.entrySet()) { 277 | Matcher matcher = entry.getKey().matcher(useragent); 278 | if (matcher.find()) { 279 | uaInfo.setOsEntry(osMap.get(entry.getValue())); 280 | return; 281 | } 282 | } 283 | } 284 | 285 | /** 286 | * Searches in the devices regex table. if found a match copies the device data 287 | * 288 | * @param useragent 289 | * @param uaInfo 290 | */ 291 | protected void processDeviceRegex(String useragent, UserAgentInfo uaInfo) { 292 | if (compiledDeviceRegMap != null && deviceMap != null) { 293 | for (Map.Entry entry : compiledDeviceRegMap.entrySet()) { 294 | Matcher matcher = entry.getKey().matcher(useragent); 295 | if (matcher.find()) { 296 | uaInfo.setDeviceEntry(deviceMap.get(entry.getValue())); 297 | return; 298 | } 299 | } 300 | } 301 | } 302 | 303 | /** 304 | * loads the data file and creates all internal data structures 305 | * 306 | * @param definitionFile 307 | * @throws IOException 308 | */ 309 | protected void loadDataFromFile(File definitionFile) throws IOException { 310 | PHPFileParser fp = new PHPFileParser(definitionFile); 311 | createInternalDataStructure(fp.getSections()); 312 | } 313 | 314 | /** 315 | * loads the data file and creates all internal data structs 316 | * 317 | * @param is 318 | * @throws IOException 319 | */ 320 | protected void loadDataFromFile(InputStream is) throws IOException { 321 | PHPFileParser fp = new PHPFileParser(is); 322 | createInternalDataStructure(fp.getSections()); 323 | } 324 | 325 | /** 326 | * Creates the internal data structures from the sectionList 327 | * 328 | * @param sectionList 329 | */ 330 | protected void createInternalDataStructure(List
sectionList) { 331 | for (Section sec : sectionList) { 332 | if ("robots".equals(sec.getName())) { 333 | Map robotsMapTmp = new HashMap(); 334 | for (Entry en : sec.getEntries()) { 335 | RobotEntry re = new RobotEntry(en.getData()); 336 | robotsMapTmp.put(re.getUserAgentString(), re); 337 | } 338 | robotsMap = robotsMapTmp; 339 | } else if ("os".equals(sec.getName())) { 340 | Map osMapTmp = new HashMap(); 341 | for (Entry en : sec.getEntries()) { 342 | OsEntry oe = new OsEntry(en.getData()); 343 | osMapTmp.put(Long.parseLong(en.getKey()), oe); 344 | } 345 | osMap = osMapTmp; 346 | } else if ("browser".equals(sec.getName())) { 347 | Map browserMapTmp = new HashMap(); 348 | for (Entry en : sec.getEntries()) { 349 | BrowserEntry be = new BrowserEntry(en.getData()); 350 | browserMapTmp.put(Long.parseLong(en.getKey()), be); 351 | } 352 | browserMap = browserMapTmp; 353 | } else if ("browser_type".equals(sec.getName())) { 354 | Map browserTypeMapTmp = new HashMap(); 355 | for (Entry en : sec.getEntries()) { 356 | browserTypeMapTmp.put(Long.parseLong(en.getKey()), en.getData().iterator().next()); 357 | } 358 | browserTypeMap = browserTypeMapTmp; 359 | } else if ("browser_reg".equals(sec.getName())) { 360 | Map browserRegMapTmp = new LinkedHashMap(); 361 | for (Entry en : sec.getEntries()) { 362 | Iterator it = en.getData().iterator(); 363 | browserRegMapTmp.put(convertPerlToJavaRegex(it.next()), Long.parseLong(it.next())); 364 | } 365 | browserRegMap = browserRegMapTmp; 366 | } else if ("browser_os".equals(sec.getName())) { 367 | Map browserOsMapTmp = new HashMap(); 368 | for (Entry en : sec.getEntries()) { 369 | browserOsMapTmp.put(Long.parseLong(en.getKey()), Long.parseLong(en.getData().iterator().next())); 370 | } 371 | browserOsMap = browserOsMapTmp; 372 | } else if ("os_reg".equals(sec.getName())) { 373 | Map osRegMapTmp = new LinkedHashMap(); 374 | for (Entry en : sec.getEntries()) { 375 | Iterator it = en.getData().iterator(); 376 | osRegMapTmp.put(convertPerlToJavaRegex(it.next()), Long.parseLong(it.next())); 377 | } 378 | osRegMap = osRegMapTmp; 379 | } else if ("device".equals(sec.getName())) { 380 | Map deviceMapTmp = new HashMap(); 381 | for (Entry en : sec.getEntries()) { 382 | DeviceEntry de = new DeviceEntry(en.getData()); 383 | deviceMapTmp.put(Long.parseLong(en.getKey()), de); 384 | } 385 | deviceMap = deviceMapTmp; 386 | } else if ("device_reg".equals(sec.getName())) { 387 | Map deviceRegMapTmp = new LinkedHashMap(); 388 | for (Entry en : sec.getEntries()) { 389 | Iterator it = en.getData().iterator(); 390 | deviceRegMapTmp.put(convertPerlToJavaRegex(it.next()), Long.parseLong(it.next())); 391 | } 392 | deviceRegMap = deviceRegMapTmp; 393 | } 394 | } 395 | preCompileRegExes(); 396 | } 397 | 398 | /** 399 | * Converts a PERL style regex into the Java style. That means in removes the leading and the last / and removes the modifiers 400 | * 401 | * @param regex 402 | * @return 403 | */ 404 | protected String convertPerlToJavaRegex(String regex) { 405 | regex = regex.substring(1); 406 | int lastIndex = regex.lastIndexOf('/'); 407 | regex = regex.substring(0, lastIndex); 408 | return regex; 409 | } 410 | 411 | } 412 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/UserAgentInfo.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | /** 4 | * Encapsulates all information pertaining to a User Agent. Returned by calling 5 | * {@link UASparser#parse(String)}. 6 | * 7 | *

Note that all information comes from the database provided at 8 | * user-agent-string.info. If you have problems with 9 | * or questions about the data returned, please contact the maintainer of the database directly. 10 | * 11 | * @author oli 12 | * @author Felix Siegrist, Inventage AG 13 | * 14 | */ 15 | public class UserAgentInfo { 16 | 17 | public static final String UNKNOWN = "unknown"; 18 | 19 | private String type; 20 | private String browserVersionInfo; 21 | 22 | private RobotEntry robotEntry; 23 | private BrowserEntry browserEntry; 24 | private OsEntry osEntry; 25 | private DeviceEntry deviceEntry; 26 | 27 | public UserAgentInfo() { 28 | this.type = UNKNOWN; 29 | } 30 | 31 | /** 32 | * Returns true if this represents a Robot 33 | * @return 34 | */ 35 | public boolean isRobot() { 36 | return UASparser.ROBOT.equals(type); 37 | } 38 | 39 | public boolean hasOsInfo() { 40 | return osEntry != null; 41 | } 42 | 43 | public boolean hasDeviceInfo() { 44 | return deviceEntry != null; 45 | } 46 | 47 | /** 48 | * Retrieve the type of UA. Can be one of the following: 49 | * 50 | *

    51 | *
  • "Browser" 52 | *
  • "Offline Browser" 53 | *
  • "Mobile Browser" 54 | *
  • "Email client" 55 | *
  • "Library" 56 | *
  • "Wap Browser" 57 | *
  • "Validator" 58 | *
  • "Feed Reader" 59 | *
  • "Multimedia Player" 60 | *
  • "Other" 61 | *
  • "Useragent Anonymizer" 62 | *
  • "Robot" 63 | *
64 | * 65 | * @return {@link String} type 66 | */ 67 | public String getType() { 68 | if (type == null) { 69 | return UNKNOWN; 70 | } 71 | return type; 72 | } 73 | 74 | public void setType(String type) { 75 | this.type = type; 76 | } 77 | 78 | /** 79 | * Retrieve the product family; i.e., given the UA: 80 | * 81 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

82 | * 83 | *

it would return "Firefox"

84 | * 85 | * @return {@link String} URL 86 | */ 87 | public String getUaFamily() { 88 | if (browserEntry != null) { 89 | return browserEntry.getFamily(); 90 | } 91 | if (robotEntry != null) { 92 | return robotEntry.getFamily(); 93 | } 94 | return UNKNOWN; 95 | } 96 | 97 | /** 98 | * Retrieve the UA name and version; i.e., given the UA: 99 | * 100 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

101 | * 102 | *

it would return "Firefox 3.5.1"

103 | * 104 | * @return {@link String} UA name 105 | */ 106 | public String getUaName() { 107 | if (browserEntry != null) { 108 | if (browserVersionInfo != null && !browserVersionInfo.isEmpty()) { 109 | return getUaFamily() + " " + browserVersionInfo; 110 | } 111 | return getUaFamily(); 112 | } 113 | if (robotEntry != null) { 114 | return robotEntry.getName(); 115 | } 116 | return UNKNOWN; 117 | } 118 | 119 | /** 120 | * Retrieve the URL of the UA's product page; i.e., given the UA: 121 | * 122 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

123 | * 124 | *

it would return "http://www.firefox.com/"

125 | * 126 | * @return {@link String} URL 127 | */ 128 | public String getUaUrl() { 129 | if (browserEntry != null) { 130 | return browserEntry.getUrl(); 131 | } 132 | if (robotEntry != null) { 133 | return robotEntry.getUrl(); 134 | } 135 | return UNKNOWN; 136 | } 137 | 138 | /** 139 | * Retrieve the URL path for the given UA on user-agent-string.info; i.e., given the UA: 140 | * 141 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

142 | * 143 | *

it would return "/list-of-ua/browser-detail?browser=Firefox" which could then be accessed

144 | *

at http://user-agent-string.info/list-of-ua/browser-detail?browser=Firefox

145 | * 146 | * @return {@link String} URL path 147 | */ 148 | public String getUaInfoUrl() { 149 | if (browserEntry != null) { 150 | return UASparser.INFO_URL + browserEntry.getInfoUrl(); 151 | } 152 | if (robotEntry != null) { 153 | return UASparser.INFO_URL + robotEntry.getInfoUrl(); 154 | } 155 | return UNKNOWN; 156 | } 157 | 158 | /** 159 | * Retrieve the name of the company which developed the given UA; i.e., given the UA: 160 | * 161 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

162 | * 163 | *

it would return "Mozilla Foundation"

164 | * 165 | * @return {@link String} URL 166 | */ 167 | public String getUaCompany() { 168 | if (browserEntry != null) { 169 | return browserEntry.getCompany(); 170 | } 171 | if (robotEntry != null) { 172 | return robotEntry.getCompany(); 173 | } 174 | return UNKNOWN; 175 | } 176 | 177 | /** 178 | * Retrieve the URL of the company which developed the given UA; i.e., given the UA: 179 | * 180 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

181 | * 182 | *

it would return "http://www.mozilla.org/"

183 | * 184 | * @return {@link String} URL 185 | */ 186 | public String getUaCompanyUrl() { 187 | if (browserEntry != null) { 188 | return browserEntry.getCompanyUrl(); 189 | } 190 | if (robotEntry != null) { 191 | return robotEntry.getCompanyUrl(); 192 | } 193 | return UNKNOWN; 194 | } 195 | 196 | /** 197 | * Retrieve the icon filename, if available; i.e., given the UA: 198 | * 199 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

200 | * 201 | *

it would return "firefox.png"

202 | * 203 | * @return {@link String} URL 204 | * @see http://user-agent-string.info/download 205 | */ 206 | public String getUaIcon() { 207 | if (browserEntry != null) { 208 | return browserEntry.getIco(); 209 | } 210 | if (robotEntry != null) { 211 | return robotEntry.getIco(); 212 | } 213 | return UNKNOWN; 214 | } 215 | 216 | /** 217 | * Retrieve the OS family name 218 | * @return 219 | */ 220 | public String getOsFamily() { 221 | if (osEntry != null) { 222 | return osEntry.getFamily(); 223 | } 224 | return UNKNOWN; 225 | } 226 | 227 | /** 228 | * Retrieve the OS name 229 | * @return 230 | */ 231 | public String getOsName() { 232 | if (osEntry != null) { 233 | return osEntry.getName(); 234 | } 235 | return UNKNOWN; 236 | } 237 | 238 | /** 239 | * Retrieve the URL to the OS vendor's product page 240 | * @return 241 | */ 242 | public String getOsUrl() { 243 | if (osEntry != null) { 244 | return osEntry.getUrl(); 245 | } 246 | return UNKNOWN; 247 | } 248 | 249 | /** 250 | * Retrieve the name of the OS vendor 251 | * @return 252 | */ 253 | public String getOsCompany() { 254 | if (osEntry != null) { 255 | return osEntry.getCompany(); 256 | } 257 | return UNKNOWN; 258 | } 259 | 260 | /** 261 | * Retrieve the URL to the OS vendor's homepage 262 | * @return 263 | */ 264 | public String getOsCompanyUrl() { 265 | if (osEntry != null) { 266 | return osEntry.getCompanyUrl(); 267 | } 268 | return UNKNOWN; 269 | } 270 | 271 | /** 272 | * Retrieve the filename of the OS icon 273 | * @return 274 | * @see http://user-agent-string.info/download 275 | */ 276 | public String getOsIcon() { 277 | if (osEntry != null) { 278 | return osEntry.getIco(); 279 | } 280 | return UNKNOWN; 281 | } 282 | 283 | /** 284 | * Retrieve the UA version number; i.e., given the UA: 285 | * 286 | *

"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1"

287 | * 288 | *

it would return "3.5.1"

289 | * 290 | * @return {@link String} version number 291 | */ 292 | public String getBrowserVersionInfo() { 293 | return browserVersionInfo; 294 | } 295 | 296 | /** 297 | * Retrieve the type of the device, if available. Can be one of the following: 298 | * 299 | *
    300 | *
  • "Personal computer" 301 | *
  • "Smartphone" 302 | *
  • "Tablet" 303 | *
  • "Game console" 304 | *
  • "Smart TV" 305 | *
  • "Other" 306 | *
307 | * 308 | * @return {@link String} type 309 | */ 310 | public String getDeviceType() { 311 | return deviceEntry != null ? deviceEntry.getType() : UNKNOWN; 312 | } 313 | 314 | /** 315 | * Retrieve the icon filename, if available; i.e., given the UA: 316 | * 317 | *

"Mozilla/5.0 (Linux; U; Android 2.3.5; de-ch; HTC_DesireHD_A9191 Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

318 | * 319 | *

it would return "phone.png"

320 | * 321 | * @return {@link String} URL 322 | * @see http://user-agent-string.info/download 323 | */ 324 | public String getDeviceIcon() { 325 | return deviceEntry != null ? deviceEntry.getIco() : UNKNOWN; 326 | } 327 | 328 | /** 329 | * Retrieve the URL path for the given UA on user-agent-string.info; i.e., given the UA: 330 | * 331 | *

"Mozilla/5.0 (Linux; U; Android 2.3.5; de-ch; HTC_DesireHD_A9191 Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

332 | * 333 | *

it would return "http://user-agent-string.info/list-of-ua/device-detail?device=Smartphone".

334 | * 335 | * @return {@link String} URL path 336 | */ 337 | public String getDeviceInfoUrl() { 338 | return deviceEntry != null ? UASparser.INFO_URL + deviceEntry.getInfoUrl() : UNKNOWN; 339 | } 340 | 341 | 342 | // setters 343 | 344 | public void setBrowserEntry(BrowserEntry browserEntry) { 345 | this.browserEntry = browserEntry; 346 | } 347 | 348 | public void setBrowserVersionInfo(String browserVersionInfo) { 349 | this.browserVersionInfo = browserVersionInfo; 350 | } 351 | 352 | public void setOsEntry(OsEntry osEntry) { 353 | this.osEntry = osEntry; 354 | } 355 | 356 | public void setRobotEntry(RobotEntry robotEntry) { 357 | this.robotEntry = robotEntry; 358 | } 359 | 360 | public void setDeviceEntry(DeviceEntry deviceEntry) { 361 | this.deviceEntry = deviceEntry; 362 | } 363 | 364 | @Override 365 | public String toString() { 366 | StringBuilder sb = new StringBuilder(); 367 | 368 | sb.append("Name: " + getUaName() + "\n"); 369 | sb.append("Type: " + getType() + "\n"); 370 | 371 | if (robotEntry != null) { 372 | sb.append(robotEntry + "\n"); 373 | } else { 374 | sb.append("Robot: no\n"); 375 | } 376 | 377 | if (browserEntry != null) { 378 | sb.append(browserEntry + "\n"); 379 | } else { 380 | sb.append("Browser: no\n"); 381 | } 382 | 383 | if (osEntry != null) { 384 | sb.append(osEntry + "\n"); 385 | } else { 386 | sb.append("Operating System: n/a\n"); 387 | } 388 | 389 | if (deviceEntry != null) { 390 | sb.append(deviceEntry + "\n"); 391 | } else { 392 | sb.append("Device: n/a\n"); 393 | } 394 | 395 | return sb.toString(); 396 | } 397 | 398 | } -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/fileparser/Entry.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser.fileparser; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * JavaBean that holds an entry from a parsed file 8 | * 9 | * @author oli 10 | */ 11 | public class Entry { 12 | 13 | private String key; 14 | private List data = new ArrayList(); 15 | 16 | public Entry(String key) { 17 | this.key = key; 18 | } 19 | 20 | public String getKey() { 21 | return key; 22 | } 23 | 24 | public void setKey(String key) { 25 | this.key = key; 26 | } 27 | 28 | public List getData() { 29 | return data; 30 | } 31 | 32 | public void setData(List data) { 33 | this.data = data; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/fileparser/PHPFileParser.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser.fileparser; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.InputStreamReader; 9 | import java.io.Reader; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * Emulates the behavior of the php function "parse_ini_file". 15 | * 16 | * Does NOT support all features of the php function. 17 | * 18 | * @author oli 19 | */ 20 | public class PHPFileParser { 21 | 22 | private List
sections; 23 | 24 | public PHPFileParser(InputStream is) throws IOException { 25 | loadFile(new InputStreamReader(is)); 26 | } 27 | 28 | public PHPFileParser(Reader reader) throws IOException { 29 | loadFile(reader); 30 | } 31 | 32 | public PHPFileParser(File file) throws IOException { 33 | Reader reader = new FileReader(file); 34 | try { 35 | loadFile(reader); 36 | } finally { 37 | try { 38 | reader.close(); 39 | } catch (IOException e) { 40 | } 41 | } 42 | } 43 | 44 | private void loadFile(Reader reader) throws IOException { 45 | this.sections = new ArrayList
(); 46 | 47 | BufferedReader bufferedReader = new BufferedReader(reader); 48 | 49 | int unnamedSectionCounter = 0; 50 | 51 | Section currentSection = null; 52 | Entry currentEntry = null; 53 | 54 | String line = bufferedReader.readLine(); 55 | while (line != null) { 56 | if (line.trim().startsWith(";")) { 57 | // comment, do nothing 58 | } else if (line.trim().startsWith("[") && line.trim().endsWith("]")) { 59 | String rawLine = line.trim(); 60 | String sectionName = rawLine.substring(1, rawLine.length() - 1); 61 | currentSection = new Section(sectionName); 62 | sections.add(currentSection); 63 | } else { 64 | if (currentSection == null) { 65 | currentSection = new Section("unname section" + (++unnamedSectionCounter)); 66 | sections.add(currentSection); 67 | } 68 | 69 | int indexOfEquals = line.indexOf('='); 70 | String key = line.substring(0, indexOfEquals); 71 | String data = line.substring(indexOfEquals + 1); 72 | key = key.replace('[', ' '); 73 | key = key.replace(']', ' '); 74 | key = key.trim(); 75 | data = data.trim(); 76 | if (data.startsWith("\"") && data.endsWith("\"")) { 77 | data = data.substring(1, data.length() - 1); 78 | } 79 | 80 | if (currentEntry == null || !currentEntry.getKey().equals(key)) { 81 | currentEntry = new Entry(key); 82 | currentSection.getEntries().add(currentEntry); 83 | } 84 | 85 | currentEntry.getData().add(data); 86 | } 87 | 88 | line = bufferedReader.readLine(); 89 | } 90 | 91 | } 92 | 93 | public List
getSections() { 94 | return sections; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/cz/mallat/uasparser/fileparser/Section.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser.fileparser; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * JavaBean that holds a section from a parsed file. A section is a row in square brackets, e.g. [main] 8 | * 9 | * @author oli 10 | */ 11 | public class Section { 12 | 13 | private String name; 14 | private List entries; 15 | 16 | public Section(String sectionName) { 17 | this.name = sectionName; 18 | this.entries = new ArrayList(); 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | 29 | public List getEntries() { 30 | return entries; 31 | } 32 | 33 | public void setEntries(List entries) { 34 | this.entries = entries; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/cz/mallat/uasparser/Benchmark.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * Performance tests 10 | * 11 | * Copyright: Copyright (c) 09.10.2012
12 | * Company: Braintags GmbH
13 | * 14 | * @author mremme 15 | */ 16 | public class Benchmark { 17 | 18 | public static InputStream getIni() { 19 | return OnlineUpdater.getVendoredInputStream(); 20 | } 21 | 22 | public static void main(String[] args) { 23 | 24 | try { 25 | List parserList = new ArrayList(); 26 | parserList.add(new UASparser(getIni())); 27 | parserList.add(new SingleThreadedUASparser(getIni())); 28 | parserList.add(new MultithreadedUASparser(getIni())); 29 | //parserList.add(new OnlineUpdateUASparser()); 30 | 31 | List uaList = new ArrayList(); 32 | uaList.add("user-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) Gecko/20050922 Fedora/1.0.7-1.1.fc3 Firefox/1.0.7"); 33 | uaList.add("user-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)"); 34 | uaList.add("WhatWeb/0.4.7"); 35 | uaList.add("check_http/v1.4.16 (nagios-plugins 1.4.16)"); 36 | uaList.add("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); 37 | 38 | List expectedTypes = new ArrayList(); 39 | expectedTypes.add("Browser"); 40 | expectedTypes.add("Browser"); 41 | expectedTypes.add("unknown"); 42 | expectedTypes.add("Other"); 43 | expectedTypes.add("Robot"); 44 | 45 | for (UASparser uaParser : parserList) { 46 | performTest(uaParser, uaList); 47 | } 48 | 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | 53 | } 54 | 55 | private static final void performTest(UASparser uaParser, List uaList) throws IOException { 56 | long startTime = System.currentTimeMillis(); 57 | 58 | int i = 0; 59 | 60 | while (i++ < 5000) { 61 | for (String tmpString : uaList) { 62 | UserAgentInfo info = uaParser.parse(tmpString); 63 | //System.out.println("getType: " + info.getType()); 64 | } 65 | } 66 | long newTime = System.currentTimeMillis() - startTime; 67 | System.out.println(uaParser.getClass().getSimpleName() + ": " + newTime); 68 | 69 | } 70 | 71 | private static final void checkThreadSafe(final UASparser uaParser, final List uaList, 72 | final List expectedType, final int threadCount, final int runs) { 73 | 74 | List threads = new ArrayList(); 75 | for (int i = 0; i < threadCount; i++) { 76 | Runnable runnable = new Runnable() { 77 | 78 | @Override 79 | public void run() { 80 | int r = 0; 81 | while (r++ < runs) { 82 | for (int k = 0; k < uaList.size(); k++) { 83 | String uaString = uaList.get(k); 84 | String expected = expectedType.get(k); 85 | try { 86 | UserAgentInfo info = uaParser.parse(uaString); 87 | if (!info.getType().equals(expected)) 88 | throw new IllegalArgumentException("not expected: " + info.getType() + " / " + expected); 89 | } catch (IOException e) { 90 | throw new RuntimeException(e); 91 | } 92 | } 93 | } 94 | System.out.println("finished Thread " + Thread.currentThread().getName()); 95 | } 96 | }; 97 | threads.add(runnable); 98 | } 99 | 100 | int i = 0; 101 | for (Runnable runnable : threads) { 102 | new Thread(runnable, "Thread " + i++).start(); 103 | } 104 | } 105 | 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/cz/mallat/uasparser/TestOldDatabase.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.zip.GZIPInputStream; 6 | 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | /** 11 | * Test against a copy of the database without device info 12 | * 13 | * @author chetan 14 | * 15 | */ 16 | public class TestOldDatabase extends TestParsers { 17 | 18 | @Before 19 | public void disableDeviceTests() { 20 | this.testDeviceInfo = false; 21 | } 22 | 23 | @Override 24 | protected InputStream getDataInputStream() { 25 | try { 26 | return new GZIPInputStream(this.getClass().getClassLoader().getResourceAsStream("uas-nodevice.txt.gz")); 27 | } catch (IOException e) { 28 | } 29 | return null; 30 | } 31 | 32 | @Override 33 | @Test 34 | public void runOnlineUAParser() throws IOException { 35 | // disable 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/cz/mallat/uasparser/TestOnlineUpdater.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import org.junit.Test; 10 | 11 | 12 | public class TestOnlineUpdater { 13 | 14 | @Test 15 | public void testUpdate() throws InterruptedException, IOException { 16 | 17 | File tmpDir = File.createTempFile("uas", ".test"); 18 | tmpDir.delete(); 19 | tmpDir.mkdirs(); 20 | // tmpDir.deleteOnExit(); 21 | 22 | try { 23 | 24 | UASparser parser = new UASparser(); 25 | assertNull(parser.browserMap); 26 | 27 | OnlineUpdater updater = new OnlineUpdater(parser, tmpDir.toString(), 1, TimeUnit.DAYS); 28 | assertNotNull(parser.browserMap); 29 | assertTrue(updater.isAlive()); 30 | updater.update(); // force immediate update 31 | 32 | TestParsers testParsers = new TestParsers(); 33 | testParsers.runUAParser(); 34 | 35 | assert(new File(tmpDir, OnlineUpdater.CACHE_FILENAME).exists()); 36 | assert(new File(tmpDir, OnlineUpdater.PROPERTIES_FILENAME).exists()); 37 | 38 | parser = new UASparser(); 39 | assertNull(parser.browserMap); 40 | parser.loadDataFromFile(new File(tmpDir, OnlineUpdater.CACHE_FILENAME)); 41 | assertNotNull(parser.browserMap); 42 | 43 | } finally { 44 | // new File(tmpDir, OnlineUpdater.CACHE_FILENAME).delete(); 45 | // new File(tmpDir, OnlineUpdater.PROPERTIES_FILENAME).delete(); 46 | } 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/cz/mallat/uasparser/TestParsers.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | 8 | import org.junit.Test; 9 | 10 | /** 11 | * Test the various parser implementations 12 | * 13 | * @author chetan 14 | * 15 | */ 16 | public class TestParsers { 17 | 18 | protected boolean testDeviceInfo = true; 19 | 20 | @Test 21 | public void runUAParser() throws IOException { 22 | UASparser p = new UASparser(getDataInputStream()); 23 | testUserAgents(p); 24 | } 25 | 26 | @Test 27 | public void runOnlineUAParser() throws IOException { 28 | UASparser p = new OnlineUpdateUASparser(); 29 | testUserAgents(p); 30 | } 31 | 32 | @Test 33 | public void runCachedOnlineUAParser() throws IOException { 34 | UASparser p = new CachingOnlineUpdateUASparser(); 35 | testUserAgents(p); 36 | } 37 | 38 | @Test 39 | public void testSingleThreadedParser() throws IOException { 40 | UASparser p = new SingleThreadedUASparser(getDataInputStream()); 41 | testUserAgents(p); 42 | } 43 | 44 | @Test 45 | public void testMultithreadedParser() throws IOException { 46 | UASparser p = new MultithreadedUASparser(getDataInputStream()); 47 | testUserAgents(p); 48 | } 49 | 50 | /** 51 | * Tests for various device types 52 | * 53 | * @throws IOException 54 | * @throws InterruptedException 55 | */ 56 | @Test 57 | public void testDeviceUA() throws IOException, InterruptedException { 58 | 59 | if (!this.testDeviceInfo) { 60 | return; 61 | } 62 | 63 | UASparser p = new UASparser(getDataInputStream()); 64 | 65 | UserAgentInfo info = p.parse("Mozilla/5.0 (Linux; U; Android 4.0.4; en-au; GT-N7000 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 Maxthon/4.1.1.2000"); 66 | assertEquals("Smartphone", info.getDeviceType()); 67 | 68 | info = p.parse("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36 Mozilla/4.0 (compatible; MSIE 5.0; Windows NT;)"); 69 | assertEquals("Personal computer", info.getDeviceType()); 70 | 71 | info = p.parse("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"); 72 | assertEquals("Smartphone", info.getDeviceType()); 73 | 74 | info = p.parse("Mozilla/5.0 (compatible; 008/0.83; http://www.80legs.com/spider.html;) Gecko/2008032620"); 75 | assertEquals("Other", info.getDeviceType()); 76 | } 77 | 78 | /** 79 | * Get database file to test against as an {@link InputStream} 80 | * @return 81 | */ 82 | protected InputStream getDataInputStream() { 83 | return OnlineUpdater.getVendoredInputStream(); 84 | } 85 | 86 | private void testUserAgents(UASparser parser) throws IOException { 87 | testRobotAgents(parser); 88 | testBrowserAgent(parser); 89 | testEmailAgent(parser); 90 | testTabletAgent(parser); 91 | testSmartphoneAgent(parser); 92 | } 93 | 94 | private void testRobotAgents(UASparser parser) throws IOException { 95 | UserAgentInfo uai = parser.parse("Mozilla/5.0 (compatible; 008/0.83; http://www.80legs.com/spider.html;) Gecko/2008032620"); 96 | assertTrue(uai.isRobot()); 97 | if (this.testDeviceInfo) { 98 | assertEquals("Datafiniti, LLC.", uai.getUaCompany()); 99 | } else { 100 | // when using the 'old db', this may be either of the two strings.. 101 | // on a normal run/test, it will be Computational, but the caching test will result in Datafiniti.. 102 | assertTrue(uai.getUaCompany().equals("Computational Crawling, LP") || uai.getUaCompany().equals("Datafiniti, LLC.")); 103 | } 104 | 105 | uai = parser.parse("Googlebot/2.1 (+http://www.googlebot.com/bot.html)"); 106 | assertFalse(uai.isRobot()); // not currently detected 107 | 108 | uai = parser.parse("Pingdom.com_bot_version_1.4_(http://www.pingdom.com/)"); 109 | assertTrue(uai.isRobot()); 110 | } 111 | 112 | private void testBrowserAgent(UASparser parser) throws IOException { 113 | UserAgentInfo uai = parser.parse("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12"); 114 | assertNotNull(uai); 115 | assertEquals("Browser", uai.getType()); 116 | assertEquals("Firefox 3.0.12", uai.getUaName()); 117 | assertEquals("Firefox", uai.getUaFamily()); 118 | assertEquals("Mozilla Foundation", uai.getUaCompany()); 119 | assertEquals("Windows XP", uai.getOsName()); 120 | assertEquals("Windows", uai.getOsFamily()); 121 | assertEquals("Microsoft Corporation.", uai.getOsCompany()); 122 | } 123 | 124 | private void testEmailAgent(UASparser parser) throws IOException { 125 | UserAgentInfo uai = parser.parse("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/534.50.2 (KHTML, like Gecko)"); 126 | assertNotNull(uai); 127 | assertEquals("Email client", uai.getType()); 128 | assertEquals("Apple Mail", uai.getUaName()); 129 | assertEquals("Apple Mail", uai.getUaFamily()); 130 | assertEquals("Apple Inc.", uai.getUaCompany()); 131 | assertEquals("OS X 10.5 Leopard", uai.getOsName()); 132 | assertEquals("OS X", uai.getOsFamily()); 133 | assertEquals("Apple Computer, Inc.", uai.getOsCompany()); 134 | } 135 | 136 | private void testTabletAgent(UASparser parser) throws IOException { 137 | UserAgentInfo uai = parser.parse("Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/6.0 Mobile/11A465 Safari/9537.53"); 138 | assertNotNull(uai); 139 | assertEquals("Mobile Browser", uai.getType()); 140 | assertEquals("Mobile Safari 6.0", uai.getUaName()); 141 | assertEquals("Mobile Safari", uai.getUaFamily()); 142 | assertEquals("Apple Inc.", uai.getUaCompany()); 143 | assertEquals("iOS 6", uai.getOsName()); 144 | assertEquals("iOS", uai.getOsFamily()); 145 | assertEquals("Apple Inc.", uai.getOsCompany()); 146 | 147 | if (!testDeviceInfo) { 148 | return; 149 | } 150 | assertTrue(uai.hasDeviceInfo()); 151 | assertEquals("Tablet", uai.getDeviceType()); 152 | assertEquals("tablet.png", uai.getDeviceIcon()); 153 | assertEquals("http://user-agent-string.info/list-of-ua/device-detail?device=Tablet", uai.getDeviceInfoUrl()); 154 | } 155 | 156 | private void testSmartphoneAgent(UASparser parser) throws IOException { 157 | UserAgentInfo uai = parser.parse("Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/546.10 (KHTML, like Gecko) Version/6.0 Mobile/7E18WD Safari/8536.25"); 158 | assertNotNull(uai); 159 | assertEquals("Mobile Browser", uai.getType()); 160 | assertEquals("Mobile Safari 6.0", uai.getUaName()); 161 | assertEquals("Mobile Safari", uai.getUaFamily()); 162 | assertEquals("Apple Inc.", uai.getUaCompany()); 163 | assertEquals("iOS 6", uai.getOsName()); 164 | assertEquals("iOS", uai.getOsFamily()); 165 | assertEquals("Apple Inc.", uai.getOsCompany()); 166 | 167 | // if (!testDeviceInfo) { 168 | // return; 169 | // } 170 | // assertTrue(uai.hasDeviceInfo()); 171 | // assertEquals("Smartphone", uai.getDeviceType()); 172 | // assertEquals("phone.png", uai.getDeviceIcon()); 173 | // assertEquals("http://user-agent-string.info/list-of-ua/device-detail?device=Smartphone", uai.getDeviceInfoUrl()); 174 | } 175 | 176 | @Test 177 | public void testArrayIndexBug() throws IOException { 178 | // should not throw exception 179 | UASparser p = new UASparser(getDataInputStream()); 180 | UserAgentInfo uai = p.parse("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; MyIE2; MRA 4.7 (build 01670); .NET CLR 1.1.4322)"); 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/test/java/cz/mallat/uasparser/TestSuite.java: -------------------------------------------------------------------------------- 1 | package cz.mallat.uasparser; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.junit.runners.Suite; 5 | import org.junit.runners.Suite.SuiteClasses; 6 | 7 | @RunWith(Suite.class) 8 | @SuiteClasses({ TestOnlineUpdater.class, TestParsers.class, TestOldDatabase.class }) 9 | public class TestSuite { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/test/resources/uas-nodevice.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetan/UASparser/c92ceffbfcbd1bb18d75e320bc45149eaaacd89e/src/test/resources/uas-nodevice.txt.gz --------------------------------------------------------------------------------