├── .gitignore ├── .travis.yml ├── LICENCE ├── README.md ├── autocolourcorrelogram ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── cameraforensics │ │ └── elasticsearch │ │ └── plugins │ │ ├── AutoColourCorrelogramDistancePlugin.java │ │ ├── AutoColourCorrelogramDistanceScript.java │ │ └── AutoColourCorrelogramDistanceScriptFactory.java │ └── resources │ └── plugin-descriptor.properties ├── build.gradle ├── dist.sh ├── euclideandistance ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── cameraforensics │ │ └── elasticsearch │ │ └── plugins │ │ └── EuclideanDistanceScriptEngine.java │ └── resources │ └── plugin-descriptor.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── hammingdistance ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── cameraforensics │ │ └── elasticsearch │ │ └── plugins │ │ └── HammingDistanceScriptEngine.java │ └── resources │ └── plugin-descriptor.properties ├── settings.gradle ├── travis-build.gradle └── urltokenizer ├── build.gradle └── src ├── main ├── java │ └── com │ │ └── cameraforensics │ │ └── elasticsearch │ │ └── plugins │ │ ├── UrlTokenizer.java │ │ ├── UrlTokenizerFactory.java │ │ └── UrlTokenizerPlugin.java └── resources │ └── plugin-descriptor.properties └── test └── java └── com └── cameraforensics └── elasticsearch └── plugins └── UrlTokenizerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | **/build 3 | .gradle 4 | *.iml 5 | .idea 6 | */.idea 7 | 8 | .DS_Store 9 | **/.DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | script: gradle -b travis-build.gradle build 3 | install: true 4 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #ElasticSearch Native Script Plugins 2 | 3 | [![Build Status](https://travis-ci.org/CameraForensics/elasticsearch-plugins.svg?branch=master)](https://travis-ci.org/CameraForensics/elasticsearch-plugins) 4 | 5 | # Introduction 6 | This repository contains native scoring scripts for use with elasticsearch. 7 | 8 | **Disclaimer:** They have only been tested with elasticsearch versions 2.3.1 and 6.2.4, and even then against a very strict document set. 9 | 10 | ## Hamming Distance 11 | This script will calculate the hamming distance between two hex-encoded bit-strings (ie: strings made up of 1’s and 0’s and then hexidecimally encoded), one hash being passed in as a parameter: `param_hash`, and the other being stored in a field also identified by a parameter: `param_field`. 12 | 13 | It will then return your search results scored accordingly, where the smallest distance (ie: most similar strings) appear nearer the top of the results list. 14 | 15 | **Note:** If the parameter hash and the document hash are not the same length, the result will be a score of `0.0f`. 16 | 17 | ### Caveats 18 | The hashes must be the same length in every document, or the relative scoring won’t be accurate. 19 | 20 | ## Euclidean Distance 21 | This script compares the euclidean distance of two hexadecimal-encoded hashes by first decoding them into strings of integers, and then calculating the distance between them by comparing each integer in the string. 22 | 23 | The result is subtracted from Double.MAX_VALUE to create a descending scoring value. So documents with less of a euclidean distance from the parameter hash shoudl appear nearer the top of the results list. 24 | 25 | The first hash is sent in as a parameter: `param_hash`, the other is expected to be stored in a field also identified by a parameter: `param_field`. 26 | 27 | ## AutoColourCorrelogram 28 | This script will calculate a distance between a given 64x4 correlogram (4 distance sets) in the format: 29 | ``` 30 | X0Y0,X0Y1,X0Y2,X0Y4;X1Y0,X1Y1,X1Y2,X1Y3;...;X64Y0,X64Y1,X64Y2,X64Y3 31 | ``` 32 | Because in distance terms, the smaller the distance the more likely the match, an in elastic terms, the greater the score the more likely 33 | the match, we need to turn the score on its head. So the result returned is actually `Integer.MAX_VALUE - distance`. 34 | 35 | If the parameter is incorrect, or the document does not have all the expected fields for the correlogram, the result will be `Integer.MAX_VALUE`. 36 | 37 | The script expects that the correlogram is stored in a field called `correlogram` in the same format as the parameter is provided (see above). 38 | 39 | ## URL Tokenizer 40 | This script splits a URL into a set of perumtations of URL segmentation. For example, given the URL: `https://farm1.domain.com/one/two/three/four.jpg?param1=value1¶m2=value2`, 41 | the following tokens are created: 42 | 43 | * `farm1.domain.com` 44 | * `one` 45 | * `two` 46 | * `three` 47 | * `four.jpg` 48 | * `param1=value1¶m2=value2` 49 | * `param1=value1` 50 | * `param2=value2` 51 | * `https://farm1.domain.com/one` 52 | * `https://farm1.domain.com/one/two` 53 | * `https://farm1.domain.com/one/two/three` 54 | * `https://farm1.domain.com/one/two/three/four.jpg` 55 | * `farm1.domain.com/one` 56 | * `farm1.domain.com/one/two` 57 | * `farm1.domain.com/one/two/three` 58 | * `farm1.domain.com/one/two/three/four.jpg` 59 | * `one/two/three/four.jpg` 60 | * `two/three/four.jpg` 61 | * `three/four.jpg` 62 | * `one/two/three` 63 | * `one/two` 64 | * `two/three` 65 | 66 | The main purpose of this plugin is to cater for URL path/sub-path querying without the need of wildcards. Performance testing showed that it generated 67 | more accurate results than the standard tokenizer, although it does take up more database. 68 | 69 | **See Usage Examples below for clarity.** 70 | 71 | # Setup 72 | **Note:** If you only want to use one of the plugins, modify the following to exclude instructions for the other. 73 | 74 | ## Step 1: Configuration 75 | 76 | Include the following in your elasticsearch.yml config file: 77 | 78 | script.native: 79 | hamming_distance.type: com.cameraforensics.elasticsearch.plugins.AutoColourCorrelogramDistanceScriptFactory 80 | euclidean_distance.type: com.cameraforensics.elasticsearch.plugins.EuclideanDistanceScriptFactory 81 | 82 | **Note:** If you don’t do this, they still show up on the plugins list (see later) but you’ll get errors when you try to use either of them saying that elasticsearch can’t find the plugin. 83 | 84 | ## Step 2: Build 85 | To build the plugins simply run: `gradle build`. 86 | 87 | The results will be located in: `PLUGIN_NAME/build/libs/` 88 | 89 | For example: 90 | 91 | * `hammingdistance/build/libs/hammingdistance-2.3.1.0.jar` 92 | * `euclideandistance/build/libs/euclideandistance-2.3.1.0.jar` 93 | 94 | **Note:** This has been built using Gradle v2.7. 95 | 96 | ## Step 3: Deployment 97 | Don't bother using the elasticsearch plugin script to install it - it's just a pain the ass and all it seems to do is unpack your stuff - a bit pointless. 98 | 99 | Instead put the .jar file in `%ELASTICSEARCH_HOME%/plugins/hamming_distance` for hamming distance, and `%ELASTICSEARCH_HOME%/plugins/euclidean_distance` for euclidean distance, then restart elasticsearch. 100 | 101 | **Note:** If you installed elasticsearch according to docs, this `%ELASTICSEARCH_HOME%` will default to `/usr/share/elasticsearch/` 102 | 103 | If all has gone well, you'll see them being loaded on elasticsearch startup: 104 | 105 | [1982-07-06 12:02:43,765][INFO ][plugins ] [Junta] loaded [marvel, hamming_distance, euclidean_distance, urltokenizer], sites [marvel] 106 | 107 | AND when you call the list of plugins they’ll be there: 108 | 109 | curl http://localhost:9200/_cat/plugins?v 110 | 111 | produces something like: 112 | 113 | name component version type url 114 | Junta hamming_distance 2.3.1.0 j 115 | Junta euclidean_distance 2.3.1.0 j 116 | Junta urltokenizer 2.3.1.0 j 117 | 118 | 119 | # Usage Examples 120 | 121 | ### Hamming Distance 122 | 123 | curl -XPOST 'http://localhost:9200/twitter/_search?pretty' -d '{ 124 | "query": { 125 | "function_score": { 126 | "min_score": IDEAL MIN SCORE HERE, 127 | "query":{ 128 | "match_all":{} 129 | }, 130 | "functions": [ 131 | { 132 | "script_score": { 133 | "script": "hamming_distance", 134 | "lang" : "native", 135 | "params": { 136 | "param_hash": "HASH TO COMPARE WITH", 137 | "param_field":"FIELD WHERE HASH IS STORED" 138 | } 139 | } 140 | } 141 | ] 142 | } 143 | } 144 | }' 145 | 146 | 147 | ### Euclidean Distance 148 | 149 | curl -XPOST 'http://localhost:9200/twitter/_search?pretty' -d '{ 150 | "query": { 151 | "function_score": { 152 | "min_score": IDEAL MIN SCORE HERE, 153 | "query":{ 154 | "match_all":{} 155 | }, 156 | "functions": [ 157 | { 158 | "script_score": { 159 | "script": "euclidean_distance", 160 | "lang" : "native", 161 | "params": { 162 | "param_hash": "HASH TO COMPARE WITH", 163 | "param_field":"FIELD WHERE HASH IS STORED" 164 | } 165 | } 166 | } 167 | ] 168 | } 169 | } 170 | }' 171 | 172 | ### Auto Colour Correlogram 173 | 174 | curl -XPOST 'http://localhost:9200/twitter/_search?pretty' -d '{ 175 | "query": { 176 | "function_score": { 177 | "min_score": IDEAL MIN SCORE HERE, 178 | "query":{ 179 | "match_all":{} 180 | }, 181 | "functions": [ 182 | { 183 | "script_score": { 184 | "script": "autocolourcorrelogram", 185 | "lang" : "native", 186 | "params": { 187 | "param_acc": "CORRELOGRAM TO COMPARE WITH" 188 | } 189 | } 190 | } 191 | ] 192 | } 193 | } 194 | }' 195 | 196 | ### URL Tokenizer 197 | In your index mappings/settings file: 198 | ``` 199 | ... 200 | "settings": { 201 | "index.requests.cache.enable": true, 202 | "analysis":{ 203 | "analyzer":{ 204 | "urlanalyzer":{ 205 | "type": "custom", 206 | "tokenizer": "urltokenizer" 207 | } 208 | } 209 | } 210 | }, 211 | ... 212 | "url": { 213 | "type": "string", 214 | "analyzer": "urlanalyzer" 215 | }, 216 | ... 217 | ``` 218 | -------------------------------------------------------------------------------- /autocolourcorrelogram/build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.cameraforensics' 2 | version '2.4.1.0' 3 | 4 | sourceCompatibility = JavaVersion.VERSION_1_7 5 | targetCompatibility = JavaVersion.VERSION_1_7 6 | 7 | configurations { 8 | provided 9 | } 10 | 11 | apply plugin: 'idea' 12 | 13 | idea { 14 | module { 15 | scopes.PROVIDED.plus += [configurations.provided] 16 | } 17 | } 18 | 19 | sourceSets { 20 | main.compileClasspath += configurations.provided 21 | test.compileClasspath += configurations.provided 22 | test.runtimeClasspath += configurations.provided 23 | } 24 | 25 | jar { 26 | baseName = 'autocolourcorrelogram' 27 | version = '2.4.1.0' 28 | from { 29 | configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 30 | } 31 | } 32 | 33 | dependencies { 34 | provided 'org.elasticsearch:elasticsearch:2.4.1' 35 | compile "commons-codec:commons-codec:1.10" 36 | } 37 | -------------------------------------------------------------------------------- /autocolourcorrelogram/src/main/java/com/cameraforensics/elasticsearch/plugins/AutoColourCorrelogramDistancePlugin.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.elasticsearch.plugins.Plugin; 4 | import org.elasticsearch.script.ScriptModule; 5 | 6 | public class AutoColourCorrelogramDistancePlugin extends Plugin { 7 | 8 | private static final String PLUGIN_NAME = "autocolourcorrelogram"; 9 | 10 | @Override 11 | public String name() { 12 | return PLUGIN_NAME; 13 | } 14 | 15 | @Override 16 | public String description() { 17 | return "A scoring function to calculate the distance between two Auto Colour Correlograms."; 18 | } 19 | 20 | public void onModule(ScriptModule scriptModule) { 21 | scriptModule.registerScript(PLUGIN_NAME, AutoColourCorrelogramDistanceScriptFactory.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /autocolourcorrelogram/src/main/java/com/cameraforensics/elasticsearch/plugins/AutoColourCorrelogramDistanceScript.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.elasticsearch.index.fielddata.ScriptDocValues; 4 | import org.elasticsearch.script.AbstractFloatSearchScript; 5 | 6 | import java.util.Map; 7 | 8 | public class AutoColourCorrelogramDistanceScript extends AbstractFloatSearchScript { 9 | 10 | private static final int SIZE_X = 64; 11 | private static final int SIZE_Y = 4; 12 | 13 | private float[][] queryCorrelogram = new float[SIZE_X][SIZE_Y]; 14 | 15 | public AutoColourCorrelogramDistanceScript(Map params) { 16 | super(); 17 | queryCorrelogram = parseCorrelogram((String) params.get("param_acc")); 18 | } 19 | 20 | /** 21 | * EG: This: 22 | * ``` 23 | * 11.0,9.0,7.0,7.0;13.0,12.0,12.0,11.0;8.0,5.0,4.0,3.0;10.0,7.0,6.0,6.0;5.0,3.0,2.0,1.0;3.0,0.0,0.0,0.0;2.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;10.0,8.0,6.0,5.0;8.0,4.0,3.0,2.0;12.0,10.0,9.0,8.0;10.0,7.0,6.0,5.0;8.0,5.0,4.0,3.0;10.0,6.0,3.0,1.0;1.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;6.0,3.0,1.0,1.0;3.0,0.0,0.0,0.0;3.0,1.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;7.0,3.0,2.0,2.0;4.0,1.0,0.0,0.0;3.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;1.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;1.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;7.0,3.0,1.0,1.0;15.0,14.0,13.0,13.0;10.0,7.0,6.0,4.0;15.0,15.0,14.0,14.0;13.0,11.0,9.0,8.0;15.0,15.0,15.0,15.0;1.0,0.0,0.0,0.0;10.0,7.0,5.0,3.0;11.0,8.0,6.0,5.0;12.0,10.0,9.0,9.0;13.0,11.0,10.0,9.0;4.0,1.0,0.0,0.0;5.0,2.0,1.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;8.0,5.0,3.0,2.0;9.0,7.0,5.0,5.0;5.0,2.0,1.0,0.0;0.0,0.0,0.0,0.0;1.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;11.0,8.0,7.0,6.0;11.0,8.0,7.0,7.0;6.0,2.0,1.0,0.0;2.0,0.0,0.0,0.0;2.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0;0.0,0.0,0.0,0.0; 24 | * ``` 25 | * will produce: 26 | * [[11.0, 9.0, 7.0, 7.0], [13.0, 12.0, 12.0, 11.0] ... ] 27 | * @param correlogramStr 28 | * @return 29 | */ 30 | private float[][] parseCorrelogram(String correlogramStr) { 31 | if (correlogramStr == null) { 32 | return null; 33 | } 34 | 35 | float[][] correlogram = new float[SIZE_X][SIZE_Y]; 36 | String[] rows = correlogramStr.split(";"); 37 | if (rows.length != SIZE_X) { 38 | return null; 39 | } 40 | 41 | for (int i = 0; i < rows.length; i++) { 42 | String[] cols = rows[i].split(","); 43 | if (cols.length != SIZE_Y) { 44 | return null; 45 | } 46 | 47 | for (int j = 0; j < cols.length; j++) { 48 | try { 49 | correlogram[i][j] = Integer.parseInt(cols[j]); 50 | } catch (NumberFormatException nfe) { 51 | return null; 52 | } 53 | } 54 | } 55 | return correlogram; 56 | } 57 | 58 | private float getDistance(float[][] correlogram, float[][] queryCorrelogram) { 59 | float result = 0; 60 | for (int i = 0; i < correlogram.length; i++) { 61 | float[] ints = correlogram[i]; 62 | for (int j = 0; j < ints.length; j++) { 63 | result += (correlogram[i][j] > 0 ? (correlogram[i][j] / 2f) * Math.log((2f * correlogram[i][j]) / (correlogram[i][j] + queryCorrelogram[i][j])) : 0) + 64 | (queryCorrelogram[i][j] > 0 ? (queryCorrelogram[i][j] / 2f) * Math.log((2f * queryCorrelogram[i][j]) / (correlogram[i][j] + queryCorrelogram[i][j])) : 0); 65 | } 66 | } 67 | 68 | return (float) Integer.MAX_VALUE - result; 69 | } 70 | 71 | @Override 72 | public float runAsFloat() { 73 | if (queryCorrelogram == null) { 74 | return Integer.MAX_VALUE; 75 | } 76 | 77 | float[][] correlogram = parseCorrelogram(((ScriptDocValues.Strings) doc().get("correlogram")).getValue()); 78 | if (correlogram == null) { 79 | return Integer.MAX_VALUE; 80 | } 81 | 82 | return getDistance(correlogram, queryCorrelogram); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /autocolourcorrelogram/src/main/java/com/cameraforensics/elasticsearch/plugins/AutoColourCorrelogramDistanceScriptFactory.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.elasticsearch.common.Nullable; 4 | import org.elasticsearch.script.ExecutableScript; 5 | import org.elasticsearch.script.NativeScriptFactory; 6 | 7 | import java.util.Map; 8 | 9 | public class AutoColourCorrelogramDistanceScriptFactory implements NativeScriptFactory { 10 | @Override 11 | public ExecutableScript newScript(@Nullable Map params) { 12 | return new AutoColourCorrelogramDistanceScript(params); 13 | } 14 | 15 | @Override 16 | public boolean needsScores() { 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /autocolourcorrelogram/src/main/resources/plugin-descriptor.properties: -------------------------------------------------------------------------------- 1 | name=autocolourcorrelogram 2 | description=A scoring function to calculate the distance between two Auto Colour Correlograms. 3 | version=2.4.1.0 4 | jvm=true 5 | classname=com.cameraforensics.elasticsearch.plugins.AutoColourCorrelogramDistancePlugin 6 | java.version=1.7 7 | elasticsearch.version=2.4.1 -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.cameraforensics' 2 | version '6.2.4.0' 3 | 4 | apply plugin: 'java' 5 | 6 | subprojects { 7 | group 'com.cameraforensics' 8 | version '6.2.4.0' 9 | 10 | apply plugin: 'maven' 11 | apply plugin: 'java' 12 | apply plugin: 'idea' 13 | 14 | sourceCompatibility = JavaVersion.VERSION_1_8 15 | targetCompatibility = JavaVersion.VERSION_1_8 16 | 17 | repositories { 18 | mavenLocal() 19 | maven { url "${artifactoryUrl}/libs-release"} 20 | mavenCentral() 21 | } 22 | 23 | configurations { 24 | provided 25 | } 26 | 27 | idea { 28 | module { 29 | scopes.PROVIDED.plus += [configurations.provided] 30 | } 31 | } 32 | 33 | sourceSets { 34 | main.compileClasspath += configurations.provided 35 | test.compileClasspath += configurations.provided 36 | test.runtimeClasspath += configurations.provided 37 | } 38 | 39 | // custom tasks for creating source/javadoc jars 40 | task sourcesJar(type: Jar, dependsOn:classes) { 41 | classifier = 'sources' 42 | from sourceSets.main.allSource 43 | } 44 | 45 | task javadocJar(type: Jar, dependsOn:javadoc) { 46 | classifier = 'javadoc' 47 | from javadoc.destinationDir 48 | } 49 | 50 | // add javadoc/source jar tasks as artifacts 51 | artifacts { 52 | archives sourcesJar 53 | archives javadocJar 54 | } 55 | 56 | dependencies { 57 | provided 'org.elasticsearch:elasticsearch:6.2.4' 58 | testCompile 'junit:junit:4.11' 59 | testCompile 'org.mockito:mockito-all:1.9.5' 60 | } 61 | 62 | 63 | // task prePrepare(type: Copy, dependsOn:build) { 64 | // from { 65 | // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 66 | // } 67 | // into "${buildDir}/elasticsearch" 68 | // } 69 | // 70 | // 71 | // task prepare(type: Zip, dependsOn:prePrepare) { 72 | // from "${buildDir}/elasticsearch" 73 | // // new File(""){ 74 | // // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 75 | // // } 76 | // } 77 | 78 | // 79 | // task prepare(type: Zip, dependsOn:build) { 80 | // from { 81 | // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 82 | // } 83 | // } 84 | } -------------------------------------------------------------------------------- /dist.sh: -------------------------------------------------------------------------------- 1 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 2 | CLUSTER_NAME=$2 3 | EXTRA_SSH_PARAMS=$3 4 | 5 | echo $DIR 6 | 7 | get_dns_names() { 8 | echo "Finding servers in cluster: ${CLUSTER_NAME}" 9 | dns_names_str=$(aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" "Name=tag-key,Values=Name" "Name=tag-value,Values=$CLUSTER_NAME" --query "Reservations[*].Instances[*].PublicDnsName | [][]" --output text) 10 | echo $dns_names_str 11 | IFS=' ' read -r -a dns_names <<< "$dns_names_str" 12 | echo "Found ${#dns_names[@]} servers" 13 | } 14 | 15 | get_module_file() { 16 | module=$1 17 | module_file=$(ls ${DIR}/${module}/build/distributions/*.zip | head -n1 | tr "/" "\n" | tail -n1) 18 | } 19 | 20 | build(){ 21 | module=$1 22 | module_name=$(echo "${module}" | sed s/://g) 23 | echo "Building ${module_name}" 24 | gradle -b ${DIR}/build.gradle ${module}clean ${module}build ${module}prepare 25 | } 26 | 27 | upload(){ 28 | module=$1 29 | for i in "${dns_names[@]}"; do 30 | echo "Uploading ${module} to ${i}" 31 | scp ${EXTRA_SSH_PARAMS} ${DIR}/${module}/build/distributions/*.zip ubuntu@${i}:./ 32 | done 33 | } 34 | 35 | install() { 36 | module=$1 37 | get_module_file $module 38 | for i in "${dns_names[@]}"; do 39 | echo "Installing ${module} on ${i}" 40 | ssh ${EXTRA_SSH_PARAMS} ubuntu@${i} << EOF 41 | sudo /usr/share/elasticsearch/bin/plugin install -b file:///home/ubuntu/${module_file} 42 | sudo service elasticsearch restart 43 | EOF 44 | done 45 | } 46 | 47 | case "$1" in 48 | all) 49 | build 50 | get_dns_names 51 | upload "euclideandistance" 52 | upload "hammingdistance" 53 | install "euclideandistance" 54 | install "hammingdistance" 55 | ;; 56 | euclideandistance) 57 | build ":euclideandistance:" 58 | get_dns_names 59 | upload "euclideandistance" 60 | install "euclideandistance" 61 | ;; 62 | hammingdistance) 63 | build ":hammingdistance:" 64 | get_dns_names 65 | upload "hammingdistance" 66 | install "hammingdistance" 67 | ;; 68 | uploadall) 69 | build 70 | get_dns_names 71 | upload "euclideandistance" 72 | upload "hammingdistance" 73 | ;; 74 | *) 75 | echo $" 76 | 77 | This script allows you to build, upload and install elasticsearch plugins. 78 | 79 | Usage: $0 {all|euclideandistance|hammingdistance} ES-CLUSTER-NAME [EXTRA-SSH-COMMANDS] 80 | 81 | Options: 82 | all - build, upload and install both euclideandistance and hammingdistance plugins 83 | euclideandistance - build, upload and install just the euclideandistance scoring script plugin 84 | hammingdistance - build, upload and install just the hammingdistance scoring script plugin 85 | 86 | Params: 87 | ES-CLUSTER-NAME - the name of the elasticsearch cluster (eg: dev-cluster-bob-geldoff) 88 | EXTRA-SSH-COMMANDS - additional parameters to include with the scp and ssh commands (eg:-i my_key_file.pem) (Optional) 89 | " 90 | exit 1 91 | esac -------------------------------------------------------------------------------- /euclideandistance/build.gradle: -------------------------------------------------------------------------------- 1 | def baseName = 'hammingdistance' 2 | def version = '6.2.4.0' 3 | 4 | jar { 5 | baseName = "${baseName}" 6 | version = "${version}" 7 | from { 8 | configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 9 | } 10 | } 11 | 12 | task prePrepare(type: Copy, dependsOn:build) { 13 | from { 14 | [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 15 | } 16 | into "${buildDir}/elasticsearch" 17 | } 18 | 19 | task prepare(type: Zip, dependsOn:prePrepare) { 20 | from "${buildDir}/elasticsearch" 21 | // new File(""){ 22 | // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 23 | // } 24 | } 25 | 26 | 27 | dependencies { 28 | compile "commons-codec:commons-codec:1.10" 29 | } 30 | -------------------------------------------------------------------------------- /euclideandistance/src/main/java/com/cameraforensics/elasticsearch/plugins/EuclideanDistanceScriptEngine.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.apache.commons.codec.binary.Base64; 4 | import org.apache.lucene.index.LeafReaderContext; 5 | import org.elasticsearch.index.fielddata.ScriptDocValues; 6 | import org.elasticsearch.script.ScriptContext; 7 | import org.elasticsearch.script.ScriptEngine; 8 | import org.elasticsearch.script.SearchScript; 9 | 10 | import java.io.IOException; 11 | import java.util.Map; 12 | 13 | public class EuclideanDistanceScriptEngine implements ScriptEngine { 14 | @Override 15 | public String getType() { 16 | return "expert_scripts"; 17 | } 18 | 19 | @Override 20 | public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) { 21 | if (context.equals(SearchScript.CONTEXT) == false) { 22 | throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]"); 23 | } 24 | // we use the script "source" as the script identifier 25 | if ("euclidean_distance".equals(scriptSource)) { 26 | SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() { 27 | final String field; 28 | final String hash; 29 | final byte[] paramHash; 30 | private int maxScore = 9363600; 31 | 32 | { 33 | if (p.containsKey("field") == false) { 34 | throw new IllegalArgumentException("Missing parameter [field]"); 35 | } 36 | if (p.containsKey("hash") == false) { 37 | throw new IllegalArgumentException("Missing parameter [hash]"); 38 | } 39 | field = p.get("field").toString(); 40 | hash = p.get("hash").toString(); 41 | if (hash != null) { 42 | paramHash = convertFromString(hash); 43 | } 44 | else { 45 | paramHash = null; 46 | } 47 | 48 | } 49 | 50 | private byte[] convertFromString(String hashStr) { 51 | return Base64.decodeBase64(hashStr); 52 | } 53 | 54 | @Override 55 | public SearchScript newInstance(LeafReaderContext context) throws IOException { 56 | return new SearchScript(p, lookup, context) { 57 | 58 | @Override 59 | public double runAsDouble() { 60 | String fieldValue = ((ScriptDocValues.Strings) getDoc().get(field)).getValue(); 61 | if (hash == null || fieldValue == null) { 62 | return (float) maxScore; 63 | } 64 | 65 | byte[] fieldValueHash = convertFromString(fieldValue); 66 | 67 | if (fieldValueHash.length != paramHash.length) { 68 | return (float) maxScore; 69 | } 70 | double distance = 0.0; 71 | for (int i = 0; i < fieldValueHash.length; i++) { 72 | final int diff = fieldValueHash[i] - paramHash[i]; 73 | distance += diff * diff; 74 | } 75 | return (float) Math.floor(maxScore - distance); 76 | 77 | } 78 | }; 79 | } 80 | 81 | @Override 82 | public boolean needs_score() { 83 | return false; 84 | } 85 | }; 86 | return context.factoryClazz.cast(factory); 87 | } 88 | throw new IllegalArgumentException("Unknown script name " + scriptSource); 89 | } 90 | 91 | @Override 92 | public void close() { 93 | // optionally close resources 94 | } 95 | } -------------------------------------------------------------------------------- /euclideandistance/src/main/resources/plugin-descriptor.properties: -------------------------------------------------------------------------------- 1 | name=euclidean_distance 2 | description=A scoring function to calculate the euclidean distance between two hex encoded strings. 3 | version=6.2.4.0 4 | classname=com.cameraforensics.elasticsearch.plugins.EuclideanDistanceScriptEngine 5 | java.version=1.8 6 | elasticsearch.version=6.2.4 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CameraForensics/elasticsearch-plugins/db6f6a2c1a00bfffb5668b67518c29fe877327b0/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Sep 16 10:12:38 BST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /hammingdistance/build.gradle: -------------------------------------------------------------------------------- 1 | def baseName = 'hammingdistance' 2 | def version = '6.2.4.0' 3 | 4 | jar { 5 | baseName = "${baseName}" 6 | version = "${version}" 7 | from { 8 | configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 9 | } 10 | } 11 | 12 | task prePrepare(type: Copy, dependsOn:build) { 13 | from { 14 | [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 15 | } 16 | into "${buildDir}/elasticsearch" 17 | } 18 | 19 | 20 | task prepare(type: Zip, dependsOn:prePrepare) { 21 | from "${buildDir}/elasticsearch" 22 | // new File(""){ 23 | // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 24 | // } 25 | } 26 | -------------------------------------------------------------------------------- /hammingdistance/src/main/java/com/cameraforensics/elasticsearch/plugins/HammingDistanceScriptEngine.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.apache.lucene.index.LeafReaderContext; 4 | import org.elasticsearch.index.fielddata.ScriptDocValues; 5 | import org.elasticsearch.script.ScriptContext; 6 | import org.elasticsearch.script.ScriptEngine; 7 | import org.elasticsearch.script.SearchScript; 8 | 9 | import java.io.IOException; 10 | import java.util.Map; 11 | 12 | public class HammingDistanceScriptEngine implements ScriptEngine { 13 | @Override 14 | public String getType() { 15 | return "expert_scripts"; 16 | } 17 | 18 | @Override 19 | public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) { 20 | if (context.equals(SearchScript.CONTEXT) == false) { 21 | throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]"); 22 | } 23 | // we use the script "source" as the script identifier 24 | if ("hamming_distance".equals(scriptSource)) { 25 | SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() { 26 | final String field; 27 | final String hash; 28 | final int length; 29 | 30 | { 31 | if (p.containsKey("field") == false) { 32 | throw new IllegalArgumentException("Missing parameter [field]"); 33 | } 34 | if (p.containsKey("hash") == false) { 35 | throw new IllegalArgumentException("Missing parameter [hash]"); 36 | } 37 | field = p.get("field").toString(); 38 | hash = p.get("hash").toString(); 39 | if (hash != null) { 40 | length = hash.length(); 41 | } 42 | else { 43 | length = 0; 44 | } 45 | } 46 | 47 | @Override 48 | public SearchScript newInstance(LeafReaderContext context) throws IOException { 49 | return new SearchScript(p, lookup, context) { 50 | private int hammingDistance(CharSequence lhs, CharSequence rhs) { 51 | int distance = length; 52 | for (int i = 0, l = lhs.length(); i < l; i++) { 53 | if (lhs.charAt(i) != rhs.charAt(i)) { 54 | distance--; 55 | } 56 | } 57 | 58 | return distance; 59 | } 60 | 61 | @Override 62 | public double runAsDouble() { 63 | String fieldValue = ((ScriptDocValues.Strings) getDoc().get(field)).getValue(); 64 | if (hash == null || fieldValue == null || fieldValue.length() != hash.length()) { 65 | return 0.0f; 66 | } 67 | 68 | return hammingDistance(fieldValue, hash); 69 | } }; 70 | } 71 | 72 | @Override 73 | public boolean needs_score() { 74 | return false; 75 | } 76 | }; 77 | return context.factoryClazz.cast(factory); 78 | } 79 | throw new IllegalArgumentException("Unknown script name " + scriptSource); 80 | } 81 | 82 | @Override 83 | public void close() { 84 | // optionally close resources 85 | } 86 | } -------------------------------------------------------------------------------- /hammingdistance/src/main/resources/plugin-descriptor.properties: -------------------------------------------------------------------------------- 1 | name=hamming_distance 2 | description=A scoring function to calculate hamming distance between two hex encoded strings. 3 | version=6.2.4.0 4 | classname=com.cameraforensics.elasticsearch.plugins.HammingDistanceScriptEngine 5 | java.version=1.8 6 | elasticsearch.version=6.2.4 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'elasticsearch-plugins' 2 | include 'hammingdistance' 3 | include 'euclideandistance' 4 | include 'urltokenizer' 5 | 6 | -------------------------------------------------------------------------------- /travis-build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.cameraforensics' 2 | version '2.4.1' 3 | 4 | apply plugin: 'java' 5 | 6 | sourceCompatibility = JavaVersion.VERSION_1_7 7 | 8 | -------------------------------------------------------------------------------- /urltokenizer/build.gradle: -------------------------------------------------------------------------------- 1 | def baseName = 'urltokenizer' 2 | def version = '6.2.4.0' 3 | 4 | 5 | jar { 6 | baseName = "${baseName}" 7 | version = "${version}" 8 | from { 9 | configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 10 | } 11 | } 12 | 13 | task prePrepare(type: Copy, dependsOn:build) { 14 | from { 15 | [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 16 | } 17 | into "${buildDir}/predist/elasticsearch" 18 | } 19 | 20 | task prepare(type: Zip, dependsOn:prePrepare) { 21 | from "${buildDir}/predist" 22 | // new File(""){ 23 | // [new File("build/libs/${baseName}-${version}.jar"), new File("build/resources/main/plugin-descriptor.properties")] 24 | // } 25 | } 26 | 27 | dependencies { 28 | compile "commons-codec:commons-codec:1.10" 29 | } 30 | -------------------------------------------------------------------------------- /urltokenizer/src/main/java/com/cameraforensics/elasticsearch/plugins/UrlTokenizer.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.apache.lucene.analysis.Tokenizer; 4 | import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; 5 | import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; 6 | import org.apache.lucene.analysis.tokenattributes.OffsetAttributeImpl; 7 | import org.apache.lucene.util.AttributeFactory; 8 | 9 | import java.io.IOException; 10 | import java.io.Reader; 11 | import java.net.MalformedURLException; 12 | import java.net.URL; 13 | import java.util.*; 14 | 15 | public class UrlTokenizer extends Tokenizer { 16 | 17 | private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); 18 | // private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class); 19 | 20 | protected List tokens = new ArrayList<>(); 21 | 22 | protected String stringToTokenize; 23 | 24 | protected int position = 0; 25 | 26 | public UrlTokenizer() { 27 | super(DEFAULT_TOKEN_ATTRIBUTE_FACTORY); 28 | } 29 | 30 | @Override 31 | public final boolean incrementToken() throws IOException { 32 | clearAttributes(); 33 | if (position >= tokens.size()) { 34 | position = 0; 35 | return false; 36 | } else { 37 | String token = tokens.get(position); 38 | termAtt.setEmpty().append(token); 39 | termAtt.setLength(token.length()); 40 | // int startOffset = stringToTokenize.indexOf(token); //Index of is linear and so not performant. Record start/ends when splitting 41 | // offsetAtt.setOffset(startOffset, startOffset + token.length()); 42 | position++; 43 | return true; 44 | } 45 | } 46 | 47 | protected List splitUrl(String url) { 48 | return splitUrl(url, true); 49 | } 50 | 51 | protected List splitUrl(String url, boolean includeParams) { 52 | Set parts = new HashSet<>(); 53 | URL realUrl; 54 | try { 55 | realUrl = new URL(url); 56 | String host = realUrl.getHost(); 57 | parts.add(host); 58 | 59 | if (includeParams) { 60 | String query = realUrl.getQuery(); 61 | if (query != null && !"".equals(query.trim())) { 62 | parts.addAll(Arrays.asList(realUrl.getQuery().split("&"))); 63 | parts.add(realUrl.getQuery()); 64 | parts.add(url.substring(0, url.length() - (query.length() + 1))); 65 | } 66 | } 67 | 68 | String path = realUrl.getPath(); 69 | if (path != null && !"".equals(path.trim())) { 70 | parts.add(realUrl.getPath().substring(1)); 71 | String[] pathSegments = realUrl.getPath().substring(1).split("/"); 72 | 73 | int idx = url.indexOf(realUrl.getHost() + "/") + (realUrl.getHost() + "/").length(); 74 | String upToHost = url.substring(0, idx); 75 | 76 | for (int i = 0; i < pathSegments.length; i++) { 77 | parts.add(pathSegments[i]); 78 | for (int j = i+1; j <= pathSegments.length; j++) { 79 | String permutation = join(Arrays.copyOfRange(pathSegments, i, j), "/"); // + (j == pathSegments.length ? "" : "/"); 80 | parts.add(/* "/" + */permutation); 81 | if (i == 0) { 82 | parts.add(upToHost + permutation); 83 | parts.add(host + "/" + permutation); 84 | } 85 | } 86 | } 87 | } 88 | } catch (MalformedURLException e) { 89 | // Ok, we'll do it the old skool way: 90 | // Let's assume that there's no hippity tippities 91 | String path = null; 92 | if (url.indexOf('?') != -1) { 93 | if (!url.startsWith("?")) { 94 | path = url.substring(0, url.indexOf('?')); 95 | } 96 | if (!url.endsWith("?")) { 97 | if (includeParams) { 98 | String queryString = url.substring(url.indexOf('?') + 1); 99 | parts.addAll(Arrays.asList(queryString.split("&"))); 100 | } 101 | } 102 | } else { 103 | path = url; 104 | } 105 | 106 | if (path != null) { 107 | String[] pathSegments = path.split("/"); 108 | for (int i = 0; i < pathSegments.length; i++) { 109 | parts.add(pathSegments[i]); 110 | for (int j = i+1; j <= pathSegments.length; j++) { 111 | String permutation = join(Arrays.copyOfRange(pathSegments, i, j), "/"); // + (j == pathSegments.length ? "" : "/"); 112 | parts.add(/* "/" + */permutation); 113 | } 114 | 115 | } 116 | } 117 | } 118 | 119 | return new ArrayList<>(parts); 120 | } 121 | 122 | private String join(String[] values, String delimiter) { 123 | StringBuffer strbuf = new StringBuffer(); 124 | 125 | boolean first = true; 126 | 127 | for (String value : values) { 128 | if (!first) { strbuf.append(delimiter); } else { first = false; } 129 | strbuf.append(value); 130 | } 131 | 132 | return strbuf.toString(); 133 | } 134 | 135 | @Override 136 | public void end() throws IOException { 137 | super.end(); 138 | tokens.clear(); 139 | position = 0; 140 | } 141 | 142 | @Override 143 | public void reset() throws IOException { 144 | super.reset(); 145 | fillBuffer(input); 146 | // position = 0; 147 | } 148 | 149 | final char[] buffer = new char[8192]; 150 | private void fillBuffer(Reader input) throws IOException { 151 | int len; 152 | StringBuilder str = new StringBuilder(); 153 | str.setLength(0); 154 | while ((len = input.read(buffer)) > 0) { 155 | str.append(buffer, 0, len); 156 | } 157 | stringToTokenize = str.toString(); 158 | tokens = splitUrl(stringToTokenize, false); 159 | } 160 | 161 | } 162 | -------------------------------------------------------------------------------- /urltokenizer/src/main/java/com/cameraforensics/elasticsearch/plugins/UrlTokenizerFactory.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.apache.lucene.analysis.Tokenizer; 4 | import org.elasticsearch.common.inject.Inject; 5 | import org.elasticsearch.common.settings.Settings; 6 | import org.elasticsearch.env.Environment; 7 | import org.elasticsearch.index.IndexSettings; 8 | import org.elasticsearch.index.analysis.AbstractTokenizerFactory; 9 | 10 | public class UrlTokenizerFactory extends AbstractTokenizerFactory { 11 | 12 | @Inject 13 | public UrlTokenizerFactory(IndexSettings indexSettings, Environment env, String name, Settings settings){ 14 | super(indexSettings, name, settings); 15 | } 16 | 17 | @Override 18 | public Tokenizer create() { 19 | return new UrlTokenizer(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /urltokenizer/src/main/java/com/cameraforensics/elasticsearch/plugins/UrlTokenizerPlugin.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.elasticsearch.index.analysis.TokenizerFactory; 4 | import org.elasticsearch.indices.analysis.AnalysisModule; 5 | import org.elasticsearch.plugins.AnalysisPlugin; 6 | import org.elasticsearch.plugins.Plugin; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | public class UrlTokenizerPlugin extends Plugin implements AnalysisPlugin { 12 | 13 | 14 | @Override 15 | public Map> getTokenizers() { 16 | Map> extra = new HashMap<>(); 17 | extra.put("urltokenizer", UrlTokenizerFactory::new); 18 | return extra; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /urltokenizer/src/main/resources/plugin-descriptor.properties: -------------------------------------------------------------------------------- 1 | name=urltokenizer 2 | description=A custom tokenizer to produce tokens for all permutations of URL path segmentation. 3 | version=6.2.4.0 4 | classname=com.cameraforensics.elasticsearch.plugins.UrlTokenizerPlugin 5 | java.version=1.8 6 | elasticsearch.version=6.2.4 7 | -------------------------------------------------------------------------------- /urltokenizer/src/test/java/com/cameraforensics/elasticsearch/plugins/UrlTokenizerTest.java: -------------------------------------------------------------------------------- 1 | package com.cameraforensics.elasticsearch.plugins; 2 | 3 | import org.junit.Test; 4 | 5 | import java.net.MalformedURLException; 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | import static org.junit.Assert.assertEquals; 10 | import static org.junit.Assert.assertTrue; 11 | 12 | public class UrlTokenizerTest { 13 | 14 | private UrlTokenizer urlTokenizer = new UrlTokenizer(); 15 | 16 | @Test 17 | public void correctly_split_double_segment() { 18 | // given 19 | String url = "129136207330/good-times-only"; 20 | 21 | // when 22 | List splits = urlTokenizer.splitUrl(url); 23 | 24 | // then 25 | assertTrue(splits.contains("129136207330")); 26 | assertTrue(splits.contains("good-times-only")); 27 | assertTrue(splits.contains(url)); 28 | assertEquals(3, splits.size()); 29 | } 30 | 31 | @Test 32 | public void correctly_splits_single_segment() { 33 | // given 34 | String url = "good-times-only"; 35 | 36 | // when 37 | List splits = urlTokenizer.splitUrl(url); 38 | 39 | // then 40 | assertTrue(splits.contains("good-times-only")); 41 | assertEquals(1, splits.size()); 42 | } 43 | 44 | @Test 45 | public void correctly_splits_url_without_domain_or_protocol() { 46 | // given 47 | String url = "129136207330/good-times-only?one=two&three=four"; 48 | 49 | // when 50 | List splits = urlTokenizer.splitUrl(url); 51 | 52 | // then 53 | assertTrue(splits.contains("129136207330")); 54 | assertTrue(splits.contains("129136207330/good-times-only")); 55 | assertTrue(splits.contains("good-times-only")); 56 | assertTrue(splits.contains("one=two")); 57 | assertTrue(splits.contains("three=four")); 58 | assertEquals(5, splits.size()); 59 | } 60 | 61 | @Test 62 | public void correctly_splits_long_url_with_params() throws MalformedURLException { 63 | // given 64 | String url = "https://farm1.domain.com/one/two/three/four.jpg?param1=value1¶m2=value2"; 65 | 66 | // when 67 | List splits = urlTokenizer.splitUrl(url); 68 | 69 | // then 70 | assertTrue(splits.contains("farm1.domain.com")); 71 | assertTrue(splits.contains("one")); 72 | assertTrue(splits.contains("two")); 73 | assertTrue(splits.contains("three")); 74 | assertTrue(splits.contains("four.jpg")); 75 | assertTrue(splits.contains("param1=value1¶m2=value2")); 76 | assertTrue(splits.contains("param1=value1")); 77 | assertTrue(splits.contains("param2=value2")); 78 | assertTrue(splits.contains("https://farm1.domain.com/one")); 79 | assertTrue(splits.contains("https://farm1.domain.com/one/two")); 80 | assertTrue(splits.contains("https://farm1.domain.com/one/two/three")); 81 | assertTrue(splits.contains("https://farm1.domain.com/one/two/three/four.jpg")); 82 | assertTrue(splits.contains("farm1.domain.com/one")); 83 | assertTrue(splits.contains("farm1.domain.com/one/two")); 84 | assertTrue(splits.contains("farm1.domain.com/one/two/three")); 85 | assertTrue(splits.contains("farm1.domain.com/one/two/three/four.jpg")); 86 | assertTrue(splits.contains("one/two/three/four.jpg")); 87 | assertTrue(splits.contains("two/three/four.jpg")); 88 | assertTrue(splits.contains("three/four.jpg")); 89 | assertTrue(splits.contains("one/two/three")); 90 | assertTrue(splits.contains("one/two")); 91 | assertTrue(splits.contains("two/three")); 92 | assertEquals(22, splits.size()); 93 | } 94 | 95 | @Test 96 | public void correctly_splits_long_url_and_excludes_params() throws MalformedURLException { 97 | // given 98 | String url = "https://farm1.domain.com/one/two/three/four.jpg?param1=value1¶m2=value2"; 99 | 100 | // when 101 | List splits = urlTokenizer.splitUrl(url, false); 102 | 103 | // then 104 | assertTrue(splits.contains("farm1.domain.com")); 105 | assertTrue(splits.contains("one")); 106 | assertTrue(splits.contains("two")); 107 | assertTrue(splits.contains("three")); 108 | assertTrue(splits.contains("four.jpg")); 109 | assertTrue(splits.contains("https://farm1.domain.com/one")); 110 | assertTrue(splits.contains("https://farm1.domain.com/one/two")); 111 | assertTrue(splits.contains("https://farm1.domain.com/one/two/three")); 112 | assertTrue(splits.contains("https://farm1.domain.com/one/two/three/four.jpg")); 113 | assertTrue(splits.contains("farm1.domain.com/one")); 114 | assertTrue(splits.contains("farm1.domain.com/one/two")); 115 | assertTrue(splits.contains("farm1.domain.com/one/two/three")); 116 | assertTrue(splits.contains("farm1.domain.com/one/two/three/four.jpg")); 117 | assertTrue(splits.contains("one/two/three/four.jpg")); 118 | assertTrue(splits.contains("two/three/four.jpg")); 119 | assertTrue(splits.contains("three/four.jpg")); 120 | assertTrue(splits.contains("one/two/three")); 121 | assertTrue(splits.contains("one/two")); 122 | assertTrue(splits.contains("two/three")); 123 | assertEquals(19, splits.size()); 124 | } 125 | 126 | @Test 127 | public void correctly_splits_slightly_shorter_url_with_params() throws MalformedURLException { 128 | // given 129 | String url = "https://farm1.domain.com/one/two/four.jpg?param1=value1¶m2=value2"; 130 | 131 | // when 132 | List splits = urlTokenizer.splitUrl(url); 133 | 134 | // then 135 | assertTrue(splits.contains("farm1.domain.com")); 136 | assertTrue(splits.contains("one")); 137 | assertTrue(splits.contains("two")); 138 | assertTrue(splits.contains("four.jpg")); 139 | assertTrue(splits.contains("param1=value1¶m2=value2")); 140 | assertTrue(splits.contains("param1=value1")); 141 | assertTrue(splits.contains("param2=value2")); 142 | assertTrue(splits.contains("https://farm1.domain.com/one")); 143 | assertTrue(splits.contains("https://farm1.domain.com/one/two")); 144 | assertTrue(splits.contains("https://farm1.domain.com/one/two/four.jpg")); 145 | assertTrue(splits.contains("farm1.domain.com/one")); 146 | assertTrue(splits.contains("farm1.domain.com/one/two")); 147 | assertTrue(splits.contains("farm1.domain.com/one/two/four.jpg")); 148 | assertTrue(splits.contains("one/two/four.jpg")); 149 | assertTrue(splits.contains("two/four.jpg")); 150 | assertTrue(splits.contains("one/two")); 151 | assertEquals(16, splits.size()); 152 | } 153 | 154 | @Test 155 | public void correctly_splits_url_with_no_path() throws MalformedURLException { 156 | // given 157 | String url = "https://farm1.domain.com/four.jpg?param1=value1¶m2=value2"; 158 | 159 | // when 160 | List splits = urlTokenizer.splitUrl(url); 161 | Collections.sort(splits); 162 | for (String part : splits) { 163 | System.out.println(part); 164 | } 165 | 166 | // then 167 | assertTrue(splits.contains("farm1.domain.com")); 168 | assertTrue(splits.contains("https://farm1.domain.com/four.jpg")); 169 | assertTrue(splits.contains("farm1.domain.com/four.jpg")); 170 | assertTrue(splits.contains("four.jpg")); 171 | assertTrue(splits.contains("param1=value1¶m2=value2")); 172 | assertTrue(splits.contains("param1=value1")); 173 | assertTrue(splits.contains("param2=value2")); 174 | assertEquals(7, splits.size()); 175 | } 176 | 177 | } 178 | --------------------------------------------------------------------------------