├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.sh ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── alienvault │ │ └── otx │ │ ├── CommandlineRunner.java │ │ ├── connect │ │ ├── ConnectionUtil.java │ │ ├── OTXConnection.java │ │ ├── OTXEndpointParameterTypes.java │ │ ├── OTXEndpointParameters.java │ │ ├── OTXEndpoints.java │ │ └── internal │ │ │ ├── HTTPConfig.java │ │ │ └── HeaderSettingRequestFactory.java │ │ └── model │ │ ├── Page.java │ │ ├── events │ │ ├── Event.java │ │ └── EventPage.java │ │ ├── indicator │ │ ├── Indicator.java │ │ ├── IndicatorPage.java │ │ ├── IndicatorSections.java │ │ └── IndicatorType.java │ │ ├── pulse │ │ ├── OtxDateDeserializer.java │ │ ├── Pulse.java │ │ └── PulsePage.java │ │ └── user │ │ ├── User.java │ │ ├── UserActions.java │ │ └── UserPage.java └── resources │ ├── application.properties │ └── banner.txt └── test ├── java └── com │ └── alienvault │ └── otx │ └── OtxJavaSdkApplicationTests.java └── resources └── test_application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### JetBrains template 3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 4 | 5 | *.iml 6 | 7 | ## Directory-based project format: 8 | .idea/ 9 | # if you remove the above rule, at least ignore the following: 10 | 11 | # User-specific stuff: 12 | # .idea/workspace.xml 13 | # .idea/tasks.xml 14 | # .idea/dictionaries 15 | 16 | # Sensitive or high-churn files: 17 | # .idea/dataSources.ids 18 | # .idea/dataSources.xml 19 | # .idea/sqlDataSources.xml 20 | # .idea/dynamic.xml 21 | # .idea/uiDesigner.xml 22 | 23 | # Gradle: 24 | # .idea/gradle.xml 25 | # .idea/libraries 26 | 27 | # Mongo Explorer plugin: 28 | # .idea/mongoSettings.xml 29 | 30 | ## File-based project format: 31 | *.ipr 32 | *.iws 33 | 34 | ## Plugin-specific files: 35 | 36 | # IntelliJ 37 | out/ 38 | 39 | # mpeltonen/sbt-idea plugin 40 | .idea_modules/ 41 | 42 | # JIRA plugin 43 | atlassian-ide-plugin.xml 44 | 45 | # Crashlytics plugin (for Android Studio and IntelliJ) 46 | com_crashlytics_export_strings.xml 47 | crashlytics.properties 48 | crashlytics-build.properties 49 | 50 | 51 | ### Java template 52 | *.class 53 | 54 | # Mobile Tools for Java (J2ME) 55 | .mtj.tmp/ 56 | 57 | # Package Files # 58 | *.jar 59 | *.war 60 | *.ear 61 | 62 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 63 | hs_err_pid* 64 | 65 | 66 | ### Maven template 67 | target/ 68 | pom.xml.tag 69 | pom.xml.releaseBackup 70 | pom.xml.versionsBackup 71 | pom.xml.next 72 | release.properties 73 | dependency-reduced-pom.xml 74 | 75 | 76 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | install: true 3 | script: 4 | - bash build.sh 5 | env: 6 | global: 7 | - secure: g0A9usPhe/Tj0lnuCwUHgA88fsJ0eU1sgBCUUEUXDSE9wqyHs8ossEagRXOv3RFA+mULCXHuiSyD0CCkvfSfvL9zYzZO3XOcNiMy8GWZahUtYJph256bvw8D5/Y+HJTD8ppvPYjptKs6RyQSfQw796XIMUWHQQhUaKX6a2jho40= 8 | - secure: aV7iNqT38xPCa0PaDP9daA0ykB08j6tK+hVp5aEiQLmZZqCZXnSzPNESZDvLq7IqT5vbynNGMti96gi0jVEnltFY+5ZTSXEmSQycYNzoBOG2zRrb3mk5rYBd3cu/vvA8J3JvJEb+oRuIt8rCL27Qa/oL/+qdvL+vlPnHPK0v+zo= 9 | deploy: 10 | provider: releases 11 | skip_cleanup: true 12 | api_key: 13 | secure: cRwkspFGljS0CPHGsYmpKCP9tSDdGRNv40zJa8+GL6rsiMeAGnbOuVNkkGMFK6whXh5Xwc6dgX2a5s04Qo2Uivvu3qANLlTccRsthnufJM0RG9B+atZhbqgNF6Njpuy6O4afdGdcMsceBErLhgK8f18VVKUyFZ5NTbDnornD5QQ= 14 | file: target/*.jar 15 | file_glob: true 16 | on: 17 | tags: true 18 | repo: AlienVault-OTX/OTX-Java-SDK 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015 AlienVault, Inc. 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 2015 AlienVault, Inc. 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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OTX DirectConnect Java SDK 2 | 3 | [Build Status](https://travis-ci.org/AlienVault-OTX/OTX-Java-SDK.svg?branch=master) 4 | 5 | OTX DirectConnect provides a mechanism to automatically pull indicators of compromise from the Open Threat Exchange portal into your environment. The DirectConnect API provides access to all _Pulses_ that you have subscribed to in Open Threat Exchange (https://otx.alienvault.com). 6 | 7 | ## Installation and Usage 8 | 1. Clone this repo 9 | 2. Using maven (https://maven.apache.org/) run 10 | ``` bash 11 | mvn install -DskipTests 12 | ``` 13 | 3. Then execute the resulting jar file 14 | ``` bash 15 | java -jar target/DirectConnect-Java-SDK-0.1.0.jar 16 | ``` 17 | 18 | ## Running the test suite 19 | 1. Edit the file ./src/test/resources/test\_application.properties and add your ATX API key to key= property 20 | ``` 21 | ... 22 | key= 23 | ... 24 | ``` 25 | 2. Using maven, run 26 | ``` bash 27 | mvn install 28 | ``` 29 | 30 | ## Commandline Usage 31 | | Option | Long Format | Description | 32 | | ------:| ------:| :------| 33 | | -d | --date | Only pulses modified since the date provided will be downloaded | 34 | | -i | --indicators | Indicator types to save to the file. Provide a comma separated string of indicators (IPV4,IPV6,DOMAIN,HOSTNAME,EMAIL,URL,URI,MD5,SHA1,SHA256,PEHASH,IMPHASH,CIDR,PATH,MUTEX,CVE) | 35 | | -k | --key | API Key from OTX Settings Page (https://otx.alienvault.com/settings/). | 36 | | -o | --output-file | File to save indicators (Optional, default will write to console) | 37 | 38 | 39 | _Example_ 40 | Print all IPV4 and DOMAIN indicators from all pulses that you have subscribed to in the web interface that have been modified since April 15th, 2015. 41 | ``` bash 42 | java -jar target/DirectConnect-Java-SDK-0.1.0.jar -k -d 2015-04-15 -i IPV4,DOMAIN 43 | ``` 44 | 45 | ## Embedding in an Application 46 | 47 | 1. Follow installation and usage steps outlined above 48 | 2. Add the compiled jar file to your classpath (DirectConnect-Java-SDK-0.1.0.jar) 49 | 3. Create a new [OTXConnection](AlienVault-Labs/OTX-Java-SDK/blob/master/src/main/java/com/alienvault/otx/connect/OTXConnection.java) object using the constructor that accepts an API key 50 | 4. Call the utility methods provided by OTXConnection to retrieve Pulses 51 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | set -e 2 | 3 | if [ ! -z "${TRAVIS_TAG:-}" ]; then 4 | mvn versions:set -DnewVersion="${TRAVIS_TAG#v}" 5 | fi 6 | 7 | mvn install 8 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.alienvault.otx 7 | DirectConnect-Java-SDK 8 | 0.1.0 9 | jar 10 | 11 | OTX Java SDK 12 | OTX DirectConnect SDK for Java 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.2.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | com.alienvault.otx.CommandlineRunner 24 | 1.7 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.springframework 35 | spring-web 36 | 37 | 38 | com.fasterxml.jackson.core 39 | jackson-databind 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-test 44 | test 45 | 46 | 47 | joda-time 48 | joda-time 49 | 2.5 50 | 51 | 52 | commons-cli 53 | commons-cli 54 | 1.2 55 | 56 | 57 | org.springframework.retry 58 | spring-retry 59 | 1.1.0.RELEASE 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-maven-plugin 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/CommandlineRunner.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx; 2 | 3 | import com.alienvault.otx.connect.ConnectionUtil; 4 | import com.alienvault.otx.connect.OTXConnection; 5 | import com.alienvault.otx.model.indicator.Indicator; 6 | import com.alienvault.otx.model.indicator.IndicatorType; 7 | import com.alienvault.otx.model.pulse.Pulse; 8 | import org.apache.commons.cli.*; 9 | import org.joda.time.DateTime; 10 | import org.springframework.boot.SpringApplication; 11 | import org.springframework.boot.autoconfigure.SpringBootApplication; 12 | import org.springframework.context.ConfigurableApplicationContext; 13 | import org.springframework.util.StringUtils; 14 | import org.springframework.web.client.HttpClientErrorException; 15 | 16 | import java.io.*; 17 | import java.net.MalformedURLException; 18 | import java.net.URISyntaxException; 19 | import java.util.*; 20 | 21 | @SpringBootApplication 22 | public class CommandlineRunner { 23 | 24 | private static Options getOptions() { 25 | Options opts = new Options(); 26 | opts.addOption("k", "key", true, "API Key from OTX Settings Page (https://otx.alienvault.com/settings/)."); 27 | opts.addOption("o", "output-file", true, "File to save indicators"); 28 | opts.addOption("d", "date", true, "Only pulses modified since the date provided will be downloaded"); 29 | opts.addOption("i", "indicators", true, "Indicator types to save to the file. Provide a comma separated string of indicators (" + IndicatorType.toTypeList() + ")"); 30 | return opts; 31 | 32 | } 33 | 34 | public static void main(String[] args) { 35 | ConfigurableApplicationContext run = SpringApplication.run(CommandlineRunner.class, args); 36 | 37 | List filteredArgs = new ArrayList<>(); 38 | for (String arg : args) { 39 | if (!"--spring.output.ansi.enabled=always".equals(arg)) 40 | filteredArgs.add(arg); 41 | } 42 | try { 43 | CommandLineParser parser = new BasicParser(); 44 | CommandLine cmd = parser.parse(getOptions(), filteredArgs.toArray(new String[filteredArgs.size()])); 45 | String apiKey; 46 | if (cmd.hasOption('k')) 47 | apiKey = cmd.getOptionValue('k'); 48 | else 49 | throw new ParseException("-key is a required option"); 50 | DateTime date = null; 51 | if (cmd.hasOption('d')) 52 | date = DateTime.parse(cmd.getOptionValue('d')); 53 | File dest = null; 54 | if (cmd.hasOption('o')) 55 | dest = new File(cmd.getOptionValue('o')); 56 | PrintWriter outs = getPrintStream(dest); 57 | Set types = new HashSet<>(Arrays.asList(IndicatorType.values())); 58 | if (cmd.hasOption('i')) 59 | types = parseTypes(cmd.getOptionValue('i')); 60 | 61 | OTXConnection connection = ConnectionUtil.getOtxConnection(run.getEnvironment(), apiKey); 62 | List pulses; 63 | if (date != null) 64 | pulses = connection.getPulsesSinceDate(date); 65 | else 66 | pulses = connection.getAllPulses(); 67 | for (Pulse pulse : pulses) { 68 | List indicators = pulse.getIndicators(); 69 | for (Indicator indicator : indicators) { 70 | if (types.contains(indicator.getType())) { 71 | outs.println(indicator.getIndicator()); 72 | outs.flush(); 73 | } 74 | } 75 | } 76 | } catch (URISyntaxException | MalformedURLException e) { 77 | System.out.println("Error configuring OTX connection: " + e.getMessage()); 78 | } catch (HttpClientErrorException ex) { 79 | System.out.println("Error retrieving data: " + ex.getMessage()); 80 | } catch (FileNotFoundException e) { 81 | System.out.println("Error writing to the output file: " + e.getMessage()); 82 | } catch (ParseException e) { 83 | System.out.println("Error parsing commandline options: " + e.getMessage()); 84 | printUsage(); 85 | } 86 | } 87 | 88 | private static Set parseTypes(String types) throws ParseException { 89 | Set strings = StringUtils.commaDelimitedListToSet(types); 90 | Set ret = new HashSet<>(); 91 | for (String string : strings) { 92 | try { 93 | ret.add(IndicatorType.valueOf(string.toUpperCase())); 94 | } catch (IllegalArgumentException e) { 95 | throw new ParseException("Error parsing enum type: " +string); 96 | } 97 | } 98 | return ret; 99 | } 100 | 101 | private static PrintWriter getPrintStream(File dest) throws FileNotFoundException { 102 | if (dest == null) 103 | return new PrintWriter(System.out); 104 | else 105 | return new PrintWriter(new FileOutputStream(dest)); 106 | } 107 | 108 | private static void printUsage() { 109 | HelpFormatter formatter = new HelpFormatter(); 110 | formatter.setWidth(80); 111 | formatter.printHelp("otx", getOptions()); 112 | } 113 | 114 | } 115 | 116 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/ConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect; 2 | 3 | import org.springframework.context.ConfigurableApplicationContext; 4 | import org.springframework.core.env.ConfigurableEnvironment; 5 | import org.springframework.core.env.Environment; 6 | 7 | /** 8 | * Created by rspitler on 5/10/16. 9 | */ 10 | public class ConnectionUtil { 11 | public static OTXConnection getOtxConnection(Environment environment, String apiKey) { 12 | String otxHost = environment.getProperty("host"); 13 | String otxScheme = environment.getProperty("scheme"); 14 | String otxPort = environment.getProperty("port"); 15 | Integer port = null; 16 | if (otxPort != null) 17 | port = Integer.valueOf(otxPort); 18 | return new OTXConnection(apiKey, otxHost, otxScheme, port); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/OTXConnection.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect; 2 | 3 | import com.alienvault.otx.connect.internal.HTTPConfig; 4 | import com.alienvault.otx.model.*; 5 | import com.alienvault.otx.model.events.Event; 6 | import com.alienvault.otx.model.events.EventPage; 7 | import com.alienvault.otx.model.indicator.Indicator; 8 | import com.alienvault.otx.model.indicator.IndicatorPage; 9 | import com.alienvault.otx.model.pulse.Pulse; 10 | import com.alienvault.otx.model.pulse.PulsePage; 11 | import com.alienvault.otx.model.user.User; 12 | import com.alienvault.otx.model.user.UserActions; 13 | import com.alienvault.otx.model.user.UserPage; 14 | import org.apache.commons.logging.Log; 15 | import org.apache.commons.logging.LogFactory; 16 | import org.joda.time.DateTime; 17 | import org.joda.time.format.DateTimeFormatter; 18 | import org.joda.time.format.ISODateTimeFormat; 19 | import org.springframework.http.ResponseEntity; 20 | import org.springframework.http.client.ClientHttpRequestFactory; 21 | import org.springframework.retry.RetryCallback; 22 | import org.springframework.retry.RetryContext; 23 | import org.springframework.retry.backoff.ExponentialBackOffPolicy; 24 | import org.springframework.retry.policy.SimpleRetryPolicy; 25 | import org.springframework.retry.support.RetryTemplate; 26 | import org.springframework.web.client.RestClientException; 27 | import org.springframework.web.client.RestTemplate; 28 | import org.springframework.web.util.UriUtils; 29 | 30 | import java.io.UnsupportedEncodingException; 31 | import java.net.*; 32 | import java.util.*; 33 | 34 | /** 35 | * OTXConnextion takes care of the requests made to 36 | * the OTX service. The utility methods provided give you 37 | * the mechanisms necessary to get the Pulses that have 38 | * been subscribed to in the OTX API. 39 | *

