Files
EasyDrop/src/main/java/de/rwu/easydrop/api/client/EbayItemDataSource.java
2023-05-31 13:47:29 +02:00

89 lines
2.4 KiB
Java

package de.rwu.easydrop.api.client;
import java.net.MalformedURLException;
import java.net.URL;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.ReadContext;
import de.rwu.easydrop.api.dto.ProductDTO;
/**
* Interface to an eBay data source.
*
* @since 0.2.0
*/
public final class EbayItemDataSource extends AbstractDataSource {
/**
* Name of this data source.
*/
private static final String DATA_ORIGIN = "eBay";
/**
* Base URL to the eBay data source.
*/
private String baseUrl;
/**
* Credential key to authorize access.
*/
private String apiKey;
/**
* Sets up instance with Base URL and API Key.
*
* @param newBaseUrl
* @param newApiKey
*/
public EbayItemDataSource(final String newBaseUrl, final String newApiKey) {
this.baseUrl = newBaseUrl;
this.apiKey = newApiKey;
}
/**
* @param searchQuery Exact product name or other valid identifier.
*/
@Override
public URL createApiUrl(final String searchQuery) throws MalformedURLException {
return new URL(baseUrl
+ "/buy/browse/v1/item_summary/search?q="
+ searchQuery
+ "&limit=1&offset=0");
}
/**
* Enriches a ProductDTO with API-gathered data.
*
* @param product Unfinished ProductDTO
* @param json Product data
* @return Finished ProductDTO
*/
public ProductDTO buildProductDTO(final ProductDTO product, final String json) {
String root = "$.itemSummaries[0].";
ReadContext ctx = JsonPath.parse(json);
try {
product.setDataOrigin(DATA_ORIGIN);
product.setAvailable(
ctx.read(root + "shippingOptions[0].guaranteedDelivery", boolean.class));
product.setCurrentPrice(ctx.read(root + "price.value", double.class));
product.setDeliveryPrice(
ctx.read(root + "shippingOptions[0].shippingCost.value", double.class));
product.setMerchant(ctx.read(root + "seller.username", String.class));
} catch (PathNotFoundException e) {
// Pass, allow incomplete ProductDTO to pass for later validation
}
return product;
}
@Override
protected String getDataOrigin() {
return DATA_ORIGIN;
}
@Override
protected String getApiKey() {
return this.apiKey;
}
}