Skip to content

Commit

Permalink
DATA-3189 - Add POST endpoints. Add upload file. (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
swhelan091 committed Dec 12, 2019
1 parent 0121532 commit b6655ce
Show file tree
Hide file tree
Showing 38 changed files with 427 additions and 235 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.2.0
* Add support for POST request endpoints.
* Refactor exception handling such that exceptions are no longer nested classes of the factory. _This is a breaking change._

## 0.1.0
* Initial version of the client.

Expand Down
50 changes: 46 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,25 @@ Add this dependency to your project's POM:
<dependency>
<groupId>com.jwplayer</groupId>
<artifactId>jwplatform</artifactId>
<version>0.1.0</version>
<version>0.2.0</version>
</dependency>
```

## Usage

The following is an example of how to use the client.
The following is an example of how to use the client for a video of sourcetype `url`:

```java

import com.jwplayer.jwplatform.JWPlatformClient;
import com.jwplayer.jwplatform.exception.JWPlatformException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;

public class JWPlatformClientExample {

public static void main(String[] args) throws Exception {
public static void main(String[] args) {
String apiKey = "key";
String apiSecret = "secret";

Expand All @@ -55,7 +58,7 @@ public class JWPlatformClientExample {
System.out.println(videosCreateResponse);

// Show the properties of the created video
String videoKey = videosCreateResponse.getJSONObject("video").get("key").toString();
String videoKey = videosCreateResponse.getJSONObject("video").getString("key");
Map<String, String> videosShowParams = new HashMap<>();
videosShowParams.put("video_key", videoKey);
JSONObject videosShowResponse = client.request(videosShowPath, videosShowParams);
Expand All @@ -68,6 +71,45 @@ public class JWPlatformClientExample {

```

The following is an example of how to use the client for a video of sourcetype `file`:

```java

import com.jwplayer.jwplatform.JWPlatformClient;
import com.jwplayer.jwplatform.exception.JWPlatformException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;

public class JWPlatformClientExample {

public static void main(String[] args) {
String apiKey = "key";
String apiSecret = "secret";

String videosCreatePath = "videos/create";
Map<String, String> videosCreateParams = new HashMap<>();
videosCreateParams.put("sourcetype", "file");
videosCreateParams.put("title", "Some Video Title");

String localFilePath = "/some/path//test_video.mp4";

try {
JWPlatformClient client = JWPlatformClient.create(apiKey, apiSecret);

// Create a video asset
JSONObject videosCreateResponse = client.request(videosCreatePath, videosCreateParams);
System.out.println(videosCreateResponse);

// Upload the video from local file system
JSONObject videoUploadResponse = client.upload(videosCreateResponse, localFilePath);
System.out.println(videoUploadResponse);
} catch (JWPlatformException e) {
e.printStackTrace();
}
}
```

## Supported operations

All API methods documentated on the API are available in this client.
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.jwplayer</groupId>
<artifactId>jwplatform</artifactId>
<version>0.1.0</version>
<version>0.2.0</version>
<packaging>jar</packaging>

<name>JWPlatform-Java</name>
Expand Down
172 changes: 144 additions & 28 deletions src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package com.jwplayer.jwplatform;

import com.google.common.base.Preconditions;
import com.google.common.io.CharStreams;
import com.jwplayer.jwplatform.exception.JWPlatformException;
import com.jwplayer.jwplatform.exception.JWPlatformUnknownException;
import com.jwplayer.jwplatform.exception.MediaAPIExceptionFactory;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -19,6 +21,7 @@
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

/**
* JW Platform API client.
Expand Down Expand Up @@ -89,39 +92,31 @@ private String encodeStringForJWPlatformAPI(final String stringToEncode)
// string replacements to align with the API
return encodedValue.replace("%7E", "~").replace("*", "%2A").replace("+", "%20");
} catch (final UnsupportedEncodingException e) {
throw new MediaAPIExceptionFactory.JWPlatformUnknownException(
throw new JWPlatformUnknownException(
String.format("Exception thrown encoding URL parameter %s", e.toString()));
}
}

/**
* Make an API call to the JWPlatform API.
* Check if the API response is an non-200. If so, throw the
* appropriate JWPlatformException exception based on the
* error message.
*
* @param request - a {@code GetRequest} object
* @return - {@code HTTPResponse} if request was successful
* @param response - a {@code HttpResponse} object with the API response
* @throws JWPlatformException - API returned an exception
*/
private HttpResponse<JsonNode> buildResponse(final GetRequest request) throws JWPlatformException {
HttpResponse<JsonNode> response;
try {
response = request.asJson();
} catch (final UnirestException e) {
throw new MediaAPIExceptionFactory.JWPlatformUnknownException(
String.format("Non-JSON response from server: %s", e.toString()));
}
private void checkForNon200Response(final HttpResponse<JsonNode> response) throws JWPlatformException {
if (response.getStatus() != 200) {
try {
final String errorType = response.getBody().getObject().get("code").toString();
final String message = response.getBody().getObject().toString(2);
MediaAPIExceptionFactory.throwJWPlatformException(
StringUtils.stripEnd(errorType, "Error"), message);
} catch (final JSONException e) {
throw new MediaAPIExceptionFactory.JWPlatformUnknownException(
throw new JWPlatformUnknownException(
String.format("Unknown JSONException thrown: %s", e.toString()));
}
}

return response;
}

/**
Expand Down Expand Up @@ -159,13 +154,75 @@ private String buildRequestUrl(
return host + path + "?" + paramsNoSignature + "&api_signature=" + hexDigest;
}

/**
* Upload a video file from the local file system.
*
* @param uploadPath - the fully constructed upload url
* @param localFilePath - the path to the video file on the local file system.
* @return - JSON response from JW Platform API
* @throws JWPlatformException - API returned an exception
*/
private JSONObject uploadVideo(final String uploadPath, final String localFilePath)
throws JWPlatformException {
JSONObject response;
try {
HttpResponse<InputStream> r = Unirest.post(uploadPath)
.field("file", new File(localFilePath))
.asBinary();

final Reader reader = new InputStreamReader(r.getBody());
response = XML.toJSONObject(CharStreams.toString(reader));
} catch (final UnirestException | IOException e) {
throw new JWPlatformUnknownException(
String.format("Non-JSON response from server: %s", e.toString()));
}

final JSONObject responseBlock = response.getJSONObject("response");
final String status = responseBlock.getString("status");
if (status.toUpperCase().equals("ERROR")) {
final String errorType = responseBlock.getString("code");
final String message = responseBlock.getString("message");
MediaAPIExceptionFactory.throwJWPlatformException(
StringUtils.stripEnd(errorType, "Error"), message);
}

return response;
}

/**
* see {@link #request(String, Map, boolean, String)}.
*/
public JSONObject request(final String path) throws JWPlatformException {
return this.request(path, new HashMap<>());
}

/**
* see {@link #request(String, Map, boolean, String)}.
*/
public JSONObject request(final String path, final Map<String, String> params)
throws JWPlatformException {
return this.request(path, params, false,"Get");
}

/**
* see {@link #request(String, Map, boolean, String)}.
*/
public JSONObject request(final String path, final String requestType)
throws JWPlatformException {
return this.request(path, new HashMap<>(), false, requestType);
}

/**
* Send a request to the Management API of the JWPlatform.
*
* <p>This function generates an API signature, makes request to JWPlatform API and returns
* result.
*
* @param path - endpoint to be used in API request
* @param params - Parameters to be included in the request
* @param isBodyParams - Whether the parameters are to be included as query params or in
* the body of the request. This is only relevant for POST requests.
* @param requestType - The type of HTTP. Valid values are ["GET", "POST"].
* @return - JSON response from JW Platform API
* @throws JWPlatformException - JWPlatform API returned an exception. Because we dynamically
* build our exceptions, if you wish to retrieve the error message, you must call it
Expand All @@ -177,18 +234,47 @@ private String buildRequestUrl(
* Example: this will contain error message
* {@code e.getCause().getMessage()}
*/
public JSONObject request(final String path) throws JWPlatformException {
return this.request(path, new HashMap<>());
public JSONObject request(final String path, final Map<String, String> params,
final boolean isBodyParams, final String requestType)
throws JWPlatformException {
final String requestUrl;
final HttpResponse<JsonNode> response;
try {
switch (requestType.toUpperCase()) {
case "GET":
requestUrl = this.buildRequestUrl(host, path, params);
response = Unirest.get(requestUrl).asJson();
break;
case "POST":
if (isBodyParams) {
requestUrl = this.buildRequestUrl(host, path, Collections.emptyMap());
response = Unirest.post(requestUrl).body(new JSONObject(params)).asJson();
} else {
requestUrl = this.buildRequestUrl(host, path, params);
response = Unirest.post(requestUrl).asJson();
}
break;
default:
throw new JWPlatformException(String.format("%s is not a supported request type.", requestType));
}
checkForNon200Response(response);

return response.getBody().getObject();
} catch (final UnirestException e) {
throw new JWPlatformUnknownException(
String.format("Non-JSON response from server: %s", e.toString()));
}
}

/**
* Send a request to the Management API of the JWPlatform.
* Upload a video file for a video created with `sourcetype: file`.
*
* <p>This function generates an API signature, makes request to JWPlatform API and returns
* result.
* <p>The upload url is constructed from the {@code JSONObject} response object
* of the `videos/create` API call. If you do not have this object, you
* can supply the upload url yourself using {@link #upload(String, String)}.
*
* @param path - endpoint to be used in API request
* @param params - Parameters to be included in the request
* @param videosCreateResponse - the response object from a 'videos/create' API call.
* @param localFilePath - path to the video file on the local file system.
* @return - JSON response from JW Platform API
* @throws JWPlatformException - JWPlatform API returned an exception. Because we dynamically
* build our exceptions, if you wish to retrieve the error message, you must call it
Expand All @@ -200,10 +286,40 @@ public JSONObject request(final String path) throws JWPlatformException {
* Example: this will contain error message
* {@code e.getCause().getMessage()}
*/
public JSONObject request(final String path, final Map<String, String> params) throws JWPlatformException {
final String requestUrl = this.buildRequestUrl(host, path, params);
final GetRequest request = Unirest.get(requestUrl);
public JSONObject upload(final JSONObject videosCreateResponse, final String localFilePath)
throws JWPlatformException {
final JSONObject link = videosCreateResponse.getJSONObject("link");
final String path = link.getString("path");
final String protocol = link.getString("protocol");
final String address = link.getString("address");
final JSONObject query = link.getJSONObject("query");
final String key = query.getString("key");
final String token = query.getString("token");
final String uploadUrl =
protocol + "://" + address + path + "?api_format=xml&key=" + key + "&token=" + token;

return this.upload(uploadUrl, localFilePath);
}

return buildResponse(request).getBody().getObject();
/**
* Upload a video file for a video created with `sourcetype: file`.
*
* @param uploadPath - the fully constructed upload url. Refer to the JWPlatform documentation for
* instructions on how to build the url.
* @param localFilePath - path to the video file on the local file system.
* @return - JSON response from JW Platform API
* @throws JWPlatformException - JWPlatform API returned an exception. Because we dynamically
* build our exceptions, if you wish to retrieve the error message, you must call it
* from the cause, not the exception directly. The exception's message will be {@code null}.
*
* Example: this will be {@code null}
* {@code e.getMessage()}
*
* Example: this will contain error message
* {@code e.getCause().getMessage()}
*/
public JSONObject upload(final String uploadPath, final String localFilePath)
throws JWPlatformException {
return uploadVideo(uploadPath, localFilePath);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformApiKeyInvalidException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformApiKeyMissingException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformCallFailedException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformCallInvalidException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformCallUnavailableException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformDatabaseException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformDigestInvalidException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformDigestMissingException extends JWPlatformException {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.jwplayer.jwplatform.exception;

public class JWPlatformFileSizeInvalidException extends JWPlatformException {
}
Loading

0 comments on commit b6655ce

Please sign in to comment.