From 5f892481443b54ee7ee654dd5b0cb6ce9d0728bd Mon Sep 17 00:00:00 2001 From: pablo-kropilnicki Date: Fri, 30 Nov 2018 09:58:07 -0500 Subject: [PATCH 1/5] Update for 5.5.1 develop merge --- current/core/pom.xml | 4 +- .../brightcove/wrapper/BrightcoveAPI.java | 11 +- .../brightcove/wrapper/api/CmsAPI.java | 2 +- .../brightcove/wrapper/objects/Account.java | 1 + .../brightcove/wrapper/objects/Platform.java | 34 +- .../sling/ConfigurationServiceImpl.java | 17 +- .../brightcove/wrapper/sling/ServiceUtil.java | 24 +- .../wrapper/utils/HttpServices.java | 193 ++- .../wrapper/utils/S3UploadUtil.java | 146 +- .../webservices/AssetPropertyIntegrator.java | 25 +- .../wrapper/webservices/BrcApi.java | 88 +- .../tests/impl/TestBrightcoveModels.java | 51 + .../brightcove/wrapper/APITest.java | 1286 +++++++++++++++++ current/pom.xml | 14 +- current/ui.apps/pom.xml | 6 +- .../brightcoveadmin/clientlibs/js/brcUI.js | 12 + 16 files changed, 1739 insertions(+), 175 deletions(-) create mode 100755 current/core/src/test/java/com/coresecure/brightcove/tests/impl/TestBrightcoveModels.java create mode 100644 current/core/src/test/java/com/coresecure/brightcove/wrapper/APITest.java diff --git a/current/core/pom.xml b/current/core/pom.xml index 49d5474..5aa6164 100644 --- a/current/core/pom.xml +++ b/current/core/pom.xml @@ -51,7 +51,7 @@ com.coresecure.brightcove.cq5 brightcove_connector - 5.5.0 + 5.5.1-SNAPSHOT ../pom.xml brightcove-services @@ -383,4 +383,4 @@ test - + \ No newline at end of file diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/BrightcoveAPI.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/BrightcoveAPI.java index 10afdd3..6f81d31 100755 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/BrightcoveAPI.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/BrightcoveAPI.java @@ -47,9 +47,10 @@ public class BrightcoveAPI { public final CmsAPI cms; private static final Logger LOGGER = LoggerFactory.getLogger(BrightcoveAPI.class); - public BrightcoveAPI(String aClientId, String aClientSecret, String aAccountId) { + public BrightcoveAPI(String aClientId, String aClientSecret, String aAccountId, String proxy) { LOGGER.debug("BrightcoveAPI Init aAccount_id {}", aAccountId); platform = new Platform(); + platform.setProxy(proxy); account = new Account(platform, aClientId, aClientSecret, aAccountId); cms = new CmsAPI(account); } @@ -60,14 +61,10 @@ public BrightcoveAPI(String key) { ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); ConfigurationService brcService = cg.getConfigurationService(key); - if (brcService.getProxy()!=null && brcService.getProxy().length()>0) { - setProxy(brcService.getProxy()); - } + platform.setProxy(brcService.getProxy()); + account = new Account(platform, brcService.getClientID(), brcService.getClientSecret(), brcService.getAccountID()); cms = new CmsAPI(account); } - public void setProxy(String proxy) { - platform.setProxy(proxy); - } } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/CmsAPI.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/CmsAPI.java index 77942cb..abfc666 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/CmsAPI.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/CmsAPI.java @@ -433,7 +433,7 @@ public JSONArray getVideos(String q, int limit, int offset, String sort, boolean if (!response.isEmpty()) { json = JsonReader.readJsonArrayFromString(response); LOGGER.debug(Constants.RESPONSE, response); - LOGGER.debug("json {}", json); +// LOGGER.trace("json {}", json); } else if (!q.isEmpty() && NumberUtils.isNumber(q)) { json.put(getVideo(q)); } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Account.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Account.java index 39f9a92..b7ad311 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Account.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Account.java @@ -54,6 +54,7 @@ public class Account { public final Platform platform; private static final Logger LOGGER = LoggerFactory.getLogger(Account.class); + public Account(Platform aPlatform, String aClient_id, String aClient_secret, String aAccount_id) { client_id = aClient_id; client_secret = aClient_secret; diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Platform.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Platform.java index 6f938c6..a4f61f5 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Platform.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Platform.java @@ -50,12 +50,10 @@ public class Platform { private final String PLAYERS_API_Url; private final String API_Url; private final String DI_API_Url; - private Proxy PROXY = Proxy.NO_PROXY; private static final Logger LOGGER = LoggerFactory.getLogger(Platform.class); - public Platform() - { - this(null,null,null,null); + public Platform() { + this(null, null, null, null); } public Platform(String aOAUTH_Url, String aAPI_Url, String aDI_API_Url, String aPLAYERS_API_Url) { @@ -83,6 +81,7 @@ public String getDI_API_Url() { public String getAPI(String targetURL, String urlParameters, Map headers) { String URL = getAPI_Url() + targetURL; + LOGGER.info("getAPI: " + URL); String response = HttpServices.executeGet(URL, urlParameters, headers); return response; } @@ -95,7 +94,7 @@ public String getPLAYERS_API(String targetURL, String urlParameters, Map headers) { String URL = getAPI_Url() + targetURL; - LOGGER.trace("POST URL: "+URL); + LOGGER.trace("POST URL: " + URL); String response = HttpServices.executePost(URL, payload, headers); LOGGER.trace(response); @@ -112,7 +111,7 @@ public String patchAPI(String targetURL, String payload, Map hea public String postDI_API(String targetURL, String payload, Map headers) { String URL = getDI_API_Url() + targetURL; - LOGGER.trace("postDI_API: "+URL); + LOGGER.trace("postDI_API: " + URL); String response = HttpServices.executePost(URL, payload, headers); LOGGER.trace(response); return response; @@ -120,7 +119,7 @@ public String postDI_API(String targetURL, String payload, Map h public String getDI_API(String targetURL, String payload, Map headers) { String URL = getDI_API_Url() + targetURL; - LOGGER.trace("getDI_API: "+URL); + LOGGER.trace("getDI_API: " + URL); String response = HttpServices.executeGet(URL, payload, headers); LOGGER.trace(response); return response; @@ -128,7 +127,7 @@ public String getDI_API(String targetURL, String payload, Map he public String postDIRequest_API(String targetURL, String payload, Map headers) { String URL = getDI_API_Url() + targetURL; - LOGGER.trace("postDI_API: "+URL); + LOGGER.trace("postDI_API: " + URL); String response = HttpServices.executePost(URL, payload, headers, JSONResponse.RESPONSE_CONTENT_TYPE); LOGGER.trace(response); return response; @@ -136,7 +135,7 @@ public String postDIRequest_API(String targetURL, String payload, Map headers) { String URL = getAPI_Url() + targetURL; - LOGGER.trace("deleteAPI: "+URL); + LOGGER.trace("deleteAPI: " + URL); String response = HttpServices.executeDelete(URL, headers); LOGGER.trace(response); return response; @@ -144,15 +143,16 @@ public String deleteAPI(String targetURL, String videoID, Map he public void setProxy(String proxy) { - Proxy newProxy = Proxy.NO_PROXY; - - if(proxy!=null) { - String[] parts = proxy.split(":"); - if (parts.length==2) { - PROXY = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(parts[0], Integer.parseInt(parts[1]))); + LOGGER.info("setProxy: " + proxy); + Proxy newProxy = Proxy.NO_PROXY; + + if (proxy != null) { + String[] parts = proxy.split(":"); + if (parts.length == 2) { + newProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(parts[0], Integer.parseInt(parts[1]))); + } } - } - HttpServices.setProxy(PROXY); + HttpServices.setProxy(newProxy); } } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationServiceImpl.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationServiceImpl.java index 5815fe8..8140c89 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationServiceImpl.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationServiceImpl.java @@ -61,7 +61,7 @@ @Property(name = "allowed_groups", label = "Allowed Groups", description = "Groups that are allowed to see this account data", value = {"", ""}), @Property(name = "playersstore", label = "Players Store Path", description = "Path of the players store locatione", value = "/content/brightcovetools/players"), @Property(name = "defVideoPlayerID", label = "Default Video Player ID", description = "Default Video Player ID", value = "default"), - @Property(name = "defVideoPlayerKey", label="Default Video Player Key", description="Default Video Player Key - DEPRECATED", value=""), + @Property(name = "defVideoPlayerKey", label = "Default Video Player Key", description = "Default Video Player Key - DEPRECATED", value = ""), @Property(name = "defPlaylistPlayerID", label = "Default Playlist Player ID", description = "Default Playlist Player ID", value = "default"), @Property(name = "defPlaylistPlayerKey", label = "Default Playlist Player Key", description = "Default Playlist Player Key - DEPRECATED", value = ""), @Property(name = "proxy", label = "Proxy server", description = "Proxy server in the form proxy.foo.com:3128", value = {""}), @@ -83,11 +83,20 @@ private Dictionary getProperties() { } @Activate + @Modified void activate(ComponentContext aComponentContext) { + loggerVar.info("activate"); this.componentContext = aComponentContext; this.prop = componentContext.getProperties(); + loggerVar.debug(componentContext.getProperties().toString()); } + @Deactivate + void deactivate(ComponentContext aComponentContext) { + loggerVar.info("deactivate"); + } + + public String getClientID() { return (String) getProperties().get("client_id"); } @@ -151,7 +160,9 @@ public List getAllowedGroupsList() { public String getProxy() { - return (String) getProperties().get("proxy"); + String proxy = (String) getProperties().get("proxy"); + loggerVar.debug("getProxy() " + proxy); + return proxy; } public String getIngestProfile() { @@ -173,7 +184,7 @@ private String[] cleanStringArray(String[] input) { } - private boolean isValidPath(String filePathString){ + private boolean isValidPath(String filePathString) { Path path = Paths.get(filePathString); return Files.exists(path); } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ServiceUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ServiceUtil.java index 8544634..09c24b7 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ServiceUtil.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ServiceUtil.java @@ -36,6 +36,7 @@ import com.coresecure.brightcove.wrapper.enums.EconomicsEnum; import com.coresecure.brightcove.wrapper.objects.*; import com.coresecure.brightcove.wrapper.utils.Constants; +import com.coresecure.brightcove.wrapper.utils.HttpServices; import com.coresecure.brightcove.wrapper.utils.JcrUtil; import com.coresecure.brightcove.wrapper.utils.S3UploadUtil; import com.day.cq.commons.jcr.JcrConstants; @@ -485,15 +486,22 @@ public JSONObject createVideoS3(Video aVideo, String filename, InputStream is) { result.put(Constants.OBJECT_KEY, videoIngested.get(Constants.OBJECT_KEY)); result.put(Constants.API_REQUEST_URL, videoIngested.get(Constants.API_REQUEST_URL)); result.put(Constants.SIGNED_URL, videoIngested.get(Constants.SIGNED_URL)); - boolean sent = S3UploadUtil.uploadToUrl(new URL(videoIngested.getString(Constants.SIGNED_URL)), is); + + ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); + ConfigurationService brcService = cg.getConfigurationService(account_id); + String proxy_address = brcService.getProxy(); + + LOGGER.trace("******CREATE ASSET s3 [ 1 ] " + proxy_address); + + boolean sent = S3UploadUtil.uploadToUrl(new URL(videoIngested.getString(Constants.SIGNED_URL)), is , HttpServices.getProxy()); result.put(Constants.SENT, sent); if (!sent) { brAPI.cms.deleteVideo(newVideoId); } else { - ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); - ConfigurationService brcService = cg.getConfigurationService(account_id); + cg = ServiceUtil.getConfigurationGrabber(); + brcService = cg.getConfigurationService(account_id); String ingest_profile = brcService.getIngestProfile(); result.put("job", brAPI.cms.requestIngestURL(newVideoId, ingest_profile, videoIngested.getString(Constants.API_REQUEST_URL), true)); } @@ -521,7 +529,15 @@ public JSONObject createAssetS3(String newVideoId, String filename, InputStream result.put(Constants.OBJECT_KEY, assetIngested.get(Constants.OBJECT_KEY)); result.put(Constants.API_REQUEST_URL, assetIngested.get(Constants.API_REQUEST_URL)); result.put(Constants.SIGNED_URL, assetIngested.get(Constants.SIGNED_URL)); - boolean sent = S3UploadUtil.uploadToUrl(new URL(assetIngested.getString(Constants.SIGNED_URL)), is); + + + ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); + ConfigurationService brcService = cg.getConfigurationService(account_id); + String proxy_address = brcService.getProxy(); + + LOGGER.trace("******CREATE ASSET s3 [ 2 ] " + proxy_address); + + boolean sent = S3UploadUtil.uploadToUrl(new URL(assetIngested.getString(Constants.SIGNED_URL)), is , HttpServices.getProxy()); result.put(Constants.SENT, sent); } catch (Exception e) { LOGGER.error(e.getClass().getName(), e); diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/HttpServices.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/HttpServices.java index 02f8399..660c55d 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/HttpServices.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/HttpServices.java @@ -34,9 +34,11 @@ import com.coresecure.brightcove.wrapper.objects.BinaryObj; import com.coresecure.brightcove.wrapper.sling.CertificateListService; +import org.apache.commons.codec.Encoder; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.webdav.DavMethods; +import org.apache.sling.commons.json.JSONArray; import org.apache.sling.commons.json.JSONException; import org.apache.sling.commons.json.JSONObject; import org.apache.sling.servlets.post.JSONResponse; @@ -56,6 +58,7 @@ import java.net.Proxy; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -75,6 +78,7 @@ public class HttpServices { public static void setProxy(Proxy proxy) { + LOGGER.info("setProxy: " + proxy.toString()); if (proxy == null) { PROXY = Proxy.NO_PROXY; } else { @@ -82,8 +86,13 @@ public static void setProxy(Proxy proxy) { } } + public static Proxy getProxy() { + return PROXY; + } + public static String executeDelete(String targetURL, - Map headers) { + Map headers) { + LOGGER.debug("executeDelete: " + targetURL); URL url; HttpsURLConnection connection = null; String payload = "{}"; @@ -108,7 +117,8 @@ public static String executeDelete(String targetURL, // Send request wr = new DataOutputStream(connection.getOutputStream()); - wr.writeBytes(payload); + wr.write(payload.getBytes("UTF-8")); +// wr.writeBytes(payload); // Get Response LOGGER.debug("getResponseCode: " + connection.getResponseCode()); @@ -124,11 +134,11 @@ public static String executeDelete(String targetURL, } delResponse = response.toString(); } else { - delResponse= "{'error_code':"+connection.getResponseCode()+",'message':'"+connection.getResponseMessage()+"'}"; + delResponse = "{'error_code':" + connection.getResponseCode() + ",'message':'" + connection.getResponseMessage() + "'}"; } } catch (Exception e) { LOGGER.error(Constants.ERROR_LOG_TMPL, e); - delResponse= "{'error_code':-1,'message':'Exception in executeDelete'}"; + delResponse = "{'error_code':-1,'message':'Exception in executeDelete'}"; } finally { @@ -157,27 +167,33 @@ public static String executeDelete(String targetURL, } public static String executePost(String targetURL, String payload, - Map headers) { + Map headers) { return executePost(targetURL, payload, - headers, "application/x-www-form-urlencoded"); + headers, "application/x-www-form-urlencoded"); } + public static String executePost(String targetURL, String payload, Map headers, String contentType) { + LOGGER.info("executePost: " + targetURL); URL url; HttpsURLConnection connection = null; String exPostResponse = null; BufferedReader rd = null; DataOutputStream wr = null; + JSONObject responseJSON = new JSONObject(); + try { // Create connection url = new URL(targetURL.replaceAll(" ", "%20")); - LOGGER.debug("URL :"+targetURL); - LOGGER.debug("payload :"+payload); + LOGGER.debug("URL :" + targetURL); + LOGGER.debug("payload :" + payload); connection = getSSLConnection(url, targetURL); + LOGGER.debug("is proxy valid? :" + PROXY.toString()); connection = (HttpsURLConnection) url.openConnection(PROXY); + connection.setRequestMethod(DavMethods.METHOD_POST); connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER, contentType); @@ -194,14 +210,23 @@ public static String executePost(String targetURL, String payload, // Send request wr = new DataOutputStream(connection.getOutputStream()); - wr.writeBytes(payload); + wr.write(payload.getBytes("UTF-8")); + // wr.writeBytes(payload); + //Todo: Revise - // Get Response - if (connection.getResponseCode() < 400) - { - InputStream is = connection.getInputStream(); + InputStream is; + + if (connection.getResponseCode() != 200 && connection.getResponseCode() != 201) { + is = connection.getErrorStream(); + } else { + is = connection.getInputStream(); + + } + + + if (is != null) { rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); @@ -211,21 +236,31 @@ public static String executePost(String targetURL, String payload, } exPostResponse = response.toString(); - } - else if (connection.getResponseCode() == 422) - { - exPostResponse = "{\"error\":422}"; - } - else if (connection.getResponseCode() == 409) - { - exPostResponse = "{\"error\":409}"; - } - else { - LOGGER.debug("getResponseCode: {} getResponseMessage: {}" ,connection.getResponseCode(), connection.getResponseMessage()); + LOGGER.trace("exPostResponse >>>" + exPostResponse); + + if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) { + //CORRECT ADDITION OF THE REQUEST BODY + responseJSON = new JSONObject(exPostResponse); + responseJSON.put("error", connection.getResponseCode()); + } else { + + JSONArray errorArray = new JSONArray(exPostResponse); + responseJSON = new JSONObject(); + responseJSON.put("error", errorArray.getJSONObject(0).has("error_code") ? errorArray.getJSONObject(0).get("error_code") : "DefaultError"); + responseJSON.put("error_message", errorArray.getJSONObject(0).has("message") ? errorArray.getJSONObject(0).get("message") : "Default Message"); + } + + LOGGER.debug(String.format("getResponseCode: %s getResponseMessage: %s getResponseJSON: %s", connection.getResponseCode(), connection.getResponseMessage(), responseJSON.toString())); + } else { + throw new Exception("**** Input Stream Coming Back is Null"); + } + LOGGER.debug(String.format("getResponseCode: %s getResponseMessage: %s getResponseJSON: %s", connection.getResponseCode(), connection.getResponseMessage(), responseJSON.toString())); + + } catch (Exception e) { - LOGGER.error(Constants.ERROR_LOG_TMPL, e); + LOGGER.error("*** Connection Error * Check Connection / Proxy Configuration", e); } finally { if (connection != null) { @@ -236,7 +271,7 @@ else if (connection.getResponseCode() == 409) try { rd.close(); } catch (IOException e) { - LOGGER.error(e.getClass().getName(),e); + LOGGER.error(e.getClass().getName(), e); } } if (null != wr) { @@ -244,33 +279,36 @@ else if (connection.getResponseCode() == 409) wr.flush(); wr.close(); } catch (IOException e) { - LOGGER.error(e.getClass().getName(),e); + LOGGER.error(e.getClass().getName(), e); } } } - LOGGER.debug("exPostResponse[1]: {}", exPostResponse); - - return exPostResponse; + LOGGER.debug("finally - > exPostResponse[1]: {}", responseJSON.toString()); + return responseJSON.toString(); } + public static String executePatch(String targetURL, String payload, - Map headers) { + Map headers) { + LOGGER.debug("executePatch - START: " + targetURL); URL url; HttpsURLConnection connection = null; - String exPostResponse = null; + String exPatchResponse = null; BufferedReader rd = null; DataOutputStream wr = null; + boolean isError = true; try { + // Create connection url = new URL(targetURL.replaceAll(" ", "%20")); - LOGGER.debug("URL :"+targetURL); - LOGGER.debug("payload :"+payload); + LOGGER.debug("URL :" + targetURL); + LOGGER.debug("payload :" + payload); connection = getSSLConnection(url, targetURL); connection = (HttpsURLConnection) url.openConnection(PROXY); connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); - setRequestMethod(connection,"PATCH"); + setRequestMethod(connection, "PATCH"); connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER, JSONResponse.RESPONSE_CONTENT_TYPE); for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); @@ -281,26 +319,30 @@ public static String executePatch(String targetURL, String payload, // Send request wr = new DataOutputStream(connection.getOutputStream()); - wr.writeBytes(payload); + wr.write(payload.getBytes("UTF-8")); + // wr.writeBytes(payload); - if (200 == connection.getResponseCode()) { - InputStream is = connection.getInputStream(); - rd = new BufferedReader(new InputStreamReader(is)); - String line; - StringBuffer response = new StringBuffer(); - while ((line = rd.readLine()) != null) { - response.append(line); - response.append("\r\n"); - } - exPostResponse = response.toString(); + if (200 == connection.getResponseCode()) { + isError = false; } else { - LOGGER.debug("getResponseCode: {} {}",connection.getResponseCode() ,connection.getResponseMessage()); + LOGGER.debug("getResponseCode: {} {}", connection.getResponseCode(), connection.getResponseMessage()); + } + InputStream is = connection.getInputStream(); + rd = new BufferedReader(new InputStreamReader(is)); + String line; + StringBuffer response = new StringBuffer(); + while ((line = rd.readLine()) != null) { + response.append(line); + response.append("\r\n"); } - LOGGER.debug("exPostResponse[2]: {}" , exPostResponse); + + exPatchResponse = response.toString(); + + LOGGER.debug("exPatchResponse[2]: {}", exPatchResponse); } catch (Exception e) { - LOGGER.error(Constants.ERROR_LOG_TMPL,e); + LOGGER.error(Constants.ERROR_LOG_TMPL, e); } finally { @@ -312,7 +354,7 @@ public static String executePatch(String targetURL, String payload, try { rd.close(); } catch (IOException e) { - LOGGER.error(Constants.ERROR_LOG_TMPL,e); + LOGGER.error(Constants.ERROR_LOG_TMPL, e); } } if (null != wr) { @@ -325,8 +367,11 @@ public static String executePatch(String targetURL, String payload, } } } - return exPostResponse; + + LOGGER.debug("executePatch - END"); + return exPatchResponse; } + private static void setRequestMethod(final HttpURLConnection c, final String value) { try { final Object target; @@ -340,14 +385,15 @@ private static void setRequestMethod(final HttpURLConnection c, final String val final Field f = HttpURLConnection.class.getDeclaredField("method"); f.setAccessible(true); f.set(target, value); - } catch (IllegalAccessException ex){ + } catch (IllegalAccessException ex) { throw new AssertionError(ex); - } catch ( NoSuchFieldException ex){ + } catch (NoSuchFieldException ex) { throw new AssertionError(ex); } } + public static String executeGet(String targetURL, String urlParameters, - Map headers) { + Map headers) { String exGetResponse = null; try { JSONObject response = executeFullGet(targetURL, urlParameters, headers); @@ -358,8 +404,10 @@ public static String executeGet(String targetURL, String urlParameters, } return exGetResponse; } + public static JSONObject executeFullGet(String targetURL, String urlParameters, Map headers) { + LOGGER.debug("executeFullGet: " + targetURL); URL url; URLConnection connection = null; @@ -367,10 +415,10 @@ public static JSONObject executeFullGet(String targetURL, String urlParameters, try { // Create connection url = new URL(targetURL.replaceAll(" ", "%20") + "?" + urlParameters); - LOGGER.trace("url: "+targetURL + "?" + urlParameters+" Protocol:"+url.getProtocol()); + LOGGER.trace("url: " + targetURL + "?" + urlParameters + " Protocol:" + url.getProtocol()); if ("http".equals(url.getProtocol())) { connection = getSSLConnection(url, targetURL, HttpURLConnection.class); - }else { + } else { connection = getSSLConnection(url, targetURL, HttpsURLConnection.class); } @@ -381,7 +429,7 @@ public static JSONObject executeFullGet(String targetURL, String urlParameters, connection.setRequestProperty(Constants.CONTENT_LANGUAGE_HEADER, Constants.CONTENT_LANGUAGE_LOCALITY); for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); - LOGGER.trace("-H \""+key+": "+headers.get(key)+"\""); + LOGGER.trace("-H \"" + key + ": " + headers.get(key) + "\""); } connection.setUseCaches(false); connection.setDoInput(true); @@ -400,8 +448,8 @@ public static JSONObject executeFullGet(String targetURL, String urlParameters, } LOGGER.trace("response committed!"); - exGetResponse.put(Constants.RESPONSE,new String(response.toByteArray(), "UTF-8")); - exGetResponse.put(Constants.BINARY,response.toByteArray()); + exGetResponse.put(Constants.RESPONSE, new String(response.toByteArray(), "UTF-8")); + exGetResponse.put(Constants.BINARY, response.toByteArray()); exGetResponse.put(Constants.MIME_TYPE, connection.getContentType()); } catch (Exception e) { LOGGER.error(Constants.ERROR_LOG_TMPL, e); @@ -429,6 +477,7 @@ private static HttpsURLConnection getSSLConnection(URL url, String targetURL) th private static T getSSLConnection(URL url, String targetURL, Class classType) throws IOException { + LOGGER.debug("getSSLConnection: " + targetURL + " PROXY: " + PROXY.toString()); T connection = (T) url.openConnection(PROXY); try { @@ -451,8 +500,7 @@ private static T getSSLConnection(URL url, String targetURL, Class classT } } - } catch (Exception e) - { + } catch (Exception e) { LOGGER.error(e.getClass().getName(), e); } @@ -503,9 +551,7 @@ private static CertificateListService getServiceReference() { .getService(osgiRef); } } - } - catch (Exception e) - { + } catch (Exception e) { LOGGER.error(e.getClass().getName(), e); } return serviceRef; @@ -549,19 +595,19 @@ private static SSLContext getSSlContext(String certPath) { } catch (IOException ioe) { LOGGER.error(ioe.getClass().getName(), ioe); } catch (NoSuchAlgorithmException nae) { - LOGGER.error(nae.getClass().getName(),nae); + LOGGER.error(nae.getClass().getName(), nae); } catch (KeyStoreException kse) { - LOGGER.error(kse.getClass().getName(),kse); + LOGGER.error(kse.getClass().getName(), kse); } catch (CertificateException ce) { - LOGGER.error(ce.getClass().getName(),ce); + LOGGER.error(ce.getClass().getName(), ce); } catch (KeyManagementException ke) { - LOGGER.error(ke.getClass().getName(),ke); + LOGGER.error(ke.getClass().getName(), ke); } finally { if (null != caInput) { try { caInput.close(); } catch (IOException ioe) { - LOGGER.error(ioe.getClass().getName(),ioe); + LOGGER.error(ioe.getClass().getName(), ioe); } } } @@ -569,18 +615,19 @@ private static SSLContext getSSlContext(String certPath) { return context; } - public static boolean isLocalPath(String path){ + public static boolean isLocalPath(String path) { return path.startsWith("/") && !path.startsWith("//"); } public static BinaryObj getRemoteBinary(String path, String urlParameters, Map headers) throws JSONException { + LOGGER.debug("getRemoteBinary: " + path); BinaryObj binary = new BinaryObj(); - JSONObject get_response = HttpServices.executeFullGet(path, urlParameters, headers!= null ? headers :new HashMap()); + JSONObject get_response = HttpServices.executeFullGet(path, urlParameters, headers != null ? headers : new HashMap()); if (get_response != null && get_response.has(Constants.BINARY)) { InputStream binarystream = new ByteArrayInputStream((byte[]) get_response.get(Constants.BINARY)); String mime_type = get_response.getString(Constants.MIME_TYPE); //< SET MIME TYPE - binary = new BinaryObj(binarystream,mime_type); + binary = new BinaryObj(binarystream, mime_type); } return binary; } -} +} \ No newline at end of file diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/S3UploadUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/S3UploadUtil.java index f305b84..4b7679d 100644 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/S3UploadUtil.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/S3UploadUtil.java @@ -32,20 +32,39 @@ */ package com.coresecure.brightcove.wrapper.utils; +import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber; +import com.coresecure.brightcove.wrapper.sling.ConfigurationService; +import com.coresecure.brightcove.wrapper.sling.ServiceUtil; +import org.apache.sling.api.SlingHttpServletRequest; +import org.apache.sling.api.SlingHttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.ServletException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; /** * Created by alessandro.bonfatti on 7/14/17. */ public class S3UploadUtil { + private transient ServiceUtil serviceUtil = null; + private transient ConfigurationGrabber cg; + private transient com.coresecure.brightcove.wrapper.BrightcoveAPI brAPI; + private List allowedGroups = new ArrayList(); + private transient ConfigurationService cs; + + public S3UploadUtil() {/* default implementation ignored */} static int BUFFER_SIZE = 4096; @@ -53,9 +72,12 @@ public S3UploadUtil() {/* default implementation ignored */} public static boolean uploadToUrl(URL url, InputStream inputStream) { - HttpURLConnection connection; int responseCode = 0; try { + HttpURLConnection connection; + + + //UNCOMMENT FOR REGULAR CONNECTION connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); @@ -91,4 +113,126 @@ public static boolean uploadToUrl(URL url, InputStream inputStream) { return responseCode == 200; } + + + public static boolean uploadToUrl(URL url, InputStream inputStream, String proxy_address) { + + LOGGER.trace("*** INPUT PROXY ADDRESS ***" + proxy_address); + + + String _host = ""; + int _port = 0; + if(!proxy_address.isEmpty() && proxy_address.contains(":")) + { + _host = proxy_address.split(":")[0]; + _port = Integer.parseInt(proxy_address.split(":")[1]); + } + + LOGGER.trace("*** PROCESSED ADDRESS: " + _host + ":" + _port); + + int responseCode = 0; + try { + + HttpURLConnection connection; + //MANUAL PROXY ADDITION + //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.11.89", 3128)); + + + LOGGER.trace("***>>>" + proxy_address); + + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(_host, _port)); + connection = proxy!=null ? (HttpsURLConnection) url.openConnection(proxy) : (HttpURLConnection) url.openConnection(); + + //UNCOMMENT FOR REGULAR CONNECTION + // connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + connection.setRequestMethod("PUT"); + OutputStream out = connection.getOutputStream(); + + byte[] buf = new byte[1024]; + int count; + int total = 0; + + while ((count =inputStream.read(buf)) != -1) + { + if (Thread.interrupted()) + { + throw new IOException(); + } + out.write(buf, 0, count); + total += count; + + LOGGER.trace(String.format("bytes: %d", total)); + } + out.close(); + inputStream.close(); + + LOGGER.debug("Finishing..."); + responseCode = connection.getResponseCode(); + + if (responseCode == 200) { + LOGGER.info("Successfully uploaded."); + } + } catch (IOException e) { + LOGGER.error("IOException",e); + } + return responseCode == 200; + + } + + + + public static boolean uploadToUrl(URL url, InputStream inputStream, Proxy proxy) { + + LOGGER.trace("*** INPUT PROXY ADDRESS ***" + proxy.toString()); + + + int responseCode = 0; + try { + + HttpURLConnection connection; + //MANUAL PROXY ADDITION + //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.11.89", 3128)); + connection = proxy!=null ? (HttpsURLConnection) url.openConnection(proxy) : (HttpURLConnection) url.openConnection(); + + //UNCOMMENT FOR REGULAR CONNECTION + // connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + connection.setRequestMethod("PUT"); + OutputStream out = connection.getOutputStream(); + + byte[] buf = new byte[1024]; + int count; + int total = 0; + + while ((count =inputStream.read(buf)) != -1) + { + if (Thread.interrupted()) + { + throw new IOException(); + } + out.write(buf, 0, count); + total += count; + + LOGGER.trace(String.format("bytes: %d", total)); + } + out.close(); + inputStream.close(); + + LOGGER.debug("Finishing..."); + responseCode = connection.getResponseCode(); + + if (responseCode == 200) { + LOGGER.info("Successfully uploaded."); + } + } catch (IOException e) { + LOGGER.error("IOException",e); + } + return responseCode == 200; + + } + + + + } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/AssetPropertyIntegrator.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/AssetPropertyIntegrator.java index 97184ef..0b3e4ef 100755 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/AssetPropertyIntegrator.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/AssetPropertyIntegrator.java @@ -91,21 +91,18 @@ protected void doPost(final SlingHttpServletRequest req, final SlingHttpServletR executeRequest(req, resp); } - private void executeRequest(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) - { + private void executeRequest(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) { //INITIALIZING THE RESOURCE RESOLVER ExecutorService executor = Executors.newFixedThreadPool(assetIntegratorCronBundle.getMaxThreadNum()); List> list = new ArrayList>(); LOGGER.trace("BRIGHTCOVE ASSET INTEGRATION - SYNCHRONIZING DATABASE"); - try - { + try { //MAIN TRY - CONFIGURATION GRAB SERVICE ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); //GETCONFIG SERVICE Set services = cg.getAvailableServices(); //BUILD SERVICES - for(String requestedAccount: services) - { + for (String requestedAccount : services) { final String requestedServiceAccount = requestedAccount; //GET CURRENT CONFIGURATION ConfigurationService cs = cg.getConfigurationService(requestedAccount); @@ -156,24 +153,22 @@ private void executeRequest(final SlingHttpServletRequest req, final SlingHttpSe } + } catch (Exception e) { + LOGGER.error("ERROR", e); } - catch (Exception e) - { - LOGGER.error("ERROR" , e); - } - for(Future fut : list){ + for (Future fut : list) { try { - LOGGER.trace(new Date()+ "::"+fut.get()); + LOGGER.trace(new Date() + "::" + fut.get()); } catch (Exception e) { - LOGGER.error("ERROR" , e); + LOGGER.error("ERROR", e); } } //shut down the executor service now executor.shutdown(); } + @Override - protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException - { + protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { executeRequest(req, resp); } diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcApi.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcApi.java index eeb081a..670a41e 100755 --- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcApi.java +++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcApi.java @@ -75,7 +75,7 @@ @Service @Component @Properties(value = { - @Property(name = "sling.servlet.extensions", value = {"json","js"}), + @Property(name = "sling.servlet.extensions", value = {"json", "js"}), @Property(name = "sling.servlet.paths", value = "/bin/brightcove/api") }) public class BrcApi extends SlingAllMethodsServlet { @@ -86,6 +86,7 @@ public class BrcApi extends SlingAllMethodsServlet { private transient com.coresecure.brightcove.wrapper.BrightcoveAPI brAPI; private List allowedGroups = new ArrayList(); private transient ConfigurationService cs; + @Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); @@ -93,20 +94,18 @@ protected void doPost(final SlingHttpServletRequest request, final SlingHttpServ @Override protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { - executeRequest(request,response); + executeRequest(request, response); } - private boolean getServices( SlingHttpServletRequest request) { + private boolean getServices(SlingHttpServletRequest request) { + LOGGER.info("getServices"); boolean result = false; String requestedAccount = AccountUtil.getSelectedAccount(request); Set services = cg.getAvailableServices(request); if (services.contains(requestedAccount)) { cs = cg.getConfigurationService(requestedAccount); - brAPI = new com.coresecure.brightcove.wrapper.BrightcoveAPI(cs.getClientID(), cs.getClientSecret(), requestedAccount); + brAPI = new com.coresecure.brightcove.wrapper.BrightcoveAPI(cs.getClientID(), cs.getClientSecret(), requestedAccount, cs.getProxy()); serviceUtil = new ServiceUtil(requestedAccount); - if (cs.getProxy() != null && cs.getProxy().length() > 0) { - brAPI.setProxy(cs.getProxy()); - } result = true; } return result; @@ -179,6 +178,7 @@ private JSONObject getListPlaylists(SlingHttpServletRequest request) throws JSON } return result; } + private JSONObject searchVideos(SlingHttpServletRequest request) throws JSONException { JSONObject result = new JSONObject(); LOGGER.debug("query: " + request.getParameter(Constants.QUERY)); @@ -206,6 +206,7 @@ private JSONObject searchVideos(SlingHttpServletRequest request) throws JSONExce } return result; } + private JSONObject searchPlaylist(SlingHttpServletRequest request) throws JSONException { JSONObject result = new JSONObject(); if ("true".equals(request.getParameter("isID"))) { @@ -229,6 +230,7 @@ private JSONObject searchPlaylist(SlingHttpServletRequest request) throws JSONEx } return result; } + private JSONObject deleteVideo(SlingHttpServletRequest request) throws JSONException { JSONObject result = new JSONObject(); String[] ids = request.getParameter(Constants.QUERY).split(","); @@ -243,9 +245,10 @@ private JSONObject deleteVideo(SlingHttpServletRequest request) throws JSONExcep result = new JSONObject(serviceUtil.searchVideo("", Integer.parseInt(request.getParameter(Constants.START)), Integer.parseInt(request.getParameter(Constants.LIMIT)), request.getParameter(Constants.SORT))); return result; } + private JSONObject createPlaylist(SlingHttpServletRequest request) throws JSONException { JSONObject result = new JSONObject(); - RequestParameter requestParameter = request.getRequestParameter(Constants.PLST); + RequestParameter requestParameter = request.getRequestParameter(Constants.PLST); if (requestParameter == null) { result.put(Constants.ERROR, 500); return result; @@ -272,19 +275,17 @@ private JSONObject createPlaylist(SlingHttpServletRequest request) throws JSONEx playlist.setVideoIds(videoIDs); JSONObject videoItem = brAPI.cms.createPlaylist(playlist); LOGGER.info("New Playlist id: " + videoItem.toString(1)); - if (!videoItem.has(Constants.ID)) - { + if (!videoItem.has(Constants.ID)) { result.put(Constants.ERROR, 409); - } - else - { + } else { result = null; } return result; } + private JSONObject createVideo(SlingHttpServletRequest request) throws JSONException { JSONObject result = new JSONObject(); - RequestParameter requestParameter = request.getRequestParameter(Constants.PLST); + RequestParameter requestParameter = request.getRequestParameter(Constants.PLST); if (requestParameter == null) { result.put(Constants.ERROR, 500); return result; @@ -292,7 +293,7 @@ private JSONObject createVideo(SlingHttpServletRequest request) throws JSONExcep String ingestURL = requestParameter.getString(); String ingestProfile = "balanced-high-definition"; - RequestParameter requestIngestParameter = request.getRequestParameter("profile_Ingest"); + RequestParameter requestIngestParameter = request.getRequestParameter("profile_Ingest"); if (requestIngestParameter != null) { ingestProfile = requestIngestParameter.getString(); } @@ -340,6 +341,7 @@ private JSONObject createVideo(SlingHttpServletRequest request) throws JSONExcep } return result; } + private JSONObject updateVideo(SlingHttpServletRequest request) throws JSONException { Collection tagsToAdd = new ArrayList(); if (request.getParameter("tags") != null) { @@ -369,13 +371,14 @@ private JSONObject updateVideo(SlingHttpServletRequest request) throws JSONExcep return null; } + private JSONObject removeTextTrack(SlingHttpServletRequest request) throws JSONException { try { String trackID = request.getParameter("track"); String videoID = request.getParameter(Constants.ID); LOGGER.trace("TRACK DELETION ACTIVATED FOR TRACK {}", trackID); //PUT TOGETHER THE TEXT TRACKS JSON OBJECT IN ORDER TO SEND - LOGGER.trace("VideoID: {}" ,videoID); + LOGGER.trace("VideoID: {}", videoID); //GET VIDEO FOR THIS VIDEO ID - REMOVE FORM THE JSON OBJECT AND RESEND UP //GET VIDEO AND UPDATE TEXT TRACKS JSON @@ -389,12 +392,10 @@ private JSONObject removeTextTrack(SlingHttpServletRequest request) throws JSONE JSONArray updated_tracks = new JSONArray(); LOGGER.trace("OLD TRACKS LIST {}", trackslist.length()); - for(int x = 0 ; x < trackslist.length(); x++) - { + for (int x = 0; x < trackslist.length(); x++) { JSONObject track = trackslist.getJSONObject(x); curID = track.getString(Constants.ID); - if(!trackID.equals(curID)) - { + if (!trackID.equals(curID)) { Text_track currentTrack = new Text_track(track); updated_tracks.put(currentTrack.toJSON()); } @@ -422,14 +423,13 @@ private JSONObject removeTextTrack(SlingHttpServletRequest request) throws JSONE //LOGGER.debug("GOT VIDEO: "+ down_video.toString(1)); LOGGER.debug("REBUILT VIDEO: {}", video.toJSON().toString(1)); JSONObject videoItem = brAPI.cms.updateVideo(video); - LOGGER.trace("RESP TXT TRACK : {}", videoItem.toString(1) ); - } - catch (JSONException e) - { + LOGGER.trace("RESP TXT TRACK : {}", videoItem.toString(1)); + } catch (JSONException e) { LOGGER.error(Constants.ERROR_LOG_TMPL, e); } return null; } + private JSONObject uploadTextTrack(SlingHttpServletRequest request, SlingHttpServletResponse response) throws JSONException, UnsupportedEncodingException, IOException { JSONObject text_track_payload = new JSONObject(); JSONArray text_track_arr = new JSONArray(); @@ -439,9 +439,9 @@ private JSONObject uploadTextTrack(SlingHttpServletRequest request, SlingHttpSer text_track.put(Constants.KIND, request.getParameter(Constants.TRACK_KIND)); String label = request.getParameter(Constants.TRACK_LABEL); String filename; - if (label!= null && !label.isEmpty()) { + if (label != null && !label.isEmpty()) { text_track.put(Constants.LABEL, label); - filename = label.replaceAll(" ","_")+".vtt"; + filename = label.replaceAll(" ", "_") + ".vtt"; } else { filename = "no_label.vtt"; } @@ -452,31 +452,25 @@ private JSONObject uploadTextTrack(SlingHttpServletRequest request, SlingHttpSer //FILE UPLOAD CASE*** //HERE IT GETS THE TRACK SOURCE - HANDLE CASE OF FILE UPLOAD - if("".equals(request.getParameter(Constants.TRACK_SOURCE)) && !"".equals(request.getParameter(Constants.TRACK_FILEPATH)) ) - { + if ("".equals(request.getParameter(Constants.TRACK_SOURCE)) && !"".equals(request.getParameter(Constants.TRACK_FILEPATH))) { LOGGER.trace("FILEPATH: {} ", request.getParameter(Constants.TRACK_FILEPATH)); //DO PUSH OF THE FILE GIVEN THE FILEPATH AND THEN PUSH THE NEW OBJECT TRACK TO VIDEO AS BEFORE //CHECK THAT IT IS A VTT FILE??? END OF NAME??? - InputStream is = new ByteArrayInputStream(request.getParameter(Constants.TRACK_FILEPATH).getBytes("UTF-8" )); + InputStream is = new ByteArrayInputStream(request.getParameter(Constants.TRACK_FILEPATH).getBytes("UTF-8")); //REQUEST INGEST URL - JSONObject s3_url_resp = serviceUtil.createAssetS3(request.getParameter(Constants.ID),filename, is); + JSONObject s3_url_resp = serviceUtil.createAssetS3(request.getParameter(Constants.ID), filename, is); //IF SUCCESS - if (s3_url_resp != null && s3_url_resp.has(Constants.SENT) && s3_url_resp.getBoolean(Constants.SENT)) - { + if (s3_url_resp != null && s3_url_resp.has(Constants.SENT) && s3_url_resp.getBoolean(Constants.SENT)) { //text_track.put("url", s3_url_resp.getString("signed_url")); text_track.put(Constants.URL, s3_url_resp.getString(Constants.API_REQUEST_URL)); LOGGER.trace("S3URLRESP: {}", s3_url_resp); - } - else - { + } else { LOGGER.error("FAILED TO INITIALIZE BUCKET"); } - } - else if (!"".equals(request.getParameter(Constants.TRACK_SOURCE))) - { + } else if (!"".equals(request.getParameter(Constants.TRACK_SOURCE))) { LOGGER.trace("SOURCEPATH: {}", request.getParameter(Constants.TRACK_SOURCE)); text_track.put(Constants.URL, request.getParameter(Constants.TRACK_SOURCE)); @@ -490,10 +484,9 @@ else if (!"".equals(request.getParameter(Constants.TRACK_SOURCE))) JSONObject videoItem = brAPI.cms.uploadInjest(request.getParameter(Constants.ID), text_track_payload); //DEBUGGER PRINT - LOGGER.trace("**:" + videoItem.toString(1)); - if(videoItem.has(Constants.RESPONSE)) - { + if (videoItem.has(Constants.RESPONSE)) { JSONObject responseOBJ = new JSONObject(videoItem.getString(Constants.RESPONSE)); - LOGGER.trace("**has id object: {}", responseOBJ.has(Constants.ID) ); + LOGGER.trace("**has id object: {}", responseOBJ.has(Constants.ID)); //response.sendError(422, "Incompatible Payload for Audio Track"); LOGGER.trace("Text Track Upload Complete"); @@ -502,6 +495,7 @@ else if (!"".equals(request.getParameter(Constants.TRACK_SOURCE))) } return null; } + private JSONObject uploadImage(SlingHttpServletRequest request) throws JSONException { LOGGER.trace("upload_thumbnail"); @@ -554,7 +548,7 @@ private JSONObject apiLogic(SlingHttpServletRequest request, SlingHttpServletRes result = createVideo(request); } else if ("update_video".equals(requestedAPI)) { result = updateVideo(request); - } else if("remove_text_track".equals(requestedAPI)) { + } else if ("remove_text_track".equals(requestedAPI)) { result = removeTextTrack(request); } else if ("upload_text_track".equals(requestedAPI)) { result = uploadTextTrack(request, response); @@ -575,9 +569,10 @@ private void executeRequest(final SlingHttpServletRequest request, boolean js = "js".equals(extension); boolean hasError = false; JSONObject result = new JSONObject(); - String resultstr="{\""+Constants.ITEMS+"\":[],\""+Constants.TOTALS+"\":0,\""+Constants.ERROR+"\":"+error_code+"}"; + String resultstr = "{\"" + Constants.ITEMS + "\":[],\"" + Constants.TOTALS + "\":0,\"" + Constants.ERROR + "\":" + error_code + "}"; - try_loop: try { + try_loop: + try { result.put("items", new JSONArray()); result.put(Constants.TOTALS, 0); result.put("error", JSONObject.NULL); @@ -590,7 +585,7 @@ private void executeRequest(final SlingHttpServletRequest request, } result = apiLogic(request, response, result); - if (result== null) { + if (result == null) { //NOTE : This had to be added to fix a limitation of etx.js where a json response was non acceptable on file submission response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("true"); @@ -620,8 +615,7 @@ private void executeRequest(final SlingHttpServletRequest request, error_code = 500; } - if (error_code >= 400) - { + if (error_code >= 400) { response.setStatus(error_code); } diff --git a/current/core/src/test/java/com/coresecure/brightcove/tests/impl/TestBrightcoveModels.java b/current/core/src/test/java/com/coresecure/brightcove/tests/impl/TestBrightcoveModels.java new file mode 100755 index 0000000..dc63940 --- /dev/null +++ b/current/core/src/test/java/com/coresecure/brightcove/tests/impl/TestBrightcoveModels.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Adobe Systems Incorporated + * + * 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.coresecure.brightcove.tests.impl; + +import com.coresecure.brightcove.wrapper.models.BrightcoveAdminPage; +import junitx.util.PrivateAccessor; +import org.apache.sling.settings.SlingSettingsService; +import org.junit.Before; +import org.junit.Test; + +import java.util.UUID; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Simple JUnit test verifying the HelloServiceImpl + */ +public class TestBrightcoveModels { + + private BrightcoveAdminPage brightcoveAdminPage; + + private String slingId; + + @Before + public void setup() throws Exception { + brightcoveAdminPage = new BrightcoveAdminPage(); + } + + @Test + public void testBrightCoveModel() throws Exception { + // some very basic junit tests + assertNotNull(brightcoveAdminPage.getConfigurationServices()); + } + +} diff --git a/current/core/src/test/java/com/coresecure/brightcove/wrapper/APITest.java b/current/core/src/test/java/com/coresecure/brightcove/wrapper/APITest.java new file mode 100644 index 0000000..7806a51 --- /dev/null +++ b/current/core/src/test/java/com/coresecure/brightcove/wrapper/APITest.java @@ -0,0 +1,1286 @@ +package com.coresecure.brightcove.wrapper; + +import com.coresecure.brightcove.tests.impl.TestBrightcoveModels; +import com.coresecure.brightcove.wrapper.api.CmsAPI; +import com.coresecure.brightcove.wrapper.enums.EconomicsEnum; +import com.coresecure.brightcove.wrapper.enums.GeoFilterCodeEnum; +import com.coresecure.brightcove.wrapper.enums.PlaylistFieldEnum; +import com.coresecure.brightcove.wrapper.enums.PlaylistTypeEnum; +import com.coresecure.brightcove.wrapper.filter.CustomAddDialogTabFilter; +import com.coresecure.brightcove.wrapper.models.VideoPlayer; +import com.coresecure.brightcove.wrapper.models.VideoPlayerConfiguration; +import com.coresecure.brightcove.wrapper.objects.*; +import com.coresecure.brightcove.wrapper.schedulers.asset_integrator.callables.VideoImportCallable; +import com.coresecure.brightcove.wrapper.schedulers.asset_integrator.impl.AssetIntegratorCronBundleImpl; +import com.coresecure.brightcove.wrapper.schedulers.asset_integrator.runnables.AssetPropertyIntegratorRunnable; +import com.coresecure.brightcove.wrapper.sling.*; +import com.coresecure.brightcove.wrapper.utils.*; +import com.coresecure.brightcove.wrapper.webservices.*; +import com.day.cq.dam.api.Asset; +import com.day.cq.replication.ReplicationTransaction; +import com.day.cq.replication.TransportContext; +import com.day.cq.wcm.api.components.ComponentContext; +import com.google.common.collect.ImmutableMap; +import org.apache.felix.scr.annotations.Reference; +import org.apache.sling.api.SlingHttpServletRequest; +import org.apache.sling.api.SlingHttpServletResponse; +import org.apache.sling.api.resource.Resource; +import org.apache.sling.api.resource.ResourceResolver; +import org.apache.sling.api.resource.ResourceResolverFactory; +import org.apache.sling.api.resource.ValueMap; +import org.apache.sling.api.servlets.HttpConstants; +import org.apache.sling.commons.json.JSONArray; +import org.apache.sling.commons.json.JSONException; +import org.apache.sling.commons.json.JSONObject; +import org.apache.sling.commons.mime.MimeTypeService; + + + + +//USING TO ACCESS PRIVATE METHODS +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + + +import org.apache.sling.testing.mock.sling.MockSling; +import org.apache.sling.testing.mock.sling.ResourceResolverType; +import org.apache.sling.testing.mock.sling.junit.SlingContext; +import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo; +import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest; +import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.osgi.framework.BundleContext; + +import javax.activation.MimeType; +import javax.inject.Inject; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.lang.reflect.Modifier; +import java.net.Proxy; +import java.net.URL; +import java.util.*; +import java.util.List; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.ArrayList; + +/** + * Created by pablo.kropilnicki on 12/21/17. + */ +public class APITest { + + //Mocking Library + + @Rule + public final SlingContext context = new SlingContext(ResourceResolverType.RESOURCERESOLVER_MOCK); + + // prepare sling request + ResourceResolver resourceResolver = MockSling.newResourceResolver(); + MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resourceResolver); + MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); + + // SlingHttpServletRequest req = mock(SlingHttpServletRequest.class); + // SlingHttpServletResponse resp = mock(SlingHttpServletResponse.class); + + //STATIC TESTING VARIABLES + public static String CLIENT_ID = "bfc763b9-1492-48c0-ae8f-837782a8b885"; + public static String CLIENT_SECRET = "lJvCasqov1E05VSOBUmaNp1BUVDcpam30cP94KjWVk1kkucpaI5ieFY_-P3AqU1x_RO_c5SwLoJh1zLndnXQfw"; + public static String ACCOUNT_ID = "1153191516001"; + + public static Platform defaultPlatform; + public static BrightcoveAPI brightcoveAPI; + public static Account account; + public static CmsAPI api; + public static AccountUtil accountUtil; + public static HttpServices service = new HttpServices(); + public static ServiceUtil serviceUtil = mock(ServiceUtil.class, ACCOUNT_ID); //CALLS CONFIGURATION GRABBER = FAILS + + + + @Test + public void MainTest() { + defaultPlatform = new Platform(Constants.DEFAULT_OAUTH_URL, Constants.DEFAULT_API_URL, Constants.DEFAULT_DI_API_URL, Constants.DEFAULT_PLAYERS_API_URL); + PlatformTest(); + + + account = new Account(defaultPlatform, CLIENT_ID, CLIENT_SECRET, ACCOUNT_ID); + AccountTest(); + + api = new CmsAPI(account); + ApiTest(api); + + brightcoveAPI = new BrightcoveAPI(CLIENT_ID, CLIENT_SECRET, ACCOUNT_ID, ""); + TestBrightcoveAPI(); + + accountUtil = mock(AccountUtil.class); + + TestAccountUtil(); + + TestHTTPServices(); + + TestStaticStructures(); + + //TEST INTEGRATION TEST//TODO: Not ready + TestModelsAEM(); + + BundleActivatorTest(); + + AssetIntegratorTest(); + + AssetPropertyIntegratorRunnableTest(); + + BrcApiTests(); + + AssetPropertyIntegratorRunnableTests(); + AssetPropertyIntegratorTests(); + BrcAccountsUITests(); + BrcImageApiTests(); + BrcReplicationHandlerTests(); + IngestTests(); + S3UploadUtilTests(); + + BrcSuggestionsTests(); + CertificateListServiceImplTests(); + ConfigurationGrabberImplTests(); + ConfigurationServiceImplTests(); + BrcAccountsTests(); + + + + //IN PROGRESS +// ObjectSerializerTest(); + + + //FAILING TESTS + TestVideoImportCallable(); + TestConfigGrabber(); + MockTests(); + + } + + private void PlatformTest() { + assertNotNull(defaultPlatform.getDI_API_Url()); + assertNotNull(defaultPlatform.getOAUTH_Url()); + assertNotNull(defaultPlatform.getAPI_Url()); + assertNotNull(defaultPlatform.getPLAYERS_API_URL()); + defaultPlatform.setProxy("test"); + + String targetURL = "url"; + String targetVideoID = "123"; + String payload = "pay"; + Map headers = new HashMap(); + headers.put("headerone", "valueone"); + + String r_deleteAPI = defaultPlatform.deleteAPI("url", "videoID", headers); + String r_postAPI = defaultPlatform.postAPI(targetURL, payload, headers); + String r_patchAPI = defaultPlatform.patchAPI(targetURL, payload, headers); + String r_postDI_API = defaultPlatform.postDI_API(targetURL, payload, headers); + String r_getDI_API = defaultPlatform.getDI_API(targetURL, payload, headers); + String r_postDIRequest_API = defaultPlatform.postDIRequest_API(targetURL, payload, headers); + } + + private void ApiTest(CmsAPI api) { + + //SINCE GET VIDEOS IS RECURSIVE - IF WE GIVE MORE PARAMETERS IT WILL TEST / CASCADE DOWN + JSONArray videos = api.getVideos(); + assertNotNull(videos); + if (videos.length() > 0) { + try { + Video video = new Video(videos.getJSONObject(0)); + assertTrue(api.getVideo(video.id).has(Constants.ID)); + assertNotNull(video.toString()); + assertTrue(api.getVideo(video.id).has(Constants.LONG_DESCRIPTION)); + } catch (JSONException e) { + assertTrue(false); + } + } + + + //GET PLAYLISTS COUNT + assertNotNull(api.getPlaylistsCount()); + + //GET PLAYLISTS -- + //NULL PLAYLUIST -> JSONException + try { + Playlists errPlaylists = new Playlists(new JSONObject()); + } catch (JSONException e) { + System.out.println("Playlists null case"); + //e.printStackTrace(); + } + JSONArray playlists = api.getPlaylists(); + if (playlists.length() > 0) { + try { + + //PLAYLIST TESTS - ////////////////////////////////////////////////////////////////////////////////////////// + Playlist playlist = new Playlist(playlists.getJSONObject(0)); + +// Playlist stringPlaylistNull = new Playlist(null); // BAD CODE + Playlist stringPlaylistEmpty = new Playlist("{}"); + assertTrue(api.getPlaylist(playlist.getId()).has(Constants.ID)); + + //ITERATING ITSELF THROUGH GET FUNCTIONS AND SET FUNCTIONS USING RECURSION + List videoIds = playlist.getVideoIds(); + playlist.setId(playlist.getId()); + playlist.setReferenceId(playlist.getReferenceId()); + playlist.setAccountId(playlist.getAccountId()); + playlist.setName(playlist.getName()); + playlist.setDescription(playlist.getDescription()); + playlist.setVideoIds(videoIds); + playlist.setPlaylistType(playlist.getPlaylistType()); + playlist.toJSON(); + + //END PLAYLIST TESTS - ////////////////////////////////////////////////////////////////////////////////////////// + + JSONObject playlistObj = new JSONObject(); + JSONArray playlistsItems = new JSONArray(); + playlistsItems.put(0, playlists.getJSONObject(0)); + playlistObj.put("items", playlistsItems); + playlistObj.put("total_count", 0); //purposeful mismatch + + //WE ADD A STATIC PLAYLIST OBJ INITIALIZATION + Playlists recursiveConstructedPlaylists = new Playlists(playlistObj); + assertNotNull(recursiveConstructedPlaylists.getTotalCount()); + //System.out.println(playlistObj.toString(1)); //testprint + + + + //ERR Trigger + playlistObj.remove("total_count"); + Playlists recursiveConstructedPlaylistsErr = new Playlists(playlistObj); + + + try { + //PLAYLIST REFLECT + PlaylistTypeEnum playEnum = PlaylistTypeEnum.ALPHABETICAL; + Method getType = Playlist.class.getDeclaredMethod("getType", String.class); + getType.setAccessible(true); + PlaylistTypeEnum getTypeResp1 = (PlaylistTypeEnum) getType.invoke(playlist, "OLDEST_TO_NEWEST"); + PlaylistTypeEnum getTypeResp2 = (PlaylistTypeEnum) getType.invoke(playlist, "NEWEST_TO_OLDEST"); + PlaylistTypeEnum getTypeResp3 = (PlaylistTypeEnum) getType.invoke(playlist, "ALPHABETICAL"); + PlaylistTypeEnum getTypeResp4 = (PlaylistTypeEnum) getType.invoke(playlist, "PLAYSTOTAL"); + PlaylistTypeEnum getTypeResp5 = (PlaylistTypeEnum) getType.invoke(playlist, "PLAYS_TRAILING_WEEK"); + PlaylistTypeEnum getTypeResp6 = (PlaylistTypeEnum) getType.invoke(playlist, "EXPLICIT"); + PlaylistTypeEnum getTypeResp7 = (PlaylistTypeEnum) getType.invoke(playlist, "ERROR"); + + } catch (Exception e) { + System.out.println("PlaylistReflect: " + e); + //e.printStackTrace(); + } + + + } catch (JSONException e) { + assertTrue(false); + } + } + + + assertTrue(api.getCustomFields().has("custom_fields")); + assertTrue(api.getPlayers().has("items")); + + //VIDEO INITIALIZATIONS - DEPENDENT PARAMETER CONSTRUCTION TESTS - //////////////////////////////////////////////////////////////////////////////////////// + try { + + + String aId = "1234"; + String aName = "videoName"; + String aReference_id = "1234"; + String aDescription = "test1234"; + String aLong_description = "test1234"; + String aState = "test1234"; + boolean aComplete = false; + EconomicsEnum aEconomics; + String aAccountId = "test1234"; + + + //PROJECTION STATIC + String aProjection = "test1234"; + Projection projectionStatic = new Projection("equirectangular"); + projectionStatic.toString(); + + /////////////////////////////////// - GEO + //EX: {"geo":{"restricted":true,"exclude_countries":false,"countries":["ph","in","my","ja"]}} + + Geo aGeo; + //BUILDING SAMPLE GEO + JSONObject jsonGeo = new JSONObject(); + JSONObject geo = new JSONObject(); + JSONArray countries = new JSONArray(); + + + //Populate Constructor JSON + countries.put(0, "ph"); + countries.put(1, "in"); + countries.put(2, "my"); + countries.put(3, "ja"); + geo.put("countries", countries); + geo.put("exclude_countries", false); + geo.put("restricted", true); + jsonGeo.put("geo", geo); + + //Create Geo + aGeo = new Geo(geo); + + + //Globals + assertNotNull(aGeo.exclude_countries); + assertNotNull(aGeo.countries); + assertNotNull(aGeo.restricted); + + //Test Printout + assertNotNull(aGeo.toJSON()); + + + Collection aCountries = new ArrayList(); + + + //STATIC GEO + Geo geoStatic = new Geo(false, false, aCountries); + + + /////////////////////////////////// - END GEO + + + /////////////////////////////////// - TAGS + Collection aTags = new ArrayList(Arrays.asList(new String[]{"sam", "ple", "tags"})); + /////////////////////////////////// - END TAGS + + + /////////////////////////////////// - SCHEDULE + Schedule aSchedule; + + //{"name":"greatblueheron.mp4","schedule":{"starts_at":"2017-03-10","ends_at":"2018-12-31"}} + + JSONObject jsonSchedule = new JSONObject(); + JSONObject schedule = new JSONObject(); + schedule.put("starts_at", "2017-03-10"); + schedule.put("ends_at", "2017-03-10"); + jsonSchedule.put("name", "greatblueheron.mp4"); + jsonSchedule.put("schedule", schedule); + + //WAS: aSchedule = new Schedule(jsonSchedule) + aSchedule = new Schedule(schedule.getString("starts_at"), schedule.getString("starts_at")); + + //Globals + assertNotNull(aSchedule.starts_at); + assertNotNull(aSchedule.ends_at); + + //Test Printout + assertNotNull(aSchedule.toJSON()); + assertNotNull(aSchedule.toString()); + + //Static Construction + Schedule jSchedule = new Schedule(aSchedule.toJSON()); + + Schedule errSchedule = new Schedule("2017-03-10", null); + assertNotNull(errSchedule.toString()); + + ///////////////////////////////////>>> - END SCHEDULE + + + /////////////////////////////////// - RELATED LINK START + RelatedLink aLink; + + JSONObject jsonRelatedLink = new JSONObject(); + jsonRelatedLink.put("text", "sampletext"); + jsonRelatedLink.put("url", "https://www.sample.com"); + + aLink = new RelatedLink(jsonRelatedLink); + assertNotNull(aLink.text); + assertNotNull(aLink.url); + assertNotNull(aLink.toJSON()); + assertNotNull(aLink.toString()); + + /////////////////////////////////// - RELATED LINK END + + /////////////////////////////////// - CUSTOM FIELDS + Map aCustom_fields = new HashMap(); + aCustom_fields.put("customFieldOne", true); + aCustom_fields.put("customFieldTwo", false); + /////////////////////////////////// - CUSTOM FIELDS END + + /////////////////////////////////// - CUSTOM FIELDS END + JSONArray aText_tracks = new JSONArray(); + /////////////////////////////////// - CUSTOM FIELDS END + + /////////////////////////////////// - IMAGES -> (POSTER + THUMBNAIL) + Poster poster; + Thumbnail thumbnail; + Images aImages; + + //POSTER + JSONObject jsonPoster = new JSONObject(); + jsonPoster.put("src", "postersourcelocation"); + poster = new Poster(jsonPoster); + + //POSTER TESTS + assertNotNull(poster.url); + assertNotNull(poster.toJSON()); + assertNotNull(poster.toString()); + + //THUMBNAIL + JSONObject jsonThumbnail = new JSONObject(); + jsonThumbnail.put("src", "thumbnailsourcelocation"); + thumbnail = new Thumbnail(jsonThumbnail); + + //THUMBNAIL TESTS + assertNotNull(thumbnail.url); + assertNotNull(thumbnail.toJSON()); + assertNotNull(thumbnail.toString()); + + //IMAGES + JSONObject jsonImages = new JSONObject(); + jsonImages.put("poster", jsonPoster); + jsonImages.put("thumbnail", jsonThumbnail); + aImages = new Images(jsonImages); + + + + + + + //IMAGES TESTS + assertNotNull(aImages.poster); + assertNotNull(aImages.thumbnail); + assertNotNull(aImages.toJSON()); + assertNotNull(aImages.toString()); + + + try { + ObjectSerializer objSerial = new ObjectSerializer(); + String json_key = "key"; + JSONObject fieldJson = new JSONObject(); + Object fieldObj = new Object(); + Class serializerClass = ObjectSerializer.class; + Field[] fieldArr = serializerClass.getFields(); + Field field = fieldArr[0]; + Byte[] annotationsBytes = new Byte[10]; + + + final Constructor constructor = Field.class.getDeclaredConstructor(); + if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) + { + Assert.fail("constructor is not private"); + } + constructor.setAccessible(true); + ObjectSerializer objSerialConstructed = (ObjectSerializer)constructor.newInstance(serializerClass, serializerClass.getName(), serializerClass,1, 1, "Singature",annotationsBytes); + constructor.setAccessible(false); + + + Method textTrackSerialization = ObjectSerializer.class.getDeclaredMethod("addFieldToJson", Field.class, Object.class, JSONObject.class, String.class); + textTrackSerialization.invoke(aImages.getClass(), aImages, fieldJson, json_key); + } + catch (Exception e) + { + System.out.println("Serializer"); + } + + + //VIDEO CREATION FROM STATIC - ////////////////////////////////////////////////////////////////////////////////////////// + Video testvideo = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, null, aProjection, aText_tracks, aImages); + + //ADDITIONAL CONSTRUCTORS - DID NOT CASCADE.... + + assertNotNull(testvideo); + assertNotNull(testvideo.toJSON()); + assertNotNull(testvideo.toString()); + + System.out.println("[" + testvideo.toString() + "]"); + + //VIDEO INITAILIZATION FROM FIRST VIDEO CREATED - NOW IN JSON + Video jsonTestVideo = new Video(testvideo.toJSON()); + assertNotNull(jsonTestVideo); + assertNotNull(jsonTestVideo.toJSON()); + assertNotNull(jsonTestVideo.toString()); + + + //STATIC CALLS - GEO ENUM + //Cannot instantiate enum... + GeoFilterCodeEnum geoEnum = GeoFilterCodeEnum.AD; + assertNotNull(GeoFilterCodeEnum.lookupByCode("zm")); + assertNotNull(GeoFilterCodeEnum.lookupByName("ZAMBIA")); + assertTrue(GeoFilterCodeEnum.lookupByName("ENGLISH") == null); + assertNotNull(geoEnum.getName()); + assertNotNull(geoEnum.getCode()); + assertNotNull(geoEnum.toString()); + assertTrue((GeoFilterCodeEnum.lookupByName(null) == null)); + assertTrue((GeoFilterCodeEnum.lookupByCode(null) == null)); + + //STATIC CONSTRUCTORS + Video video0 = new Video(aName); + Video video1 = new Video(aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink); + Video video2 = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink); + Video video3 = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, null); + Video video4 = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, null, aProjection); + Video video5 = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, null, aProjection, aText_tracks); + Video video6 = new Video(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, null, aProjection, aText_tracks, aImages); + + //STATIC - EMPTY + Video.class.toString(); + + String output = video6.toString(); + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + //JSONREADER - REFLECT//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + try { + + final Constructor constructor = JsonReader.class.getDeclaredConstructor(); + if (constructor.isAccessible() || !Modifier.isPrivate(constructor.getModifiers())) + { + Assert.fail("constructor is not private"); + } + constructor.setAccessible(true); + constructor.newInstance(); + constructor.setAccessible(false); + } + catch (Exception e) + { + System.out.print("superfail"); + } + + + + //JsonReader jReader = new JsonReader(); + + //EMPTY COVERAGE +// RelatedLink.class.toString(); //Todo: try to fire this off + //END STATIC CALLS - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + //NOW THAT WE HAVE VIDEO... + + + JSONObject payload = new JSONObject(); + String payloadVideoID = video1.id; + String profile = ""; + String master = ""; + Ingest ingest = new Ingest(profile, master); + String filename = ""; + Playlist playlist = new Playlist(); + String q = ""; + JSONArray input = new JSONArray(); + + //TODO: Implemment this the right way - with a integration test video (requires research) + JSONObject uploadInjestResponse = api.uploadInjest(payloadVideoID, payload); + JSONObject requestIngestURLResponse = api.requestIngestURL(payloadVideoID, profile, master, false); + JSONObject getIngestURLResponse = api.getIngestURL(payloadVideoID, filename); + JSONObject createVideoResponse = api.createVideo(video1); + JSONObject updateVideoResponse = api.updateVideo(video1); + JSONObject deleteVideoResponse = api.deleteVideo(payloadVideoID); + JSONObject createPlaylistResponse = api.createPlaylist(playlist); + JSONObject getVideosCountResponse = api.getVideosCount(q); + JSONObject createIngestResponse = api.createIngest(video1, ingest); + JSONArray getVideoSourcesResponse = api.getVideoSources(payloadVideoID); + JSONObject getVideoImagesByRefResponse = api.getVideoImagesByRef(payloadVideoID); + JSONArray getVideoSourcesByRefResponse = api.getVideoSourcesByRef(payloadVideoID); + JSONObject getVideoByRefResponse = api.getVideoByRef(payloadVideoID); + JSONObject getCustomFieldsResponse = api.getCustomFields(); + JSONObject getVideoImagesResponse = api.getVideoImages(payloadVideoID); + JSONArray addThumbnailResponse = api.addThumbnail(input); + JSONArray getVideosResponse = api.getVideos("0", "10"); + JSONArray getVideosResponseWLimit = api.getVideos("0", "10", 10); + JSONArray getVideosResponseWSort = api.getVideos(0, 10, "created_at"); + + + } catch (JSONException e) { + System.out.println("test exception - json - Images" + e); + assertTrue(false); + } + + /////////////////////////////////// - END IMAGES -> (POSTER + THUMBNAIL) + + +// + + + } + + private void TestHTTPServices() { + + //final SlingHttpServletRequest request = null; - TODO: figure out how to do inject this + + try { + + String videoId = "123"; + String accountKeyStr = "1153191516001"; + String queryStr = ""; + int offset = 0; + int limit = 30; + String query = ""; + Boolean exportCSV = false; + String sort = ""; + String querystr = ""; + String limits = ""; + String playlistID = ""; + String q = ""; + + Video video = new Video("sup"); + String filename = ""; + + String videoIds = ""; + String videoProperties = ""; + + try { + Method getAccountCookieMethod = ServiceUtil.class.getMethod("getAccountCookie", SlingHttpServletRequest.class); + getAccountCookieMethod.setAccessible(true); + Cookie accountCookie = (Cookie) getAccountCookieMethod.invoke(serviceUtil, request); + } catch (Exception e) { + System.out.println("accountCookie"); + } + + +// String AccountFromCookie = serviceUtil.getAccountFromCookie(request); +// List sortedMap = serviceUtil.sortByValue(final Map m); +// String length = serviceUtil.getLength(videoId, accountKeyStr); +// +// +// + + + String ingestURL = ""; + String ingestProfile = ""; + InputStream is = new InputStream() { + @Override + public int read() throws IOException { + return 0; + } + }; + + + ServiceUtil service = new ServiceUtil(ACCOUNT_ID); + ConfigurationGrabber configGrabber = service.getConfigurationGrabber(); + String videoName = service.getName(videoId, accountKeyStr); + + boolean videoDelete = service.deleteVideo(videoId); + boolean isLong = service.isLong("123"); + boolean full_scroll = false; + + String queryListOne = service.getList(exportCSV, query); + String queryListTwo = service.getList(exportCSV, offset, limit, full_scroll, query); + String queryListThree = service.getList(exportCSV, offset, limit, full_scroll, query, sort); + String videoSearch = service.searchVideo(querystr, offset, limit); + String findVideo = service.searchVideo(querystr, offset, limit, sort); + String findVideoByID = service.getVideoByRefID(videoId); + String getSideMenuList = service.getListSideMenu(limits); + String getSuggestions = service.getSuggestions(querystr, offset, limit); + String playlistsQueryOne = service.getPlaylists(offset, limit, exportCSV, full_scroll); + String playlistsQueryTwo = service.getPlaylists(q, offset, limit, exportCSV, full_scroll); + + JSONObject players = service.getPlayers(); + JSONObject playlistsByID = service.getPlaylistByID(playlistID); + JSONObject updateVideoObj = service.updateVideo(video); + JSONObject createVideo = service.createVideo(video, ingestURL, ingestProfile); + JSONObject createVideoS3 = service.createVideoS3(video, filename, is); + JSONObject selectedVideosObj = service.getSelectedVideo(videoId); + JSONObject customFieldsObj = service.getCustomFields(); + + JSONArray sourcesArray = service.getVideoSources(videoId); + JSONArray videoJSONArray = service.getVideosJsonByIds(videoIds, videoProperties); + + } catch (NullPointerException e) { + System.out.println("TestHTTPServices:" + e); + } catch (Exception e) { + System.out.println("TestHTTPServices:" + e); + } + + } + + private void TestStaticStructures() { + try + { + EnumsTests(); + IngestTests(); + AccountTest(); + TokenTest(); + TestBinaryObj(); + TestTextTrackObj(); + TestTextUtil(); + TestImageUtils(); + TestVideoPlayerModel(); + TestVideoPlayerConfiguration(); + CustomAddDialogTabFilterTests(); + + //./////////////////////////////////////////////////////////////CONSTANTS + try { Constants constants = new Constants(); } catch (Exception e) { System.out.println("Constants Exception: " + e); } + + //./////////////////////////////////////////////////////////////JCR UTILS < pre int test + try { JcrUtil.now2calendar(); } catch (Exception e) { System.out.println("ExceptionFromJCR: " + e); } + + } + catch (Exception e) + { + System.out.println(e); + } + } + + private void TestModelsAEM() { + TestVideoPlayerModel(); + TestVideoPlayerConfiguration(); + } + + private void BundleActivatorTest() { + Activator activator = new Activator(); + BundleContext bundleContext = mock(BundleContext.class); + //Todo: Figure out right mock for BundleContext + try { + activator.start(bundleContext); + activator.stop(bundleContext); + } catch (Exception e) { + System.out.println("Activator err: " + e); + } + } + + private void AssetIntegratorTest() { + AssetIntegratorCronBundleImpl assetIntegratorCronBundle = new AssetIntegratorCronBundleImpl(); + assetIntegratorCronBundle.getStatus(); + } + + private void AssetPropertyIntegratorRunnableTest() { + MimeTypeService mType = mock(MimeTypeService.class); + ResourceResolverFactory resourceResolverFactory = mock(ResourceResolverFactory.class); + int maxThreadNum = 1; + AssetPropertyIntegratorRunnable runnableInit = new AssetPropertyIntegratorRunnable(mType, resourceResolverFactory, maxThreadNum); + runnableInit.run(); + } + + /* Static Tests */ + + //ENUMS + private void EnumsTests() { + try { + EconomicsEnum econEnumString = EconomicsEnum.AD_SUPPORTED; + EconomicsEnum econEnumString2 = EconomicsEnum.FREE; + + assertNotNull(econEnumString.toString()); + + PlaylistFieldEnum playlistFieldEnum = PlaylistFieldEnum.ACCOUNTID; + assertNotNull(playlistFieldEnum.toString()); + + assertNotNull(playlistFieldEnum.getJsonName()); + assertNotNull(playlistFieldEnum.toString()); + assertNotNull(playlistFieldEnum.getDefinition()); + + EnumSet enumSet = playlistFieldEnum.CreateEmptyEnumSet(); + EnumSet enumSet2 = playlistFieldEnum.CreateFullEnumSet(); + + assertNotNull(enumSet); + assertNotNull(enumSet2); + } catch (Exception e) { + System.out.println("Exception Enums" + e); + } + } + + private void IngestTests() { + try { + //Ingest - 88% + final Map master = new HashMap(); + master.put("Test", "String"); + Ingest ingest1 = new Ingest("", master); + Ingest ingest2 = new Ingest("", ""); + assertNotNull(ingest1.toJSON()); + assertNotNull(ingest2.toString()); + } catch (Exception e) { + System.out.println("IngestTests" + e); + } + } + + private void AccountTest() { + assertNotNull(account.getLoginToken()); + assertNotNull(account.getAccount_ID()); + } + + private void TokenTest() { + TokenObj token = account.getToken(); + assertNotNull(token.getToken()); + assertNotNull(token.getTokenType()); + assertNotNull(token.getExpire_in()); + } + + private void TestBinaryObj() { + try { + //./////////////////////////////////////////////////////////////BinaryObj + String str = "THISISACORESECURETESTSTRING"; + // String -> Input Stream + InputStream is = new ByteArrayInputStream(str.getBytes()); + // Input -> Buffered Reader + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + br.close(); + + BinaryObj binaryObj = new BinaryObj(); + BinaryObj binaryObjInit = new BinaryObj(is, "text/plain"); + } catch (Exception e) { + System.out.println("BinaryObjTests" + e); + } + } + + private void TestTextTrackObj(){ + + try { + /////////////////////////////////////////////////////////////TextTrackObject + String id = "1234"; + String account_id = "1234"; + String src = "1234"; + String srclang = "1234"; + String label = "1234"; + String kind = "1234"; + String mime_type = "1234"; + String asset_id = "1234"; + Boolean _default = false; + JSONArray sources = new JSONArray(); + + JSONObject text_track_constructor = new JSONObject(); + text_track_constructor.put(Constants.ID, id); + text_track_constructor.put(Constants.ACCOUNT_ID, account_id); + text_track_constructor.put(Constants.SRC, src); + text_track_constructor.put(Constants.SRCLANG, srclang); + text_track_constructor.put(Constants.LABEL, label); + text_track_constructor.put(Constants.KIND, kind); + text_track_constructor.put(Constants.MIME_TYPE, mime_type); + text_track_constructor.put(Constants.ASSET_ID, asset_id); + text_track_constructor.put(Constants.SOURCES, sources); + text_track_constructor.put(Constants.DEFAULT, false); + + Text_track hardConstTT = new Text_track(id, account_id, src, srclang, label, kind, mime_type, asset_id, _default, sources); + Text_track hardJsonTT = new Text_track(text_track_constructor); + + text_track_constructor.put(Constants.ID, (JSONObject) null); + text_track_constructor.put(Constants.ID, (JSONObject) null); + text_track_constructor.put(Constants.ACCOUNT_ID, (JSONObject) null); + text_track_constructor.put(Constants.SRC, (JSONObject) null); + text_track_constructor.put(Constants.SRCLANG, (JSONObject) null); + text_track_constructor.put(Constants.LABEL, (JSONObject) null); + text_track_constructor.put(Constants.KIND, (JSONObject) null); + text_track_constructor.put(Constants.MIME_TYPE, (JSONObject) null); + text_track_constructor.put(Constants.ASSET_ID, (JSONObject) null); + text_track_constructor.put(Constants.SOURCES, (JSONObject) null); + text_track_constructor.put(Constants.DEFAULT, (JSONObject) null); + + Text_track hardJsonTTT = new Text_track(text_track_constructor); + + //MISSING EXCEPTINO THROW SEE TEXT TRACK... + assertNotNull(hardConstTT.toJSON()); + assertNotNull(hardJsonTT.toString()); + + + assertNotNull(hardConstTT.toString()); + + } + catch (Exception e) + { + System.out.println("TextTrackObjTest " + e); + } +} + + private void TestTextUtil() { + //./////////////////////////////////////////////////////////////TextUtil + TextUtil textUtil = new TextUtil(); + assertNotNull(textUtil.isEmpty("String")); + assertNotNull(textUtil.notEmpty("AnotherString")); + assertNotNull(!(textUtil.notEmpty(null))); + } + + private void TestImageUtils() { + /////////////////////////////////////////////////////////////Image Utils + BufferedImage bufferedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB); + Rectangle rectObj = new Rectangle(50, 100); + assertNotNull(ImageUtil.cropImage(bufferedImage, rectObj)); + assertNotNull(ImageUtil.cropImage(bufferedImage, rectObj)); + assertNotNull(ImageUtil.cropImage(bufferedImage, rectObj)); + } + + private void TestVideoPlayerModel() { + VideoPlayer videoPlayerModel = new VideoPlayer(); + try { + + try { + Method myInitMethod = VideoPlayer.class.getDeclaredMethod("init", null); + myInitMethod.setAccessible(true); + myInitMethod.invoke(null); + } catch (Exception e) { + System.out.println("TestModelsAEM Property Exception"); + //e.printStackTrace(); + } + + videoPlayerModel.toString(); + videoPlayerModel.getComponentID(); + videoPlayerModel.getCurrentNode(); + videoPlayerModel.getVideoID(); + videoPlayerModel.getPlaylistID(); + videoPlayerModel.getAccount(); + videoPlayerModel.getPlayerPath(); + videoPlayerModel.getPlayerID(); + videoPlayerModel.getPlayerDataEmbed(); + videoPlayerModel.getPlayerKey(); + videoPlayerModel.getContainerID(); + videoPlayerModel.getContainerClass(); + videoPlayerModel.getAlign(); + videoPlayerModel.getWidth(); + videoPlayerModel.getHeight(); + videoPlayerModel.getHasSize(); + videoPlayerModel.getIgnoreComponentProperties(); + videoPlayerModel.getVersion(); + videoPlayerModel.getDropTargetPrefix(); + ComponentContext playerContext = videoPlayerModel.getComponentContext(); + ValueMap playerProps = videoPlayerModel.getPlayerProperties(); + Resource videPlayerRes = videoPlayerModel.getPlayerPageResource(); + videoPlayerModel.getInlineCSS();//Only one which throws exception... + + + } catch (Exception e) { + System.out.println("TestAEM Exception" + e); + //e.printStackTrace(); + } + } + + private void TestVideoPlayerConfiguration() { + //VideoPlayerConfiguration + VideoPlayerConfiguration videoPlayerConfiguration = new VideoPlayerConfiguration(); + try { + ComponentContext playerContext = videoPlayerConfiguration.getComponentContext(); + videoPlayerConfiguration.getDialogPath(); + videoPlayerConfiguration.getTitle(); + videoPlayerConfiguration.getDropTargetPrefix(); + + //THROW NULL POINTER - TODO:fix + //since the init function is not really implemented there are no JCR to acceess props.... + //videoPlayerConfiguration.getInlineCSS(); + //videoPlayerConfiguration.getVideoWidth(); + //videoPlayerConfiguration.getVideoHeight(); + + + } catch (NullPointerException e) { + System.out.println("VideoPlayerConfiguration NullPointer: " + e); + } catch (Exception e) { + System.out.println("VideoPlayerConfiguration Error: " + e); + } + } + + private void CustomAddDialogTabFilterTests() { + CustomAddDialogTabFilter customAddDialogTabFilter = new CustomAddDialogTabFilter(); + + try { + FilterChain pChain = FilterChain.class.newInstance(); + customAddDialogTabFilter.init(); + customAddDialogTabFilter.getServletInfo(); + customAddDialogTabFilter.destroy(); + customAddDialogTabFilter.doFilter(request, response, pChain); + } catch (Exception e) { + System.out.println("CustomAddDialogTabFilterTests" + e); + } + } + + + + private void TestAccountUtil() { + //Mock Experiment [ACCOUNT UTIL] + String resourcePath = ""; + String selectors = ""; + String extension = ""; + String suffix = ""; + String queryString = ""; + + ConfigurationGrabber cg = mock(ConfigurationGrabber.class); + ConfigurationService cs = cg.getConfigurationService(ACCOUNT_ID); //GET + + try { + + //Would not work + //MockSlingHttpServletRequest req = new MockSlingHttpServletRequest(resourcePath, selectors, extension, suffix, queryString); + SlingHttpServletRequest slingReq = mock(SlingHttpServletRequest.class); + + //ACCOUNT UTIL - Todo: Fix +// accountUtil.isAuthorized(slingReq, cs); +// accountUtil.getSelectedAccount(slingReq); +// accountUtil.getSelectedServices(slingReq); + + } catch (Exception e) { + System.out.println("TestAccountUtil: "+ e); + //e.printStackTrace(); + } + + + } + private void BrcAccountsTests() { + BrcAccounts brcAccounts = new BrcAccounts(); + + try { + + } catch (Exception e) { + System.out.println("BrcAccountsTests" + e); + } + } + private void BrcSuggestionsTests() { + BrcSuggestions brcSuggestions = new BrcSuggestions(); + + try { + // PROTECTED + // brcSuggestions.doGet(); + } catch (Exception e) { + System.out.println("BrcSuggestionsTests" + e); + } + } + + //IN QUESTION + private void ConfigurationGrabberImplTests() { + + + + + + ConfigurationGrabberImpl configurationGrabberImpl = new ConfigurationGrabberImpl(); + + + + + try { + configurationGrabberImpl.getAvailableServices(); + configurationGrabberImpl.getAvailableServices(request); + configurationGrabberImpl.getConfigurationService("KEY"); + } catch (Exception e) { + System.out.println("ConfigurationGrabberImplTests" + e); + } + } + private void ConfigurationServiceImplTests() { + ConfigurationServiceImpl configurationServiceImpl = new ConfigurationServiceImpl(); + try { + configurationServiceImpl.getAccountAlias(); + configurationServiceImpl.getAccountID(); + configurationServiceImpl.getAllowedGroups(); + configurationServiceImpl.getAllowedGroupsList(); + configurationServiceImpl.getAssetIntegrationPath(); + configurationServiceImpl.getClientID(); + configurationServiceImpl.getClientSecret(); + configurationServiceImpl.getDefPlaylistPlayerID(); + configurationServiceImpl.getDefPlaylistPlayerKey(); + configurationServiceImpl.getDefVideoPlayerDataEmbedded(); + configurationServiceImpl.getDefVideoPlayerID(); + configurationServiceImpl.getDefVideoPlayerKey(); + configurationServiceImpl.getPlayersLoc(); + configurationServiceImpl.getProxy(); + + Method configsServiceCleanStringArray = ConfigurationServiceImpl.class.getDeclaredMethod("cleanStringArray", String[].class); + } catch (Exception e) { + System.out.println("ConfigurationServiceImplTests" + e); + } + } + private void CertificateListServiceImplTests() { + CertificateListServiceImpl certificateListServiceImpl = new CertificateListServiceImpl(); + certificateListServiceImpl.getCertificatePaths(); + certificateListServiceImpl.getEnableTrustedCertificate(); + } + private void BrcReplicationHandlerTests() { + try { + BrcReplicationHandler brcReplicationHandler = new BrcReplicationHandler(); + TransportContext ctx = mock(TransportContext.class); + ReplicationTransaction tx = mock(ReplicationTransaction.class); + // brcReplicationHandler.deliver(ctx, tx); + + //Unsure how to initialize the abstract class - TransportContext + + } catch (Exception e) { + System.out.println("BrcReplicationHandlerTests" + e); + } + + } + private void S3UploadUtilTests() { + try { + //S3UploadUtil - 66% + S3UploadUtil s3UploadUtil = new S3UploadUtil(); + URL url = new URL("http://www.test.com"); + String str = "THISISACORESECURETESTSTRING"; + InputStream is = new ByteArrayInputStream(str.getBytes()); + s3UploadUtil.uploadToUrl(url, is); + } catch (Exception e) { + System.out.println("S3UploadUtilTests" + e); + } + } + private void BrcImageApiTests() { + try + { + BrcImageApi brcImageApi = new BrcImageApi(); + brcImageApi.init(); + } + catch (Exception e) + { + System.out.println("BrcImageApiTests" + e); + } + } + private void BrcAccountsUITests() { + try { + BrcAccountsUI brcAccountsUIMock = new BrcAccountsUI(); + brcAccountsUIMock.routeUIrequest(request, response); // Nullpointer + brcAccountsUIMock.api(request, response); + } catch (Exception e) { + System.out.println("BrcAccountsUITests" + e); + } + + } + private void AssetPropertyIntegratorTests() { + try { + AssetPropertyIntegrator assetPropertyIntegrator = mock(AssetPropertyIntegrator.class); + assetPropertyIntegrator.init(); + //Private Methods + } catch (Exception e) { + System.out.println("AssetPropertyIntegratorTests" + e); + } + } + private void AssetPropertyIntegratorRunnableTests() { + AssetPropertyIntegratorRunnable assetPropertyIntegratorRunnable = mock(AssetPropertyIntegratorRunnable.class); + assetPropertyIntegratorRunnable.run(); + } + + private void BrcApiTests() { + BrcApi myBrcAPI = new BrcApi(); + JSONObject outputJSON = new JSONObject(); + + try { + //ALL METHODS PRIVATE - MUST REFLECT + // brcAPI.getServletInfo(); + // brcAPI.getServletConfig(); + // brcAPI.getServletContext(); + + + //FIRST GOOD CASE TO USE REFLECTION + + myBrcAPI.init(); + String output; + Boolean outputBool; + + + //GET SERVICES + Method myGetServices = BrcApi.class.getDeclaredMethod("getServices", SlingHttpServletRequest.class); + myGetServices.setAccessible(true); + outputBool = (Boolean) myGetServices.invoke(myBrcAPI, request); +// + + + + } catch (Exception e) { + //e.printStackTrace(); + System.out.println("BrcApiTests : " + e); + } + + + try + { + Method myLocalPlayers = BrcApi.class.getDeclaredMethod("getLocalPlayers", SlingHttpServletRequest.class); + myLocalPlayers.setAccessible(true); + outputJSON = (JSONObject) myLocalPlayers.invoke(myBrcAPI, request); + } + catch (Exception e) + { + System.out.println("getLocalPlayers : " + e); + //e.printStackTrace(); + } + + try + { + Method myLocalPlayers1 = BrcApi.class.getDeclaredMethod("getPlayers"); + myLocalPlayers1.setAccessible(true); + outputJSON = (JSONObject) myLocalPlayers1.invoke(myBrcAPI, request); + } + catch (Exception e) + { + System.out.println("GetPlayersTest : " + e); + //e.printStackTrace(); + } + + + } + private void TestBrightcoveAPI() { + + + //TEST STATIC : TODO : Reference actual services and complete test - otherwise = nullpointer + try { + BrightcoveAPI static_BC_API = new BrightcoveAPI("1153191516001"); + } catch (NullPointerException e) { + System.out.println("Null static BC API"); + } + } + + private void TestVideoImportCallable() { + JSONObject innerObj = new JSONObject(); + String confPath = ""; + String requestedServiceAccount = ""; + ResourceResolverFactory resourceResolverFactory = mock(ResourceResolverFactory.class); + MimeTypeService mType = mock(MimeTypeService.class); + ServiceUtil serviceUtil = mock(ServiceUtil.class); + + String localpath = ""; + String id = ""; + String brightcove_filename = ""; + + try { + VideoImportCallable videoImportCallable = new VideoImportCallable(innerObj, confPath, requestedServiceAccount, resourceResolverFactory, mType, serviceUtil); + videoImportCallable.call(); + + Method createAssetMethod = videoImportCallable.getClass().getDeclaredMethod("createAsset", String.class, String.class, String.class); + + createAssetMethod.setAccessible(true); + Asset outputAsset = (Asset) createAssetMethod.invoke(videoImportCallable, localpath, id, brightcove_filename); + assertNotNull(outputAsset); + + } + catch (Exception e) + { + System.out.println("VideoImportCallable"); + } + } + + private void TestConfigGrabber(){ + + try { + ConfigurationGrabberImpl cg = ConfigurationGrabberImpl.class.newInstance(); + + + cg.getConfigurationService("key"); + cg.getAvailableServices(); + } + catch (Exception e) + { + System.out.println(e); + } + } + + + //NEEDS TO BE IMPROVED + private void MockTests() { + + try { + + VideoPlayerConfiguration videoPlayerConfiguration = mock(VideoPlayerConfiguration.class); + + /* Throws NullPointer + BrcAccountsUI brcAccountsUI = new BrcAccountsUI(); //Throws Nullpoint + brcAccountsUI.routeUIrequest(req, resp); + */ + BrcAccountsUI brcAccountsUIMock2 = new BrcAccountsUI(); + brcAccountsUIMock2.routeUIrequest(request, response); + Class clazz2 = brcAccountsUIMock2.getClass(); + Method method2 = clazz2.getDeclaredMethod("doGet"); + method2.setAccessible(true); + System.out.println("Method2"+method2.invoke(brcAccountsUIMock2)); + } catch (Exception e) { + System.out.println("Mock Tests: " + e); + } + + } + + + + +} + + diff --git a/current/pom.xml b/current/pom.xml index 91f3b77..f3c36ba 100644 --- a/current/pom.xml +++ b/current/pom.xml @@ -50,7 +50,7 @@ com.coresecure.brightcove.cq5 brightcove_connector pom - 5.5.0 + 5.5.1-SNAPSHOT Parent Maven POM for the 'Adobe CQ5 Brightcove Connector API' project. @@ -73,6 +73,11 @@ + + com.amashchenko.maven.plugin + gitflow-maven-plugin + 1.9.0 + org.apache.maven.plugins @@ -163,6 +168,11 @@ + + com.amashchenko.maven.plugin + gitflow-maven-plugin + 1.9.0 + org.apache.maven.plugins @@ -550,4 +560,4 @@ - + \ No newline at end of file diff --git a/current/ui.apps/pom.xml b/current/ui.apps/pom.xml index 3c3f376..2de9edf 100644 --- a/current/ui.apps/pom.xml +++ b/current/ui.apps/pom.xml @@ -54,7 +54,7 @@ com.coresecure.brightcove.cq5 brightcove_connector - 5.5.0 + 5.5.1-SNAPSHOT ../pom.xml @@ -232,7 +232,7 @@ com.coresecure.brightcove.cq5 brightcove-services - 5.5.0 + 5.5.1-SNAPSHOT @@ -257,4 +257,4 @@ - + \ No newline at end of file diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcUI.js b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcUI.js index 424655b..50b4316 100644 --- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcUI.js +++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcUI.js @@ -32,6 +32,18 @@ //CONFIG +//FIX FOR PROBLEM 5.5 TODO:REMOVE +$( document ).ready(function() { + console.log($("#selAccount").val()); + if(CQ.Ext!=null) + { + CQ.Ext.util.Cookies.set('brc_act', $("#selAccount").val()); + } +}); + + + + var $ACTIVE_TRACKS; var brc_admin = brc_admin || {}; From e76c7f8bfa76c05293a5fa405e48d2c9388498c6 Mon Sep 17 00:00:00 2001 From: pablo-kropilnicki Date: Fri, 7 Dec 2018 10:14:43 -0500 Subject: [PATCH 2/5] Updating documents --- LICENSE | 2 +- License.txt | 3 ++- README | 3 --- current/README.md | 5 ++--- 4 files changed, 5 insertions(+), 8 deletions(-) delete mode 100644 README diff --git a/LICENSE b/LICENSE index b22dcde..050e16d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 Coresecure, Inc. +Copyright (c) 2018 Coresecure, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/License.txt b/License.txt index bd61024..9334b45 100644 --- a/License.txt +++ b/License.txt @@ -1,9 +1,10 @@ Adobe CQ5 Brightcove Connector -Copyright (C) 2011 Coresecure Inc. +Copyright (C) 2018 Coresecure Inc. Authors: Alessandro Bonfatti Yan Kisen + Pablo Kropilnicki This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/README b/README deleted file mode 100644 index 5be2ec9..0000000 --- a/README +++ /dev/null @@ -1,3 +0,0 @@ -Adobe-AEM-Brightcove-Connector - -Brightcove Connector for Adobe AEM diff --git a/current/README.md b/current/README.md index 10b9bfe..9f1d040 100644 --- a/current/README.md +++ b/current/README.md @@ -45,8 +45,8 @@ The project comes with the auto-public repository configured. To setup the repos ##License - Copyright (C) 2017 **[Coresecure Inc.](https://www.coresecure.com)** - + Copyright (C) 2018 **[Coresecure Inc.](https://www.coresecure.com)** + #####Authors: - Alessandro Bonfatti - Yan Kisen @@ -72,4 +72,3 @@ squeakysand-commons and squeakysand-osgi (or a modified version of those libraries), containing parts covered by the terms of APACHE LICENSE 2.0 or MIT License, the licensors of this Program grant you additional permission to convey the resulting work. - From ae9d08cf5d3fc5cc67f2dd494735d58cb1231984 Mon Sep 17 00:00:00 2001 From: pablo-kropilnicki Date: Fri, 7 Dec 2018 10:23:56 -0500 Subject: [PATCH 3/5] Adding release script exclusion --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2bf4746..bcc54cf 100644 --- a/.gitignore +++ b/.gitignore @@ -83,4 +83,6 @@ cs_commons-dev/ ## Plugin-specific files: *.dir # IntelliJ -/out/ \ No newline at end of file +/out/ + +/current/prepareRelease.sh From ab1538891ab6336c54779e5d67ddc11b9d2f0911 Mon Sep 17 00:00:00 2001 From: pablo-kropilnicki Date: Fri, 7 Dec 2018 10:25:45 -0500 Subject: [PATCH 4/5] Updating release information --- current/core/pom.xml | 2 +- .../main/java/com/coresecure/brightcove/wrapper/Activator.java | 2 +- .../java/com/coresecure/brightcove/wrapper/BrightcoveAPI.java | 2 +- .../com/coresecure/brightcove/wrapper/enums/EconomicsEnum.java | 2 +- .../coresecure/brightcove/wrapper/enums/GeoFilterCodeEnum.java | 2 +- .../coresecure/brightcove/wrapper/enums/PlaylistFieldEnum.java | 2 +- .../coresecure/brightcove/wrapper/enums/PlaylistTypeEnum.java | 2 +- .../brightcove/wrapper/filter/CustomAddDialogTabFilter.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Account.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/BinaryObj.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Geo.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Images.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Ingest.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Platform.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Playlist.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Playlists.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Poster.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Projection.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/RelatedLink.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Schedule.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Text_track.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/Thumbnail.java | 2 +- .../com/coresecure/brightcove/wrapper/objects/TokenObj.java | 2 +- .../java/com/coresecure/brightcove/wrapper/objects/Video.java | 2 +- .../schedulers/asset_integrator/AssetIntegratorCronBundle.java | 2 +- .../asset_integrator/callables/VideoImportCallable.java | 2 +- .../asset_integrator/impl/AssetIntegratorCronBundleImpl.java | 2 +- .../runnables/AssetPropertyIntegratorRunnable.java | 2 +- .../brightcove/wrapper/sling/CertificateListService.java | 2 +- .../brightcove/wrapper/sling/CertificateListServiceImpl.java | 2 +- .../brightcove/wrapper/sling/ConfigurationGrabber.java | 2 +- .../brightcove/wrapper/sling/ConfigurationGrabberImpl.java | 2 +- .../brightcove/wrapper/sling/ConfigurationService.java | 2 +- .../brightcove/wrapper/sling/ConfigurationServiceImpl.java | 2 +- .../com/coresecure/brightcove/wrapper/sling/ServiceUtil.java | 2 +- .../com/coresecure/brightcove/wrapper/utils/AccountUtil.java | 2 +- .../com/coresecure/brightcove/wrapper/utils/HttpServices.java | 2 +- .../java/com/coresecure/brightcove/wrapper/utils/ImageUtil.java | 2 +- .../java/com/coresecure/brightcove/wrapper/utils/JcrUtil.java | 2 +- .../com/coresecure/brightcove/wrapper/utils/JsonReader.java | 2 +- .../coresecure/brightcove/wrapper/utils/ObjectSerializer.java | 2 +- .../com/coresecure/brightcove/wrapper/utils/S3UploadUtil.java | 2 +- .../java/com/coresecure/brightcove/wrapper/utils/TextUtil.java | 2 +- .../brightcove/wrapper/webservices/AssetPropertyIntegrator.java | 2 +- .../coresecure/brightcove/wrapper/webservices/BrcAccounts.java | 2 +- .../brightcove/wrapper/webservices/BrcAccountsUI.java | 2 +- .../com/coresecure/brightcove/wrapper/webservices/BrcApi.java | 2 +- .../coresecure/brightcove/wrapper/webservices/BrcImageApi.java | 2 +- .../brightcove/wrapper/webservices/BrcReplicationHandler.java | 2 +- .../brightcove/wrapper/webservices/BrcSuggestions.java | 2 +- current/pom.xml | 2 +- current/ui.apps/pom.xml | 2 +- .../apps/brightcove/clientlibs/cq-shared/css/shared.css | 2 +- .../clientlibs/cq-widgets/source/css/brightcoveUpload.css | 2 +- .../brightcove/clientlibs/cq-widgets/source/js/brc_account.js | 2 +- .../brightcove/clientlibs/cq-widgets/source/js/brc_combobox.js | 2 +- .../apps/brightcove/clientlibs/cq-widgets/source/js/brc_util.js | 2 +- .../clientlibs/cq-widgets/source/js/brightcoveUpload.js | 2 +- .../cq-widgets/themes/default/source/css/content-finder.css | 2 +- .../cq-widgets/themes/default/source/css/cq-console.css | 2 +- .../content/brightcoveplayer-playlist/inline-styles.html | 2 +- .../content/brightcoveplayer-playlist/player-embed.html | 2 +- .../components/content/brightcoveplayer/brightcoveplayer.html | 2 +- .../components/content/brightcoveplayer/inline-styles.html | 2 +- .../components/content/brightcoveplayer/player-embed.html | 2 +- .../components/content/brightcoveplaylist/player-embed.html | 2 +- .../components/content/brightcovevideo/player-embed.html | 2 +- .../components/page/brightcoveIframe/brightcoveIframe.html | 2 +- .../components/page/brightcoveplayer/brightcoveplayer.html | 2 +- .../components/page/brightcoveplayer/clientlib/listener.js | 2 +- .../apps/brightcove/components/shared/autoDialog/autoDialog.jsp | 2 +- .../brightcove/components/shared/autoDialog/infinity.json.jsp | 2 +- .../jcr_root/apps/brightcove/components/shared/global.jsp | 2 +- .../components/tools/brightcoveadmin/clientlibs/css/style.css | 2 +- .../components/tools/brightcoveadmin/clientlibs/js/brcAdmin.js | 2 +- .../components/tools/brightcoveadmin/clientlibs/js/brcUI.js | 2 +- .../brightcove/extensions/contentfinder/brightcovePlayers.js | 2 +- .../brightcove/extensions/contentfinder/brightcovePlaylist.js | 2 +- .../apps/brightcove/extensions/contentfinder/brightcoveVideo.js | 2 +- .../brightcove/players/html5-player/js/BrightcoveExperiences.js | 2 +- .../designs/cs/brightcove/players/smart-player/css/style.css | 2 +- .../brightcove/players/smart-player/js/BrightcoveExperiences.js | 2 +- 82 files changed, 82 insertions(+), 82 deletions(-) diff --git a/current/core/pom.xml b/current/core/pom.xml index 5aa6164..9e19ee8 100644 --- a/current/core/pom.xml +++ b/current/core/pom.xml @@ -2,7 +2,7 @@