40 | * Construct this class passing in your API key found in the 41 | * 'Settings' page of the web interface. 42 | */ 43 | public class OTXConnection { 44 | 45 | private RestTemplate restTemplate; 46 | private RetryTemplate retryTemplate; 47 | 48 | private String otxHost = "otx.alienvault.com"; 49 | private String otxScheme = "https"; 50 | private Integer otxPort = null; 51 | private static DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis(); 52 | private Log log = LogFactory.getLog(OTXConnection.class); 53 | 54 | /** 55 | * Construct the OTX Connection providing full connection details. 56 | * 57 | * @param apiKey - API key for your OTX Account 58 | * @param host - host of the OTX server (otx.alienvault.com by default) 59 | * @param scheme - scheme to use for the connection to the server (https by default) 60 | * @param port - port for the connection to the server (443 by default) 61 | */ 62 | public OTXConnection(String apiKey, String host, String scheme, Integer port) { 63 | if (host != null) 64 | this.otxHost = host; 65 | if (scheme != null) 66 | this.otxScheme = scheme; 67 | if (port != null) 68 | otxPort = port; 69 | configureRestTemplate(apiKey); 70 | } 71 | 72 | /** 73 | * Construct the OTX Connection providing full connection details. 74 | * 75 | * @param apiKey - API key for your OTX Account 76 | * @param otxHost - host of the OTX server (otx.alienvault.com by default) 77 | * @param otxScheme - scheme to use for the connection to the server (https by default) 78 | */ 79 | public OTXConnection(String apiKey, String otxHost, String otxScheme) { 80 | this.otxHost = otxHost; 81 | this.otxScheme = otxScheme; 82 | configureRestTemplate(apiKey); 83 | } 84 | 85 | /** 86 | * Construct the OTX Connection providing full connection details. 87 | * 88 | * @param apiKey - API key for your OTX Account 89 | */ 90 | public OTXConnection(String apiKey) { 91 | configureRestTemplate(apiKey); 92 | } 93 | 94 | /** 95 | * Construct the OTX Connection providing full connection details. 96 | * 97 | * @param apiKey - API key for your OTX Account 98 | * @param otxHost - host of the OTX server (otx.alienvault.com by default) 99 | */ 100 | public OTXConnection(String apiKey, String otxHost) { 101 | this.otxHost = otxHost; 102 | configureRestTemplate(apiKey); 103 | } 104 | 105 | /** 106 | * Internal API to configure RestTemplate 107 | * 108 | * @param apiKey - API key to configure authorization header 109 | */ 110 | private void configureRestTemplate(String apiKey) { 111 | ClientHttpRequestFactory requestFactory = HTTPConfig.createRequestFactory(apiKey); 112 | restTemplate = new RestTemplate(requestFactory); 113 | retryTemplate = new RetryTemplate(); 114 | retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy()); 115 | } 116 | 117 | /** 118 | * Utility method to access all Pulses subscribed to in the web interface. 119 | * 120 | * @return All of the Pulses 121 | * @throws URISyntaxException 122 | * @throws MalformedURLException 123 | */ 124 | public List getAllPulses() throws URISyntaxException, MalformedURLException { 125 | return getPulses(null); 126 | } 127 | 128 | /** 129 | * Access all indicators for a given pulse id 130 | * 131 | * @param pulseId id of pulse 132 | * @return List indicators contained within pulse 133 | * @throws MalformedURLException 134 | * @throws URISyntaxException 135 | */ 136 | public List getAllIndicatorsForPulse(String pulseId) throws MalformedURLException, URISyntaxException { 137 | return (List) getPagedResults(Collections.singletonMap(OTXEndpointParameters.ID, pulseId), new IndicatorPage(), OTXEndpoints.INDICATORS_FOR_PULSE); 138 | } 139 | 140 | /** 141 | * Access all pulses related to a given pulse id 142 | * 143 | * @param pulseId id of pulse 144 | * @return List pulses related to the given pulse id 145 | * @throws MalformedURLException 146 | * @throws URISyntaxException 147 | */ 148 | public List getAllRelatedPulses(String pulseId) throws MalformedURLException, URISyntaxException { 149 | return (List) getPagedResults(Collections.singletonMap(OTXEndpointParameters.ID, pulseId), new PulsePage(), OTXEndpoints.RELATED_TO_PULSE); 150 | } 151 | 152 | /** 153 | * Utility method to access all Pulses modified since the date passed to the API. 154 | * 155 | * @param lastUpdated - date to cut off the list of pulses 156 | * @return All of the Pulses modified since the lastUpdated date 157 | * @throws URISyntaxException 158 | * @throws MalformedURLException 159 | */ 160 | public List getPulsesSinceDate(DateTime lastUpdated) throws URISyntaxException, MalformedURLException { 161 | return getPulses(Collections.singletonMap(OTXEndpointParameters.MODIFIED_SINCE, fmt.print(lastUpdated))); 162 | } 163 | 164 | /** 165 | * @param pulseId 166 | * @return 167 | * @throws MalformedURLException 168 | * @throws URISyntaxException 169 | */ 170 | public Pulse getPulseDetails(String pulseId) throws MalformedURLException, URISyntaxException { 171 | return executeGetRequest(OTXEndpoints.PULSE_DETAILS, Collections.singletonMap(OTXEndpointParameters.ID, pulseId), Pulse.class); 172 | 173 | } 174 | 175 | /** 176 | * @param searchQuery 177 | * @return 178 | * @throws MalformedURLException 179 | * @throws URISyntaxException 180 | */ 181 | public List searchForPulses(String searchQuery) throws MalformedURLException, URISyntaxException { 182 | return (List) getPagedResults(Collections.singletonMap(OTXEndpointParameters.QUERY, searchQuery), new PulsePage(), OTXEndpoints.SEARCH_PULSES); 183 | } 184 | 185 | /** 186 | * @param searchQuery 187 | * @return 188 | * @throws MalformedURLException 189 | * @throws URISyntaxException 190 | */ 191 | public List searchForUsers(String searchQuery) throws MalformedURLException, URISyntaxException { 192 | return (List) getPagedResults(Collections.singletonMap(OTXEndpointParameters.QUERY, searchQuery), new UserPage(), OTXEndpoints.SEARCH_USERS); 193 | } 194 | 195 | /** 196 | * Get the User object representing the authenticated user 197 | * @return User 198 | * @throws MalformedURLException 199 | * @throws URISyntaxException 200 | */ 201 | public User getMyDetails() throws MalformedURLException, URISyntaxException { 202 | return executeGetRequest(OTXEndpoints.USERS_ME, null, User.class); 203 | } 204 | 205 | /** 206 | * Create a new pulse. 207 | * 208 | * @param newPulse - object representing the pulse to create 209 | * @return the newly created Pulse object with ID and created meta-data 210 | * @throws MalformedURLException 211 | * @throws URISyntaxException 212 | */ 213 | public Pulse createPulse(Pulse newPulse) throws MalformedURLException, URISyntaxException { 214 | return (Pulse) executePostRequest(OTXEndpoints.PULSE_CREATE, newPulse, Pulse.class).getBody(); 215 | } 216 | 217 | /** 218 | * Allows the ability to follow, subscribe, unfollow, and unsubscribe 219 | * 220 | * @param username - NOTE this is case-sensitive 221 | * @param action - the action to perform 222 | * @return - the response with a value for the key 'status' 223 | * @throws MalformedURLException 224 | * @throws URISyntaxException 225 | */ 226 | public Map performUserAction(String username, UserActions action) throws MalformedURLException, URISyntaxException { 227 | Map parameterMap = new HashMap<>(); 228 | parameterMap.put(OTXEndpointParameters.USERNAME, username); 229 | parameterMap.put(OTXEndpointParameters.ACTION, action.getAction()); 230 | return restTemplate.postForEntity(buildURI(OTXEndpoints.USERS_ACTION, parameterMap), null, Map.class).getBody(); 231 | } 232 | 233 | /** 234 | * Get all events related to the authenticated account 235 | * @return List 236 | * @throws MalformedURLException 237 | * @throws URISyntaxException 238 | */ 239 | public List getAllEvents() throws MalformedURLException, URISyntaxException { 240 | return (List) getPagedResults(null, new EventPage(), OTXEndpoints.EVENTS); 241 | } 242 | 243 | /** 244 | * Get all events related to the authenticated account since the passed timeframe 245 | * @param cutoffDate only events after this date will be returned 246 | * @return List 247 | * @throws MalformedURLException 248 | * @throws URISyntaxException 249 | */ 250 | public List getEventsSince(DateTime cutoffDate) throws MalformedURLException, URISyntaxException { 251 | return (List) getPagedResults(Collections.singletonMap(OTXEndpointParameters.MODIFIED_SINCE, fmt.print(cutoffDate)), new EventPage(), OTXEndpoints.EVENTS); 252 | } 253 | 254 | private List getPulses(Map endpointParametersMap) throws URISyntaxException, MalformedURLException { 255 | 256 | return (List) getPagedResults(endpointParametersMap, new PulsePage(), OTXEndpoints.SUBSCRIBED); 257 | } 258 | 259 | private List getPagedResults(Map endpointParametersMap, Page page, OTXEndpoints endpoint) throws MalformedURLException, URISyntaxException { 260 | if (endpointParametersMap == null || !endpointParametersMap.containsKey(OTXEndpointParameters.LIMIT)){ 261 | Map newParams; 262 | if (endpointParametersMap != null) { 263 | newParams = new HashMap(endpointParametersMap); 264 | }else{ 265 | newParams = new HashMap(); 266 | } 267 | newParams.put(OTXEndpointParameters.LIMIT, 20); 268 | endpointParametersMap = newParams; 269 | } 270 | List pulseList = new ArrayList<>(); 271 | Page firstPage = executeGetRequest(endpoint, endpointParametersMap, page.getClass()); 272 | pulseList.addAll(firstPage.getResults()); 273 | while (firstPage.getNext() != null) { 274 | String rawQuery = firstPage.getNext().getRawQuery(); 275 | String nextPage = getParameterFromQueryString(rawQuery, OTXEndpointParameters.PAGE); 276 | // cskellie - passed in new parameter with page count to fetch next page of results. 277 | Map parametersMap = new HashMap<>(); 278 | if (endpointParametersMap!=null) { 279 | parametersMap.putAll(endpointParametersMap); 280 | } 281 | parametersMap.putAll(Collections.singletonMap(OTXEndpointParameters.PAGE, nextPage)); 282 | firstPage = executeGetRequest(endpoint, parametersMap, page.getClass()); 283 | pulseList.addAll(firstPage.getResults()); 284 | } 285 | return pulseList; 286 | 287 | } 288 | 289 | private String getParameterFromQueryString(String rawQuery, OTXEndpointParameters page) { 290 | String[] pairs = rawQuery.split("&"); 291 | 292 | Map query_pairs = new HashMap(); 293 | for (String pair : pairs) { 294 | int idx = pair.indexOf("="); 295 | try { 296 | query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8")); 297 | } catch (UnsupportedEncodingException e) { 298 | log.error("Unexpected issue with encoding", e); 299 | } 300 | } 301 | return query_pairs.get(page.getParameterName()); 302 | 303 | } 304 | 305 | private T executeGetRequest(final OTXEndpoints subscribed, final Map endpointParametersMap, final Class classType) throws MalformedURLException, URISyntaxException { 306 | 307 | final URI url = buildURI(subscribed, endpointParametersMap); 308 | 309 | return retryTemplate.execute(new RetryCallback() { 310 | 311 | public T doWithRetry(RetryContext context) { 312 | // Do stuff that might fail, e.g. webservice operation 313 | return restTemplate.getForObject(url, classType); 314 | } 315 | 316 | }); 317 | } 318 | 319 | private URI buildURI(OTXEndpoints endpoint, Map endpointParametersMap) throws URISyntaxException, MalformedURLException { 320 | 321 | String endpointString = endpoint.getEndpoint(); 322 | if (endpointParametersMap != null) { 323 | boolean first = true; 324 | for (Map.Entry otxEndpointParametersEntry : endpointParametersMap.entrySet()) { 325 | if (otxEndpointParametersEntry.getKey().isRestVariable()) { 326 | endpointString = endpointString.replace("{" + otxEndpointParametersEntry.getKey().getParameterName() + "}", otxEndpointParametersEntry.getValue().toString()); 327 | } else { 328 | if (first) { 329 | endpointString = endpointString + "?"; 330 | first = false; 331 | } 332 | try { 333 | String parameterName = otxEndpointParametersEntry.getKey().getParameterName(); 334 | String value = UriUtils.encodeQueryParam(otxEndpointParametersEntry.getValue().toString(), "UTF-8"); 335 | endpointString = endpointString + String.format("%s=%s&", parameterName, value); 336 | } catch (UnsupportedEncodingException e) { 337 | log.error("Unpossible"); 338 | } 339 | } 340 | } 341 | } 342 | if (otxPort != null) { 343 | return new URL(otxScheme, otxHost, otxPort, endpointString).toURI(); 344 | } else { 345 | return new URL(otxScheme, otxHost, endpointString).toURI(); 346 | } 347 | } 348 | 349 | 350 | private ResponseEntity executePostRequest(OTXEndpoints endpoint, Object toPost, Class responseType) throws MalformedURLException, URISyntaxException { 351 | return restTemplate.postForEntity(buildURI(endpoint, null), toPost, responseType); 352 | } 353 | 354 | } 355 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/OTXEndpointParameterTypes.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect; 2 | 3 | /** 4 | * The type used by OTX parameters 5 | */ 6 | public enum OTXEndpointParameterTypes { 7 | DATE, 8 | STRING, 9 | INTEGER 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/OTXEndpointParameters.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect; 2 | 3 | /** 4 | * Parameters used by OTX Endpoints 5 | */ 6 | public enum OTXEndpointParameters { 7 | /** 8 | * Limit is used by any Paged endpoint to set the page size 9 | */ 10 | LIMIT("limit", OTXEndpointParameterTypes.INTEGER), 11 | /** 12 | * Modified since is used by the SUBSCRIBED endpoint to limit the Pulses return. 13 | */ 14 | MODIFIED_SINCE("modified_since", OTXEndpointParameterTypes.DATE), 15 | /** 16 | * Page is used by any Paged endpoint to set the page to retrieve 17 | */ 18 | PAGE("page", OTXEndpointParameterTypes.INTEGER), 19 | /** 20 | * id is used by a number of endpoints for indicator and pulse retrieval 21 | */ 22 | ID("id", OTXEndpointParameterTypes.STRING, true), 23 | /** 24 | * query is used for search endpoints 25 | */ 26 | QUERY("q", OTXEndpointParameterTypes.STRING), 27 | /** 28 | * username is used for user related actions 29 | */ 30 | USERNAME("username", OTXEndpointParameterTypes.STRING,true), 31 | /** 32 | * action is used for user 33 | */ 34 | ACTION("action",OTXEndpointParameterTypes.STRING,true); 35 | 36 | private String parameterName; 37 | private OTXEndpointParameterTypes type; 38 | private boolean restVariable; 39 | 40 | OTXEndpointParameters(String parameterName, OTXEndpointParameterTypes type) { 41 | this.parameterName = parameterName; 42 | this.type = type; 43 | } 44 | 45 | OTXEndpointParameters(String parameterName, OTXEndpointParameterTypes type, boolean restVariable) { 46 | this.parameterName = parameterName; 47 | this.type = type; 48 | this.restVariable = restVariable; 49 | } 50 | 51 | /** 52 | * @return Parameter string used in the GET URL 53 | */ 54 | public String getParameterName() { 55 | return parameterName; 56 | } 57 | 58 | /** 59 | * @return the type used by the parameter 60 | */ 61 | public OTXEndpointParameterTypes getType() { 62 | return type; 63 | } 64 | 65 | /** 66 | * @return whether this is a rest variable 67 | */ 68 | public boolean isRestVariable() { 69 | return restVariable; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/OTXEndpoints.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * The enumeration of OTX Endpoints 8 | * @see OTXEndpointParameters for associated paramenters 9 | */ 10 | public enum OTXEndpoints { 11 | INDICATOR_IPV4("indicators/IPv4/{indicator}/{section}"), 12 | INDICATOR_IPV6("indicators/IPv6/{indicator}/{section}"), 13 | INDICATOR_DOMAIN("indicators/domain/{indicator}/{section}"), 14 | INDICATOR_HOSTNAME("indicators/hostname/{indicator}/{section}"), 15 | INDICATOR_FILE("indicators/file/{indicator}/{section}"), 16 | INDICATOR_URL("indicators/url/{indicator}/{section}"), 17 | INDICATOR_CVE("indicators/cve/{indicator}/{section}"), 18 | 19 | INDICATORS_FOR_PULSE("pulses/{id}/indicators"), 20 | RELATED_TO_PULSE("pulses/{id}/related"), 21 | PULSE_DETAILS("pulses/{id}"), 22 | SUBSCRIBED("pulses/subscribed"), 23 | ACTIVITY("pulses/activity"), 24 | EVENTS("pulses/events"), 25 | PULSE_CREATE("pulses/create"), 26 | PULSE_CREATE_VALIDATE_INDICATORS("pulses/indicators/validate"), 27 | 28 | SEARCH_USERS("search/users"), 29 | SEARCH_PULSES("search/pulses"), 30 | 31 | USERS_ME("users/me"), 32 | USERS_ACTION("users/{username}/{action}"); 33 | 34 | private final String endpoint; 35 | 36 | OTXEndpoints(String endpoint) { 37 | this.endpoint = "/api/v1/" + endpoint; 38 | } 39 | 40 | /** 41 | * @return Relative URL for endpoint 42 | */ 43 | public String getEndpoint() { 44 | return endpoint; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/internal/HTTPConfig.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect.internal; 2 | 3 | import com.alienvault.otx.connect.internal.HeaderSettingRequestFactory; 4 | import org.springframework.http.client.ClientHttpRequestFactory; 5 | 6 | /** 7 | * Internal factory for secure communication 8 | */ 9 | public class HTTPConfig { 10 | 11 | /** 12 | * Internal API to create the request factory used for communication with 13 | * OTX. 14 | * @param apiKey - API key used to authenticate the requests 15 | * @return Client request factory for use in a RestTemplate 16 | */ 17 | public static ClientHttpRequestFactory createRequestFactory(String apiKey) { 18 | return new HeaderSettingRequestFactory(apiKey); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/connect/internal/HeaderSettingRequestFactory.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.connect.internal; 2 | 3 | import org.springframework.http.HttpHeaders; 4 | import org.springframework.http.HttpMethod; 5 | import org.springframework.http.client.ClientHttpRequest; 6 | import org.springframework.http.client.ClientHttpRequestFactory; 7 | import org.springframework.http.client.SimpleClientHttpRequestFactory; 8 | 9 | import java.io.IOException; 10 | import java.net.URI; 11 | 12 | /** 13 | * Internal utility class to set the authorization header used for the OTX API 14 | * authentication. 15 | */ 16 | public class HeaderSettingRequestFactory extends SimpleClientHttpRequestFactory { 17 | private static final String SDK_USER_AGENT = String.format("%s/%s/%s", 18 | System.getProperty("otx.sdk.project", "OTX Java SDK"), 19 | System.getProperty("otx.sdk.version", "1.0"), 20 | System.getProperty("java.version")); 21 | private String apiKey; 22 | 23 | public HeaderSettingRequestFactory(String apiKey) { 24 | this.apiKey = apiKey; 25 | } 26 | 27 | @Override 28 | public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { 29 | ClientHttpRequest request = super.createRequest(uri, httpMethod); 30 | request.getHeaders().add("X-OTX-API-KEY",apiKey); 31 | request.getHeaders().add(HttpHeaders.USER_AGENT,SDK_USER_AGENT); 32 | return request; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/Page.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import java.net.URI; 6 | import java.util.List; 7 | 8 | /** 9 | * A Page of results 10 | */ 11 | @JsonIgnoreProperties(ignoreUnknown = true) 12 | public class Page { 13 | private Integer count; 14 | private URI next; 15 | private URI previous; 16 | private List results; 17 | 18 | public List getResults() { 19 | return results; 20 | } 21 | 22 | public void setResults(List results) { 23 | this.results = results; 24 | } 25 | 26 | public Integer getCount() { 27 | return count; 28 | } 29 | 30 | public void setCount(Integer count) { 31 | this.count = count; 32 | } 33 | 34 | public URI getNext() { 35 | return next; 36 | } 37 | 38 | public void setNext(URI nextURI) { 39 | this.next = nextURI; 40 | } 41 | 42 | public URI getPrevious() { 43 | return previous; 44 | } 45 | 46 | public void setPrevious(URI previousURI) { 47 | this.previous = previousURI; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/events/Event.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.events; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | import java.util.Date; 7 | 8 | /** 9 | * POJO for Event 10 | * { 11 | "action": "delete", 12 | "object_type": "pulse", 13 | "created": "2015-08-18T05:08:22.972000" 14 | } 15 | */ 16 | @JsonIgnoreProperties(ignoreUnknown = true) 17 | public class Event { 18 | private String action; 19 | @JsonProperty("object_type") 20 | private String objectType; 21 | private Date created; 22 | 23 | public String getAction() { 24 | return action; 25 | } 26 | 27 | public void setAction(String action) { 28 | this.action = action; 29 | } 30 | 31 | public String getObjectType() { 32 | return objectType; 33 | } 34 | 35 | public void setObjectType(String objectType) { 36 | this.objectType = objectType; 37 | } 38 | 39 | public Date getCreated() { 40 | return created; 41 | } 42 | 43 | public void setCreated(Date created) { 44 | this.created = created; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/events/EventPage.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.events; 2 | 3 | import com.alienvault.otx.model.Page; 4 | 5 | /** 6 | * Created by rspitler on 5/10/16. 7 | */ 8 | public class EventPage extends Page { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/indicator/Indicator.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.indicator; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * Indicator represents an indicator of compromise. This 9 | * is the atomic element of Open Threat Exchange. 10 | */ 11 | @JsonIgnoreProperties(ignoreUnknown = true) 12 | public class Indicator { 13 | private String indicator; 14 | private IndicatorType type; 15 | private String description; 16 | private Date created; 17 | 18 | /** 19 | * The actual indicator represented by this object. See getType() 20 | * for the type of this indicator 21 | * @return the string representation of this indicator 22 | */ 23 | public String getIndicator() { 24 | return indicator; 25 | } 26 | 27 | public void setIndicator(String indicator) { 28 | this.indicator = indicator; 29 | } 30 | 31 | /** 32 | * Returns the type of this indicator 33 | * @see IndicatorType 34 | * @return ip, domain, md5 35 | */ 36 | public IndicatorType getType() { 37 | return type; 38 | } 39 | 40 | public void setType(IndicatorType type) { 41 | this.type = type; 42 | } 43 | 44 | /** 45 | * The description provided by the original submitter of the indicator 46 | * @return the description 47 | */ 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | /** 57 | * @return the date the indicator was originally submitted to OTX 58 | */ 59 | public Date getCreated() { 60 | return created; 61 | } 62 | 63 | public void setCreated(Date created) { 64 | this.created = created; 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | return "Indicator{" + 70 | "indicator='" + indicator + '\'' + 71 | ", type='" + type + '\'' + 72 | ", description='" + description + '\'' + 73 | ", created=" + created + 74 | '}'; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/indicator/IndicatorPage.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.indicator; 2 | 3 | import com.alienvault.otx.model.Page; 4 | 5 | /** 6 | * Created by rspitler on 5/6/16. 7 | */ 8 | public class IndicatorPage extends Page { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/indicator/IndicatorSections.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.indicator; 2 | 3 | /** 4 | * Created by rspitler on 5/10/16. 5 | */ 6 | public enum IndicatorSections { 7 | /** 8 | * general: General information about the IP, such as geo data, and a list of the other sections currently available for this IP address. 9 | */ 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/indicator/IndicatorType.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.indicator; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonValue; 5 | import org.springframework.util.StringUtils; 6 | 7 | import java.util.Arrays; 8 | 9 | /** 10 | * Indicator types supported by OTX. 11 | */ 12 | public enum IndicatorType { 13 | 14 | IPV4("IPv4", "An IPv4 address indicating the online location of a server or other computer."), 15 | IPV6("IPv6", "An IPv6 address indicating the online location of a server or other computer."), 16 | DOMAIN("domain", "A domain name for a website or server. Domains encompass a series of hostnames."), 17 | HOSTNAME("hostname", "The hostname for a server located within a domain."), 18 | EMAIL("email", "An email associated with suspicious activity."), 19 | URL("URL", " Uniform Resource Location (URL) summarizing the online location of a file or resource."), 20 | URI("URI", "Uniform Resource Indicator (URI) describing the explicit path to a file hosted online."), 21 | MD5("FileHash-MD5", "A MD5-format hash that summarizes the architecture and content of a file."), 22 | SHA1("FileHash-SHA1", "A SHA-format hash that summarizes the architecture and content of a file."), 23 | SHA256("FileHash-SHA256", "A SHA-256-format hash that summarizes the architecture and content of a file."), 24 | PEHASH("FileHash-PEHASH", "A PEPHASH-format hash that summarizes the architecture and content of a file."), 25 | IMPHASH("FileHash-IMPHASH", "An IMPHASH-format hash that summarizes the architecture and content of a file."), 26 | CIDR("CIDR", "Classless Inter-Domain Routing (CIDR) address, which describes both a server's IP address and the network architecture (routing path) surrounding that server."), 27 | PATH("FilePath", "A unique location in a file system."), 28 | MUTEX("Mutex", "The name of a mutex resource describing the execution architecture of a file."), 29 | CVE("CVE", "Common Vulnerability and Exposure (CVE) entry describing a software vulnerability that can be exploited to engage in malicious activity."); 30 | 31 | private final String identifer; 32 | private final String description; 33 | 34 | IndicatorType(String identifer, String description) { 35 | this.identifer = identifer; 36 | this.description = description; 37 | } 38 | 39 | public String getIdentifer() { 40 | return identifer; 41 | } 42 | 43 | public String getDescription() { 44 | return description; 45 | } 46 | 47 | public static String toTypeList() { 48 | return StringUtils.collectionToCommaDelimitedString(Arrays.asList(IndicatorType.values())); 49 | } 50 | 51 | 52 | @JsonValue 53 | public String getValue() { 54 | return this.identifer; 55 | } 56 | 57 | @JsonCreator 58 | public static IndicatorType create(String val) { 59 | IndicatorType[] types = IndicatorType.values(); 60 | for (IndicatorType type : types) { 61 | if (type.getValue().equals(val)) { 62 | return type; 63 | } 64 | } 65 | return CVE; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/pulse/OtxDateDeserializer.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.pulse; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.DeserializationContext; 6 | import com.fasterxml.jackson.databind.JsonDeserializer; 7 | 8 | import java.io.IOException; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | 12 | public class OtxDateDeserializer extends JsonDeserializer { 13 | 14 | @Override 15 | public Date deserialize(JsonParser jsonparser, 16 | DeserializationContext deserializationcontext) throws IOException, JsonProcessingException { 17 | 18 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 19 | String date = jsonparser.getText(); 20 | try { 21 | return format.parse(date); 22 | } catch (Exception e) { 23 | throw new RuntimeException(e); 24 | } 25 | 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/pulse/Pulse.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.pulse; 2 | 3 | import com.alienvault.otx.model.indicator.Indicator; 4 | import com.fasterxml.jackson.annotation.JsonGetter; 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import com.fasterxml.jackson.annotation.JsonSetter; 7 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 8 | 9 | import java.util.Arrays; 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | /** 14 | * A utility object to represent a Pulse 15 | */ 16 | @JsonIgnoreProperties(ignoreUnknown = true) 17 | public class Pulse { 18 | private String id; 19 | private String name; 20 | private String description; 21 | private String author_name; 22 | private String adversary; 23 | private String tlp; 24 | @JsonDeserialize(using = OtxDateDeserializer.class) 25 | private Date modified; 26 | @JsonDeserialize(using = OtxDateDeserializer.class) 27 | private Date created; 28 | private List tags; 29 | private List references; 30 | private List industries; 31 | private List targeted_countries; 32 | private Integer revision; 33 | private List indicators; 34 | private boolean isPublic = true; 35 | 36 | /** 37 | * The internal ID of the pulse 38 | * 39 | * @return string representing the pulse id 40 | */ 41 | public String getId() { 42 | return id; 43 | } 44 | 45 | public void setId(String id) { 46 | this.id = id; 47 | } 48 | 49 | /** 50 | * The name of the pulse 51 | * 52 | * @return the pulse name 53 | */ 54 | public String getName() { 55 | return name; 56 | } 57 | 58 | public void setName(String name) { 59 | this.name = name; 60 | } 61 | 62 | /** 63 | * The description of the pulse 64 | * 65 | * @return the description provided when the pulse was originally created 66 | */ 67 | public String getDescription() { 68 | return description; 69 | } 70 | 71 | public void setDescription(String description) { 72 | this.description = description; 73 | } 74 | 75 | /** 76 | * The name of the author of the pulse 77 | * 78 | * @return the author who originally submitted the pulse 79 | */ 80 | public String getAuthor_name() { 81 | return author_name; 82 | } 83 | 84 | public void setAuthor_name(String author_name) { 85 | this.author_name = author_name; 86 | } 87 | 88 | /** 89 | * The last date this pulse was updated 90 | * 91 | * @return last modification date 92 | */ 93 | public Date getModified() { 94 | return modified; 95 | } 96 | 97 | public void setModified(Date modified) { 98 | this.modified = modified; 99 | } 100 | 101 | /** 102 | * The date this pulse was created 103 | * 104 | * @return creation date 105 | */ 106 | public Date getCreated() { 107 | return created; 108 | } 109 | 110 | public void setCreated(Date created) { 111 | this.created = created; 112 | } 113 | 114 | /** 115 | * Tags associted with this pulse 116 | * 117 | * @return list of tags 118 | */ 119 | public List getTags() { 120 | return tags; 121 | } 122 | 123 | public void setTags(List tags) { 124 | this.tags = tags; 125 | } 126 | 127 | /** 128 | * Industries associated with this pulse 129 | * 130 | * @return list of industries 131 | */ 132 | public List getIndustries(){ 133 | return industries; 134 | } 135 | public void setIndustries(List industries){ 136 | this.industries = industries; 137 | } 138 | /** 139 | * Adversary 140 | */ 141 | public String getAdversary(){ 142 | return adversary; 143 | } 144 | public void setAdversary(String adversary){ 145 | this.adversary = adversary; 146 | } 147 | /** 148 | * The list of references associated with this pulse 149 | * 150 | * @return a list of references 151 | */ 152 | public List getReferences() { 153 | return references; 154 | } 155 | 156 | public void setReferences(List references) { 157 | this.references = references; 158 | } 159 | 160 | 161 | 162 | /** 163 | * The revision of this representation of the pulse 164 | * 165 | * @return 166 | */ 167 | public Integer getRevision() { 168 | return revision; 169 | } 170 | 171 | public void setRevision(Integer revision) { 172 | this.revision = revision; 173 | } 174 | 175 | /** 176 | * The indicators associated with this pulse 177 | * 178 | * @return List of indicators 179 | */ 180 | public List getIndicators() { 181 | return indicators; 182 | } 183 | 184 | public void setIndicators(List indicators) { 185 | this.indicators = indicators; 186 | } 187 | 188 | 189 | @Override 190 | public String toString() { 191 | return "Pulse{" + 192 | "name='" + name + '\'' + 193 | ", description='" + description + '\'' + 194 | ", tags=" + tags + 195 | ", indicators=" + Arrays.deepToString((indicators == null ? new String[]{} : indicators.toArray())) + 196 | '}'; 197 | } 198 | @JsonSetter("public") 199 | public void setPublic(boolean isPublic) { 200 | this.isPublic = isPublic; 201 | } 202 | @JsonGetter("public") 203 | public boolean isPublic() { 204 | return isPublic; 205 | } 206 | 207 | @JsonGetter("tlp") 208 | public String getTlp() { 209 | return tlp; 210 | } 211 | 212 | @JsonSetter("tlp") 213 | public void setTlp(String tlp) { 214 | this.tlp = tlp; 215 | } 216 | @JsonGetter("targeted_countries") 217 | public List getTargetedCountries(){ 218 | return targeted_countries; 219 | } 220 | @JsonSetter("targeted_countries") 221 | public void setTargetedCountries(List targeted_countries){ 222 | this.targeted_countries = targeted_countries; 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/pulse/PulsePage.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.pulse; 2 | 3 | import com.alienvault.otx.model.Page; 4 | 5 | /** 6 | * Created by rspitler on 5/6/16. 7 | */ 8 | public class PulsePage extends Page { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/user/User.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.user; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | /** 6 | * POJO for User JSON 7 | * { 8 | * "username": "root", 9 | * "pulse_count": 0, 10 | * "subscriber_count": 1, 11 | * "follower_count": 3, 12 | * "award_count": 0, 13 | * "member_since": "453 days ago ", 14 | * "accepted_edits_count": 0, 15 | * "avatar_url": "https://otx20-dev-web-media.s3.amazonaws.com/media/avatars/root/resized/80/otx-learning-center_d7TpH1y.png" 16 | * } 17 | */ 18 | @JsonIgnoreProperties(ignoreUnknown = true) 19 | public class User { 20 | private String username; 21 | private int pulse_count; 22 | private int subscriber_count; 23 | private int follower_count; 24 | private int award_count; 25 | private int accepted_edits_count; 26 | private String member_since; 27 | private String avatar_url; 28 | 29 | public String getUsername() { 30 | return username; 31 | } 32 | 33 | public void setUsername(String username) { 34 | this.username = username; 35 | } 36 | 37 | public int getPulse_count() { 38 | return pulse_count; 39 | } 40 | 41 | public void setPulse_count(int pulse_count) { 42 | this.pulse_count = pulse_count; 43 | } 44 | 45 | public int getSubscriber_count() { 46 | return subscriber_count; 47 | } 48 | 49 | public void setSubscriber_count(int subscriber_count) { 50 | this.subscriber_count = subscriber_count; 51 | } 52 | 53 | public int getFollower_count() { 54 | return follower_count; 55 | } 56 | 57 | public void setFollower_count(int follower_count) { 58 | this.follower_count = follower_count; 59 | } 60 | 61 | public int getAward_count() { 62 | return award_count; 63 | } 64 | 65 | public void setAward_count(int award_count) { 66 | this.award_count = award_count; 67 | } 68 | 69 | public int getAccepted_edits_count() { 70 | return accepted_edits_count; 71 | } 72 | 73 | public void setAccepted_edits_count(int accepted_edits_count) { 74 | this.accepted_edits_count = accepted_edits_count; 75 | } 76 | 77 | public String getMember_since() { 78 | return member_since; 79 | } 80 | 81 | public void setMember_since(String member_since) { 82 | this.member_since = member_since; 83 | } 84 | 85 | public String getAvatar_url() { 86 | return avatar_url; 87 | } 88 | 89 | public void setAvatar_url(String avatar_url) { 90 | this.avatar_url = avatar_url; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/user/UserActions.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.user; 2 | 3 | /** 4 | * Created by rspitler on 5/10/16. 5 | */ 6 | public enum UserActions { 7 | /** 8 | * subscribe: Include all of this users' pulses in my threat intelligence feed. 9 | */ 10 | SUBSCRIBE("subscribe"), 11 | /** 12 | * unsubscribe: Remove all of this users' pulses from my threat intelligence feed. 13 | */ 14 | UNSUBSCRIBE("unsubscribe"), 15 | /** 16 | * follow: Include all of this users' pulses in my activity feed, (Individual pulses must be subscribed to directly for inclusion in threat intelligence feed). 17 | */ 18 | FOLLOW("follow"), 19 | /** 20 | * unfollow: Remove all of this users' pulses from my activity feed. 21 | */ 22 | UNFOLLOW("unfollow"); 23 | 24 | private String action; 25 | 26 | UserActions(String action) { 27 | this.action = action; 28 | } 29 | 30 | public String getAction() { 31 | return action; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/alienvault/otx/model/user/UserPage.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx.model.user; 2 | 3 | import com.alienvault.otx.model.Page; 4 | 5 | /** 6 | * Created by rspitler on 5/6/16. 7 | */ 8 | public class UserPage extends Page { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | host=otx.alienvault.com 2 | scheme=https 3 | logging.level.org.springframework=ERROR 4 | logging.level.com.alienvault=ERROR -------------------------------------------------------------------------------- /src/main/resources/banner.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlienVault-OTX/OTX-Java-SDK/30e1d6949cfe9a617fbfeacb7bf17b2a85356cbc/src/main/resources/banner.txt -------------------------------------------------------------------------------- /src/test/java/com/alienvault/otx/OtxJavaSdkApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.alienvault.otx; 2 | 3 | import com.alienvault.otx.connect.ConnectionUtil; 4 | import com.alienvault.otx.connect.OTXConnection; 5 | import com.alienvault.otx.model.events.Event; 6 | import com.alienvault.otx.model.indicator.Indicator; 7 | import com.alienvault.otx.model.indicator.IndicatorType; 8 | import com.alienvault.otx.model.pulse.Pulse; 9 | import com.alienvault.otx.model.user.User; 10 | import com.alienvault.otx.model.user.UserActions; 11 | import org.joda.time.DateTime; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.SpringApplicationConfiguration; 17 | import org.springframework.context.ConfigurableApplicationContext; 18 | import org.springframework.core.env.Environment; 19 | import org.springframework.test.context.TestPropertySource; 20 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 21 | import org.springframework.util.StringUtils; 22 | 23 | import java.net.MalformedURLException; 24 | import java.net.URISyntaxException; 25 | import java.util.Collections; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.Random; 29 | 30 | import static org.junit.Assert.assertTrue; 31 | 32 | @RunWith(SpringJUnit4ClassRunner.class) 33 | @SpringApplicationConfiguration(classes = CommandlineRunner.class) 34 | @TestPropertySource(locations = "classpath:test_application.properties") 35 | public class OtxJavaSdkApplicationTests { 36 | public String VALID_PULSE_NAME; 37 | public String VALID_PULSE_ID; 38 | public String VALID_USERNAME; 39 | @Autowired 40 | ConfigurableApplicationContext context; 41 | @Autowired 42 | Environment env; 43 | 44 | OTXConnection otxConnection; 45 | 46 | @Before 47 | public void setUp() throws Exception { 48 | String property = env.getProperty("key"); 49 | if(StringUtils.isEmpty(property)) 50 | throw new Exception("Error loading API key. Please enter your api key in src/test/resources/test_applications.properties before running tests"); 51 | otxConnection = ConnectionUtil.getOtxConnection(env, property); 52 | VALID_PULSE_NAME = env.getProperty("VALID_PULSE_NAME"); 53 | VALID_PULSE_ID = env.getProperty("VALID_PULSE_ID"); 54 | VALID_USERNAME = env.getProperty("VALID_USERNAME"); 55 | } 56 | 57 | @Test 58 | public void testListAllPulses() throws MalformedURLException, URISyntaxException { 59 | List allPulses = otxConnection.getAllPulses(); 60 | assertTrue(allPulses.size() > 0); 61 | } 62 | 63 | @Test 64 | public void testListSinceDate() throws MalformedURLException, URISyntaxException { 65 | List allPulses = otxConnection.getPulsesSinceDate(DateTime.now().minusDays(10)); 66 | assertTrue(allPulses.size() > 0); 67 | } 68 | 69 | @Test 70 | public void testListIndicatorsForPulse() throws MalformedURLException, URISyntaxException { 71 | List allPulses = otxConnection.getPulsesSinceDate(DateTime.now().minusDays(10)); 72 | assertTrue(allPulses.size() > 0); 73 | Pulse pulse = allPulses.get(0); 74 | List allIndicatorsForPulse = otxConnection.getAllIndicatorsForPulse(pulse.getId()); 75 | //a bit of a guess that the first pulse in the last 10 days has indicators 76 | assertTrue(allIndicatorsForPulse.size() > 0); 77 | } 78 | 79 | @Test 80 | public void testGetRelatedPulses() throws MalformedURLException, URISyntaxException { 81 | List allRelatedPulses = otxConnection.getAllRelatedPulses(VALID_PULSE_ID); 82 | int NUM_RELATED_PULSES = Integer.valueOf(env.getProperty("NUMBER_PULSES_RELATED_TO_VALID_PULSE_ID")); 83 | assertTrue(allRelatedPulses.size() >= NUM_RELATED_PULSES); 84 | } 85 | 86 | @Test 87 | public void testGetPulseDetails() throws MalformedURLException, URISyntaxException { 88 | Pulse pulseDetails = otxConnection.getPulseDetails(VALID_PULSE_ID); 89 | assertTrue("Did not get a pulse", pulseDetails != null); 90 | } 91 | 92 | @Test 93 | public void testSearchPulses() throws MalformedURLException, URISyntaxException { 94 | List pulses = otxConnection.searchForPulses(VALID_PULSE_NAME); 95 | assertTrue("Could not find pulse", pulses.size() >= 1); 96 | } 97 | 98 | @Test 99 | public void testSearchUsers() throws MalformedURLException, URISyntaxException { 100 | List users = otxConnection.searchForUsers(VALID_USERNAME); 101 | assertTrue("Could not find users", users.size() > 1); 102 | } 103 | 104 | @Test 105 | public void testGetMyDetails() throws MalformedURLException, URISyntaxException { 106 | User myDetails = otxConnection.getMyDetails(); 107 | assertTrue("Did not get a user", myDetails != null); 108 | } 109 | 110 | @Test 111 | public void testCreatePulse() throws MalformedURLException, URISyntaxException { 112 | Pulse newPulse = getPulse(); 113 | Pulse createdPulse = otxConnection.createPulse(newPulse); 114 | assertTrue("Pulse creation success", createdPulse != null); 115 | } 116 | 117 | private Pulse getPulse() { 118 | Pulse newPulse = new Pulse(); 119 | newPulse.setName("New Pulse from Javaaa"+ new Random().nextInt()); 120 | newPulse.setDescription("New Pulse from Javaaa. The SDK!"); 121 | List indis = Collections.singletonList(getIndicator()); 122 | newPulse.setIndicators(indis); 123 | newPulse.setTags(Collections.singletonList("Tags Test")); 124 | newPulse.setReferences(Collections.singletonList("http://reference.com")); 125 | newPulse.setTlp("white"); 126 | newPulse.setPublic(false); 127 | return newPulse; 128 | } 129 | 130 | @Test 131 | public void testUserAction() throws MalformedURLException, URISyntaxException { 132 | Map response = otxConnection.performUserAction(VALID_USERNAME, UserActions.FOLLOW); 133 | assertTrue("Unexpected status", response.get("status").equals("followed")); 134 | response = otxConnection.performUserAction(VALID_USERNAME, UserActions.UNFOLLOW); 135 | assertTrue("Unexpected status", response.get("status").equals("unfollowed")); 136 | } 137 | 138 | @Test 139 | public void testListEvents() throws MalformedURLException, URISyntaxException { 140 | List allEvents = otxConnection.getAllEvents(); 141 | // Map response = otxConnection.performUserAction(VALID_USERNAME, UserActions.SUBSCRIBE); 142 | // assertTrue("Unexpected status", response.get("status").equals("followed")); 143 | // List eventsSince = otxConnection.getEventsSince(DateTime.now().minusDays(5)); 144 | assertTrue("No events returned", allEvents.size() > 0); 145 | // assertTrue("No events since returned", eventsSince.size() > 0); 146 | // assertTrue("All events not larger then a subset", allEvents.size() > eventsSince.size()); 147 | } 148 | 149 | private Indicator getIndicator() { 150 | Indicator indie = new Indicator(); 151 | indie.setType(IndicatorType.DOMAIN); 152 | indie.setIndicator("www.google.com"); 153 | indie.setDescription(" bad www.google.com"); 154 | return indie; 155 | } 156 | 157 | 158 | } 159 | -------------------------------------------------------------------------------- /src/test/resources/test_application.properties: -------------------------------------------------------------------------------- 1 | host=${TARGET_HOST} 2 | key=${API_KEY} 3 | scheme=https 4 | logging.level.org.springframework=INFO 5 | logging.level.com.alienvault=ERROR 6 | VALID_PULSE_NAME=Spying On US Visa Applicants 7 | VALID_USERNAME=AlienVault 8 | VALID_PULSE_ID=5756b9746eb8c60134a9e203 9 | NUMBER_PULSES_RELATED_TO_VALID_PULSE_ID=1 --------------------------------------------------------------------------------