diff --git a/.gitignore b/.gitignore deleted file mode 100644 index ba13d11..0000000 --- a/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -*~ -.* -bin -!.gitignore -*.class - -# Package Files # -*.jar -*.war -*.ear -Main.java diff --git a/README.md b/README.md index edfeae5..79cbf36 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,27 @@ -# semantics3 +# semantics3-java semantics3-java is a Java client for accessing the Semantics3 Products API, which provides structured information, including pricing histories, for a large number of products. See https://www.semantics3.com for more information. -## Requirements -* signpost-core-1.2.1.2.jar - OAuth2 implementation -* commons-codec-1.7.jar - Apache Commons Codec library for Base64 implementation +## Installation +* The JAVA version used for this library is JDK 7. + +* Add the following to your pom.xml + +```xml + + com.semantics3 + Sem3Java + 1.2.4 + +``` + +* For projects which don't use Maven each stable [release](https://github.com/Semantics3/semantics3-java/releases/download/Sem3Java-1.2.4/Sem3Java-1.2.4-jar-with-dependencies.jar) is also available as a fat jar. ## Getting Started In order to use the client, you must have both an API key and an API secret. To obtain your key and secret, you need to first create an account at https://www.semantics3.com/ -You can access your API access credentials from the user dashboard at https://www.semantics3.com/dashboard/applications +You can access your API access credentials from the user dashboard at https://dashboard.semantics3.com. ### Setup Work @@ -26,119 +37,194 @@ Products products = new Products( ); ``` -### First Query aka 'Hello World': +### First Request aka 'Hello World': -Let's make our first query! For this query, we are going to search for all Toshiba products that fall under the category of "Computers and Accessories", whose cat_id is 4992. +Let's make our first Request! We are going to run a simple search for the word "iPhone" as follows: ```java -/* Build the query */ +/* Build the Request */ products - .productsField( "cat_id", 4992 ) - .productsField( "brand", "Toshiba" ); + .productsField( "search", "iphone" ); -/* Make the query */ +/* Make the Request */ JSONObject results = products.getProducts(); /* or */ results = products.get(); -/* View the results of the query */ +/* View the results of the Request */ System.out.println(results); ``` -## Examples +## Sample Requests -The following examples show you how to interface with some of the core functionality of the Semantics3 Products API. For more detailed examples check out the Quickstart guide: https://www.semantics3.com/quickstart +The following Requests show you how to interface with some of the core functionality of the Semantics3 Products API : -### Explore the Category Tree +### UPC Query -In this example we are going to be accessing the categories endpoint. We are going to be specifically exploiring the "Computers and Accessories" category, which has a cat_id of 4992. For more details regarding our category tree and associated cat_ids check out our API docs at https://www.semantics3.com/docs +Running a UPC/EAN/GTIN request is as simple as running a search request: -```java -/* Build the query */ -products.categoriesField( "cat_id", 4992 ); + ```java +/* Build the Request */ +products + .productsField( "upc", "883974958450" ) + .productsField( "fields", "name","gtins" ); -/* Execute the query */ -JSONObject results = products.getCategories(); +/* Make the Request */ +JSONObject results = products.getProducts(); +/* or */ +results = products.get(); -/* View the results of the query */ +/* View the results of the Request */ System.out.println(results); ``` -### Nested Search Query +### URL Query -You can intuitively construct all your complex queries but just repeatedly using the products_field() or add() methods. -Here is how we translate the following JSON query: +Get the picture? You can run URL Requests as follows: -```javascript -{ - "cat_id" : 4992, - "brand" : "Toshiba", - "weight" : { "gte":1000000, "lt":1500000 }, - "sitedetails" : { - "name" : "newegg.com", - "latestoffers" : { - "currency": "USD", - "price" : { "gte" : 100 } - } - } -} +```java +products + .productsField( "url", "http://www.walmart.com/ip/15833173" ); + JSONObject results = products.getProducts(); + System.out.println(results); ``` +### Price Filter -This query returns all Toshiba products within a certain weight range narrowed down to just those that retailed recently on newegg.com for >= USD 100. +Filter by price using the "lt" (less than) tag: ```java -/* Build the query */ -Products products = new Products( api_key, api_secret ); products - .field("cat_id", 4992) - .field("brand", "Toshiba") - .field("weight", "gte", 1000000) - .field("weight", "lt", 1500000) - .siteDetails("name","newegg.com") - .latestOffers("currency","USD") - .latestOffers("price","gte",100); - -/* Let's make a modification - say we no longer want the weight attribute */ -products.remove( "products", "weight" ); - -/* Make the query */ -JSONObject results = products.getProducts(); -System.out.println(results); + .productsField( "search", "iphone" ) + .productsField( "price", "lt", 300 ); + JSONObject results = products.getProducts(); + System.out.println(results); ``` +### Category ID Query - -### Explore Price Histories -For this example, we are going to look at a particular product that is sold by select merchants and has a price of >= USD 30 and seen after a specific date (specified as a UNIX timestamp). +To lookup details about a cat_id, run your request against the categories resource: ```java /* Build the query */ -products.offersField("sem3_id", "4znupRCkN6w2Q4Ke4s6sUC"); -products.offersField("seller", new String[] { "LFleurs","Frys","Walmart" }); -products.offersField("currency", "USD"); -products.offersField("price", "gte", 30); -products.offersField("lastrecorded_at", "gte", 1348654600); +products + .categoriesField( "cat_id", 4992 ); -/* Make the query */ -JSONObject results = products.getOffers() +/* Execute the query */ + JSONObject results = products.getCategories(); /* View the results of the query */ -System.out.println(results) + System.out.println(results); ``` +### Webhooks +You can use webhooks to get near-real-time price updates from Semantics3. +## Creating a webhook + +You can register a webhook with Semantics3 by sending a POST request to ```"webhooks"``` endpoint. To verify that your URL is active, a GET request will be sent to your server with a ```verification_code``` parameter. Your server should respond with ```verification_code``` in the response body to complete the verification process. + +```java +String apiKey = "SEM3xxxxxxxxxxxxxxxxxxxxxx"; +String apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; +String endpoint = "webhooks"; +Semantics3Request request = new Semantics3Request(apiKey, apiSecret, endpoint); +HashMap params = new HashMap(); +params.put("webhook_uri", "http://mydomain.com/webhooks-callback-url"); +JSONObject results = request.runQuery(endpoint, "POST", params); +System.out.println(results.toString(4)); +``` +To fetch existing webhooks + +```java +String endpoint = "webhooks"; +Semantics3Request request = new Semantics3Request(apiKey, apiSecret, endpoint); +HashMap params = new HashMap(); +JSONObject results = request.runQuery(endpoint, "GET", params); +System.out.println(results.toString(4)); +``` +To remove a webhook + +```java +String webhookId = "7JcGN81u"; +String endpoint = "webhooks/" + webhookId; +Semantics3Request request = new Semantics3Request(apiKey, apiSecret, endpoint); + +HashMap params = new HashMap(); + +JSONObject results = request.runQuery(endpoint, "DELETE", params); +System.out.println(results.toString(4)); +``` + +### Registering events + +Once you register a webhook, you can start adding events to it. Semantics3 server will send you notifications when these events occur. To register events for a specific webhook send a POST request to the ```"webhooks/{webhook_id}/events"``` endpoint + +```java +String webhookId = "7JcGN81u"; +String endpoint = "webhooks/" +webhookId+ "/events"; + +Semantics3Request request = new Semantics3Request(apiKey, apiSecret, endpoint); + +HashMap params = new HashMap(); +HashMap product = new HashMap(); +HashMap constraints = new HashMap(); +params.put("type", "price.change"); +product.put("sem3_id", "1QZC8wchX62eCYS2CACmka"); +params.put("product", product); +constraints.put("gte", 10); +constraints.put("lte", 100); +params.put("constraints", constraints); +JSONObject results = request.runQuery(endpoint, "POST", params); +System.out.println(results.toString(4)); +``` + +To fetch all registered events for a give webhook + +```java +String webhookId = "7JcGN81u"; +String endpoint = "webhooks/" +webhookId+ "/events"; + +Semantics3Request request = new Semantics3Request(apiKey, apiSecret, endpoint); +HashMap params = new HashMap(); +JSONObject results = request.runQuery(endpoint, "GET", params); +``` +## Webhook Notifications + +Once you have created a webhook and registered events on it, notifications will be sent to your registered webhook URI via a POST request when the corresponding events occur. Make sure that your server can accept POST requests. Here is how a sample notification object looks like + +```json +{ + "type": "price.change", + "event_id": "XyZgOZ5q", + "notification_id": "X4jsdDsW", + "changes": [{ + "site": "abc.com", + "url": "http://www.abc.com/def", + "previous_price": 45.50, + "current_price": 41.00 + }, { + "site": "walmart.com", + "url": "http://www.walmart.com/ip/20671263", + "previous_price": 34.00, + "current_price": 42.00 + }] +} + +``` ## Contributing Use GitHub's standard fork/commit/pull-request cycle. If you have any questions, email . -## Author +## Authors + +* Asmit Kumar -* Shawn Tan +* Shawn Tan ## Copyright -Copyright (c) 2013 Semantics3 Inc. +Copyright (c) 2015 Semantics3 Inc. ## License diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..cea89bf --- /dev/null +++ b/pom.xml @@ -0,0 +1,164 @@ + + + 4.0.0 + + com.semantics3 + Sem3Java + 1.2.5-SNAPSHOT + Semantics3 Java Library + https://github.com/Semantics3/semantics3-java + Java bindings for Semantics3 API + + https://github.com/Semantics3/semantics3-java/issues + GitHub Issues + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + repo + + + + + abishek@semantics3.com + Abishek Bhat + https://github.com/abishekk92 + abishekk92 + + + asmit@semantics3.com + Asmit Kumar + https://github.com/asmitkumar + asmitkumar + + + Shawn Tan + https://github.com/shawntan + shawntan + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5 + + true + false + release + deploy -Dmaven.test.skip=true + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.4 + + ${gpg.passphrase} + + + + sign-artifacts + verify + + sign + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2.1 + + + jar-with-dependencies + + + + + + assemble-all + package + + single + + + + + + + + + junit + junit + 4.11 + test + + + oauth.signpost + signpost-core + 1.2.1 + + + commons-codec + commons-codec + 1.10 + + + + scm:git:git://github.com/Semantics3/semantics3-java.git + scm:git:git@github.com:Semantics3/semantics3-java.git + https://github.com/Semantics3/semantics3-java + HEAD + + + + sonatype-nexus-snapshots + Sonatype Nexus snapshot repository + https://oss.sonatype.org/content/repositories/snapshots + + + sonatype-nexus-staging + Sonatype Nexus release repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + diff --git a/src/Example.java b/src/Example.java deleted file mode 100644 index a2fd087..0000000 --- a/src/Example.java +++ /dev/null @@ -1,36 +0,0 @@ -import java.io.IOException; - -import oauth.signpost.exception.OAuthCommunicationException; -import oauth.signpost.exception.OAuthExpectationFailedException; -import oauth.signpost.exception.OAuthMessageSignerException; - -import org.json.JSONObject; - -import com.semantics3.api.Products; - -public class Example { - - /** - * @param args - */ - public static void main(String args[]) { - - try { - Products products = new Products( - "", - "" - ); - products - .field( "cat_id", 4992 ) - .field( "brand", "Toshiba" ); - JSONObject results; - results = products.get(); - System.out.println(results.toString(4)); - } catch (OAuthMessageSignerException | OAuthExpectationFailedException - | OAuthCommunicationException | IOException e) { - e.printStackTrace(); - } - - } - -} diff --git a/src/com/semantics3/api/Semantics3Request.java b/src/com/semantics3/api/Semantics3Request.java deleted file mode 100644 index 369c1bb..0000000 --- a/src/com/semantics3/api/Semantics3Request.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.semantics3.api; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.HashMap; -import org.json.JSONObject; -import org.json.JSONTokener; - -import com.semantics3.errors.Semantics3Exception; - -import oauth.signpost.OAuthConsumer; -import oauth.signpost.basic.DefaultOAuthConsumer; -import oauth.signpost.exception.OAuthCommunicationException; -import oauth.signpost.exception.OAuthExpectationFailedException; -import oauth.signpost.exception.OAuthMessageSignerException; - -public class Semantics3Request{ - final static private String API_DOMAIN = "api.semantics3.com"; - final static private String API_BASE = "https://" + API_DOMAIN + "/v1/"; - - private String apiKey; - private String apiSecret; - private String endpoint; - private String endpointURL; - private OAuthConsumer consumer; - private HashMap query = new HashMap(); - private JSONObject queryResult; - private StringBuffer urlBuilder; - - public Semantics3Request(String apiKey, String apiSecret, String endpoint) { - if (apiKey == null) { - throw new Semantics3Exception( - "API Credentials Missing", - "You did not supply an apiKey. Please sign up at https://semantics3.com/ to obtain your api_key." - ); - } - if (apiSecret == null) { - throw new Semantics3Exception( - "API Credentials Missing", - "You did not supply an apiSecret. Please sign up at https://semantics3.com/ to obtain your api_key." - ); - } - - this.apiKey = apiKey; - this.apiSecret = apiSecret; - this.endpoint = endpoint; - this.consumer = new DefaultOAuthConsumer(apiKey, apiSecret); - consumer.setTokenWithSecret("", ""); - } - - protected JSONObject fetch(String endpoint, String params) throws - OAuthMessageSignerException, - OAuthExpectationFailedException, - OAuthCommunicationException, - IOException { - String req = new StringBuffer() - .append(API_BASE) - .append(endpoint) - .append("?q=") - .append(URLEncoder.encode(params, "UTF-8")) - .toString(); - URL url = new URL(req); - - HttpURLConnection request = (HttpURLConnection) url.openConnection(); - request.setRequestProperty("User-Agent", "Semantics3 Java Library"); - consumer.sign(request); - request.connect(); - JSONObject json = new JSONObject(new JSONTokener(request.getInputStream())); - - return json; - } - - public Semantics3Request add(String endpoint, Object... fields) { - JSONObject endpointQuery; - if ((endpointQuery = query.get(endpoint)) == null) { - endpointQuery = new JSONObject(); - query.put(endpoint,endpointQuery); - } - JSONObject sq = endpointQuery; - for (int i=0;i query = new HashMap(); + private JSONObject queryResult; + private StringBuffer urlBuilder; + + public Semantics3Request(String apiKey, String apiSecret, String endpoint) { + if (apiKey == null) { + throw new Semantics3Exception( + "API Credentials Missing", + "You did not supply an apiKey. Please sign up at https://semantics3.com/ to obtain your api_key." + ); + } + if (apiSecret == null) { + throw new Semantics3Exception( + "API Credentials Missing", + "You did not supply an apiSecret. Please sign up at https://semantics3.com/ to obtain your api_key." + ); + } + + this.apiKey = apiKey; + this.apiSecret = apiSecret; + this.endpoint = endpoint; + this.consumer = new DefaultOAuthConsumer(apiKey, apiSecret); + consumer.setTokenWithSecret("", ""); + } + + public Semantics3Request(String apiKey, String apiSecret) { + if (apiKey == null) { + throw new Semantics3Exception( + "API Credentials Missing", + "You did not supply an apiKey. Please sign up at https://semantics3.com/ to obtain your api_key." + ); + } + if (apiSecret == null) { + throw new Semantics3Exception( + "API Credentials Missing", + "You did not supply an apiSecret. Please sign up at https://semantics3.com/ to obtain your api_key." + ); + } + + this.apiKey = apiKey; + this.apiSecret = apiSecret; + this.consumer = new DefaultOAuthConsumer(apiKey, apiSecret); + consumer.setTokenWithSecret("", ""); + } + + protected JSONObject fetch(String endpoint, String params) throws + OAuthMessageSignerException, + OAuthExpectationFailedException, + OAuthCommunicationException, + IOException, URISyntaxException { + String req = new StringBuffer() + .append(API_BASE) + .append(endpoint) + .append("?q=") + .append(URLEncoder.encode(params, "UTF-8")) + .toString(); + URL url = new URL(req); + url = url.toURI().normalize().toURL(); + HttpURLConnection request = (HttpURLConnection) url.openConnection(); + request.setRequestProperty("User-Agent", "Semantics3 Java Library"); + consumer.sign(request); + request.connect(); + try { + JSONObject json = new JSONObject(new JSONTokener(request.getInputStream())); + if (!json.has("code")){ + json.put("code", "OK"); + } + return json; + } + catch (IOException e) { + InputStream error = ((HttpURLConnection) request).getErrorStream(); + JSONObject json = new JSONObject(new JSONTokener(error)); + if (!json.has("code")) { + json.put("code", "Error"); + } + else { + Object value = json.get("code"); + json.put("code", value.toString()); + } + return json; + } + } + + protected JSONObject fetch(String endpoint, String method, HashMap params) throws + OAuthMessageSignerException, + OAuthExpectationFailedException, + OAuthCommunicationException, + IOException, URISyntaxException { + String req = new StringBuffer() + .append(API_BASE) + .append(endpoint) + .toString(); + URL url = new URL(req); + url = url.toURI().normalize().toURL(); + HttpURLConnection request = (HttpURLConnection) url.openConnection(); + request.setRequestProperty("User-Agent", "Semantics3 Java Library"); + if(method == "POST") { + request.setDoInput(true); + request.setDoOutput(true); + request.setRequestMethod(method); + request.setRequestProperty("Content-Type", "application/json"); + request.setRequestProperty("Accept", "application/json"); + consumer.sign(request); + JSONObject jsonParams = new JSONObject(params); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(request.getOutputStream()); + outputStreamWriter.write(jsonParams.toString()); + outputStreamWriter.flush(); + outputStreamWriter.close(); + } + else { + request.setRequestMethod(method); + consumer.sign(request); + } + request.connect(); + try { + JSONObject json = new JSONObject(new JSONTokener(request.getInputStream())); + if (!json.has("code")){ + json.put("code", "OK"); + } + return json; + } + catch (IOException e) { + InputStream error = ((HttpURLConnection) request).getErrorStream(); + JSONObject json = new JSONObject(new JSONTokener(error)); + if (!json.has("code")) { + json.put("code", "Error"); + } + else { + Object value = json.get("code"); + json.put("code", value.toString()); + } + return json; + } + } + + public Semantics3Request add(String endpoint, Object... fields) { + JSONObject endpointQuery; + if ((endpointQuery = query.get(endpoint)) == null) { + endpointQuery = new JSONObject(); + query.put(endpoint,endpointQuery); + } + JSONObject sq = endpointQuery; + for (int i=0;i params) throws + OAuthMessageSignerException, + OAuthExpectationFailedException, + OAuthCommunicationException, + IOException, URISyntaxException { + if(method == "GET"){ + JSONObject jsonObject = new JSONObject(params); + this.query.put(endpoint, jsonObject); + this.runQuery(endpoint); + + } + else { + this.queryResult = fetch(endpoint, method, params); + } + if (!this.queryResult.getString("code").equals("OK")) { + throw new Semantics3Exception( + this.queryResult.getString("code"), + this.queryResult.getString("message") + ); + + } + return this.queryResult; + } + + public JSONObject get() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, URISyntaxException { + return get(this.endpoint); + } + + public JSONObject get(String endpoint) throws + OAuthMessageSignerException, + OAuthExpectationFailedException, + OAuthCommunicationException, + IOException, URISyntaxException { + this.runQuery(endpoint); + return this.queryResult; + } +} diff --git a/src/main/java/com/semantics3/api/TestUtils.java b/src/main/java/com/semantics3/api/TestUtils.java new file mode 100644 index 0000000..a65b155 --- /dev/null +++ b/src/main/java/com/semantics3/api/TestUtils.java @@ -0,0 +1,20 @@ +package com.semantics3.api; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Created by abishek on 03/04/15. + */ +public class TestUtils { + public static Properties getConfig(String fileName) throws IOException { + Properties property = new Properties(); + InputStream input = TestUtils.class.getClassLoader().getResourceAsStream(fileName); + if(input==null){ + System.out.println("Sorry, unable to find " + fileName); + } + property.load(input); + return property; + } +} diff --git a/src/com/semantics3/errors/Semantics3Exception.java b/src/main/java/com/semantics3/errors/Semantics3Exception.java similarity index 100% rename from src/com/semantics3/errors/Semantics3Exception.java rename to src/main/java/com/semantics3/errors/Semantics3Exception.java diff --git a/src/org/json/CDL.java b/src/main/java/org/json/CDL.java similarity index 100% rename from src/org/json/CDL.java rename to src/main/java/org/json/CDL.java diff --git a/src/org/json/Cookie.java b/src/main/java/org/json/Cookie.java similarity index 100% rename from src/org/json/Cookie.java rename to src/main/java/org/json/Cookie.java diff --git a/src/org/json/CookieList.java b/src/main/java/org/json/CookieList.java similarity index 100% rename from src/org/json/CookieList.java rename to src/main/java/org/json/CookieList.java diff --git a/src/org/json/HTTP.java b/src/main/java/org/json/HTTP.java similarity index 100% rename from src/org/json/HTTP.java rename to src/main/java/org/json/HTTP.java diff --git a/src/org/json/HTTPTokener.java b/src/main/java/org/json/HTTPTokener.java similarity index 100% rename from src/org/json/HTTPTokener.java rename to src/main/java/org/json/HTTPTokener.java diff --git a/src/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java similarity index 100% rename from src/org/json/JSONArray.java rename to src/main/java/org/json/JSONArray.java diff --git a/src/org/json/JSONException.java b/src/main/java/org/json/JSONException.java similarity index 100% rename from src/org/json/JSONException.java rename to src/main/java/org/json/JSONException.java diff --git a/src/org/json/JSONML.java b/src/main/java/org/json/JSONML.java similarity index 100% rename from src/org/json/JSONML.java rename to src/main/java/org/json/JSONML.java diff --git a/src/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java similarity index 100% rename from src/org/json/JSONObject.java rename to src/main/java/org/json/JSONObject.java diff --git a/src/org/json/JSONString.java b/src/main/java/org/json/JSONString.java similarity index 100% rename from src/org/json/JSONString.java rename to src/main/java/org/json/JSONString.java diff --git a/src/org/json/JSONStringer.java b/src/main/java/org/json/JSONStringer.java similarity index 100% rename from src/org/json/JSONStringer.java rename to src/main/java/org/json/JSONStringer.java diff --git a/src/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java similarity index 100% rename from src/org/json/JSONTokener.java rename to src/main/java/org/json/JSONTokener.java diff --git a/src/org/json/JSONWriter.java b/src/main/java/org/json/JSONWriter.java similarity index 100% rename from src/org/json/JSONWriter.java rename to src/main/java/org/json/JSONWriter.java diff --git a/src/org/json/None.java b/src/main/java/org/json/None.java similarity index 100% rename from src/org/json/None.java rename to src/main/java/org/json/None.java diff --git a/src/org/json/XML.java b/src/main/java/org/json/XML.java similarity index 100% rename from src/org/json/XML.java rename to src/main/java/org/json/XML.java diff --git a/src/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java similarity index 100% rename from src/org/json/XMLTokener.java rename to src/main/java/org/json/XMLTokener.java diff --git a/src/test/java/com/semantics3/api/ProductsTest.java b/src/test/java/com/semantics3/api/ProductsTest.java new file mode 100644 index 0000000..7eab00f --- /dev/null +++ b/src/test/java/com/semantics3/api/ProductsTest.java @@ -0,0 +1,108 @@ +package com.semantics3.api; + +import com.semantics3.errors.Semantics3Exception; +import oauth.signpost.exception.OAuthCommunicationException; +import oauth.signpost.exception.OAuthExpectationFailedException; +import oauth.signpost.exception.OAuthMessageSignerException; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Properties; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Created by abishek on 03/04/15. + */ +public class ProductsTest { + @Test + public void TestProductsQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products.productsField("search", "iphone"); + JSONObject results = products.getProducts(); + JSONArray resultsArray = (JSONArray) results.get("results"); + assertThat(resultsArray.length() > 0, is(true)); + } + + @Test + public void TestUPCQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products.productsField("upc", "883974958450"); + products.productsField("fields", "name", "gtins"); + JSONObject results = products.getProducts(); + JSONArray resultsArray = (JSONArray) results.get("results"); + assertThat(resultsArray.length() > 0, is(true)); + } + + @Test + public void TestURLQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products.productsField("url", "http://www.walmart.com/ip/15833173"); + JSONObject results = products.getProducts(); + JSONArray resultsArray = (JSONArray) results.get("results"); + assertThat(resultsArray.length() > 0, is(true)); + } + + @Test + public void TestPriceFilterQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products + .productsField("search", "iphone") + .productsField("price", "lt", 300); + JSONObject results = products.getProducts(); + JSONArray resultsArray = (JSONArray) results.get("results"); + assertThat(resultsArray.length() > 0, is(true)); + } + + @Test + public void TestCategoryIDQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products + .categoriesField("cat_id", 4992); JSONObject results = products.getCategories(); JSONArray resultsArray = (JSONArray) results.get("results"); assertThat(resultsArray.length() > 0, is(true)); } @Test + public void TestSKUQuery() throws OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, IOException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Semantics3Request semantics3Request = new Semantics3Request(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + HashMap params = new HashMap(); + params.put("site", "abercrombie.com"); + JSONObject jsonObject = semantics3Request.runQuery("skus", "GET", params); + JSONArray resultsArray = (JSONArray) jsonObject.get("results"); + assertThat(resultsArray.length() > 0, is(true)); + } + + @Test(expected = Semantics3Exception.class) + public void TestSiteQuery() throws IOException, OAuthExpectationFailedException, OAuthCommunicationException, OAuthMessageSignerException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Products products = new Products(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + products .productsField("url", "zsdfseobn.com/sdgeafg"); + JSONObject results = products.getProducts(); + } + + @Ignore + public void TestPagination() throws IOException, OAuthCommunicationException, OAuthExpectationFailedException, OAuthMessageSignerException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Semantics3Request semantics3Request = new Semantics3Request(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + HashMap params = new HashMap(); + params.put("site", "macys.com"); + JSONObject jsonObject = semantics3Request.runQuery("skus", "GET", params); + while(jsonObject.has("next")){ + JSONObject next = (JSONObject)jsonObject.get("next"); + String page = next.getString("page"); + System.out.println(page); + params.remove("site"); + params.put("page", page); + jsonObject = semantics3Request.runQuery("skus", "GET", params); + System.out.println(jsonObject.toString()); + } + } +} diff --git a/src/test/java/com/semantics3/api/Semantics3RequestTest.java b/src/test/java/com/semantics3/api/Semantics3RequestTest.java new file mode 100644 index 0000000..135dc1f --- /dev/null +++ b/src/test/java/com/semantics3/api/Semantics3RequestTest.java @@ -0,0 +1,66 @@ +package com.semantics3.api; + +import com.semantics3.errors.Semantics3Exception; +import oauth.signpost.exception.OAuthCommunicationException; +import oauth.signpost.exception.OAuthExpectationFailedException; +import oauth.signpost.exception.OAuthMessageSignerException; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Properties; + +import static org.hamcrest.CoreMatchers.anything; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Created by abishek on 03/04/15. + */ +public class Semantics3RequestTest { + @Test + public void testRunQueryPost() throws IOException, OAuthCommunicationException, OAuthExpectationFailedException, OAuthMessageSignerException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Semantics3Request sem3 = new Semantics3Request(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + HashMap params = new HashMap(); + params.put("webhook_uri", " http://sem3-webhooks-verification.ngrok.com"); + try { + JSONObject result = sem3.runQuery("webhooks", "POST", params); + assertThat(result.getString("code"), equalTo("OK")); + } catch (Semantics3Exception e) { + String message = e.getMessage(); + assertThat(message, anything("Duplicate")); + } + } + + @Test + public void testRunQueryGet() throws IOException, OAuthCommunicationException, OAuthExpectationFailedException, OAuthMessageSignerException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Semantics3Request sem3 = new Semantics3Request(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + HashMap params = new HashMap(); + JSONObject result = sem3.runQuery("webhooks", "GET", params); + assertThat(result.getString("code"), equalTo("OK")); + + } + + @Test + public void testRunQueryDelete() throws IOException, OAuthCommunicationException, OAuthExpectationFailedException, OAuthMessageSignerException, URISyntaxException { + Properties property = TestUtils.getConfig("api.config"); + Semantics3Request sem3 = new Semantics3Request(property.get("API_KEY").toString(), property.get("API_SECRET").toString()); + HashMap params = new HashMap(); + JSONObject result = sem3.runQuery("webhooks", "GET", params); + JSONArray data = result.getJSONArray("data"); + if (data.length() > 0) { + JSONObject webhooks = (JSONObject) data.get(0); + String webhooksId = webhooks.getString("id"); + String endpoint = "webhooks/" + webhooksId; + JSONObject response = sem3.runQuery(endpoint, "DELETE", params); + assertThat(response.getString("code"), equalTo("OK")); + } + } + + +} diff --git a/src/test/resources/api.config.sample b/src/test/resources/api.config.sample new file mode 100644 index 0000000..a0a986b --- /dev/null +++ b/src/test/resources/api.config.sample @@ -0,0 +1,4 @@ +API_KEY= +API_SECRET= +SKU_API_KEY= +SKU_API_SECRET=