- * Filters the contents of an unzipped feed file
- *
- *
- * @param filterRequest
- * Consists of all the parameters that are required for filtering.
- *
- * In case of filtering by level two or level three categories, it is mandatory to pass
- *
+ * Filters the contents of an unzipped feed file
+ *
+ *
+ * @param filterRequest
+ * Consists of all the parameters that are required for filtering.
+ *
+ * In case of filtering by level two or level three categories, it is
+ * mandatory to pass
+ *
- * Unzip downloaded feed file and create a new file
- *
- *
- * @param filePath The absolute path to the gzipped feed file
- * @return Response Response
- */
- public Response unzip(String filePath);
+ /**
+ *
+ * Unzip downloaded feed file and create a new file
+ *
+ *
+ * @param filePath The absolute path to the gzipped feed file
+ * @return Response Response
+ */
+ public Response unzip(String filePath);
+ /**
+ *
+ * Downloads the feed file as specified by the parameters in the request.
+ * Based on the feedRequest values, if a file is available, then it is
+ * downloaded and the method returns the file path.
+ *
+ * If the file is not available, then the error details are returned.
+ *
+ *
+ * @param feedRequest Container for capturing parameters for downloading
+ * feed file
+ * @param downloadDirectory The local directory where the file should be
+ * downloaded. Default location is the current working directory
+ * @return GetFeedResponse GetFeedResponse
+ */
+ public GetFeedResponse get(FeedRequest feedRequest, String downloadDirectory);
- /**
- *
- * Downloads the feed file as specified by the parameters in the request. Based on the feedRequest
- * values, if a file is available, then it is downloaded and the method returns the file path.
- *
- * If the file is not available, then the error details are returned.
- *
- *
- * @param feedRequest Container for capturing parameters for downloading feed file
- * @param downloadDirectory The local directory where the file should be downloaded. Default location is
- * the current working directory
- * @return GetFeedResponse GetFeedResponse
- */
- public GetFeedResponse get(FeedRequest feedRequest, String downloadDirectory);
+ /**
+ *
+ * Downloads the feed file as specified by the parameters in the
+ * request.Based on the feedRequest values, if a file is available, then it
+ * is downloaded and the method returns the file path. If the file is not
+ * available, then the error details are returned.
+ *
+ *
+ * @param feedRequest Container for capturing parameters for downloading
+ * feed file
+ * @param downloadDirectory The local directory where the file should be
+ * downloaded. Default location is the current working directory
+ * @param credentialConfigFilePath credentials file absolute path, required
+ * for token refresh on the fly to support resume capability. Default
+ * location is the current working directory
+ * @return GetFeedResponse GetFeedResponse
+ */
+ public GetFeedResponse get(FeedRequest feedRequest, String downloadDirectory, String credentialConfigFilePath);
- /**
- *
- * Given a config file, this method parses the input, and performs necessary actions,
- * as specified in the config file.
- *
- * The config file should consist of json and follow the structure :-
- * {
- *
- * "requests": [
- * {
- * "feedRequest": {
- *
- * },
- * "filterRequest": {
- *
- * }
- * }
- *
- * ]
- * }
- *
- *
- * If the original file is already downloaded, then the feedRequest becomes optional,
- * and the unzipped file path can be provided in the 'inputFilePath' field in the
- * filter request,
- * along with the other filter characteristics.
- *
- * If the entire workflow needs to be performed i.e - download, unzip and filter,
- * then both feedRequest and filterRequest are required.
- * The inputFilePath can be omitted in this case.
- *
- *
- * @param configFile The absolute path of the file, which consists of a list of feed request or filter
- * request or both
- * @param token The oAuth token with the appropriate scope Eg - Bearer vxxx
- * @return List of type Response
- */
- public List processConfigFile(
- String configFile, String token);
+ /**
+ *
+ * Given a config file, this method parses the input, and performs necessary actions,
+ * as specified in the config file.
+ *
+ * The config file should consist of json and follow the structure :-
+ * {
+ *
+ * "requests": [
+ * {
+ * "feedRequest": {
+ *
+ * },
+ * "filterRequest": {
+ *
+ * }
+ * }
+ *
+ * ]
+ * }
+ *
+ *
+ * If the original file is already downloaded, then the feedRequest becomes optional,
+ * and the unzipped file path can be provided in the 'inputFilePath' field in the
+ * filter request,
+ * along with the other filter characteristics.
+ *
+ * If the entire workflow needs to be performed i.e - download, unzip and filter,
+ * then both feedRequest and filterRequest are required.
+ * The inputFilePath can be omitted in this case.
+ *
+ *
+ * @param configFile The absolute path of the file, which consists of a list
+ * of feed request or filter request or both
+ * @param token The oAuth token with the appropriate scope Eg - Bearer vxxx
+ * @return List of type Response
+ */
+ public List processConfigFile(
+ String configFile, String token);
}
diff --git a/src/main/java/com/ebay/feed/api/FeedImpl.java b/src/main/java/com/ebay/feed/api/FeedImpl.java
index 6d22fc9..516b6c3 100755
--- a/src/main/java/com/ebay/feed/api/FeedImpl.java
+++ b/src/main/java/com/ebay/feed/api/FeedImpl.java
@@ -11,10 +11,10 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
-
package com.ebay.feed.api;
+import com.ebay.api.client.auth.oauth2.model.AccessToken;
+import com.ebay.feed.auth.CredentialLoader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -33,7 +33,6 @@
import okhttp3.Request;
import okhttp3.Response;
-
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,472 +44,581 @@
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.internal.InvokeResponse;
+import com.ebay.feed.model.oauth.AuthRequest;
import com.ebay.feed.util.FeedUtil;
import com.ebay.feed.util.FilterUtil;
import com.ebay.feed.validator.FeedValidator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import java.util.Date;
/**
*
- * Concrete implementation which consists of the core capabilities of the SDK.
+ * Concrete implementation which consists of the core capabilities of the
+ * SDK.
*
*
get - To download the feed files
*
unzip - To unzip the gzipped files filter
- *
filter - To apply filters to the unzipped file and create a new file with the filtered
- * contents
+ *
filter - To apply filters to the unzipped file and create a new file with
+ * the filtered contents
+ * Downloads the feed file as specified by the parameters in the
+ * request.Based on the feedRequest values, if a file is available, then it
+ * is downloaded and the method returns the file path. If the file is not
+ * available, then the error details are returned.
+ *
+ *
+ * @param feedRequest Container for capturing parameters for downloading
+ * feed file
+ * @param downloadDirectory The local directory where the file should be
+ * downloaded. Default location is the current working directory
+ * @param credentialConfigFilePath credentials file absolute path, required
+ * for token refresh on the fly to support resume capability while
+ * downloading feeds. Default location is the current working directory
+ * @return GetFeedResponse GetFeedResponse
+ */
+ @Override
+ public GetFeedResponse get(FeedRequest feedRequest, String downloadDirectory, String credentialConfigFilePath) {
+
+ if (null == credentialConfigFilePath || credentialConfigFilePath.isEmpty()) {
+ LOGGER.debug("********* using default credentialFilePath = {}", credentialFilePath);
+ credentialConfigFilePath = credentialFilePath;
+ }
+ LOGGER.debug("********* Begin Feed.get()");
- if (feedRequest == null) {
- return new GetFeedResponse(-1, "feedRequest is null.Aborting..", null, null);
- }
+ GetFeedResponse response = null;
+ Path downloadDirectoryPath = null;
- // if null, then take default path - current directory
- if (downloadDirectory == null) {
- downloadDirectoryPath = Paths.get(".").toAbsolutePath().normalize();
- } else {
- downloadDirectoryPath = Paths.get(downloadDirectory);
- }
+ if (feedRequest == null) {
+ return new GetFeedResponse(-1, "feedRequest is null.Aborting..", null, null);
+ }
- LOGGER.debug("feedRequest params = {}", feedRequest.toString());
+ // if null, then take default path - current directory
+ if (downloadDirectory == null) {
+ downloadDirectoryPath = Paths.get(".").toAbsolutePath().normalize();
+ } else {
+ downloadDirectoryPath = Paths.get(downloadDirectory);
+ }
- try {
- response = process(feedRequest, downloadDirectoryPath);
+ LOGGER.debug("feedRequest params = {}", feedRequest.toString());
- } catch (Exception e) {
- LOGGER.error("Exception in Feed.get()", e);
- e.printStackTrace();
- response = new GetFeedResponse(Constants.FAILURE_CODE, e.getMessage(), null, null);
- }
+ try {
+ response = process(feedRequest, downloadDirectoryPath, credentialConfigFilePath);
- LOGGER.debug("Exiting Feed.get() {}", response.getFilePath());
- return response;
- }
+ } catch (Exception e) {
+ LOGGER.error("Exception in Feed.get()", e);
+ e.printStackTrace();
+ response = new GetFeedResponse(Constants.FAILURE_CODE, e.getMessage(), null, null);
+ }
- /**
- *
- * The process method performs pre requisite functions, before calling the feed API - Adds
- * additional headers including range - Creates default file/folder path and cleansup if already
- * present
- *
- *
- * @param feedRequest
- * @param downloadDirectory Optional local directory where files can be downloaded. Default is
- * current working directory
- * @return
- * @throws IOException
- */
- private GetFeedResponse process(FeedRequest feedRequest, Path downloadDirectory)
- throws IOException {
-
- LOGGER.debug("Entering Feed.process()");
-
- if (feedRequest.getToken() == null || feedRequest.getType() == null
- || feedRequest.getCategoryId() == null || feedRequest.getMarketplaceId() == null) {
- return new GetFeedResponse(-1, "Mandatory feedRequest parameters are null. Aborting..", null,
- null);
+ LOGGER.debug("Exiting Feed.get() {}", response.getFilePath());
+ return response;
}
- Request.Builder requestBuilder = new Request.Builder();
+ /**
+ *
+ * The process method performs pre requisite functions, before calling the
+ * feed API - Adds additional headers including range - Creates default
+ * file/folder path and cleansup if already present
+ *
+ *
+ * @param feedRequest
+ * @param downloadDirectory Optional local directory where files can be
+ * downloaded. Default is current working directory
+ * @return
+ * @throws IOException
+ */
+ private GetFeedResponse process(FeedRequest feedRequest, Path downloadDirectory, String credentialConfigFilePath)
+ throws IOException {
+
+ LOGGER.debug("Entering Feed.process()");
+
+ if (feedRequest.getToken() == null || feedRequest.getType() == null
+ || feedRequest.getCategoryId() == null || feedRequest.getMarketplaceId() == null) {
+ return new GetFeedResponse(-1, "Mandatory feedRequest parameters are null. Aborting..", null,
+ null);
+ }
- Path pathToFile =
- Paths.get(downloadDirectory.toString() + "/" + feedUtils.generateFileName(feedRequest));
- LOGGER.debug("Path to store file = {}", pathToFile);
+ // checking if date format is valid and date is within valid range
+ if (!feedValidator.isValidDateFormatAndRange(feedRequest)) {
+ LOGGER.debug("Date format is not valid or Date is not within valid range. Cannot get feed. Aborting...");
+ return new GetFeedResponse(-1, "Date format is not valid or Date is not within valid range. Cannot get feed. Aborting...",
+ null, null);
+ }
- if (Files.exists(pathToFile)) {
- Files.delete(pathToFile);
- } else {
- Files.createDirectories(pathToFile.getParent());
- }
+ Request.Builder requestBuilder = new Request.Builder();
- Path path = Files.createFile(pathToFile);
+ Path pathToFile
+ = Paths.get(downloadDirectory.toString() + "/" + feedUtils.generateFileName(feedRequest));
+ LOGGER.debug("Path to store file = {}", pathToFile);
- // generate static request
- requestBuilder = feedUtils.generateRequest(feedRequest, requestBuilder);
+ if (Files.exists(pathToFile)) {
+ Files.delete(pathToFile);
+ } else {
+ Files.createDirectories(pathToFile.getParent());
+ }
- // generate dynamic header
- Long chunkSizeLimit = feedUtils.getChunkSizeLimit(feedRequest);
- requestBuilder.addHeader(Constants.RANGE_HEADER, Constants.RANGE_PREFIX + chunkSizeLimit);
+ Path path = Files.createFile(pathToFile);
- // invoke request
- return invoker(requestBuilder, path, true, chunkSizeLimit);
- }
+ // generate static request
+ requestBuilder = feedUtils.generateRequest(feedRequest, requestBuilder);
- /**
- *
- * Invokes the feed API with the max range value of 100 MB. If the file is lesser than 100 MB,
- * then it returns the downloaded file path along with the status.
- *
- * If the file is greater than 100 MB - Iteratively calls feed API, with incrementing range
- * headers - Appends content to file - Downloads entire content and returns with downloaded file
- * path.
- *
- *
- *
- * @param request The API request
- * @param path Path of the downloaded or partially downloading file, where contents need to be
- * appended
- * @param isStart - THe first request sets this parameter to true. If subsequent requests are
- * required in case of 206, then this is set to false.
- * @param chunkSizeLimit - This indicates the max chunkSize limit. For prod, it is 100 MB and for sandbox, it is 10MB.
- * @return
- */
- private GetFeedResponse invoker(Request.Builder requestBuilder, Path path, boolean isStart, Long chunkSizeLimit) {
+ // generate dynamic header
+ Long chunkSizeLimit = feedUtils.getChunkSizeLimit(feedRequest);
+ requestBuilder.addHeader(Constants.RANGE_HEADER, Constants.RANGE_PREFIX + chunkSizeLimit);
- LOGGER.debug("Entering Feed.invoker()");
+ // invoke request
+ return invoker(requestBuilder, path, true, chunkSizeLimit, feedRequest, credentialConfigFilePath);
+ }
- Request request = requestBuilder.build();
+ /**
+ *
+ * Invokes the feed API with the max range value of 100 MB. If the file is
+ * lesser than 100 MB, then it returns the downloaded file path along with
+ * the status.
+ *
+ * If the file is greater than 100 MB - Iteratively calls feed API, with
+ * incrementing range headers - Appends content to file - Downloads entire
+ * content and returns with downloaded file path.
+ *
+ *
+ *
+ * @param request The API request
+ * @param path Path of the downloaded or partially downloading file, where
+ * contents need to be appended
+ * @param isStart - THe first request sets this parameter to true. If
+ * subsequent requests are required in case of 206, then this is set to
+ * false.
+ * @param chunkSizeLimit - This indicates the max chunkSize limit. For prod,
+ * it is 100 MB and for sandbox, it is 10MB.
+ * @return
+ */
+ private GetFeedResponse invoker(Request.Builder requestBuilder, Path path, boolean isStart, Long chunkSizeLimit, FeedRequest feedRequest, String credentialConfigFilePath) {
+
+ LOGGER.debug("Entering Feed.invoker()");
+
+ Request request = requestBuilder.build();
+
+ LOGGER.debug("API request = {}", request.toString());
+
+ InvokeResponse responseFlag = invokeIteratively(request, path);
+
+ LOGGER.debug("First API Response = {}", responseFlag.toString());
+
+ if (responseFlag.getStatusCode() == 200) {
+ LOGGER.debug("First API Response is 200. All done..");
+ return new GetFeedResponse(Constants.SUCCESS_CODE, Constants.SUCCESS, fixFilePath(path, responseFlag), null);
+
+ } else if (responseFlag.getStatusCode() == 206) {
+
+ LOGGER.debug("First API Response is 206. Performing iterations...");
+
+ long requestRangeUpperLimit
+ = Long.valueOf(requestBuilder.build().header("Range").split("-")[1]) + 1;
+ long responseRangeUpperLimit = Long.valueOf(responseFlag.getContentRange().split("/")[1]);
+
+ boolean isCredentialLoaded = false;
+ //config file path for loading credentials
+ AuthRequest authRequest = new AuthRequest(credentialConfigFilePath, null);
+ CredentialLoader credentialLoader = new CredentialLoader(authRequest);
+ AccessToken accessToken = null;
+ try {
+ credentialLoader.loadCredentials();
+ //Getting access using credentials file as we have to use this for resume capability
+ accessToken = updateAccessTokenOnTheFly(credentialLoader, feedRequest, requestBuilder);
+ isCredentialLoaded = true;
+ } catch (Exception e) {
+ }
+ while (requestRangeUpperLimit <= responseRangeUpperLimit) {
- LOGGER.debug("API request = {}", request.toString());
+ long newUpperLimit = requestRangeUpperLimit + chunkSizeLimit;
+ String val = "bytes=" + requestRangeUpperLimit + "-" + newUpperLimit;
- InvokeResponse responseFlag = invokeIteratively(request, path);
+ requestBuilder.removeHeader(Constants.RANGE_HEADER);
+ requestBuilder.addHeader(Constants.RANGE_HEADER, val);
- LOGGER.debug("First API Response = {}", responseFlag.toString());
+ //this block will not execute if token passed direcrly. Backward compatibile
+ if (isCredentialLoaded) {
+ if (checkTokenExpiry(accessToken, credentialLoader, feedRequest, requestBuilder)) {
+ return new GetFeedResponse(Constants.FAILURE_CODE, Constants.FAILURE, null, null);
+ }
+ }
- if (responseFlag.getStatusCode() == 200) {
- LOGGER.debug("First API Response is 200. All done..");
- return new GetFeedResponse(Constants.SUCCESS_CODE, Constants.SUCCESS, fixFilePath(path,responseFlag), null);
+ responseFlag = invokeIteratively(requestBuilder.build(), path);
+ //Showing download progess
+ LOGGER.debug("First API Response = {}", responseFlag.toString());
- } else if (responseFlag.getStatusCode() == 206) {
+ if (responseFlag == null) {
+ return new GetFeedResponse(-1, "Internal error. Please check the logs..", null, null);
+ }
- LOGGER.debug("First API Response is 206. Performing iterations...");
+ requestRangeUpperLimit
+ = Long.valueOf(requestBuilder.build().header(Constants.RANGE_HEADER).split("-")[1]) + 1;
+ responseRangeUpperLimit = Long.valueOf(responseFlag.getContentRange().split("/")[1]);
- long requestRangeUpperLimit =
- Long.valueOf(requestBuilder.build().header("Range").split("-")[1]) + 1;
- long responseRangeUpperLimit = Long.valueOf(responseFlag.getContentRange().split("/")[1]);
+ }
+ return new GetFeedResponse(Constants.SUCCESS_CODE, Constants.SUCCESS, fixFilePath(path, responseFlag), null);
+ } else {
+ LOGGER.debug("First API Response is error. Aborting...");
+ return new GetFeedResponse(Constants.FAILURE_CODE, Constants.FAILURE, null, null);
+ }
+ }
- while (requestRangeUpperLimit <= responseRangeUpperLimit) {
+ /**
+ *
+ * @param accessToken
+ * @param credentialLoader
+ * @param feedRequest
+ * @param requestBuilder
+ * @return
+ */
+ private boolean checkTokenExpiry(AccessToken accessToken, CredentialLoader credentialLoader, FeedRequest feedRequest, Request.Builder requestBuilder) {
+ try {
+ Date currentTime = new Date();
+ //token refresh on the fly from config file to support resume capability.
+ if (accessToken.getExpiresOn().before(currentTime)) {
+ LOGGER.debug("Old Token expiry time = {}", accessToken.getExpiresOn());
+ accessToken = updateAccessTokenOnTheFly(credentialLoader, feedRequest, requestBuilder);
+ LOGGER.info("Got refresh token on the fly and New Token Expiry time = {}", accessToken.getExpiresOn());
+ }
+ } catch (Exception e) {
+ LOGGER.info("Exception in fetching the new access token " + e.getMessage());
+ return true;
+ }
+ return false;
+ }
- long newUpperLimit = requestRangeUpperLimit + chunkSizeLimit;
- String val = "bytes=" + requestRangeUpperLimit + "-" + newUpperLimit;
+ /**
+ *
+ * Since date is optional param for getting bootstrap feed, filePath will
+ * have null value(item_bootstrap-11116-null-EBAY_US.gz) This method helps
+ * to rename the null value with LastModified api response header
+ *
+ * Invoked, only if the file size is greater than max chunk size
+ *
+ *
+ * @param request The API request
+ * @param path Path of the downloaded or partially downloading file, where
+ * contents need to be appended
+ * @return
+ */
+ private InvokeResponse invokeIteratively(Request request, Path path) {
+
+ InvokeResponse responseFlag = null;
+
+ try (Response response = client.newCall(request).execute()) {
+
+ if (!response.isSuccessful()) {
+ LOGGER.debug("Error in API response - status = {}, body = {}", response.code(), response
+ .body().string());
+ return new InvokeResponse(null, response.code());
+ }
- responseFlag = invokeIteratively(requestBuilder.build(), path);
+ InputStream is = response.body().byteStream();
- if (responseFlag == null) {
- return new GetFeedResponse(-1, "Internal error. Please check the logs..", null, null);
- }
+ OutputStream outStream = new FileOutputStream(path.toString(), true);
+ byte[] buffer = new byte[1024];
+ int bytesRead;
+ while ((bytesRead = is.read(buffer)) != -1) {
+ outStream.write(buffer, 0, bytesRead);
+ }
+ outStream.flush();
+ outStream.close();
+ is.close();
+
+ String lastModifiedHeader = response.header(Constants.LAST_MODIFIED_DATE_HEADER);
+ String lastModifiedDate = null;
+ if (!StringUtils.isEmpty(lastModifiedHeader)) {
+ LocalDate localDate = LocalDate.parse(lastModifiedHeader, DateTimeFormatter.RFC_1123_DATE_TIME);
+ lastModifiedDate = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
+ }
- requestRangeUpperLimit =
- Long.valueOf(requestBuilder.build().header(Constants.RANGE_HEADER).split("-")[1]) + 1;
- responseRangeUpperLimit = Long.valueOf(responseFlag.getContentRange().split("/")[1]);
+ responseFlag
+ = new InvokeResponse(response.header(Constants.CONTENT_RANGE_HEADER), response.code(), lastModifiedDate);
- }
- return new GetFeedResponse(Constants.SUCCESS_CODE, Constants.SUCCESS, fixFilePath(path,responseFlag), null);
- } else {
- LOGGER.debug("First API Response is error. Aborting...");
- return new GetFeedResponse(Constants.FAILURE_CODE, Constants.FAILURE, null, null);
- }
- }
-
- /**
- *
- * Since date is optional param for getting bootstrap feed, filePath will have null value(item_bootstrap-11116-null-EBAY_US.gz)
- * This method helps to rename the null value with LastModified api response header
- *
+ * Returns a new instance of response, based on the provided inputs
+ *
+ *
+ * @param statusCode
+ * @param message
+ * @param filePath
+ * @param appliedFilters
+ * @return
+ */
+ private com.ebay.feed.model.feed.operation.filter.Response createResponse(Integer statusCode,
+ String message, String filePath, FeedFilterRequest appliedFilters) {
+
+ LOGGER.debug("Returning response status code = {}, message = {}", statusCode, message);
+ LOGGER.debug("Filtered file = {}, appliedFilters = {}", filePath,
+ appliedFilters != null ? appliedFilters.toString() : null);
+
+ return new com.ebay.feed.model.feed.operation.filter.Response(statusCode, message, filePath,
+ appliedFilters);
+ }
+
+ /**
+ * Getting accessToken on the fly using credential file to support resume
+ * capability
+ *
+ * @param credentialLoader
+ * @param environment
+ * @param feedRequest
+ * @param requestBuilder
+ * @return
+ */
+ private AccessToken updateAccessTokenOnTheFly(CredentialLoader credentialLoader, FeedRequest feedRequest, Request.Builder requestBuilder) throws IOException {
+ AccessToken accessToken = credentialLoader.getOauthResponse(feedRequest.getEnv()).getAccessToken().get();
+ //using token which generated from credentials file as we don't know the expiry time of directly passed token
+ if (!accessToken.getToken().equalsIgnoreCase(feedRequest.getToken())) {
+ String token = Constants.TOKEN_BEARER_PREFIX + accessToken.getToken();
+ requestBuilder.removeHeader(Constants.AUTHORIZATION_HEADER);
+ requestBuilder.addHeader(Constants.AUTHORIZATION_HEADER, token);
+ }
+ return accessToken;
+ }
}
diff --git a/src/main/java/com/ebay/feed/api/Taxonomy.java b/src/main/java/com/ebay/feed/api/Taxonomy.java
index bb0c721..8222e52 100644
--- a/src/main/java/com/ebay/feed/api/Taxonomy.java
+++ b/src/main/java/com/ebay/feed/api/Taxonomy.java
@@ -14,7 +14,6 @@
package com.ebay.feed.api;
-import java.io.IOException;
import com.ebay.feed.model.feed.operation.taxonomy.CategoryResponse;
diff --git a/src/main/java/com/ebay/feed/auth/CredentialLoader.java b/src/main/java/com/ebay/feed/auth/CredentialLoader.java
index 26ab827..21e5072 100644
--- a/src/main/java/com/ebay/feed/auth/CredentialLoader.java
+++ b/src/main/java/com/ebay/feed/auth/CredentialLoader.java
@@ -11,14 +11,12 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.auth;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
-import com.ebay.feed.example.CombiningFilters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ebay.api.client.auth.oauth2.CredentialUtil;
@@ -30,70 +28,97 @@
/**
*
* Responsible for loading consumer credentials and generating token.
- *
- * In order to generate token, the {@link #loadCredentials() loadCredentials} method needs to be
- * invoked, which loads the credentials from the provided config file.
- *
+ *
+ * In order to generate token, the {@link #loadCredentials() loadCredentials}
+ * method needs to be invoked, which loads the credentials from the provided
+ * config file.
+ *
* Once the credentials are loaded, the token can be obtained by invoking the
* {@link #getOauthResponse() getOauthResponse}
- *
+ *
*
- * Loads the credentials provided in the config file
- *
- *
- * @throws Exception Thrown if file is not found or credentials are invalid
- */
- public void loadCredentials() throws Exception {
+ /**
+ *
+ * Loads the credentials provided in the config file
+ *
+ *
+ * @throws Exception Thrown if file is not found or credentials are invalid
+ */
+ public void loadCredentials() throws Exception {
+
+ if (authRequest == null) {
+ throw new Exception("null AuthRequest");
+ }
+
+ LOGGER.debug("****** Begin loadCredentials with configPath = {}",
+ authRequest.getConfigFilePath());
+ try {
+
+ File f = new File(authRequest.getConfigFilePath());
+ FileInputStream fs = new FileInputStream(f);
+ CredentialUtil.load(fs);
+
+ } catch (Exception e) {
+ LOGGER.debug("Exception in loadCredentials", e);
+ throw new Exception("Could not load credentials");
+ }
+ }
- if (authRequest == null)
- throw new Exception("null AuthRequest");
+ /**
+ *
+ * Generates oauth token, based on the loaded credentials
+ *
+ *
+ * @return Returns the OAuthResponse which contains the token
+ * @throws IOException Thrown if file is not found
+ */
+ public OAuthResponse getOauthResponse() throws IOException {
+
+ LOGGER.debug("****** Begin getOauthResponse with configPath = {}",
+ authRequest.getConfigFilePath());
+ OAuth2Api api = new OAuth2Api();
+ OAuthResponse res = api.getApplicationToken(Environment.PRODUCTION, authRequest.getScopes());
+ return res;
- LOGGER.debug("****** Begin loadCredentials with configPath = {}",
- authRequest.getConfigFilePath());
- try {
+ }
- File f = new File(authRequest.getConfigFilePath());
- FileInputStream fs = new FileInputStream(f);
- CredentialUtil.load(fs);
+ /**
+ *
+ * Generates oauth token, based on the loaded credentials
+ *
+ *
+ * @param environment
+ * @return Returns the OAuthResponse which contains the token
+ * @throws IOException Thrown if file is not found
+ */
+ public OAuthResponse getOauthResponse(String environment) throws IOException {
+
+ LOGGER.debug("****** Begin getOauthResponse with configPath = {}",
+ authRequest.getConfigFilePath());
+ OAuth2Api api = new OAuth2Api();
+ OAuthResponse res = null;
+ //checking environment for token
+ if (environment.equalsIgnoreCase("SANDBOX")) {
+ res = api.getApplicationToken(Environment.SANDBOX, authRequest.getScopes());
+ } else {
+ res = api.getApplicationToken(Environment.PRODUCTION, authRequest.getScopes());
+ }
+ return res;
- } catch (Exception e) {
- LOGGER.debug("Exception in loadCredentials", e);
- throw new Exception("Could not load credentials");
}
- }
-
- /**
- *
- * Generates oauth token, based on the loaded credentials
- *
- *
- * @return Returns the OAuthResponse which contains the token
- * @throws IOException Thrown if file is not found
- */
- public OAuthResponse getOauthResponse() throws IOException {
-
- LOGGER.debug("****** Begin getOauthResponse with configPath = {}",
- authRequest.getConfigFilePath());
- OAuth2Api api = new OAuth2Api();
- OAuthResponse res = api.getApplicationToken(Environment.PRODUCTION, authRequest.getScopes());
- return res;
-
- }
}
diff --git a/src/main/java/com/ebay/feed/cli/FeedCli.java b/src/main/java/com/ebay/feed/cli/FeedCli.java
index ba041ed..cc4996d 100644
--- a/src/main/java/com/ebay/feed/cli/FeedCli.java
+++ b/src/main/java/com/ebay/feed/cli/FeedCli.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.cli;
import java.util.ArrayList;
@@ -31,8 +30,6 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.auth.CredentialLoader;
-import com.ebay.feed.enums.EnvTypeEnum;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
@@ -40,283 +37,320 @@
import com.ebay.feed.model.feed.operation.filter.Response;
import com.ebay.feed.model.oauth.AuthRequest;
-
/**
*
* Wrapper for exposing feed sdk capabilities using CLI
*
- *
+ *
* @author shanganesh
*
*/
public class FeedCli {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(FeedCli.class);
-
- public static void main(String[] args) throws Exception {
-
- // ***Definition Stage***
-
- // create Options object
- Options options = new Options();
-
- options.addOption("help", false, "display help");
-
- /***
- * options for downloading the file
- */
- // date
- options.addOption("dt", true, "the date when feed file was generated");
-
- // l1 category
- options.addOption("c1", true, "the l1 category id of the feed file");
-
- // scope
- options.addOption("scope", true,
- "the feed scope. Available scopes are ALL_ACTIVE or NEWLY_LISTED");
-
- // marketplace
- options.addOption("mkt", true,
- "the marketplace id for which feed is being request. For example - EBAY_US");
-
- // token
- options.addOption("token", true, "the oauth token for the consumer. Omit the word 'Bearer'");
-
- // env
- options.addOption("env", true, "Supported environment types are SANDBOX, PRODUCTION");
- /**
- * options for filtering the files
- */
-
- Option filterL2 =
- new Option("c2f", true, "list of l2 categories which are used to filter the feed");
- filterL2.hasArgs();
- filterL2.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterL2);
-
- Option filterL3 =
- new Option("c3f", true, "list of l3 categories which are used to filter the feed");
- filterL3.hasArgs();
- filterL3.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterL3);
-
- Option filterLeaf =
- new Option("lf", true, "list of leaf categories which are used to filter the feed");
- filterLeaf.hasArgs();
- filterLeaf.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterLeaf);
-
- Option filterSeller =
- new Option("sellerf", true, "list of seller names which are used to filter the feed");
- filterSeller.hasArgs();
- filterSeller.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterSeller);
-
- Option filterLocation =
- new Option("locf", true, "list of item locations which are used to filter the feed");
- filterLocation.hasArgs();
- filterLocation.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterLocation);
-
- options.addOption("pricelf", true, "lower limit of the price range for items in the feed");
-
- options.addOption("priceuf", true, "upper limit of the price range for items in the feed");
-
-
- Option filterEpid =
- new Option("epidf", true, "list of epids which are used to filter the feed");
- filterEpid.hasArgs();
- filterEpid.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterEpid);
-
- Option filterInferredEpid =
- new Option("iepidf", true, "list of inferred epids which are used to filter the feed");
- filterInferredEpid.hasArgs();
- filterInferredEpid.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterInferredEpid);
-
- Option filterGtin =
- new Option("gtinf", true, "list of gtins which are used to filter the feed");
- filterGtin.hasArgs();
- filterGtin.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterGtin);
-
- Option filterItem =
- new Option("itemf", true, "list of item ids which are used to filter the feed");
- filterItem.hasArgs();
- filterItem.setArgs(Option.UNLIMITED_VALUES);
- options.addOption(filterItem);
+ private static final Logger LOGGER = LoggerFactory.getLogger(FeedCli.class);
+
+ public static void main(String[] args) throws Exception {
+
+ // ***Definition Stage***
+ // create Options object
+ Options options = new Options();
+
+ options.addOption("help", false, "display help");
+
+ /**
+ * *
+ * options for downloading the file
+ */
+ // date
+ options.addOption("dt", true, "the date when feed file was generated");
+
+ // snapshot_date
+ options.addOption("sdt", true, "the snapshot_date when feed file was generated");
+
+ // l1 category
+ options.addOption("c1", true, "the l1 category id of the feed file");
+
+ // scope
+ options.addOption("scope", true,
+ "the feed scope. Available scopes are ALL_ACTIVE or NEWLY_LISTED");
+
+ // marketplace
+ options.addOption("mkt", true,
+ "the marketplace id for which feed is being request. For example - EBAY_US");
+
+ // token
+ options.addOption("token", true, "the oauth token for the consumer. Omit the word 'Bearer'");
+
+ // env
+ options.addOption("env", true, "Supported environment types are SANDBOX, PRODUCTION");
+
+ // type
+ options.addOption("type", true, "Supported feed types are ITEM, ITEM_SNAPSHOT");
+
+ /**
+ * options for filtering the files
+ */
+ Option filterL2
+ = new Option("c2f", true, "list of l2 categories which are used to filter the feed");
+ filterL2.hasArgs();
+ filterL2.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterL2);
+
+ Option filterL3
+ = new Option("c3f", true, "list of l3 categories which are used to filter the feed");
+ filterL3.hasArgs();
+ filterL3.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterL3);
+
+ Option filterLeaf
+ = new Option("lf", true, "list of leaf categories which are used to filter the feed");
+ filterLeaf.hasArgs();
+ filterLeaf.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterLeaf);
+
+ Option filterSeller
+ = new Option("sellerf", true, "list of seller names which are used to filter the feed");
+ filterSeller.hasArgs();
+ filterSeller.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterSeller);
+
+ Option filterLocation
+ = new Option("locf", true, "list of item locations which are used to filter the feed");
+ filterLocation.hasArgs();
+ filterLocation.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterLocation);
+
+ options.addOption("pricelf", true, "lower limit of the price range for items in the feed");
+
+ options.addOption("priceuf", true, "upper limit of the price range for items in the feed");
+
+ Option filterEpid
+ = new Option("epidf", true, "list of epids which are used to filter the feed");
+ filterEpid.hasArgs();
+ filterEpid.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterEpid);
+
+ Option filterInferredEpid
+ = new Option("iepidf", true, "list of inferred epids which are used to filter the feed");
+ filterInferredEpid.hasArgs();
+ filterInferredEpid.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterInferredEpid);
+
+ Option filterGtin
+ = new Option("gtinf", true, "list of gtins which are used to filter the feed");
+ filterGtin.hasArgs();
+ filterGtin.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterGtin);
+
+ Option filterItem
+ = new Option("itemf", true, "list of item ids which are used to filter the feed");
+ filterItem.hasArgs();
+ filterItem.setArgs(Option.UNLIMITED_VALUES);
+ options.addOption(filterItem);
+
+ /**
+ * Overrides for file locations
+ */
+ // file location
+ options.addOption("dl", "downloadlocation", true,
+ "override for changing the directory where files are downloaded");
+
+ // oauth related
+ options.addOption("cl", "credentiallocation", true,
+ "directory where the credentials file is located");
+
+ options.addOption("authscopes", "oauthscopes", true, "list of scopes");
+
+ // ***Parsing Stage***
+ // Create a parser
+ CommandLineParser parser = new DefaultParser();
+
+ // parse the options passed as command line arguments
+ CommandLine cmd = parser.parse(options, args);
+
+ // ***Interrogation Stage***
+ // hasOptions checks if option is present or not
+ // populate feed request
+ FeedRequestBuilder builder = new FeedRequestBuilder();
+
+ if (cmd.hasOption("dt")) {
+ builder.date(cmd.getOptionValue("dt"));
+ }
+
+ if (cmd.hasOption("sdt")) {
+ builder.snapshotDate(cmd.getOptionValue("sdt"));
+ }
+
+ if (cmd.hasOption("c1")) {
+ builder.categoryId(cmd.getOptionValue("c1"));
+ }
+
+ if (cmd.hasOption("mkt")) {
+ builder.siteId(cmd.getOptionValue("mkt"));
+ }
+
+ if (cmd.hasOption("scope")) {
+ builder.feedScope(cmd.getOptionValue("scope"));
+ }
+
+ if (cmd.hasOption("token")) {
+ builder.token("Bearer " + cmd.getOptionValue("token"));
+ }
+
+ if (cmd.hasOption("env")) {
+ builder.env(cmd.getOptionValue("env"));
+ }
+
+ if (cmd.hasOption("type")) {
+ builder.type(cmd.getOptionValue("type"));
+ } else {
+ // Hardcoded item for backword compatibilty
+ builder.type("item");
+ }
+ FeedRequest feedRequest = builder.build();
+
+ // populate filter request if available
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+
+ // populate auth request if available
+ String credentialFile = null;
+ String optionalDownloadPath = null;
+ List scopes = null;
+
+ LOGGER.info(cmd.getOptionValue("lf"));
+ if (cmd.hasOption("lf")) {
+ filterRequest
+ .setLeafCategoryIds(new HashSet(Arrays.asList(cmd.getOptionValues("lf"))));
+ }
+
+ if (cmd.hasOption("c3f")) {
+ filterRequest.setLevelThreeCategories(new HashSet(Arrays.asList(cmd
+ .getOptionValues("c3f"))));
+ }
+
+ if (cmd.hasOption("c2f")) {
+ filterRequest.setLevelTwoCategories(new HashSet(Arrays.asList(cmd
+ .getOptionValues("c3f"))));
+ }
+
+ if (cmd.hasOption("sellerf")) {
+ filterRequest.setSellerNames(new HashSet(
+ Arrays.asList(cmd.getOptionValues("sellerf"))));
+ }
+
+ if (cmd.hasOption("locf")) {
+ filterRequest.setItemLocationCountries(new HashSet(Arrays.asList(cmd
+ .getOptionValues("locf"))));
+ }
+
+ if (cmd.hasOption("pricelf")) {
+ filterRequest.setPriceLowerLimit(Double.valueOf(cmd.getOptionValue("pricelf")));
+ }
+
+ if (cmd.hasOption("priceuf")) {
+ filterRequest.setPriceUpperLimit(Double.valueOf(cmd.getOptionValue("priceuf")));
+ }
+
+ if (cmd.hasOption("epidf")) {
+ filterRequest.setEpids(new HashSet(Arrays.asList(cmd.getOptionValues("epidf"))));
+ }
+
+ if (cmd.hasOption("iepidf")) {
+ filterRequest.setInferredEpids(new HashSet(Arrays.asList(cmd
+ .getOptionValues("iepidf"))));
+ }
+
+ if (cmd.hasOption("gtinf")) {
+ filterRequest.setGtins(new HashSet(Arrays.asList(cmd.getOptionValues("gtinf"))));
+ }
+
+ if (cmd.hasOption("itemf")) {
+ filterRequest.setItemIds(new HashSet(Arrays.asList(cmd.getOptionValues("itemf"))));
+ }
+
+ if (cmd.hasOption("c1")) {
+ filterRequest.setLevelOneCategory(cmd.getOptionValue("c1"));
+ }
+
+ if (cmd.hasOption("token")) {
+ filterRequest.setToken("Bearer " + cmd.getOptionValue("token"));
+ }
+
+ if (cmd.hasOption("mkt")) {
+ filterRequest.setMarketplace(cmd.getOptionValue("mkt"));
+ }
+
+ if (cmd.hasOption("type")) {
+ filterRequest.setType(cmd.getOptionValue("type"));
+ }
+
+ if (cmd.hasOption("cl")) {
+ credentialFile = cmd.getOptionValue("cl");
+ }
+
+ if (cmd.hasOption("dl")) {
+ optionalDownloadPath = cmd.getOptionValue("dl");
+ }
+
+ if (cmd.hasOption("authscopes")) {
+ scopes = new ArrayList(Arrays.asList(cmd.getOptionValues("authscopes")));
+ }
+
+ if (cmd.hasOption("help")) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setOptionComparator(null);
+ formatter.printHelp("Feed SDK CLI", options);
+ } else if (cmd.getOptions().length > 0) {
+
+ // create auth request
+ AuthRequest authRequest = new AuthRequest(credentialFile, scopes);
+
+ // start processing
+ start(feedRequest, filterRequest, authRequest, optionalDownloadPath);
+ }
+ }
/**
- * Overrides for file locations
+ *
+ * Begin the process of downloading and filtering feed based on the input
+ * parameters
+ *
+ *
+ * @param feedRequest
+ * @param filterRequest
+ * @throws Exception
*/
+ private static void start(FeedRequest feedRequest, FeedFilterRequest filterRequest,
+ AuthRequest authRequest, String optionalDownloadPath) throws Exception {
- // file location
- options.addOption("dl", "downloadlocation", true,
- "override for changing the directory where files are downloaded");
-
- // oauth related
- options.addOption("cl", "credentiallocation", true,
- "directory where the credentials file is located");
-
- options.addOption("authscopes", "oauthscopes", true, "list of scopes");
-
- // ***Parsing Stage***
- // Create a parser
- CommandLineParser parser = new DefaultParser();
+ Feed feed = new FeedImpl();
- // parse the options passed as command line arguments
- CommandLine cmd = parser.parse(options, args);
+ // if token is null, then retrieve from oauth lib and set in request
+ if (feedRequest.getToken() == null) {
+ CredentialLoader credentialLoader = new CredentialLoader(authRequest);
+ credentialLoader.loadCredentials();
+ feedRequest.setToken(credentialLoader.getOauthResponse().getAccessToken().get().getToken());
+ filterRequest.setToken(credentialLoader.getOauthResponse().getAccessToken().get().getToken());
+ }
- // ***Interrogation Stage***
- // hasOptions checks if option is present or not
+ // download feed
+ GetFeedResponse getFeedResponse = feed.get(feedRequest, optionalDownloadPath);
- // populate feed request
- FeedRequestBuilder builder = new FeedRequestBuilder();
+ if (getFeedResponse.getStatusCode() != 0) {
+ return;
+ }
- if (cmd.hasOption("dt"))
- builder.date(cmd.getOptionValue("dt"));
+ // unzip
+ Response unzipResponse = feed.unzip(getFeedResponse.getFilePath());
- if (cmd.hasOption("c1"))
- builder.categoryId(cmd.getOptionValue("c1"));
+ if (unzipResponse.getStatusCode() != 0) {
+ return;
+ }
- if (cmd.hasOption("mkt"))
- builder.siteId(cmd.getOptionValue("mkt"));
-
- if (cmd.hasOption("scope"))
- builder.feedScope(cmd.getOptionValue("scope"));
-
- if (cmd.hasOption("token"))
- builder.token("Bearer " + cmd.getOptionValue("token"));
-
- if (cmd.hasOption("env")){
- builder.env(cmd.getOptionValue("env"));
+ // filter
+ filterRequest.setInputFilePath(unzipResponse.getFilePath());
+ Response filterResponse = feed.filter(filterRequest);
+ LOGGER.info("Filter response = " + filterResponse.toString());
}
-
- // TODO : Hardcoded item
- builder.type(FeedTypeEnum.ITEM);
- FeedRequest feedRequest = builder.build();
-
- // populate filter request if available
- FeedFilterRequest filterRequest = new FeedFilterRequest();
-
- // populate auth request if available
- String credentialFile = null;
- String optionalDownloadPath = null;
- List scopes = null;
-
- System.out.println(cmd.getOptionValue("lf"));
- if (cmd.hasOption("lf"))
- filterRequest
- .setLeafCategoryIds(new HashSet(Arrays.asList(cmd.getOptionValues("lf"))));
-
- if (cmd.hasOption("c3f"))
- filterRequest.setLevelThreeCategories(new HashSet(Arrays.asList(cmd
- .getOptionValues("c3f"))));
-
- if (cmd.hasOption("c2f"))
- filterRequest.setLevelTwoCategories(new HashSet(Arrays.asList(cmd
- .getOptionValues("c3f"))));
-
- if (cmd.hasOption("sellerf"))
- filterRequest.setSellerNames(new HashSet(
- Arrays.asList(cmd.getOptionValues("sellerf"))));
-
- if (cmd.hasOption("locf"))
- filterRequest.setItemLocationCountries(new HashSet(Arrays.asList(cmd
- .getOptionValues("locf"))));
-
- if (cmd.hasOption("pricelf"))
- filterRequest.setPriceLowerLimit(Double.valueOf(cmd.getOptionValue("pricelf")));
-
- if (cmd.hasOption("priceuf"))
- filterRequest.setPriceUpperLimit(Double.valueOf(cmd.getOptionValue("priceuf")));
-
- if (cmd.hasOption("epidf"))
- filterRequest.setEpids(new HashSet(Arrays.asList(cmd.getOptionValues("epidf"))));
-
- if (cmd.hasOption("iepidf"))
- filterRequest.setInferredEpids(new HashSet(Arrays.asList(cmd
- .getOptionValues("iepidf"))));
-
- if (cmd.hasOption("gtinf"))
- filterRequest.setGtins(new HashSet(Arrays.asList(cmd.getOptionValues("gtinf"))));
-
- if (cmd.hasOption("itemf"))
- filterRequest.setItemIds(new HashSet(Arrays.asList(cmd.getOptionValues("itemf"))));
-
- if (cmd.hasOption("c1"))
- filterRequest.setLevelOneCategory(cmd.getOptionValue("c1"));
-
- if (cmd.hasOption("token"))
- filterRequest.setToken("Bearer " + cmd.getOptionValue("token"));
-
- if (cmd.hasOption("mkt"))
- filterRequest.setMarketplace(cmd.getOptionValue("mkt"));
-
- if (cmd.hasOption("cl"))
- credentialFile = cmd.getOptionValue("cl");
-
- if (cmd.hasOption("dl"))
- optionalDownloadPath = cmd.getOptionValue("dl");
-
- if (cmd.hasOption("authscopes"))
- scopes = new ArrayList(Arrays.asList(cmd.getOptionValues("authscopes")));
-
- if (cmd.hasOption("help")) {
- HelpFormatter formatter = new HelpFormatter();
- formatter.setOptionComparator(null);
- formatter.printHelp("Feed SDK CLI", options);
- } else if (cmd.getOptions().length > 0) {
-
-
- // create auth request
- AuthRequest authRequest = new AuthRequest(credentialFile, scopes);
-
- // start processing
- start(feedRequest, filterRequest, authRequest, optionalDownloadPath);
- }
- }
-
- /**
- *
- * Begin the process of downloading and filtering feed based on the input parameters
- *
- *
- * @param feedRequest
- * @param filterRequest
- * @throws Exception
- */
- private static void start(FeedRequest feedRequest, FeedFilterRequest filterRequest,
- AuthRequest authRequest, String optionalDownloadPath) throws Exception {
-
- Feed feed = new FeedImpl();
-
- // if token is null, then retrieve from oauth lib and set in request
- if (feedRequest.getToken() == null) {
- CredentialLoader credentialLoader = new CredentialLoader(authRequest);
- credentialLoader.loadCredentials();
- feedRequest.setToken(credentialLoader.getOauthResponse().getAccessToken().get().getToken());
- filterRequest.setToken(credentialLoader.getOauthResponse().getAccessToken().get().getToken());
- }
-
- // download feed
- GetFeedResponse getFeedResponse = feed.get(feedRequest, optionalDownloadPath);
-
- if (getFeedResponse.getStatusCode() != 0)
- return;
-
- // unzip
- Response unzipResponse = feed.unzip(getFeedResponse.getFilePath());
-
- if (unzipResponse.getStatusCode() != 0)
- return;
-
- // filter
- filterRequest.setInputFilePath(unzipResponse.getFilePath());
- Response filterResponse = feed.filter(filterRequest);
- System.out.println("Filter response = " + filterResponse.toString());
- }
}
diff --git a/src/main/java/com/ebay/feed/constants/Constants.java b/src/main/java/com/ebay/feed/constants/Constants.java
index 126fb28..430d211 100755
--- a/src/main/java/com/ebay/feed/constants/Constants.java
+++ b/src/main/java/com/ebay/feed/constants/Constants.java
@@ -11,60 +11,69 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.constants;
public class Constants {
- /**
- * Base path for the feed api
- */
- public static final String FEED_API_PROD_BASE = "https://api.ebay.com/buy/feed/v1_beta/";
-
- public static final String FEED_API_SANDBOX_BASE = "https://api.sandbox.ebay.com/buy/feed/v1_beta/";
-
- // max content that can be downloaded in one request, in bytes
- public static final Long PROD_CHUNK_SIZE = 104857600L;
- public static final Long SANDBOX_CHUNK_SIZE = 10485760L;
-
- // timeout for http client
- public static final Integer TIMEOUT = 30;
+ /**
+ * Base path for the feed api
+ */
+ public static final String FEED_API_PROD_BASE = "https://api.ebay.com/buy/feed/v1_beta/";
+
+ public static final String FEED_API_SANDBOX_BASE = "https://api.sandbox.ebay.com/buy/feed/v1_beta/";
+
+ // max content that can be downloaded in one request, in bytes
+ public static final Long PROD_CHUNK_SIZE = 104857600L;
+ public static final Long SANDBOX_CHUNK_SIZE = 10485760L;
+
+ // timeout for http client
+ public static final Integer TIMEOUT = 30;
+
+ // api related constants
+ public static final String AUTHORIZATION_HEADER = "Authorization";
+
+ // taxonomy
+ public static final String TAXONOMY_DEFAULT
+ = "https://api.ebay.com/commerce/taxonomy/v1_beta/get_default_category_tree_id?marketplace_id=";
+
+ public static final String TAXONOMY_CATEGORY_SUBTREE_BASE = "https://api.ebay.com/commerce/taxonomy/v1_beta/category_tree/";
+ public static final String TAXONOMY_CATEGORY_SUBTREE_QUERY = "/get_category_subtree?category_id=";
+
+ // status and util related constants
+ public static final String SUCCESS = "Success";
+ public static final Integer SUCCESS_CODE = 0;
+ public static final String FAILURE = "Failure";
+ public static final Integer FAILURE_CODE = -1;
+ public static final String RANGE_PREFIX = "bytes=0-";
+ public static final String RANGE_HEADER = "Range";
+ public static final String CONTENT_RANGE_HEADER = "Content-Range";
+ public static final String LAST_MODIFIED_DATE_HEADER = "Last-Modified";
+ public static final String TOKEN_BEARER_PREFIX = "Bearer ";
+ public static final String TRUE = "true";
+ public static final String FALSE = "false";
+ public static final String ITEM_RESOURCE_SCOPE = "item?feed_scope=";
+ public static final String ITEM_SNAPSHOT_RESOURCE = "item_snapshot?";
+ public static final String QUERY_PARAM_SEPARATOR = "&";
+ public static final String QUERY_CATEGORY_ID = "category_id=";
+ public static final String QUERY_DATE = "date=";
+ public static final String QUERY_SNAPSHOT_DATE = "snapshot_date=";
+ public static final String QUERY_DATE_FORMAT = "yyyyMMdd";
+ public static final String QUERY_SNAPSHOT_DATE_FORMAT = "yyyy-MM-dd'T'HH:00:00.000'Z'";
+ public static final String MARKETPLACE_HEADER = "X-EBAY-C-MARKETPLACE-ID";
+ public static final String CONTENT_TYPE_HEADER = "Content-type";
+ public static final String ACCEPT_HEADER = "Accept";
+
+ public static final String ALL_ACTIVE = "ALL_ACTIVE";
+ public static final String NEWLY_LISTED = "NEWLY_LISTED";
+ public static final Integer NEWLY_LISTED_AVAILABILITY_START_DAY = -14;
+ public static final Integer NEWLY_LISTED_AVAILABILITY_END_DAY = -2;
+
+ public static final Integer ITEM_SNAPSHOT_AVAILABILITY_START_DAY = -7;
+ public static final Integer ITEM_SNAPSHOT_AVAILABILITY_END_HOUR = -2;
- // api related constants
- public static final String AUTHORIZATION_HEADER = "Authorization";
-
- // taxonomy
- public static final String TAXONOMY_DEFAULT =
- "https://api.ebay.com/commerce/taxonomy/v1_beta/get_default_category_tree_id?marketplace_id=";
-
- public static final String TAXONOMY_CATEGORY_SUBTREE_BASE = "https://api.ebay.com/commerce/taxonomy/v1_beta/category_tree/";
- public static final String TAXONOMY_CATEGORY_SUBTREE_QUERY = "/get_category_subtree?category_id=";
-
- // status and util related constants
- public static final String SUCCESS = "Success";
- public static final Integer SUCCESS_CODE = 0;
- public static final String FAILURE = "Failure";
- public static final Integer FAILURE_CODE = -1;
- public static final String RANGE_PREFIX = "bytes=0-";
- public static final String RANGE_HEADER = "Range";
- public static final String CONTENT_RANGE_HEADER = "Content-Range";
- public static final String LAST_MODIFIED_DATE_HEADER = "Last-Modified";
- public static final String TOKEN_BEARER_PREFIX = "Bearer ";
- public static final String TRUE = "true";
- public static final String FALSE = "false";
- public static final String ITEM_RESOURCE_SCOPE = "item?feed_scope=";
- public static final String QUERY_PARAM_SEPARATOR = "&";
- public static final String QUERY_CATEGORY_ID = "category_id=";
- public static final String QUERY_DATE = "date=";
- public static final String MARKETPLACE_HEADER = "X-EBAY-C-MARKETPLACE-ID";
- public static final String CONTENT_TYPE_HEADER = "Content-type";
- public static final String ACCEPT_HEADER = "Accept";
+ public static final String BOOTSTRAP = "bootstrap";
+ public static final String DAILY = "daily";
+ public static final String SEPARATOR = "\\t";
+ public static final String ITEM_ID = "ItemId";
- public static final String ALL_ACTIVE = "ALL_ACTIVE";
-
- public static final String BOOTSTRAP = "bootstrap";
- public static final String DAILY = "daily";
- public static final String SEPARATOR = "\\t";
- public static final String ITEM_ID = "ItemId";
-
}
diff --git a/src/main/java/com/ebay/feed/enums/FeedTypeEnum.java b/src/main/java/com/ebay/feed/enums/FeedTypeEnum.java
index b37ff03..aac0cba 100644
--- a/src/main/java/com/ebay/feed/enums/FeedTypeEnum.java
+++ b/src/main/java/com/ebay/feed/enums/FeedTypeEnum.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.enums;
/**
@@ -23,5 +22,14 @@
*/
public enum FeedTypeEnum {
- ITEM
+ ITEM, ITEM_SNAPSHOT;
+
+ public static FeedTypeEnum getFeedEnum(String name) {
+ for (FeedTypeEnum feedEnum : FeedTypeEnum.values()) {
+ if (feedEnum.name().equalsIgnoreCase(name)) {
+ return feedEnum;
+ }
+ }
+ return null;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/CombiningFilters.java b/src/main/java/com/ebay/feed/example/CombiningFilters.java
index 385a904..cf2dc66 100644
--- a/src/main/java/com/ebay/feed/example/CombiningFilters.java
+++ b/src/main/java/com/ebay/feed/example/CombiningFilters.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,19 +18,21 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on a combination of filter criteria
- * The download location is default - current working directory
- * This example downloads the bootstrap feed file for L1 category : 1 (Collectibles) and filters on
- * :-
+ * Example showing how to download and filter feed files based on a combination
+ * of filter criteria The download location is default - current working
+ * directory
+ * This example downloads the bootstrap feed file for L1 category : 1
+ * (Collectibles) and filters on :-
* - leaf categories
* - price
* - item location
@@ -41,93 +42,95 @@
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class CombiningFilters {
- // oauth token with Bearer prefix
- static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#I^3....";
-
- // init feed
- static Feed feed = new FeedImpl();
-
- private static final String CATEGORY = "1";
-
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180805";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
-
- public static void main(String[] args) {
-
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
- .type(FeedTypeEnum.ITEM);
-
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
-
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(CombiningFilters.class);
+
+ // oauth token with Bearer prefix
+ static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#I^3....";
+
+ // init feed
+ static Feed feed = new FeedImpl();
+
+ private static final String CATEGORY = "1";
+
+ private static final String DATE = "20180805";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
+
+ public static void main(String[] args) {
+
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE);
+
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+
+ // filter for leaf category ids
+ filterRequest.setLeafCategoryIds(getLeafCategorySet());
+
+ // filter for price
+ filterRequest.setPriceLowerLimit(10.0);
+ filterRequest.setPriceUpperLimit(50.0);
+
+ // filter for item location
+ filterRequest.setItemLocationCountries(getItemLocationSet());
+
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
-
- // filter for leaf category ids
- filterRequest.setLeafCategoryIds(getLeafCategorySet());
-
- // filter for price
- filterRequest.setPriceLowerLimit(10.0);
- filterRequest.setPriceUpperLimit(50.0);
-
- // filter for item location
- filterRequest.setItemLocationCountries(getItemLocationSet());
-
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
-
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
-
- /**
- * Get the set of leaf category ids to filter on
- *
- * @return
- */
- private static Set getLeafCategorySet() {
- Set leafCategorySet = new HashSet<>();
- leafCategorySet.add("11675");
- leafCategorySet.add("3226");
- return leafCategorySet;
- }
-
- /**
- * Get the set of item locations to filter on
- *
- * @return
- */
- private static Set getItemLocationSet() {
- Set itemLocationSet = new HashSet<>();
- itemLocationSet.add("CN");
- return itemLocationSet;
- }
+ /**
+ * Get the set of leaf category ids to filter on
+ *
+ * @return
+ */
+ private static Set getLeafCategorySet() {
+ Set leafCategorySet = new HashSet<>();
+ leafCategorySet.add("11675");
+ leafCategorySet.add("3226");
+ return leafCategorySet;
+ }
+
+ /**
+ * Get the set of item locations to filter on
+ *
+ * @return
+ */
+ private static Set getItemLocationSet() {
+ Set itemLocationSet = new HashSet<>();
+ itemLocationSet.add("CN");
+ return itemLocationSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/ConfigFileBasedExample.java b/src/main/java/com/ebay/feed/example/ConfigFileBasedExample.java
index e22f08f..9ae5098 100644
--- a/src/main/java/com/ebay/feed/example/ConfigFileBasedExample.java
+++ b/src/main/java/com/ebay/feed/example/ConfigFileBasedExample.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.List;
@@ -20,33 +19,37 @@
import com.ebay.feed.auth.CredentialLoader;
import com.ebay.feed.model.feed.operation.filter.Response;
import com.ebay.feed.model.oauth.AuthRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConfigFileBasedExample {
- // credentials file absolute path
- static String credentialFilePath = "credentials.yaml";
-
- // init feed
- static Feed feed = new FeedImpl();
-
- public static void main(String[] args) throws Exception {
-
- // null scopes result in default values being used
- AuthRequest authRequest = new AuthRequest(credentialFilePath, null);
-
- // load credentials and generate token
- CredentialLoader credentialLoader = new CredentialLoader(authRequest);
- credentialLoader.loadCredentials();
- String token = credentialLoader.getOauthResponse().getAccessToken().get().getToken();
-
- // expects path to the config file. The config file should be a json with the
- // structure mirroring the pojo ConfigFileBasedRequest.java
- String configFilePath = "sample-config/config-file-download-unzip-filter";
- List responses = feed.processConfigFile(configFilePath, token);
-
- for (Response response : responses) {
- System.out.println(response.toString());
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFileBasedExample.class);
+
+ // credentials file absolute path
+ static String credentialFilePath = "credentials.yaml";
+
+ // init feed
+ static Feed feed = new FeedImpl();
+
+ public static void main(String[] args) throws Exception {
+
+ // null scopes result in default values being used
+ AuthRequest authRequest = new AuthRequest(credentialFilePath, null);
+
+ // load credentials and generate token
+ CredentialLoader credentialLoader = new CredentialLoader(authRequest);
+ credentialLoader.loadCredentials();
+ String token = credentialLoader.getOauthResponse().getAccessToken().get().getToken();
+
+ // expects path to the config file. The config file should be a json with the
+ // structure mirroring the pojo ConfigFileBasedRequest.java
+ String configFilePath = "sample-config/config-file-download-unzip-filter";
+ List responses = feed.processConfigFile(configFilePath, token);
+
+ for (Response response : responses) {
+ LOGGER.info(response.toString());
+ }
}
- }
}
diff --git a/src/main/java/com/ebay/feed/example/FeedTypeItemSnapShot.java b/src/main/java/com/ebay/feed/example/FeedTypeItemSnapShot.java
new file mode 100644
index 0000000..65c13f2
--- /dev/null
+++ b/src/main/java/com/ebay/feed/example/FeedTypeItemSnapShot.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2018 eBay Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.ebay.feed.example;
+
+import java.util.HashSet;
+import java.util.Set;
+import com.ebay.feed.api.Feed;
+import com.ebay.feed.api.FeedImpl;
+import com.ebay.feed.constants.Constants;
+import com.ebay.feed.enums.EnvTypeEnum;
+import com.ebay.feed.model.feed.download.GetFeedResponse;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
+import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
+import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * Example showing how to download and filter item_snapshot feed files based on
+ * itemIds. The download location is default - current working directory
+ * This example downloads the item_snapshot feed file for L1 category : 1
+ * (Collectibles) and filters on itemIds.
+ * The filtering is performed on the unzipped file.
+ * So the sequence of events that are followed is :-
+ * - Download feed file
+ * - Unzip feed file
+ * - Filter feed file
+ *
+ *
+ *
+ */
+public class FeedTypeItemSnapShot {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(FeedTypeItemSnapShot.class);
+
+ // oauth token - Bearer xxx
+ static String token
+ = Constants.TOKEN_BEARER_PREFIX
+ + "v^1.1#i^1#f...";
+
+ // init feed
+ static Feed feed = new FeedImpl();
+
+ private static final String CATEGORY = "625";
+ private static final String SNAPSHOT_DATE = "2021-01-29T02:00:00.000Z";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item_snapshot";
+
+ public static void main(String[] args) {
+
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+
+ builder.categoryId(CATEGORY).snapshotDate(SNAPSHOT_DATE).siteId(MKT).token(token)
+ .type(FEEDTYPE).env(EnvTypeEnum.SANDBOX.name());
+
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ // set price lower and upper limit
+ filterRequest.setPriceLowerLimit(10.0);
+ // filter for item type
+ filterRequest.setType(FEEDTYPE);
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
+
+ }
+
+ /**
+ * Get the set of seller user names to filter on
+ *
+ * @return
+ */
+ private static Set getItemIds() {
+ Set itemIdSet = new HashSet<>();
+ itemIdSet.add("132029430107");
+ itemIdSet.add("132676918161");
+ itemIdSet.add("14270967132");
+ return itemIdSet;
+ }
+
+}
diff --git a/src/main/java/com/ebay/feed/example/FilterByEnv.java b/src/main/java/com/ebay/feed/example/FilterByEnv.java
index b112730..b5115ef 100644
--- a/src/main/java/com/ebay/feed/example/FilterByEnv.java
+++ b/src/main/java/com/ebay/feed/example/FilterByEnv.java
@@ -11,86 +11,88 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
import com.ebay.feed.enums.EnvTypeEnum;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on environment. The download location
- * is default - current working directory
+ * Example showing how to download and filter feed files based on environment.
+ * The download location is default - current working directory
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByEnv {
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByEnv.class);
- // oauth token
- static String TOKEN = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#p^1#r^0#I...";
+ // oauth token
+ static String TOKEN = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#p^1#r^0#I...";
- // init feed
- static Feed feed = new FeedImpl();
+ // init feed
+ static Feed feed = new FeedImpl();
- private static final String CATEGORY = "15032";
+ private static final String CATEGORY = "15032";
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20181005";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
-
- public static void main(String[] args) {
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20181005";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
- .type(FeedTypeEnum.ITEM).env(EnvTypeEnum.SANDBOX.name());
+ public static void main(String[] args) {
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
+ .type(FEEDTYPE).env(EnvTypeEnum.SANDBOX.name());
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+
+ // set price lower and upper lomit
+ filterRequest.setPriceLowerLimit(10.0);
+ filterRequest.setPriceLowerLimit(20.0);
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
-
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
-
- // set price lower and upper lomit
- filterRequest.setPriceLowerLimit(10.0);
- filterRequest.setPriceLowerLimit(20.0);
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByEpids.java b/src/main/java/com/ebay/feed/example/FilterByEpids.java
index 6a9ceb8..d2ca812 100644
--- a/src/main/java/com/ebay/feed/example/FilterByEpids.java
+++ b/src/main/java/com/ebay/feed/example/FilterByEpids.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,88 +18,92 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on seller user names. The download
- * location is default - current working directory
- * This example downloads the bootstrap feed file for L1 category : 1 (Collectibles) and filters on
- * seller user names.
+ * Example showing how to download and filter feed files based on seller user
+ * names. The download location is default - current working directory
+ * This example downloads the bootstrap feed file for L1 category : 1
+ * (Collectibles) and filters on seller user names.
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByEpids {
- // oauth token
- static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^...";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByEpids.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // oauth token
+ static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^...";
- private static final String CATEGORY = "1281";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180805";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
+ private static final String CATEGORY = "1281";
- public static void main(String[] args) {
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20180805";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT)
- .token(token).type(FeedTypeEnum.ITEM);
+ public static void main(String[] args) {
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT)
+ .token(token).type(FEEDTYPE);
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setEpids(getEpids());
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setEpids(getEpids());
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
-
- /**
- * Get the set of seller user names to filter on
- *
- * @return
- */
- private static Set getEpids() {
- Set epidSet = new HashSet<>();
- epidSet.add("710154699");
- return epidSet;
- }
+ /**
+ * Get the set of seller user names to filter on
+ *
+ * @return
+ */
+ private static Set getEpids() {
+ Set epidSet = new HashSet<>();
+ epidSet.add("710154699");
+ return epidSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByGtins.java b/src/main/java/com/ebay/feed/example/FilterByGtins.java
index 24df20d..b9e90fa 100644
--- a/src/main/java/com/ebay/feed/example/FilterByGtins.java
+++ b/src/main/java/com/ebay/feed/example/FilterByGtins.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -21,50 +20,54 @@
import com.ebay.feed.constants.Constants;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Simple example of applying a filter on an already downlaoded file
+ * Simple example of applying a filter on an already downlaoded file
*
* The filtering is performed on the unzipped file.
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByGtins {
- // oauth token
- static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#...";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByGtins.class);
+
+ // oauth token
+ static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#...";
+
+ // init feed
+ static Feed feed = new FeedImpl();
- // init feed
- static Feed feed = new FeedImpl();
-
- public static void main(String[] args) {
+ public static void main(String[] args) {
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setGtins(getGtins());
- // set input file
- // absolute path to the unzipped file
- filterRequest
- .setInputFilePath("item_bootstrap-1281-20180708-EBAY_US");
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setGtins(getGtins());
+ // set input file
+ // absolute path to the unzipped file
+ filterRequest
+ .setInputFilePath("item_bootstrap-1281-20180708-EBAY_US");
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- }
+ }
- /**
- * Get the set of seller user names to filter on
- *
- * @return
- */
- private static Set getGtins() {
- Set gtinSet = new HashSet<>();
- gtinSet.add("647369501375");
- return gtinSet;
- }
+ /**
+ * Get the set of seller user names to filter on
+ *
+ * @return
+ */
+ private static Set getGtins() {
+ Set gtinSet = new HashSet<>();
+ gtinSet.add("647369501375");
+ return gtinSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByItemIds.java b/src/main/java/com/ebay/feed/example/FilterByItemIds.java
index 2252e6c..76b5e8e 100644
--- a/src/main/java/com/ebay/feed/example/FilterByItemIds.java
+++ b/src/main/java/com/ebay/feed/example/FilterByItemIds.java
@@ -19,12 +19,13 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
@@ -43,6 +44,9 @@
*
*/
public class FilterByItemIds {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByItemIds.class);
+
// oauth token - Bearer xxx
static String token =
@@ -54,31 +58,31 @@ public class FilterByItemIds {
private static final String CATEGORY = "1281";
- // TODO : Check if the date is within 14 days, before making the call
private static final String DATE = "20180805";
private static final String SCOPE = "ALL_ACTIVE";
private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
public static void main(String[] args) {
// create request
FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
- .type(FeedTypeEnum.ITEM);
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE);
// using null for download directory - defaults to current working directory
GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
// 0 denotes successful response
if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
return;
}
// unzip
Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
return;
}
@@ -89,8 +93,8 @@ public static void main(String[] args) {
filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByItemLocation.java b/src/main/java/com/ebay/feed/example/FilterByItemLocation.java
index 60f65b1..f46879b 100644
--- a/src/main/java/com/ebay/feed/example/FilterByItemLocation.java
+++ b/src/main/java/com/ebay/feed/example/FilterByItemLocation.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,90 +18,93 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on item location. The download
- * location is default - current working directory
+ * Example showing how to download and filter feed files based on item location.
+ * The download location is default - current working directory
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByItemLocation {
- // oauth token - Bearer xxx
- static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#p^1#..";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByItemLocation.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // oauth token - Bearer xxx
+ static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#p^1#..";
- private static final String CATEGORY = "11116";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180708";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
-
- public static void main(String[] args) {
+ private static final String CATEGORY = "11116";
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
- .type(FeedTypeEnum.ITEM);
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20180708";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ public static void main(String[] args) {
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE);
+
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setToken(token);
+ filterRequest.setItemLocationCountries(getItemLocationSet());
+
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setToken(token);
- filterRequest.setItemLocationCountries(getItemLocationSet());
-
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
-
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
-
- }
-
- /**
- * Get the set of item locations to filter on
- *
- * @return
- */
- private static Set getItemLocationSet() {
- Set itemLocationSet = new HashSet<>();
- itemLocationSet.add("CN");
- return itemLocationSet;
- }
+ /**
+ * Get the set of item locations to filter on
+ *
+ * @return
+ */
+ private static Set getItemLocationSet() {
+ Set itemLocationSet = new HashSet<>();
+ itemLocationSet.add("CN");
+ return itemLocationSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByLeafCategories.java b/src/main/java/com/ebay/feed/example/FilterByLeafCategories.java
index 7fae317..b1cd7c0 100644
--- a/src/main/java/com/ebay/feed/example/FilterByLeafCategories.java
+++ b/src/main/java/com/ebay/feed/example/FilterByLeafCategories.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,88 +18,91 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on leaf category ids. The download
- * location is default - current working directory
+ * Example showing how to download and filter feed files based on leaf category
+ * ids. The download location is default - current working directory
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByLeafCategories {
- // oauth token
- static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#I^3...";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByLeafCategories.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // oauth token
+ static String token = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#f^0#I^3...";
- private static final String CATEGORY = "1281";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180805";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
+ private static final String CATEGORY = "1281";
- public static void main(String[] args) {
+ private static final String DATE = "20180805";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
- .type(FeedTypeEnum.ITEM);
+ public static void main(String[] args) {
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE);
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setLeafCategoryIds(getLeafCategorySet());
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setLeafCategoryIds(getLeafCategorySet());
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
-
- /**
- * Get the set of leaf category ids to filter on
- *
- * @return
- */
- private static Set getLeafCategorySet() {
- Set leafCategorySet = new HashSet<>();
- leafCategorySet.add("146242");
- leafCategorySet.add("134792");
- leafCategorySet.add("117432");
- return leafCategorySet;
- }
+ /**
+ * Get the set of leaf category ids to filter on
+ *
+ * @return
+ */
+ private static Set getLeafCategorySet() {
+ Set leafCategorySet = new HashSet<>();
+ leafCategorySet.add("146242");
+ leafCategorySet.add("134792");
+ leafCategorySet.add("117432");
+ return leafCategorySet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByLevelThreeCategory.java b/src/main/java/com/ebay/feed/example/FilterByLevelThreeCategory.java
index f3a6d7b..b5817b5 100644
--- a/src/main/java/com/ebay/feed/example/FilterByLevelThreeCategory.java
+++ b/src/main/java/com/ebay/feed/example/FilterByLevelThreeCategory.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -21,115 +20,120 @@
import com.ebay.feed.api.Taxonomy;
import com.ebay.feed.api.TaxonomyImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on L3 category ids. The download
- * location is default - current working directory
- *
- * To filter on L3 category, the mapping between L3 to leaf category ids needs to be loaded. Once
- * the mapping is loaded, the operation translates to actually filtering the feed files on leaf
- * category ids, which belong to the L3 category id.
- *
+ * Example showing how to download and filter feed files based on L3 category
+ * ids. The download location is default - current working directory
+ *
+ * To filter on L3 category, the mapping between L3 to leaf category ids needs
+ * to be loaded. Once the mapping is loaded, the operation translates to
+ * actually filtering the feed files on leaf category ids, which belong to the
+ * L3 category id.
+ *
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByLevelThreeCategory {
- // oauth token : Bearer xxx
- /**
- * For filtering on level two or level three categories, the token scope should include
- * feed_scope and api_scope.
- *
- * Filtering on level two and level three categories requires an additional call
- * to taxonomy api
- */
- static String TOKEN =
- Constants.TOKEN_BEARER_PREFIX
- + "v^1.1#i^1#r^0#I^3...";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByLevelThreeCategory.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // oauth token : Bearer xxx
+ /**
+ * For filtering on level two or level three categories, the token scope
+ * should include feed_scope and api_scope.
+ *
+ * Filtering on level two and level three categories requires an additional
+ * call to taxonomy api
+ */
+ static String TOKEN
+ = Constants.TOKEN_BEARER_PREFIX
+ + "v^1.1#i^1#r^0#I^3...";
- private static final String CATEGORY = "1";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180708";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
+ private static final String CATEGORY = "1";
- // init taxonomy
- static Taxonomy taxonomy = new TaxonomyImpl();
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20180708";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- public static void main(String[] args) {
+ // init taxonomy
+ static Taxonomy taxonomy = new TaxonomyImpl();
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
- .type(FeedTypeEnum.ITEM);
+ public static void main(String[] args) {
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
+ .type(FEEDTYPE);
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
- }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
- // set input file
- filterRequest.setToken(TOKEN);
- filterRequest.setMarketplace(MKT);
+ // set input file
+ filterRequest.setToken(TOKEN);
+ filterRequest.setMarketplace(MKT);
- // level three
- filterRequest.setLevelThreeCategories(getLevelThreeCats());
+ // level three
+ filterRequest.setLevelThreeCategories(getLevelThreeCats());
- // level two
- filterRequest.setLevelTwoCategories(getLevelTwoCats());
- filterRequest.setLevelOneCategory(CATEGORY);
+ // level two
+ filterRequest.setLevelTwoCategories(getLevelTwoCats());
+ filterRequest.setLevelOneCategory(CATEGORY);
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
- Response response = feed.filter(filterRequest);
+ Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- }
+ }
- static Set getLevelThreeCats() {
- Set levelThreeSet = new HashSet<>();
- levelThreeSet.add("1313");
- levelThreeSet.add("13583");
- return levelThreeSet;
- }
+ static Set getLevelThreeCats() {
+ Set levelThreeSet = new HashSet<>();
+ levelThreeSet.add("1313");
+ levelThreeSet.add("13583");
+ return levelThreeSet;
+ }
- static Set getLevelTwoCats() {
- Set levelThreeSet = new HashSet<>();
- levelThreeSet.add("34");
- return levelThreeSet;
- }
+ static Set getLevelTwoCats() {
+ Set levelThreeSet = new HashSet<>();
+ levelThreeSet.add("34");
+ return levelThreeSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterByPrice.java b/src/main/java/com/ebay/feed/example/FilterByPrice.java
index 3127daf..011e629 100644
--- a/src/main/java/com/ebay/feed/example/FilterByPrice.java
+++ b/src/main/java/com/ebay/feed/example/FilterByPrice.java
@@ -11,85 +11,87 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on item price. The download location
- * is default - current working directory
+ * Example showing how to download and filter feed files based on item price.
+ * The download location is default - current working directory
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterByPrice {
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterByPrice.class);
- // oauth token
- static String TOKEN = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#r^0#I^3...";
+ // oauth token
+ static String TOKEN = Constants.TOKEN_BEARER_PREFIX + "v^1.1#i^1#r^0#I^3...";
- // init feed
- static Feed feed = new FeedImpl();
+ // init feed
+ static Feed feed = new FeedImpl();
- private static final String CATEGORY = "1281";
+ private static final String CATEGORY = "1281";
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180708";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
-
- public static void main(String[] args) {
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20180708";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
- .type(FeedTypeEnum.ITEM);
+ public static void main(String[] args) {
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
+ .type(FEEDTYPE);
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+
+ // set price lower and upper lomit
+ filterRequest.setPriceLowerLimit(10.0);
+ filterRequest.setPriceUpperLimit(20.0);
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
-
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
-
- // set price lower and upper lomit
- filterRequest.setPriceLowerLimit(10.0);
- filterRequest.setPriceLowerLimit(20.0);
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
}
diff --git a/src/main/java/com/ebay/feed/example/FilterBySellerUserNames.java b/src/main/java/com/ebay/feed/example/FilterBySellerUserNames.java
index 466f9a3..59ecfa1 100644
--- a/src/main/java/com/ebay/feed/example/FilterBySellerUserNames.java
+++ b/src/main/java/com/ebay/feed/example/FilterBySellerUserNames.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,92 +18,95 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on seller user names. The download
- * location is default - current working directory
- * This example downloads the bootstrap feed file for L1 category : 1 (Collectibles) and filters on
- * seller user names.
+ * Example showing how to download and filter feed files based on seller user
+ * names. The download location is default - current working directory
+ * This example downloads the bootstrap feed file for L1 category : 1
+ * (Collectibles) and filters on seller user names.
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class FilterBySellerUserNames {
- // oauth token
- static String TOKEN =
- Constants.TOKEN_BEARER_PREFIX
- + "v^1.1#i^1#r^0#I^3...";
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterBySellerUserNames.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // oauth token
+ static String TOKEN
+ = Constants.TOKEN_BEARER_PREFIX
+ + "v^1.1#i^1#r^0#I^3...";
- private static final String CATEGORY = "1281";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180708";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
+ private static final String CATEGORY = "1281";
+ // TODO : Check if the date is within 14 days, before making the call
+ private static final String DATE = "20180708";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- public static void main(String[] args) {
+ public static void main(String[] args) {
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
- .type(FeedTypeEnum.ITEM);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(TOKEN)
+ .type(FEEDTYPE);
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setSellerNames(getSellerNameSet());
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
}
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setSellerNames(getSellerNameSet());
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
-
- Response response = feed.filter(filterRequest);
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
-
- }
-
- /**
- * Get the set of seller user names to filter on
- *
- * @return
- */
- private static Set getSellerNameSet() {
- Set sellerNameSet = new HashSet<>();
- sellerNameSet.add("pro-sports1021");
- sellerNameSet.add("cbpetz");
- return sellerNameSet;
- }
+ /**
+ * Get the set of seller user names to filter on
+ *
+ * @return
+ */
+ private static Set getSellerNameSet() {
+ Set sellerNameSet = new HashSet<>();
+ sellerNameSet.add("pro-sports1021");
+ sellerNameSet.add("cbpetz");
+ return sellerNameSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/UsingCredentialFile.java b/src/main/java/com/ebay/feed/example/UsingCredentialFile.java
index a63d2e1..d3b030c 100644
--- a/src/main/java/com/ebay/feed/example/UsingCredentialFile.java
+++ b/src/main/java/com/ebay/feed/example/UsingCredentialFile.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.example;
import java.util.HashSet;
@@ -19,99 +18,101 @@
import com.ebay.feed.api.Feed;
import com.ebay.feed.api.FeedImpl;
import com.ebay.feed.auth.CredentialLoader;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.download.GetFeedResponse;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.filter.Response;
import com.ebay.feed.model.oauth.AuthRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
- * Example showing how to download and filter feed files based on item location. The download
- * location is default - current working directory
+ * Example showing how to download and filter feed files based on item location.
+ * The download location is default - current working directory
* The filtering is performed on the unzipped file.
* So the sequence of events that are followed is :-
* - Download feed file
* - Unzip feed file
* - Filter feed file
*
- *
+ *
* @author shanganesh
*
*/
public class UsingCredentialFile {
- // credentials file absolute path
- static String credentialFilePath = "sample-credentials/credentials.yaml";
+ private static final Logger LOGGER = LoggerFactory.getLogger(UsingCredentialFile.class);
- // init feed
- static Feed feed = new FeedImpl();
+ // credentials file absolute path
+ static String credentialFilePath = "sample-credentials/credentials.yaml";
- private static final String CATEGORY = "11116";
+ // init feed
+ static Feed feed = new FeedImpl();
- // TODO : Check if the date is within 14 days, before making the call
- private static final String DATE = "20180708";
- private static final String SCOPE = "ALL_ACTIVE";
- private static final String MKT = "EBAY_US";
+ private static final String CATEGORY = "11116";
- public static void main(String[] args) throws Exception {
+ private static final String DATE = "20180708";
+ private static final String SCOPE = "ALL_ACTIVE";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
- // null scopes result in default values being used
- AuthRequest authRequest = new AuthRequest(credentialFilePath, null);
+ public static void main(String[] args) throws Exception {
- // load credentials and generate token
- CredentialLoader credentialLoader = new CredentialLoader(authRequest);
- credentialLoader.loadCredentials();
- String token = credentialLoader.getOauthResponse().getAccessToken().get().getToken();
+ // null scopes result in default values being used
+ AuthRequest authRequest = new AuthRequest(credentialFilePath, null);
- // create request
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
- .type(FeedTypeEnum.ITEM);
+ // load credentials and generate token
+ CredentialLoader credentialLoader = new CredentialLoader(authRequest);
+ credentialLoader.loadCredentials();
+ String token = credentialLoader.getOauthResponse().getAccessToken().get().getToken();
- // using null for download directory - defaults to current working directory
- GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE);
- // 0 denotes successful response
- if (getFeedResponse.getStatusCode() != 0) {
- System.out.println("Exception in downloading feed. Cannot proceed");
- return;
- }
- // unzip
- Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
- if (unzipOpResponse.getStatusCode() != 0) {
- System.out.println("Exception in unzipping feed. Cannot proceed");
- return;
- }
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
- // filter
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setToken(token);
- filterRequest.setItemLocationCountries(getItemLocationSet());
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
- // set input file
- filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setToken(token);
+ filterRequest.setItemLocationCountries(getItemLocationSet());
- Response response = feed.filter(filterRequest);
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
- System.out.println("Filter status = " + response.getStatusCode());
- System.out.println("Filtered file = " + response.getFilePath());
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
- }
+ }
- /**
- * Get the set of item locations to filter on
- *
- * @return
- */
- private static Set getItemLocationSet() {
- Set itemLocationSet = new HashSet<>();
- itemLocationSet.add("CN");
- return itemLocationSet;
- }
+ /**
+ * Get the set of item locations to filter on
+ *
+ * @return
+ */
+ private static Set getItemLocationSet() {
+ Set itemLocationSet = new HashSet<>();
+ itemLocationSet.add("CN");
+ return itemLocationSet;
+ }
}
diff --git a/src/main/java/com/ebay/feed/example/UsingCredentialFileForSandBoxEnv.java b/src/main/java/com/ebay/feed/example/UsingCredentialFileForSandBoxEnv.java
new file mode 100644
index 0000000..974c4b6
--- /dev/null
+++ b/src/main/java/com/ebay/feed/example/UsingCredentialFileForSandBoxEnv.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2018 eBay Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.ebay.feed.example;
+
+import java.util.HashSet;
+import java.util.Set;
+import com.ebay.feed.api.Feed;
+import com.ebay.feed.api.FeedImpl;
+import com.ebay.feed.auth.CredentialLoader;
+import com.ebay.feed.enums.EnvTypeEnum;
+import com.ebay.feed.model.feed.download.GetFeedResponse;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
+import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
+import com.ebay.feed.model.feed.operation.filter.Response;
+import com.ebay.feed.model.oauth.AuthRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * Example showing how to download and filter feed files based on item location.
+ * The download location is default - current working directory
+ * The filtering is performed on the unzipped file.
+ * So the sequence of events that are followed is :-
+ * - Download feed file
+ * - Unzip feed file
+ * - Filter feed file
+ *
+ *
+ *
+ */
+public class UsingCredentialFileForSandBoxEnv {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(UsingCredentialFileForSandBoxEnv.class);
+
+ // credentials file absolute path
+ static String credentialFilePath = "credentials.yaml";
+
+ // init feed
+ static Feed feed = new FeedImpl();
+
+ // private static final String CATEGORY = "11116";
+ private static final String CATEGORY = "1";
+
+ private static final String DATE = "20210125";
+ private static final String SCOPE = "NEWLY_LISTED";
+ private static final String MKT = "EBAY_US";
+ private static final String FEEDTYPE = "item";
+
+ public static void main(String[] args) throws Exception {
+
+ // null scopes result in default values being used
+ AuthRequest authRequest = new AuthRequest(credentialFilePath, null);
+
+ // load credentials and generate token
+ CredentialLoader credentialLoader = new CredentialLoader(authRequest);
+ credentialLoader.loadCredentials();
+ String token = credentialLoader.getOauthResponse(EnvTypeEnum.SANDBOX.name()).getAccessToken().get().getToken();
+
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(FEEDTYPE).env(EnvTypeEnum.SANDBOX.name());
+
+ // using null for download directory - defaults to current working directory
+ // passing credentialFilePath as required for token refresh on the fly to support resume capability while downloading feed
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null, credentialFilePath);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setToken(token);
+ filterRequest.setItemLocationCountries(getItemLocationSet());
+
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
+
+ }
+
+ /**
+ * Get the set of item locations to filter on
+ *
+ * @return
+ */
+ private static Set getItemLocationSet() {
+ Set itemLocationSet = new HashSet<>();
+ itemLocationSet.add("CN");
+ return itemLocationSet;
+ }
+
+}
diff --git a/src/main/java/com/ebay/feed/example/UsingMutliThread.java b/src/main/java/com/ebay/feed/example/UsingMutliThread.java
new file mode 100644
index 0000000..ed04384
--- /dev/null
+++ b/src/main/java/com/ebay/feed/example/UsingMutliThread.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2018 eBay Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.ebay.feed.example;
+
+import java.util.HashSet;
+import java.util.Set;
+import com.ebay.feed.api.Feed;
+import com.ebay.feed.api.FeedImpl;
+import com.ebay.feed.constants.Constants;
+import com.ebay.feed.enums.EnvTypeEnum;
+import com.ebay.feed.model.feed.download.GetFeedResponse;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
+import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
+import com.ebay.feed.model.feed.operation.filter.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * Example showing how to download and filter feed files based on seller user
+ * names. The download location is default - current working directory
+ * This example downloads the bootstrap feed file for L1 category : 1
+ * (Collectibles) and filters on seller user names.
+ * The filtering is performed on the unzipped file.
+ * So the sequence of events that are followed is :-
+ * - Download feed file
+ * - Unzip feed file
+ * - Filter feed file
+ *
+ *
+ *
+ */
+public class UsingMutliThread {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(UsingMutliThread.class);
+
+ // oauth token - Bearer xxx
+ static String token
+ = Constants.TOKEN_BEARER_PREFIX
+ + "v^1.1#i^1#f...";
+
+ // init feed
+ static Feed feed = new FeedImpl();
+
+ private static final String CATEGORY = "625";
+ private static final String DATE = "20210125";
+ private static final String SNAPSHOT_DATE = "2021-01-29T02:00:00.000Z";
+ private static final String SCOPE = "NEWLY_LISTED";
+ private static final String MKT = "EBAY_US";
+
+ public static void main(String[] args) {
+
+ new Thread(() -> {
+ String feedType = "item";
+ getUnzipAndFilterFeed(feedType);
+ }).start();
+
+ new Thread(() -> {
+ String feedType = "item_snapshot";
+ getUnzipAndFilterFeed(feedType);
+ }).start();
+ }
+
+ private static void getUnzipAndFilterFeed(String feedType) {
+ LOGGER.info("starting thread for feedType: " + feedType);
+ // create request
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ if (feedType.equalsIgnoreCase("item_snapshot")) {
+ builder.categoryId(CATEGORY).snapshotDate(SNAPSHOT_DATE).siteId(MKT).token(token)
+ .type(feedType).env(EnvTypeEnum.SANDBOX.name());
+ } else {
+ builder.categoryId(CATEGORY).date(DATE).feedScope(SCOPE).siteId(MKT).token(token)
+ .type(feedType).env(EnvTypeEnum.SANDBOX.name());
+ }
+ // using null for download directory - defaults to current working directory
+ GetFeedResponse getFeedResponse = feed.get(builder.build(), null);
+
+ // 0 denotes successful response
+ if (getFeedResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in downloading feed. Cannot proceed");
+ return;
+ }
+ // unzip
+ Response unzipOpResponse = feed.unzip(getFeedResponse.getFilePath());
+
+ if (unzipOpResponse.getStatusCode() != 0) {
+ LOGGER.info("Exception in unzipping feed. Cannot proceed");
+ return;
+ }
+
+ // filter
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setItemIds(getItemIds());
+ // set input file
+ filterRequest.setInputFilePath(unzipOpResponse.getFilePath());
+
+ Response response = feed.filter(filterRequest);
+ LOGGER.info("Filter status = " + response.getStatusCode());
+ LOGGER.info("Filtered file = " + response.getFilePath());
+ LOGGER.info("finished first thread");
+ }
+
+ /**
+ * Get the set of seller user names to filter on
+ *
+ * @return
+ */
+ private static Set getItemIds() {
+ Set itemIdSet = new HashSet<>();
+ itemIdSet.add("132029430107");
+ itemIdSet.add("132676918161");
+ itemIdSet.add("14270967132");
+ return itemIdSet;
+ }
+
+}
diff --git a/src/main/java/com/ebay/feed/model/feed/operation/feed/FeedRequest.java b/src/main/java/com/ebay/feed/model/feed/operation/feed/FeedRequest.java
index baa0af8..8219eaf 100755
--- a/src/main/java/com/ebay/feed/model/feed/operation/feed/FeedRequest.java
+++ b/src/main/java/com/ebay/feed/model/feed/operation/feed/FeedRequest.java
@@ -11,12 +11,9 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
-
package com.ebay.feed.model.feed.operation.feed;
import com.ebay.feed.constants.Constants;
-import com.ebay.feed.enums.FeedTypeEnum;
/**
*
+ * Generates a file name based on the input parameters
+ *
+ * @param feedRequest Container for capturing parameters related to
+ * downloading and unzipping feed files
+ * @return string Generates a filename based on the feed type, scope,
+ * category, marketplace and date
+ */
+ public String generateFileName(FeedRequest feedRequest) {
+
+ String fileType
+ = Constants.ALL_ACTIVE.equalsIgnoreCase(feedRequest.getFeedScope()) ? Constants.BOOTSTRAP
+ : Constants.DAILY;
+
+ FeedTypeEnum type = FeedTypeEnum.getFeedEnum(feedRequest.getType());
+
+ // switch (feedRequest.getType()) {
+ switch (type) {
+ case ITEM:
+ return "item_" + fileType + "-" + feedRequest.getCategoryId() + "-" + feedRequest.getDate()
+ + "-" + feedRequest.getMarketplaceId() + ".gz";
+ case ITEM_SNAPSHOT:
+ return "item_snapshot-" + feedRequest.getCategoryId() + "-" + feedRequest.getSnapshotDate().replaceAll(":", "")
+ + "-" + feedRequest.getMarketplaceId() + ".gz";
+ default:
+ return null;
+ }
}
- }
- /**
- *
- * Unzips a file and creates a new file and returns the path Returns null in case of errors
- *
- * @param path Path to the downloaded compressed feed file
- * @return string Path to the unzipped file
- * @throws Exception Exception
- */
- public String unzip(Path path) throws Exception {
+ /**
+ *
+ * Unzips a file and creates a new file and returns the path Returns null in
+ * case of errors
+ *
+ *
+ * @param path Path to the downloaded compressed feed file
+ * @return string Path to the unzipped file
+ * @throws Exception Exception
+ */
+ public String unzip(Path path) throws Exception {
- if (path == null)
- return null;
+ if (path == null) {
+ return null;
+ }
- byte[] buffer = new byte[1024];
+ byte[] buffer = new byte[1024];
- try {
+ try {
- LOGGER.debug("Starting unzipping operation for = {}", path.toString());
- String newFilePath = (path.toString().substring(0, path.toString().length() - 3));
+ LOGGER.debug("Starting unzipping operation for = {}", path.toString());
+ String newFilePath = (path.toString().substring(0, path.toString().length() - 3));
- GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(path.toFile()));
+ GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(path.toFile()));
- FileOutputStream out = new FileOutputStream(newFilePath);
+ FileOutputStream out = new FileOutputStream(newFilePath);
- int len;
- while ((len = gzis.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- }
+ int len;
+ while ((len = gzis.read(buffer)) > 0) {
+ out.write(buffer, 0, len);
+ }
- gzis.close();
- out.close();
+ gzis.close();
+ out.close();
- LOGGER.debug("Completed unzipping operation. Unzipped file = {}", newFilePath);
- return newFilePath;
+ LOGGER.debug("Completed unzipping operation. Unzipped file = {}", newFilePath);
+ return newFilePath;
- } catch (IOException ex) {
- LOGGER.debug("Exception in unzip()", ex);
- ex.printStackTrace();
+ } catch (IOException ex) {
+ LOGGER.debug("Exception in unzip()", ex);
+ ex.printStackTrace();
+ }
+ return null;
}
- return null;
- }
}
diff --git a/src/main/java/com/ebay/feed/util/FilterUtil.java b/src/main/java/com/ebay/feed/util/FilterUtil.java
index 2670da5..4f96192 100644
--- a/src/main/java/com/ebay/feed/util/FilterUtil.java
+++ b/src/main/java/com/ebay/feed/util/FilterUtil.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.util;
import java.io.BufferedReader;
@@ -28,6 +27,7 @@
import com.ebay.feed.api.Taxonomy;
import com.ebay.feed.api.TaxonomyImpl;
import com.ebay.feed.constants.Constants;
+import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
import com.ebay.feed.model.feed.operation.taxonomy.CategoryResponse;
@@ -35,60 +35,59 @@
*
* Utility class to perform filtering on feed files
*
- *
+ *
* @author shanganesh
*
*/
public class FilterUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(FilterUtil.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(FilterUtil.class);
- /**
- *
- * Apply the filters to the contents specified in the baseFilePath
- *
- *
- * @param baseFilePath Path to the unzipped feed file
- * @param filterRequest Container for capturing the filter parameters
- * @return string The path of the filtered file
- * @throws Exception exception
- */
- public String filter(Path baseFilePath, FeedFilterRequest filterRequest) throws Exception {
+ /**
+ *
+ * Apply the filters to the contents specified in the baseFilePath
+ *
+ *
+ * @param baseFilePath Path to the unzipped feed file
+ * @param filterRequest Container for capturing the filter parameters
+ * @return string The path of the filtered file
+ * @throws Exception exception
+ */
+ public String filter(Path baseFilePath, FeedFilterRequest filterRequest) throws Exception {
- LOGGER.debug("******* Begin filtering on file = {} with parameters = {}", baseFilePath,
- filterRequest);
+ LOGGER.debug("******* Begin filtering on file = {} with parameters = {}", baseFilePath,
+ filterRequest);
- String filteredFile = getFilteredFileName(baseFilePath, filterRequest);
+ String filteredFile = getFilteredFileName(baseFilePath, filterRequest);
- try (BufferedReader r = new BufferedReader(new FileReader(baseFilePath.toFile()));
- BufferedWriter w = new BufferedWriter(new FileWriter(filteredFile))) {
+ try (BufferedReader r = new BufferedReader(new FileReader(baseFilePath.toFile()));
+ BufferedWriter w = new BufferedWriter(new FileWriter(filteredFile))) {
- String line = null;
+ String line = null;
- while ((line = r.readLine()) != null) {
- String[] tsv = line.split(Constants.SEPARATOR);
+ while ((line = r.readLine()) != null) {
+ String[] tsv = line.split(Constants.SEPARATOR);
- // only for header
- if (evaluateHeader(tsv)) {
- w.write(line + System.lineSeparator());
- }
+ // only for header
+ if (evaluateHeader(tsv)) {
+ w.write(line + System.lineSeparator());
+ }
- // actual listings
- if (evaluate(tsv, filterRequest)) {
- w.write(line + System.lineSeparator());
- }
- }
+ // actual listings
+ if (evaluate(tsv, filterRequest)) {
+ w.write(line + System.lineSeparator());
+ }
+ }
- } catch (Exception e) {
- LOGGER.error("Error in FilterUtils.filter()", e);
- throw e;
+ } catch (Exception e) {
+ LOGGER.error("Error in FilterUtils.filter()", e);
+ throw e;
+ }
+ return filteredFile;
}
- return filteredFile;
- }
-
- /**
- *
+ /**
+ *
Evaluate the provided conditions The column number passed as a parameter to the 'evaluateField'
method, represents the column number in the actual file in the response.
@@ -102,217 +101,263 @@ public String filter(Path baseFilePath, FeedFilterRequest filterRequest) throws
0 - item id
- *
- * @param line One record from the feed file
- * @param filterRequest Container for capturing the filter parameters
- * @return boolean Indicates whether any filters apply to this record
- */
- protected boolean evaluate(String[] line, FeedFilterRequest filterRequest) {
- return evaluateField(line, filterRequest.getLeafCategoryIds(), 4)
- && evaluateField(line, filterRequest.getSellerNames(), 6)
- && evaluateField(line, filterRequest.getItemLocationCountries(), 21)
- && evaluateItemPrice(line, filterRequest)
- && evaluateField(line, filterRequest.getEpids(), 12)
- && evaluateField(line, filterRequest.getInferredEpids(), 40)
- && evaluateField(line, filterRequest.getGtins(), 9)
- && evaluateField(line, filterRequest.getItemIds(), 0);
- }
-
- /**
- *
- * Evaluate if the line is a headerline
- *
- *
- * @param line One record from the feed file
- * @return boolean Checks if the line is a header line
- */
- private boolean evaluateHeader(String[] line) {
- return line[0].contains(Constants.ITEM_ID);
- }
-
- /**
- *
+ *
+ * @param line One record from the feed file
+ * @return boolean Checks if the line is a header line
+ */
+ private boolean evaluateHeader(String[] line) {
+ return line[0].contains(Constants.ITEM_ID);
+ }
+
+ /**
+ *
* Evaluate if the item price based on the inputs - within a range - higher than a limit - lower
* than given limit
- *
- *
- * @param line One record from the feed file
- * @param filterRequest Container for capturing the filter parameters
- * @return boolean Checks if the price filter applies to this item
- */
- private boolean evaluateItemPrice(String[] line, FeedFilterRequest filterRequest) {
-
- boolean isValid = true;
-
- if (filterRequest == null
- || (filterRequest.getPriceLowerLimit() == null && filterRequest.getPriceUpperLimit() == null))
- return isValid;
-
- Double price = null;
- int colNo = 15;
-
- if (!isColumnValid(colNo, line.length))
- return isValid;
-
- try {
- price = Double.valueOf(line[colNo]);
- } catch (Exception e) {
- return false;
- }
+ *
+ *
+ * @param line One record from the feed file
+ * @param filterRequest Container for capturing the filter parameters
+ * @return boolean Checks if the price filter applies to this item
+ */
+ private boolean evaluateItemPrice(String[] line, FeedFilterRequest filterRequest) {
+
+ boolean isValid = true;
+
+ if (filterRequest == null
+ || (filterRequest.getPriceLowerLimit() == null && filterRequest.getPriceUpperLimit() == null))
+ return isValid;
+
+ Double price = null;
+ int colNo = 15;
+ if (filterRequest.getType().equalsIgnoreCase(FeedTypeEnum.ITEM_SNAPSHOT.name())) {
+ colNo = 16;
+ }
+
+ if (!isColumnValid(colNo, line.length))
+ return isValid;
- // between range
- if (filterRequest.getPriceLowerLimit() != null && filterRequest.getPriceUpperLimit() != null) {
+ try {
+ price = Double.valueOf(line[colNo]);
+ } catch (Exception e) {
+ return false;
+ }
+
+ // between range
+ if (filterRequest.getPriceLowerLimit() != null && filterRequest.getPriceUpperLimit() != null) {
- if (price < filterRequest.getPriceLowerLimit() || price > filterRequest.getPriceUpperLimit()) {
- isValid = false;
+ if (price < filterRequest.getPriceLowerLimit() || price > filterRequest.getPriceUpperLimit()) {
+ isValid = false;
- }
- } else if (filterRequest.getPriceLowerLimit() != null) {
+ }
+ } else if (filterRequest.getPriceLowerLimit() != null) {
- if (price < filterRequest.getPriceLowerLimit())
- isValid = false;
+ if (price < filterRequest.getPriceLowerLimit())
+ isValid = false;
- } else if (filterRequest.getPriceUpperLimit() != null) {
+ } else if (filterRequest.getPriceUpperLimit() != null) {
- if (price > filterRequest.getPriceUpperLimit())
- isValid = false;
+ if (price > filterRequest.getPriceUpperLimit())
+ isValid = false;
+ }
+ return isValid;
}
- return isValid;
- }
-
-
- /**
- *
- * Evaluates the presence of field at 'columnNo', is present in the given set.
- *
- * This method is generic for handling filtering on 'set of string' filters.
- *
- *
- * @param line One record from the feed file
- * @param filterSet Set of filters
- * @param column Column to filter on
- * @return
- */
- private boolean evaluateField(String[] line, Set filterSet, Integer columnNo) {
-
- boolean isValid = true;
-
- // nothing to evaluate
- if (filterSet == null || filterSet.isEmpty() || columnNo == null)
- return isValid;
-
- // guard against parsing issues
- if (!isColumnValid(columnNo, line.length))
- return isValid;
-
- String field = line[columnNo];
-
- if (filterSet != null && !filterSet.isEmpty() && !filterSet.contains(field)) {
- isValid = false;
+
+ /**
+ *
+ * Evaluates the presence of field at 'columnNo', is present in the given set.
+ *
+ * This method is generic for handling filtering on 'set of string' filters.
+ *
+ *
+ * @param line One record from the feed file
+ * @param filterSet Set of filters
+ * @param column Column to filter on
+ * @return
+ */
+ private boolean evaluateField(String[] line, Set filterSet, Integer columnNo) {
+
+ boolean isValid = true;
+
+ // nothing to evaluate
+ if (filterSet == null || filterSet.isEmpty() || columnNo == null)
+ return isValid;
+
+ // guard against parsing issues
+ if (!isColumnValid(columnNo, line.length))
+ return isValid;
+
+ String field = line[columnNo];
+
+ if (filterSet != null && !filterSet.isEmpty() && !filterSet.contains(field)) {
+ isValid = false;
+ }
+ return isValid;
+
+ }
+
+
+ /**
+ *
+ * Evaluates the presence of field at 'columnNo', is present in the given set.
+ *
+ * This method is for skipping UNAVAILABLE items
+ *
+ *
+ * @param line One record from the feed file
+ * @param column Column to filter on
+ * @return
+ */
+ private boolean checkItemAvailability(String[] line, Integer columnNo) {
+ boolean isValid = true;
+
+ // guard against parsing issues
+ if (!isColumnValid(columnNo, line.length))
+ return isValid;
+
+ String field = line[columnNo];
+
+ if(columnNo == 1 && field.equalsIgnoreCase("UNAVAILABLE"))
+ isValid = false;
+
+ return isValid;
+
+ }
+
+ /**
+ *
+ * Generate filtered file name based on base file path and timestamp
+ *
+ *
+ * @param baseFilePath Path of the unzipped file
+ * @param filterRequest Container for capturing the filter parameters
+ * @return
+ */
+ private String getFilteredFileName(Path baseFilePath, FeedFilterRequest filterRequest) {
+ Date d = new Date();
+ String filteredFile = baseFilePath.toString() + "-filtered-" + d.getTime();
+ return filteredFile;
}
- return isValid;
-
- }
-
- /**
- *
- * Generate filtered file name based on base file path and timestamp
- *
- *
- * @param baseFilePath Path of the unzipped file
- * @param filterRequest Container for capturing the filter parameters
- * @return
- */
- private String getFilteredFileName(Path baseFilePath, FeedFilterRequest filterRequest) {
- Date d = new Date();
- String filteredFile = baseFilePath.toString() + "-filtered-" + d.getTime();
- return filteredFile;
- }
-
- /**
- *
- * Calculate leaf categories if level two or level three category filters have been specified
- *
- *
- *
- * @param filterRequest Container for capturing the filter parameters
- * @return Set of leaf categories
- */
- public Set calculateLeaves(FeedFilterRequest filterRequest) {
-
- Set leafCategories = new HashSet<>();
- // return null of level two and level three categories are absent.
- // no need to invoke taxonomy
- if (isLevelNAbsent(filterRequest))
- return leafCategories;
-
- Taxonomy taxonomy = new TaxonomyImpl();
+
+ /**
+ *
+ * Calculate leaf categories if level two or level three category filters have been specified
+ *
+ *
+ *
+ * @param filterRequest Container for capturing the filter parameters
+ * @return Set of leaf categories
+ */
+ public Set calculateLeaves(FeedFilterRequest filterRequest) {
+
+ Set leafCategories = new HashSet<>();
+ // return null of level two and level three categories are absent.
+ // no need to invoke taxonomy
+ if (isLevelNAbsent(filterRequest))
+ return leafCategories;
+
+ Taxonomy taxonomy = new TaxonomyImpl();
String categoryTreeId =
taxonomy.getCategoryTreeId(filterRequest.getToken(), filterRequest.getMarketplace());
- if (categoryTreeId == null) {
- LOGGER.debug("Could not load category tree id. Cannot proceed...");
- return null;
- }
+ if (categoryTreeId == null) {
+ LOGGER.debug("Could not load category tree id. Cannot proceed...");
+ return null;
+ }
CategoryResponse categoryResponse =
taxonomy.loadLeafCategories(filterRequest.getToken(), categoryTreeId,
- filterRequest.getLevelOneCategory());
-
- Set levelTwoCats = filterRequest.getLevelTwoCategories();
- Set levelThreeCats = filterRequest.getLevelThreeCategories();
-
-
- if (levelTwoCats != null && !levelTwoCats.isEmpty())
- leafCategories.addAll(getLeafCategories(categoryResponse.getLevelTwoCategoryLeaves(),
- levelTwoCats));
-
- if (levelThreeCats != null && !levelThreeCats.isEmpty())
- leafCategories.addAll(getLeafCategories(categoryResponse.getLevelThreeCategoryLeaves(),
- levelThreeCats));
-
- return leafCategories;
- }
-
- /**
- *
- * Get map of leaf categories
- *
- *
- * @param map Map of level one to children categories
- * @param catSet Set of leaf categories
- * @return Set of leaf categories
- */
- private Set getLeafCategories(Map> map, Set catSet) {
- Set leafCategorySet = new HashSet<>();
- for (String cat : catSet) {
- leafCategorySet.addAll(map.get(cat));
+ filterRequest.getLevelOneCategory());
+
+ Set levelTwoCats = filterRequest.getLevelTwoCategories();
+ Set levelThreeCats = filterRequest.getLevelThreeCategories();
+
+ if (levelTwoCats != null && !levelTwoCats.isEmpty())
+ leafCategories.addAll(getLeafCategories(categoryResponse.getLevelTwoCategoryLeaves(),
+ levelTwoCats));
+
+ if (levelThreeCats != null && !levelThreeCats.isEmpty())
+ leafCategories.addAll(getLeafCategories(categoryResponse.getLevelThreeCategoryLeaves(),
+ levelThreeCats));
+
+ return leafCategories;
+ }
+
+ /**
+ *
+ * Get map of leaf categories
+ *
+ *
+ * @param map Map of level one to children categories
+ * @param catSet Set of leaf categories
+ * @return Set of leaf categories
+ */
+ private Set getLeafCategories(Map> map, Set catSet) {
+ Set leafCategorySet = new HashSet<>();
+ for (String cat : catSet) {
+ leafCategorySet.addAll(map.get(cat));
+ }
+ return leafCategorySet;
}
- return leafCategorySet;
- }
-
- /**
- *
- * @param colNo Column number from the feed file
- * @param len Total number of columns
- * @return boolean Indicates whether the column number is valid
- */
- private boolean isColumnValid(int colNo, int len) {
- return colNo < len;
- }
-
- /**
+
+ /**
+ *
+ * @param colNo Column number from the feed file
+ * @param len Total number of columns
+ * @return boolean Indicates whether the column number is valid
+ */
+ private boolean isColumnValid(int colNo, int len) {
+ return colNo < len;
+ }
+
+ /**
* Taxonomy invocation required only if l2 or l3 categories are present Read this method as Level
* 'n' absent, to signify level 2, or 3 (maybe more levels in the future)
- *
+ *
* @return boolean - Checks presence of l2 and l3 categories. If present, returns false. If both
* are empty/null, returns true
- */
- private boolean isLevelNAbsent(FeedFilterRequest filterRequest) {
- return filterRequest == null
- || ((filterRequest.getLevelThreeCategories() == null || filterRequest
- .getLevelThreeCategories().isEmpty()) && (filterRequest.getLevelTwoCategories() == null || filterRequest
- .getLevelTwoCategories().isEmpty()));
- }
+ */
+ private boolean isLevelNAbsent(FeedFilterRequest filterRequest) {
+ return filterRequest == null
+ || ((filterRequest.getLevelThreeCategories() == null || filterRequest
+ .getLevelThreeCategories().isEmpty()) && (filterRequest.getLevelTwoCategories() == null || filterRequest
+ .getLevelTwoCategories().isEmpty()));
+ }
}
diff --git a/src/main/java/com/ebay/feed/validator/FeedValidator.java b/src/main/java/com/ebay/feed/validator/FeedValidator.java
index 7f15d26..118b187 100644
--- a/src/main/java/com/ebay/feed/validator/FeedValidator.java
+++ b/src/main/java/com/ebay/feed/validator/FeedValidator.java
@@ -11,92 +11,213 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.validator;
+import com.ebay.feed.constants.Constants;
+import com.ebay.feed.enums.FeedTypeEnum;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*
* Class responsible for validating feed and filter requests
*
- *
+ *
* @author shanganesh
*
*/
public class FeedValidator {
- /**
- * Check path validity
- *
- * @param filePath Checks if the file exists on the specified path
- * @return boolean Indicates whether the file was found on the specified path
- */
- public boolean isValidPath(String filePath) {
-
- if (filePath == null || filePath.isEmpty())
- return false;
-
- Path path = Paths.get(filePath);
-
- return Files.exists(path);
- }
-
- /**
- *
- * Check feed filter request
- *
- *
- * @param filterRequest Container for capturing parameters related to filtering the feed files
- * @return boolean Indicates whether all the mandatory parameters are present
- */
- public boolean isValidFilterRequest(FeedFilterRequest filterRequest) {
-
- if (filterRequest == null)
- return false;
+ private static final Logger LOGGER = LoggerFactory.getLogger(FeedValidator.class);
+ SimpleDateFormat sdf;
+ Calendar calendar;
- if (filterRequest.getInputFilePath() == null || filterRequest.getInputFilePath().isEmpty())
- return false;
+ /**
+ * Check path validity
+ *
+ * @param filePath Checks if the file exists on the specified path
+ * @return boolean Indicates whether the file was found on the specified
+ * path
+ */
+ public boolean isValidPath(String filePath) {
- Path path = Paths.get(filterRequest.getInputFilePath());
+ if (filePath == null || filePath.isEmpty()) {
+ return false;
+ }
- if (!Files.exists(path))
- return false;
-
- if (filterRequest.isEmpty())
- return false;
-
- if (!isValidLevelNRequest(filterRequest))
- return false;
-
- return true;
- }
+ Path path = Paths.get(filePath);
+ return Files.exists(path);
+ }
- /**
- * Check that the mandatory parameters are present, in case filtering on level 'n' is requested
- *
- * @return
- */
- private boolean isValidLevelNRequest(FeedFilterRequest filterRequest) {
+ /**
+ *
+ * Check feed filter request
+ *
+ *
+ * @param filterRequest Container for capturing parameters related to
+ * filtering the feed files
+ * @return boolean Indicates whether all the mandatory parameters are
+ * present
+ */
+ public boolean isValidFilterRequest(FeedFilterRequest filterRequest) {
+
+ if (filterRequest == null) {
+ return false;
+ }
+
+ if (filterRequest.getInputFilePath() == null || filterRequest.getInputFilePath().isEmpty()) {
+ return false;
+ }
+
+ Path path = Paths.get(filterRequest.getInputFilePath());
+
+ if (!Files.exists(path)) {
+ return false;
+ }
+
+ if (filterRequest.isEmpty()) {
+ return false;
+ }
+
+ if (!isValidLevelNRequest(filterRequest)) {
+ return false;
+ }
+
+ return true;
+ }
- boolean isValid = true;
- // check if level 'n' categories are present.
- if ((filterRequest.getLevelTwoCategories() != null && !filterRequest.getLevelTwoCategories()
- .isEmpty())
- || (filterRequest.getLevelThreeCategories() != null && !filterRequest
- .getLevelThreeCategories().isEmpty())) {
+ /**
+ * Check that the mandatory parameters are present, in case filtering on
+ * level 'n' is requested
+ *
+ * @return
+ */
+ private boolean isValidLevelNRequest(FeedFilterRequest filterRequest) {
+
+ boolean isValid = true;
+ // check if level 'n' categories are present.
+ if ((filterRequest.getLevelTwoCategories() != null && !filterRequest.getLevelTwoCategories()
+ .isEmpty())
+ || (filterRequest.getLevelThreeCategories() != null && !filterRequest
+ .getLevelThreeCategories().isEmpty())) {
+
+ if (filterRequest.getToken() == null || filterRequest.getMarketplace() == null
+ || filterRequest.getLevelOneCategory() == null) {
+ isValid = false;
+ }
+
+ }
+ return isValid;
+ }
- if (filterRequest.getToken() == null || filterRequest.getMarketplace() == null
- || filterRequest.getLevelOneCategory() == null)
- isValid = false;
+ /**
+ * Check that the date format is valid and date is within valid range for
+ * selected feed type
+ *
+ * Feed Type Item date format is yyyyMMdd and range would be within previous
+ * 3-14 days
+ *
+ * Feed Type ItemSnapshot date format is yyyy-MM-dd'T'HH:00:00.000'Z' and
+ * range would be within previous 7 days
+ *
+ * @param feedRequest
+ * @return
+ */
+ public boolean isValidDateFormatAndRange(FeedRequest feedRequest) {
+ boolean isValid = true;
+ FeedTypeEnum type = FeedTypeEnum.getFeedEnum(feedRequest.getType());
+
+ switch (type) {
+ case ITEM:
+ if (Constants.NEWLY_LISTED.equalsIgnoreCase(feedRequest.getFeedScope())) {
+ try {
+ sdf = new SimpleDateFormat(Constants.QUERY_DATE_FORMAT);
+ Date feedItemRequestDate = sdf.parse(feedRequest.getDate());
+ LOGGER.debug("feedItemRequestDate : {}", feedItemRequestDate);
+
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ LOGGER.debug("Current Time in GMT Time Zone : {}", calendar.getTime());
+// Calendar calendar = Calendar.getInstance();
+ calendar.add(Calendar.DAY_OF_MONTH, Constants.NEWLY_LISTED_AVAILABILITY_START_DAY);
+ Date feedItemAvailabilityStartDate = sdf.parse(sdf.format(calendar.getTime()));
+ LOGGER.debug("feedItemAvailabilityStartDate : {}", feedItemAvailabilityStartDate);
+
+ calendar = Calendar.getInstance();
+ calendar.add(Calendar.DAY_OF_MONTH, Constants.NEWLY_LISTED_AVAILABILITY_END_DAY);
+ Date feedItemAvailabilityEndDate = sdf.parse(sdf.format(calendar.getTime()));
+ LOGGER.debug("feedItemAvailabilityEndDate : {}", feedItemAvailabilityEndDate);
+
+ if (!isWithinRange(feedItemRequestDate, feedItemAvailabilityStartDate, feedItemAvailabilityEndDate)) {
+ isValid = false;
+ }
+ // good format and within valid range
+ } catch (ParseException ex) {
+ isValid = false;
+ LOGGER.error("Item Date format is not valid. Cannot get feed. Aborting...", ex);
+ }
+ }
+
+ break;
+
+ case ITEM_SNAPSHOT:
+ try {
+ sdf = new SimpleDateFormat(Constants.QUERY_SNAPSHOT_DATE_FORMAT);
+ Date feedItemSnapshotRequestDate = sdf.parse(feedRequest.getSnapshotDate());
+ LOGGER.debug("feedItemSnapshotRequestDate : {}", feedItemSnapshotRequestDate);
+
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ LOGGER.debug("Current Time in GMT Time Zone : {}", calendar.getTime());
+ //Calendar calendar = Calendar.getInstance();
+ calendar.add(Calendar.DAY_OF_MONTH, Constants.ITEM_SNAPSHOT_AVAILABILITY_START_DAY);
+ Date feedItemSnapshotAvailabilitStartDate = sdf.parse(sdf.format(calendar.getTime()));
+ LOGGER.debug("feedItemSnapshotAvailabilitStartDate : {}", feedItemSnapshotAvailabilitStartDate);
+
+ calendar = Calendar.getInstance();
+ calendar.add(Calendar.HOUR_OF_DAY, Constants.ITEM_SNAPSHOT_AVAILABILITY_END_HOUR);
+ Date feedItemSnapshotAvailabilitEndDate = sdf.parse(sdf.format(calendar.getTime()));
+ LOGGER.debug("feedItemSnapshotAvailabilitEndDate : {}", feedItemSnapshotAvailabilitEndDate);
+
+ if (!isWithinRange(feedItemSnapshotRequestDate, feedItemSnapshotAvailabilitStartDate, feedItemSnapshotAvailabilitEndDate)) {
+ isValid = false;
+ }
+ // good format and within valid range
+ } catch (ParseException ex) {
+ isValid = false;
+ LOGGER.error("Item Snapshot Date format is not valid. Cannot get feed. Aborting...", ex);
+ }
+ break;
+
+ default:
+ break;
+ }
+ return isValid;
}
- return isValid;
- }
-
+ /**
+ * Feed Type Item date range would be within previous 3-14 days
+ *
+ * Feed Type ItemSnapshot date range would be within previous 7 days
+ *
+ * @param queryRequestDate
+ * @param startDate
+ * @param endDate
+ * @return
+ */
+ private boolean isWithinRange(Date queryRequestDate, Date startDate, Date endDate) {
+ return !(queryRequestDate.before(startDate) || queryRequestDate.after(endDate));
+ }
}
diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml
index ac7aff9..f509dd0 100644
--- a/src/main/resources/logback.xml
+++ b/src/main/resources/logback.xml
@@ -1,48 +1,48 @@
+~ /**
+~ * Copyright (c) 2018 eBay Inc.
+~ *
+~ * Licensed under the Apache License, Version 2.0 (the "License");
+~ * you may not use this file except in compliance with the License.
+~ * You may obtain a copy of the License at
+~ *
+~ * http://www.apache.org/licenses/LICENSE-2.0
+~ *
+~ * Unless required by applicable law or agreed to in writing, software
+~ * distributed under the License is distributed on an "AS IS" BASIS,
+~ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+~ * See the License for the specific language governing permissions and
+~ * limitations under the License.
+~ **/
+-->
-
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
-
-
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
-
- ${LOG_HOME:-.}/feed-sdk-log.log
-
- feedsdk-log.%d{yyyy-MM-dd}.log
-
- 7
- 100MB
-
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
-
-
+
+ ${LOG_HOME:-.}/feed-sdk-log.log
+
+ feedsdk-log.%d{yyyy-MM-dd}.log
+
+ 7
+ 100MB
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
-
-
-
-
-
+
+
+
+
+
diff --git a/src/test/java/com/ebay/feed/util/FeedUtilTest.java b/src/test/java/com/ebay/feed/util/FeedUtilTest.java
index 42870e4..edd6078 100644
--- a/src/test/java/com/ebay/feed/util/FeedUtilTest.java
+++ b/src/test/java/com/ebay/feed/util/FeedUtilTest.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.util;
import okhttp3.Request;
@@ -21,100 +20,132 @@
import com.ebay.feed.constants.Constants;
import com.ebay.feed.enums.EnvTypeEnum;
-import com.ebay.feed.enums.FeedTypeEnum;
import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.feed.FeedRequest.FeedRequestBuilder;
public class FeedUtilTest {
- FeedUtil feedUtil = new FeedUtil();
-
- @Test
- public void getFinalUrlInvalidTypeTest() {
-
- String expectedUrl =
- Constants.FEED_API_PROD_BASE + Constants.ITEM_RESOURCE_SCOPE + "ALL_ACTIVE"
- + Constants.QUERY_PARAM_SEPARATOR + Constants.QUERY_CATEGORY_ID + "1"
- + Constants.QUERY_PARAM_SEPARATOR + Constants.QUERY_DATE + "20180101";
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("ALL_ACTIVE");
- builder.date("20180101");
-
- Assert.assertEquals(expectedUrl, feedUtil.getFinalUrl(builder.build()));
- }
-
- @Test
- public void generateRequestTest() {
-
- Request.Builder requestBuilder = new Request.Builder();
-
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("ALL_ACTIVE");
- builder.date("20180101");
- builder.token(Constants.TOKEN_BEARER_PREFIX + "v1...");
- builder.siteId("EBAY_US");
-
- feedUtil.generateRequest(builder.build(), requestBuilder);
-
- Request request = requestBuilder.build();
- Assert.assertNotNull(request.header(Constants.AUTHORIZATION_HEADER));
- Assert.assertNotNull(request.header(Constants.MARKETPLACE_HEADER));
- Assert.assertNotNull(request.header(Constants.CONTENT_TYPE_HEADER));
- Assert.assertNotNull(request.header(Constants.ACCEPT_HEADER));
- }
-
- @Test
- public void generateFileNameTest() {
-
- String expectedFileName = "item_daily-1-20180101-EBAY_US.gz";
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("NEWLY_LISTED");
- builder.date("20180101");
- builder.siteId("EBAY_US");
- Assert.assertEquals(expectedFileName, feedUtil.generateFileName(builder.build()));
- }
-
- @Test
- public void generateFileNameBootstrapTest() {
-
- String expectedFileName = "item_bootstrap-1-20180101-EBAY_US.gz";
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("ALL_ACTIVE");
- builder.date("20180101");
- builder.siteId("EBAY_US");
- Assert.assertEquals(expectedFileName, feedUtil.generateFileName(builder.build()));
- }
-
- @Test
- public void getChunkSizeLimitTest() {
- // Prod
- Long expectedChunkSize =
- Constants.PROD_CHUNK_SIZE;
- FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("ALL_ACTIVE");
- builder.date("20180101");
-
- Assert.assertEquals(expectedChunkSize, feedUtil.getChunkSizeLimit(builder.build()));
-
- // Sandbox
- expectedChunkSize =
- Constants.SANDBOX_CHUNK_SIZE;
- builder = new FeedRequestBuilder();
- builder.type(FeedTypeEnum.ITEM);
- builder.categoryId("1");
- builder.feedScope("ALL_ACTIVE");
- builder.date("20180101");
- builder.env(EnvTypeEnum.SANDBOX.name());
- Assert.assertEquals(expectedChunkSize, feedUtil.getChunkSizeLimit(builder.build()));
- }
+ FeedUtil feedUtil = new FeedUtil();
+
+ @Test
+ public void getFinalUrlInvalidTypeTest() {
+
+ String expectedUrl
+ = Constants.FEED_API_PROD_BASE + Constants.ITEM_RESOURCE_SCOPE + "ALL_ACTIVE"
+ + Constants.QUERY_PARAM_SEPARATOR + Constants.QUERY_CATEGORY_ID + "1"
+ + Constants.QUERY_PARAM_SEPARATOR + Constants.QUERY_DATE + "20180101";
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+
+ Assert.assertEquals(expectedUrl, feedUtil.getFinalUrl(builder.build()));
+ }
+
+ @Test
+ public void generateRequestTest() {
+
+ Request.Builder requestBuilder = new Request.Builder();
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+ builder.token(Constants.TOKEN_BEARER_PREFIX + "v1...");
+ builder.siteId("EBAY_US");
+
+ feedUtil.generateRequest(builder.build(), requestBuilder);
+
+ Request request = requestBuilder.build();
+ Assert.assertNotNull(request.header(Constants.AUTHORIZATION_HEADER));
+ Assert.assertNotNull(request.header(Constants.MARKETPLACE_HEADER));
+ Assert.assertNotNull(request.header(Constants.CONTENT_TYPE_HEADER));
+ Assert.assertNotNull(request.header(Constants.ACCEPT_HEADER));
+ }
+
+ @Test
+ public void generateItemSnapshotRequestTest() {
+
+ Request.Builder requestBuilder = new Request.Builder();
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("ITEM_SNAPSHOT");
+ builder.categoryId("1");
+ builder.snapshotDate("2018-08-05T02:00:00.000Z");
+ builder.token(Constants.TOKEN_BEARER_PREFIX + "v1...");
+ builder.siteId("EBAY_US");
+
+ feedUtil.generateRequest(builder.build(), requestBuilder);
+
+ Request request = requestBuilder.build();
+ Assert.assertNotNull(request.header(Constants.AUTHORIZATION_HEADER));
+ Assert.assertNotNull(request.header(Constants.MARKETPLACE_HEADER));
+ Assert.assertNotNull(request.header(Constants.CONTENT_TYPE_HEADER));
+ Assert.assertNotNull(request.header(Constants.ACCEPT_HEADER));
+ }
+
+ @Test
+ public void generateFileNameSnapshotTest() {
+
+ String expectedFileName = "item_snapshot-1281-2018-08-05T020000.000Z-EBAY_US.gz";
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item_snapshot");
+ builder.categoryId("1281");
+ builder.snapshotDate("2018-08-05T020000.000Z");
+ builder.siteId("EBAY_US");
+ Assert.assertEquals(expectedFileName, feedUtil.generateFileName(builder.build()));
+ }
+
+ @Test
+ public void generateFileNameTest() {
+
+ String expectedFileName = "item_daily-1-20180101-EBAY_US.gz";
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("NEWLY_LISTED");
+ builder.date("20180101");
+ builder.siteId("EBAY_US");
+ Assert.assertEquals(expectedFileName, feedUtil.generateFileName(builder.build()));
+ }
+
+ @Test
+ public void generateFileNameBootstrapTest() {
+
+ String expectedFileName = "item_bootstrap-1-20180101-EBAY_US.gz";
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+ builder.siteId("EBAY_US");
+ Assert.assertEquals(expectedFileName, feedUtil.generateFileName(builder.build()));
+ }
+
+ @Test
+ public void getChunkSizeLimitTest() {
+ // Prod
+ Long expectedChunkSize
+ = Constants.PROD_CHUNK_SIZE;
+ FeedRequest.FeedRequestBuilder builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+
+ Assert.assertEquals(expectedChunkSize, feedUtil.getChunkSizeLimit(builder.build()));
+
+ // Sandbox
+ expectedChunkSize
+ = Constants.SANDBOX_CHUNK_SIZE;
+ builder = new FeedRequestBuilder();
+ builder.type("item");
+ builder.categoryId("1");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+ builder.env(EnvTypeEnum.SANDBOX.name());
+ Assert.assertEquals(expectedChunkSize, feedUtil.getChunkSizeLimit(builder.build()));
+ }
}
diff --git a/src/test/java/com/ebay/feed/validator/FeedValidatorTest.java b/src/test/java/com/ebay/feed/validator/FeedValidatorTest.java
index 04ed7c8..bc62615 100644
--- a/src/test/java/com/ebay/feed/validator/FeedValidatorTest.java
+++ b/src/test/java/com/ebay/feed/validator/FeedValidatorTest.java
@@ -11,7 +11,6 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-
package com.ebay.feed.validator;
import java.util.HashSet;
@@ -19,76 +18,150 @@
import org.junit.Assert;
import org.junit.Test;
import com.ebay.feed.constants.Constants;
+import com.ebay.feed.model.feed.operation.feed.FeedRequest;
import com.ebay.feed.model.feed.operation.filter.FeedFilterRequest;
+import java.nio.file.Paths;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.TimeZone;
public class FeedValidatorTest {
- FeedValidator feedValidator = new FeedValidator();
-
- @Test
- public void isValidPathNullTest() {
- Assert.assertFalse(feedValidator.isValidPath(null));
- }
-
- @Test
- public void isValidPathBlankTrimTest() {
- Assert.assertFalse(feedValidator.isValidPath(""));
- }
-
- //@Test
- public void isValidPathBlankTest() {
- Assert.assertFalse(feedValidator.isValidPath(" "));
- }
-
- // TODO : this may fail if folder is not present
- @Test
- public void isValidPathTest() {
- Assert.assertTrue(feedValidator.isValidPath("/tmp"));
- }
-
- @Test
- public void isValidFilterRequestNullTest() {
- Assert.assertFalse(feedValidator.isValidFilterRequest(null));
- }
-
- @Test
- public void isValidFilterRequestEmptyTest() {
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
- }
-
- @Test
- public void isValidFilterRequestInvalidInputPathTest() {
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setInputFilePath("test");
- Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
- }
-
- @Test
- public void isValidFilterRequestInvalidLevelNTest() {
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setInputFilePath("/tmp");
-
- Set levelThreeCats = new HashSet<>();
- levelThreeCats.add("1");
- filterRequest.setLevelThreeCategories(levelThreeCats);
-
- Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
- }
-
- @Test
- public void isValidFilterRequestValidLevelNTest() {
- FeedFilterRequest filterRequest = new FeedFilterRequest();
- filterRequest.setInputFilePath("/tmp");
-
- Set levelThreeCats = new HashSet<>();
- levelThreeCats.add("1");
- filterRequest.setLevelThreeCategories(levelThreeCats);
-
- filterRequest.setToken(Constants.TOKEN_BEARER_PREFIX + "v1...");
- filterRequest.setMarketplace("EBAY_US");
- filterRequest.setLevelOneCategory("1");
-
- Assert.assertTrue(feedValidator.isValidFilterRequest(filterRequest));
- }
+ FeedValidator feedValidator = new FeedValidator();
+
+ @Test
+ public void isValidPathNullTest() {
+ Assert.assertFalse(feedValidator.isValidPath(null));
+ }
+
+ @Test
+ public void isValidPathBlankTrimTest() {
+ Assert.assertFalse(feedValidator.isValidPath(""));
+ }
+
+ //@Test
+ public void isValidPathBlankTest() {
+ Assert.assertFalse(feedValidator.isValidPath(" "));
+ }
+
+ // TODO : this may fail if folder is not present
+ @Test
+ public void isValidPathTest() {
+ //Assert.assertTrue(feedValidator.isValidPath("/tmp"));
+ String path = Paths.get("").toAbsolutePath().toString();
+ Assert.assertTrue(feedValidator.isValidPath(path));
+ }
+
+ @Test
+ public void isValidFilterRequestNullTest() {
+ Assert.assertFalse(feedValidator.isValidFilterRequest(null));
+ }
+
+ @Test
+ public void isValidFilterRequestEmptyTest() {
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
+ }
+
+ @Test
+ public void isValidFilterRequestInvalidInputPathTest() {
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setInputFilePath("test");
+ Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
+ }
+
+ @Test
+ public void isValidFilterRequestInvalidLevelNTest() {
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ filterRequest.setInputFilePath("/tmp");
+
+ Set levelThreeCats = new HashSet<>();
+ levelThreeCats.add("1");
+ filterRequest.setLevelThreeCategories(levelThreeCats);
+
+ Assert.assertFalse(feedValidator.isValidFilterRequest(filterRequest));
+ }
+
+ @Test
+ public void isValidFilterRequestValidLevelNTest() {
+ FeedFilterRequest filterRequest = new FeedFilterRequest();
+ //filterRequest.setInputFilePath("/tmp");
+ String path = Paths.get("").toAbsolutePath().toString();
+ filterRequest.setInputFilePath(path);
+
+ Set levelThreeCats = new HashSet<>();
+ levelThreeCats.add("1");
+ filterRequest.setLevelThreeCategories(levelThreeCats);
+
+ filterRequest.setToken(Constants.TOKEN_BEARER_PREFIX + "v1...");
+ filterRequest.setMarketplace("EBAY_US");
+ filterRequest.setLevelOneCategory("1");
+
+ Assert.assertTrue(feedValidator.isValidFilterRequest(filterRequest));
+ }
+
+ @Test
+ public void isValidDateFormatAndRangeFeedItemScopeALLACTIVETest() {
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequest.FeedRequestBuilder();
+ builder.type("item");
+ builder.feedScope("ALL_ACTIVE");
+ builder.date("20180101");
+ Assert.assertTrue(feedValidator.isValidDateFormatAndRange(builder.build()));
+ }
+
+ @Test
+ public void isValidDateFormatAndRangeFeedItemScopeNEWLYLISTEDTest() {
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequest.FeedRequestBuilder();
+ builder.type("item");
+ builder.feedScope("NEWLY_LISTED");
+ //builder.date("20210121");
+ builder.date(getFeedDate("item"));
+ Assert.assertTrue(feedValidator.isValidDateFormatAndRange(builder.build()));
+ }
+
+ private String getFeedDate(String feedType) {
+ SimpleDateFormat sdf;
+ if (feedType.equalsIgnoreCase("item")) {
+ sdf = new SimpleDateFormat(Constants.QUERY_DATE_FORMAT);
+ } else {
+ sdf = new SimpleDateFormat(Constants.QUERY_SNAPSHOT_DATE_FORMAT);
+ }
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ calendar.add(Calendar.DAY_OF_MONTH, -5);
+ String date = sdf.format(calendar.getTime());
+
+ return date;
+ }
+
+ @Test
+ public void isValidDateFormatAndRangeFeedItemSnapshotTest() {
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequest.FeedRequestBuilder();
+ builder.type("item_snapshot");
+ //builder.snapshotDate("2021-01-26T12:00:00.000Z");
+ builder.snapshotDate(getFeedDate("item_snapshot"));
+ Assert.assertTrue(feedValidator.isValidDateFormatAndRange(builder.build()));
+ }
+
+ @Test
+ public void isValidDateFormatAndRangeFeedItemScopeNEWLYLISTEDInvalidDateTest() {
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequest.FeedRequestBuilder();
+ builder.type("item");
+ builder.feedScope("NEWLY_LISTED");
+ builder.date("20180101");
+ Assert.assertFalse(feedValidator.isValidDateFormatAndRange(builder.build()));
+ }
+
+ @Test
+ public void isValidDateFormatAndRangeFeedItemSnapshotInvalidSnapshotDateTest() {
+
+ FeedRequest.FeedRequestBuilder builder = new FeedRequest.FeedRequestBuilder();
+ builder.type("item_snapshot");
+ builder.snapshotDate("2018-08-05T02:00:00.000Z");
+ Assert.assertFalse(feedValidator.isValidDateFormatAndRange(builder.build()));
+ }
}