diff --git a/current/core/pom.xml b/current/core/pom.xml
index c1f849b..49d5474 100644
--- a/current/core/pom.xml
+++ b/current/core/pom.xml
@@ -46,24 +46,44 @@
| limitations under the License.
-->
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.coresecure.brightcove.cq5
brightcove_connector
- 5.3.1
+ 5.5.0
../pom.xml
brightcove-services
bundle
brightcove - Core
Core bundle for Brightcove
+
+ jacoco
+ reuseReports
+ ${project.basedir}/../target/jacoco.exec
+
org.apache.felix
maven-scr-plugin
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.7.9
+
+
+
+ prepare-agent
+
+
+
+
+ ${sonar.jacoco.reportPath}
+
+
org.apache.felix
maven-bundle-plugin
@@ -112,6 +132,113 @@
+
+ integrationTests
+
+ false
+
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.7.2.201409121644
+
+ true
+
+
+
+
+ prepare-agent-integration
+
+
+ true
+
+
+ com.ninedemons.*
+
+ true
+ jacoco.agent.it.arg
+
+
+
+ jacoco-site
+ post-integration-test
+
+ report-integration
+
+
+ ${project.reporting.outputDirectory}/jacoco-it
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+ integration-test
+
+ integration-test
+
+
+
+ verify
+
+ verify
+
+
+
+
+ -Xmx1024m -XX:MaxPermSize=256m ${jacoco.agent.it.arg}
+ ${maven.surefire.debug}
+
+ ${tests.to.run}
+
+
+ ${test.server.url}
+ ${test.server.hostname}
+ ${test.server.username}
+ ${test.server.password}
+ ${http.port}
+ ${jar.executor.vm.options} ${jacoco.agent.it.arg}
+ ${project.basedir}/target/dependency
+ cq-quickstart.*jar$
+ ${jar.executor.work.folder}
+ ${jar.executor.jar.options}
+ ${project.basedir}/target/sling/additional-bundles
+ ${keepJarRunning}
+ 6000
+ ${sling.testing.timeout.multiplier}
+ /libs/granite/core/content/login.html:QUICKSTART_HOMEPAGE
+ 40
+ 30
+
+
+ org.apache.sling.junit.core
+ org.apache.sling.junit.scriptable
+ example.models
+ example.core
+ org.apache.sling.junit.remote
+ org.apache.sling.testing.tools
+ httpclient-osgi
+ httpcore-osgi
+
+
+
+
+
+
+
+
@@ -219,17 +346,41 @@
org.apache.sling
org.apache.sling.models.api
+
+ junit-addons
+ junit-addons
+
+
+ org.slf4j
+ slf4j-log4j12
+ 1.5.6
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.7.9
+
+
+
+ org.apache.sling
+ org.apache.sling.testing.sling-mock
+ 1.0.0
+ test
+
+
junit
junit
+ 4.12
+ test
+
org.mockito
- mockito-all
-
-
- junit-addons
- junit-addons
+ mockito-core
+ 1.10.19
+ test
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/Activator.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/Activator.java
index a532674..3e1acd6 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/Activator.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/Activator.java
@@ -50,7 +50,7 @@ public class Activator implements BundleActivator {
*/
public void start(BundleContext context) throws Exception {
log.info(context.getBundle().getSymbolicName() + " started");
- // TODO add initialization code
+ //add initialization code
}
/*
@@ -59,6 +59,6 @@ public void start(BundleContext context) throws Exception {
*/
public void stop(BundleContext context) throws Exception {
log.info(context.getBundle().getSymbolicName() + " stopped");
- // TODO add cleanup code
+ //add cleanup code
}
}
\ 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 dfda9d8..10afdd3 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
@@ -32,7 +32,7 @@
*/
package com.coresecure.brightcove.wrapper;
-import com.coresecure.brightcove.wrapper.api.Cms;
+import com.coresecure.brightcove.wrapper.api.CmsAPI;
import com.coresecure.brightcove.wrapper.objects.Account;
import com.coresecure.brightcove.wrapper.objects.Platform;
import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber;
@@ -42,21 +42,20 @@
import org.slf4j.LoggerFactory;
public class BrightcoveAPI {
- public Platform platform;
- public Account account;
- public Cms cms;
+ public final Platform platform;
+ public final Account account;
+ public final CmsAPI cms;
private static final Logger LOGGER = LoggerFactory.getLogger(BrightcoveAPI.class);
- public BrightcoveAPI(String aClient_id, String aClient_secret, String aAccount_id) {
- LOGGER.debug("BrightcoveAPI Init aAccount_id " + aAccount_id);
-
+ public BrightcoveAPI(String aClientId, String aClientSecret, String aAccountId) {
+ LOGGER.debug("BrightcoveAPI Init aAccount_id {}", aAccountId);
platform = new Platform();
- account = new Account(platform, aClient_id, aClient_secret, aAccount_id);
- cms = new Cms(account);
+ account = new Account(platform, aClientId, aClientSecret, aAccountId);
+ cms = new CmsAPI(account);
}
public BrightcoveAPI(String key) {
- LOGGER.debug("BrightcoveAPI Init key " + key);
+ LOGGER.debug("BrightcoveAPI Init key {}", key);
platform = new Platform();
ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
ConfigurationService brcService = cg.getConfigurationService(key);
@@ -65,7 +64,7 @@ public BrightcoveAPI(String key) {
setProxy(brcService.getProxy());
}
account = new Account(platform, brcService.getClientID(), brcService.getClientSecret(), brcService.getAccountID());
- cms = new Cms(account);
+ cms = new CmsAPI(account);
}
public void setProxy(String proxy) {
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/Cms.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/Cms.java
deleted file mode 100644
index 367a27e..0000000
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/Cms.java
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
-
- Adobe AEM Brightcove Connector
-
- Copyright (C) 2017 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
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
- - Additional permission under GNU GPL version 3 section 7
- If you modify this Program, or any covered work, by linking or combining
- it with httpclient 4.1.3, httpcore 4.1.4, httpmine 4.1.3, jsoup 1.7.2,
- 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.
-
- */
-package com.coresecure.brightcove.wrapper.api;
-
-import com.coresecure.brightcove.wrapper.objects.*;
-import com.coresecure.brightcove.wrapper.utils.JsonReader;
-import org.apache.commons.lang3.math.NumberUtils;
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.net.URLEncoder;
-import java.util.HashMap;
-import java.util.Map;
-
-public class Cms {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(Cms.class);
-
- private Account account;
- public final static int DEFAULT_LIMIT = 20;
- private final static int DEFAULT_OFFSET = 0;
- private final static String DEFAULT_ENCODING = "UTF-8";
-
- public Cms(Account aAccount) {
- LOGGER.debug("Cms Init aAccount " + aAccount.getAccount_ID());
- account = aAccount;
- }
-
- public JSONObject getPlayers() {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String urlParameters = "";
- String targetURL = "/accounts/" + account.getAccount_ID() + "/players";
- try {
- String response = account.platform.getPLAYERS_API(targetURL, urlParameters, headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getVideosCount(String q) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
-
- String targetURL = "/accounts/" + account.getAccount_ID() + "/counts/videos";
- try {
- String urlParameters = "q=" + ((q!= null) ? URLEncoder.encode(q, DEFAULT_ENCODING):"");
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getPlaylistsCount() {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String urlParameters = "";
- String targetURL = "/accounts/" + account.getAccount_ID() + "/counts/playlists";
- try {
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getVideo(String ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String urlParameters = "";
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + ID;
- try {
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- LOGGER.debug("getVideo response "+ response);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
-
- public JSONObject getCustomFields() {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String urlParameters = "";
- String targetURL = "/accounts/" + account.getAccount_ID() + "/video_fields";
- try {
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- LOGGER.debug("getCustomFields response "+ response);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- return json;
- }
-
-
- public JSONObject createVideo(Video aVideo) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos";
- try {
-
- JSONObject videoObj = aVideo.toJSON();
- videoObj.remove("account_id");
- String response = account.platform.postAPI(targetURL, aVideo.toJSON().toString(1), headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- LOGGER.trace("createVideo: "+aVideo.toString()+" Response: "+json.toString());
- return json;
- }
- public JSONObject createPlaylist(Playlist aPlaylist) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/playlists";
- try {
- String response = account.platform.postAPI(targetURL, aPlaylist.toJSON().toString(1), headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- LOGGER.trace("createPlaylist: "+aPlaylist.toString()+" Response: "+json.toString());
- return json;
- }
-
- public JSONObject updateVideo(Video aVideo) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/"+aVideo.id;
- try {
- LOGGER.debug("targetURL: "+targetURL);
- JSONObject video = aVideo.toJSON();
-
-
- LOGGER.trace("UPDATE VIDEO DATA OBJECT: " + video.toString(1));
- video.remove("id");
- video.remove("account_id");
-
- String response = account.platform.patchAPI(targetURL, video.toString(1), headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- return json;
- }
-
-
- public JSONObject uploadInjest(String videoId, JSONObject payload)
- {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + videoId + "/ingest-requests";
-
- try {
- LOGGER.trace("PAYLOAD PROTO>>: " + payload.toString(1));
- String response = account.platform.postDIRequest_API(targetURL, payload.toString(1), headers);
-
- if (response != null && !response.isEmpty()) json.put("response",response);
-
- }
- catch (JSONException e)
- {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
-
- return json;
- }
-
-
-
- public JSONObject createIngest(Video aVideo, Ingest aIngest) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + aVideo.id + "/ingest-requests";
- try {
- String response = account.platform.postDI_API(targetURL, aIngest.toJSON().toString(1), headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- return json;
- }
-
- public JSONObject getIngestURL(String videoId, String filename) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + videoId + "/upload-urls/"+filename;
- LOGGER.trace("getIngestURL: "+targetURL);
- try {
- String response = account.platform.getDI_API(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- return json;
- }
- public JSONObject requestIngestURL(String videoId, String profile, String master, boolean getImages) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + videoId + "/ingest-requests";
- LOGGER.trace("requestIngestURL: "+targetURL);
-
- try {
- JSONObject payload = new JSONObject("{'master': {'url': '"+master+"'},'profile': '"+profile+"','capture-images': "+getImages+"}");
-
- String response = account.platform.postDIRequest_API(targetURL, payload.toString(1), headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
- }
- return json;
- }
- public JSONObject deleteVideo(String videoID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- System.out.println(authToken.getToken());
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + videoID;
- try {
- String response = account.platform.deleteAPI(targetURL, videoID, headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- LOGGER.debug("deleteVideo response json:"+json.toString(1));
- } catch (IOException e) {
- try {
- json.put("error_code", "IOException");
- json.put("message", e.getMessage());
- }catch (JSONException ee) {
- LOGGER.error("JSONException", ee);
- }
- LOGGER.error("IOException", e);
- } catch (JSONException e) {
- try {
- json.put("error_code", "JSONException");
- json.put("message", e.getMessage());
- }catch (JSONException ee) {
- LOGGER.error("JSONException", ee);
- }
- LOGGER.error("JSONException", e);
- }
- }
- return json;
- }
-
- public JSONArray getVideoSources(String ID) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + ID + "/sources";
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getVideoImages(String ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/" + ID + "/images";
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- LOGGER.debug("getVideoImages response "+ response);
-
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONArray getVideos(String q, int limit, int offset, String sort) {
- JSONArray json = new JSONArray();
- LOGGER.debug("account: " + account.getAccount_ID());
- account.login();
- Token authToken = account.getToken();
- LOGGER.debug("authToken: " + authToken.getToken());
-
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
-
- try {
- q = (q != null) ? URLEncoder.encode(q, DEFAULT_ENCODING) : "";
- String urlParameters = "q=%2Bstate:ACTIVE%20%2Dtags:AEM_NO_DAM" + (!q.isEmpty() ? "%20%2B"+q:"") + "&limit=" + limit + "&offset=" + offset + (sort != null ? "&sort=" + sort:"");
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos";
- LOGGER.debug("urlParameters: " + urlParameters);
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- if (response != null && !response.isEmpty()) {
- json = JsonReader.readJsonArrayFromString(response);
- LOGGER.debug("response", response);
- LOGGER.debug("json", json.toString());
- }
- if (json.length() == 0 && !q.isEmpty() && NumberUtils.isNumber(q)) {
- json.put(getVideo(q));
- }
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
-
- }
-
- return json;
- }
- public JSONArray addThumbnail(JSONArray input) {
- JSONArray videos = new JSONArray();
- try {
- for (int i = 0; i < input.length(); i++) {
-
- JSONObject video = input.getJSONObject(i);
- if (video.has("id")) {
- if (video.has("images") && video.getJSONObject("images").has("thumbnail")) {
- video.put("thumbnailURL", video.getJSONObject("images").getJSONObject("thumbnail").getString("src"));
- } else {
- video.put("thumbnailURL", "/etc/designs/cs/brightcove/shared/img/noThumbnail.jpg");
- }
- videos.put(video);
- }
- }
- } catch (JSONException je) {
- LOGGER.error("JSONException", je);
- }
- return videos;
- }
-
- public JSONObject getVideoByRef(String ref_ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/ref:" + ref_ID;
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONArray getVideoSourcesByRef(String ref_ID) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/ref:" + ref_ID + "/sources";
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getPlaylist(String ref_ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/playlists/" + ref_ID;
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONArray getPlaylists(int limit, int offset, String sort) {
-
- return getPlaylists( null, limit, offset, sort);
- }
- public JSONArray getPlaylists(String q, int limit, int offset, String sort) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/playlists";
- try {
- q = (q != null) ? URLEncoder.encode(q, DEFAULT_ENCODING) : "";
- String urlParameters = "q=" + q +"&limit=" + limit + "&offset=" + offset + "&sort=" + sort;
- String response = account.platform.getAPI(targetURL, urlParameters, headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONObject getVideoImagesByRef(String ref_ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType() + " " + authToken.getToken());
- String targetURL = "/accounts/" + account.getAccount_ID() + "/videos/ref:" + ref_ID + "/images";
- try {
- String response = account.platform.getAPI(targetURL, "", headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- LOGGER.error("IOException", e);
- e.printStackTrace();
- } catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- // Command permutations
- public JSONArray getVideos() {
- return getVideos("", DEFAULT_LIMIT, DEFAULT_OFFSET, "");
- }
-
- public JSONArray getVideos(String q) {
- return getVideos(q, DEFAULT_LIMIT, DEFAULT_OFFSET, "");
- }
-
- public JSONArray getVideos(String q, String sort) {
- return getVideos(q, DEFAULT_LIMIT, DEFAULT_OFFSET, sort);
- }
-
- public JSONArray getVideos(String q, String sort, int limit) {
- return getVideos(q, limit, DEFAULT_OFFSET, sort);
- }
-
- public JSONArray getVideos(String q, int limit) {
- return getVideos(q, limit, DEFAULT_OFFSET, "");
- }
-
- public JSONArray getVideos(String q, int limit, int offset) {
- return getVideos(q, limit, offset, "");
- }
-
- public JSONArray getVideos(int limit, int offset, String sort) {
- return getVideos("", limit, offset, sort);
- }
-
-}
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
new file mode 100644
index 0000000..77942cb
--- /dev/null
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/CmsAPI.java
@@ -0,0 +1,549 @@
+package com.coresecure.brightcove.wrapper.api;
+
+import com.coresecure.brightcove.wrapper.objects.*;
+import com.coresecure.brightcove.wrapper.utils.Constants;
+import com.coresecure.brightcove.wrapper.utils.JsonReader;
+import com.coresecure.brightcove.wrapper.utils.TextUtil;
+import org.apache.commons.lang3.math.NumberUtils;
+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.json.io.JSONWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Created by pablo.kropilnicki on 12/20/17.
+ */
+public class CmsAPI {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CmsAPI.class);
+
+ private Account account;
+ private static final int DEFAULT_LIMIT = 20;
+ private static final int DEFAULT_OFFSET = 0;
+ private static final String DEFAULT_ENCODING = "UTF-8";
+
+ // CMS
+ public CmsAPI(Account aAccount){ LOGGER.debug("CmsAPI Init aAccount {}" , aAccount.getAccount_ID()); account= aAccount;}
+
+
+ //GET PLAYERS API
+ public JSONObject getPlayers() {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/players";
+ try {
+ String response = account.platform.getPLAYERS_API(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+
+ }
+ return json;
+ }
+
+ //postDIRequest_API
+ public JSONObject uploadInjest(String videoId, JSONObject payload) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null)
+ {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + videoId + Constants.INGEST_REQUEST;
+ try
+ {
+ LOGGER.trace("UploadInjestPayload: {}", payload);
+ String response = account.platform.postDIRequest_API(targetURL, payload.toString(), headers);
+ if (response != null && !response.isEmpty()) json.put(Constants.RESPONSE,response);
+ }
+ catch (JSONException e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //postDIRequest_API
+ public JSONObject requestIngestURL(String videoId, String profile, String master, boolean getImages) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + videoId + Constants.INGEST_REQUEST;
+ LOGGER.trace("requestIngestURL: {}", targetURL);
+ LOGGER.trace("ingest_profile: {} ", profile);
+
+ try {
+ //Support for profile changed as per - 12961
+ JSONObject payload = new JSONObject();
+ JSONObject master_obj = new JSONObject();
+ master_obj.put("url", master);
+ payload.put("master", master_obj);
+ payload.put("capture-images", getImages);
+ if(!TextUtil.isEmpty(profile))
+ {
+ payload.put("profile", profile);
+ }
+ String response = account.platform.postDIRequest_API(targetURL, payload.toString(1), headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //postDI_API
+ public JSONObject createIngest(Video aVideo, Ingest aIngest) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + aVideo.id + Constants.INGEST_REQUEST;
+ try {
+ String response = account.platform.postDI_API(targetURL, aIngest.toJSON().toString(1), headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //getDI_API
+ public JSONObject getIngestURL(String videoId, String filename) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + videoId + "/upload-urls/"+filename;
+ LOGGER.trace("getIngestURL: {}", targetURL);
+ try {
+ String response = account.platform.getDI_API(targetURL, "", headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //postAPI
+ public JSONObject createVideo(Video aVideo) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/videos";
+ try {
+
+ JSONObject videoObj = aVideo.toJSON();
+ videoObj.remove(Constants.ACCOUNT_ID);
+ String response = account.platform.postAPI(targetURL, aVideo.toJSON().toString(1), headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ LOGGER.trace("createVideo: {} Response: {}",aVideo , json);
+ return json;
+ }
+
+ //PatchAPI
+ public JSONObject updateVideo(Video aVideo) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH+aVideo.id;
+ try {
+ LOGGER.debug("targetURL: {}",targetURL);
+ JSONObject video = aVideo.toJSON();
+ LOGGER.trace("UPDATE VIDEO DATA OBJECT: {} ", video);
+ video.remove(Constants.ID);
+ video.remove(Constants.ACCOUNT_ID);
+
+ String response = account.platform.patchAPI(targetURL, video.toString(1), headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //deleteAPI
+ public JSONObject deleteVideo(String videoID) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + videoID;
+ try {
+ String response = account.platform.deleteAPI(targetURL, videoID, headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ LOGGER.debug("deleteVideo response json: {}" , json);
+ } catch (IOException e) {
+ try {
+ json.put("error_code", "IOException");
+ json.put("message", e.getMessage());
+ }catch (JSONException ee) {
+ LOGGER.error(ee.getClass().getName(), ee);
+ }
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ try {
+ json.put("error_code", "JSONException");
+ json.put("message", e.getMessage());
+ }catch (JSONException ee) {
+ LOGGER.error(ee.getClass().getName(), ee);
+ }
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getVideo(String id) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + id;
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getPlaylistsCount() {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null)
+ {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/counts/playlists";
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //postAPI
+ public JSONObject createPlaylist(Playlist aPlaylist) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null)
+ {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/playlists";
+ try {
+ LOGGER.debug("Playlist {}", aPlaylist.toJSON().toString());
+ String response = account.platform.postAPI(targetURL, aPlaylist.toJSON().toString(1), headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ LOGGER.trace("createPlaylist: {} Response: {}", aPlaylist, json);
+ return json;
+ }
+
+ public JSONObject getVideosCount(String q) {
+ return getVideosCount(q, false);
+ }
+ //getAPI
+ public JSONObject getVideosCount(String q, boolean dam_only) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null)
+ {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/counts/videos";
+ try {
+ String urlParameters = "q=%2Bstate:ACTIVE" + (dam_only ? "%20%2Dtags:AEM_NO_DAM" : "") + (q != null && !q.isEmpty() ? Constants.WHITESPACE_FIX+URLEncoder.encode(q, DEFAULT_ENCODING):"");
+ json = getJSONObjectResponse(targetURL, urlParameters, headers);
+ }
+ catch (UnsupportedEncodingException e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONArray getVideoSources(String id) {
+ JSONArray json = new JSONArray();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null)
+ {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + id + "/sources";
+ json = getJSONArrayResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getVideoImagesByRef(String refID) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH+Constants.REFERENCE_SEARCH_FIELD_TAG + refID + "/images";
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONArray getVideoSourcesByRef(String refID) {
+ JSONArray json = new JSONArray();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + Constants.REFERENCE_SEARCH_FIELD_TAG + refID + "/sources";
+ json = getJSONArrayResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getVideoByRef(String refID) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + Constants.VIDEOS_API_PATH + Constants.REFERENCE_SEARCH_FIELD_TAG + refID;
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getCustomFields() {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/video_fields";
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+
+ //getAPI
+ public JSONObject getVideoImages(String id) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType()+" "+authToken.getToken());
+ String targetURL =Constants.ACCOUNTS_API_PATH+account.getAccount_ID()+Constants.VIDEOS_API_PATH+id+"/images";
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS , headers);
+ }
+ return json;
+ }
+
+ //No network call
+ public JSONArray addThumbnail(JSONArray input) {
+ JSONArray videos = new JSONArray();
+ try {
+ for (int i = 0; i < input.length(); i++) {
+ JSONObject video = input.getJSONObject(i);
+ if (video.has(Constants.ID)) {
+ if (video.has(Constants.IMAGES) && video.getJSONObject(Constants.IMAGES).has(Constants.THUMBNAIL)) {
+ video.put(Constants.THUMBNAIL_URL, video.getJSONObject(Constants.IMAGES).getJSONObject(Constants.THUMBNAIL).getString(Constants.SRC));
+ } else {
+ video.put(Constants.THUMBNAIL_URL, Constants.DEFAULT_THUMBNAIL_LOCATION);
+ }
+ videos.put(video);
+ }
+ }
+ } catch (JSONException je) {
+ LOGGER.error(je.getClass().getName(), je);
+ }
+ return videos;
+ }
+
+
+ public JSONArray getVideos(String q, int limit, int offset, String sort) {
+ return getVideos(q, limit, offset, sort, false);
+ }
+
+ //ACTUAL GET VIDEOS FUNCTION
+ //DO NOT TOUCH - getAPI Adaptation - IGNORES NON ACTIVE - IGNORES VIDEOS WITH "AEM_NO_DAM" TAG
+ public JSONArray getVideos(String q, int limit, int offset, String sort, boolean dam_only) {
+ JSONArray json = new JSONArray();
+ LOGGER.debug("account: {}" , account.getAccount_ID());
+ TokenObj authToken = account.getLoginToken();
+ LOGGER.debug("authToken: {}" , authToken.getToken());
+ try {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ q = (q != null) ? URLEncoder.encode(q, DEFAULT_ENCODING) : "";
+ String urlParameters = "q=%2Bstate:ACTIVE" + (dam_only ? "%20%2Dtags:AEM_NO_DAM" : "") + (!q.isEmpty() ? Constants.WHITESPACE_FIX+URLEncoder.encode(q, DEFAULT_ENCODING):"") + "&limit=" + limit + "&offset=" + offset + (sort != null ? "&sort=" + sort:"");
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/videos";
+ LOGGER.debug("urlParameters: {}" , urlParameters);
+ String response = account.platform.getAPI(targetURL, urlParameters, headers);
+ if (!response.isEmpty()) {
+ json = JsonReader.readJsonArrayFromString(response);
+ LOGGER.debug(Constants.RESPONSE, response);
+ LOGGER.debug("json {}", json);
+ } else if (!q.isEmpty() && NumberUtils.isNumber(q)) {
+ json.put(getVideo(q));
+ }
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (NullPointerException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ return json;
+ }
+ //GET VIDEO OVERLOADS
+ public JSONArray getVideos() {
+ return getVideos(Constants.EMPTY_Q_PARAM);
+ }
+ public JSONArray getVideos(String q) {
+ return getVideos(q, DEFAULT_LIMIT);
+ }
+ public JSONArray getVideos(String q, String sort) {
+ return getVideos(q, DEFAULT_LIMIT, DEFAULT_OFFSET, sort);
+ }
+ public JSONArray getVideos(String q, String sort, int limit) {
+ return getVideos(q, limit, DEFAULT_OFFSET, sort);
+ }
+ public JSONArray getVideos(String q, int limit) {
+ return getVideos(q, limit, DEFAULT_OFFSET);
+ }
+ public JSONArray getVideos(String q, int limit, int offset) {
+ return getVideos(q, limit, offset, Constants.EMPTY_SORT_PARAM);
+ }
+ public JSONArray getVideos(int limit, int offset, String sort) {
+ return getVideos(Constants.EMPTY_Q_PARAM, limit, offset, sort);
+ }
+
+
+
+
+ //getAPI
+ public JSONObject getPlaylist(String refID) {
+ JSONObject json = new JSONObject();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/playlists/" + refID;
+ json = getJSONObjectResponse(targetURL, Constants.EMPTY_URLPARAMS, headers);
+ }
+ return json;
+ }
+ public JSONArray getPlaylists() {
+ return getPlaylists(DEFAULT_LIMIT, DEFAULT_OFFSET, Constants.NAME);
+ }
+ public JSONArray getPlaylists(int limit, int offset, String sort) {
+ return getPlaylists( null, limit, offset, sort);
+ }
+ public JSONArray getPlaylists(String q, int limit, int offset, String sort) {
+ JSONArray json = new JSONArray();
+ TokenObj authToken = account.getLoginToken();
+ if (authToken != null) {
+ Map headers = new HashMap();
+ headers.put(Constants.AUTHENTICATION_HEADER, authToken.getTokenType() + " " + authToken.getToken());
+ String targetURL = Constants.ACCOUNTS_API_PATH + account.getAccount_ID() + "/playlists";
+ try {
+ q = (q != null) ? URLEncoder.encode(q, DEFAULT_ENCODING) : "";
+ String urlParameters = "q=" + URLEncoder.encode(q, DEFAULT_ENCODING) + "&limit=" + limit + "&offset=" + offset + "&sort=" + sort;
+ json = getJSONArrayResponse(targetURL, urlParameters, headers);
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ return json;
+ }
+
+ //GET API
+ public JSONObject getJSONObjectResponse(String targetURL, String urlParameters, Map headers) {
+ JSONObject json = new JSONObject();
+ try
+ {
+ String response = account.platform.getAPI(targetURL, urlParameters, headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
+ }
+ catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ catch (JSONException e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ return json;
+
+}
+ public JSONArray getJSONArrayResponse(String targetURL, String urlParameters, Map headers) {
+ JSONArray json = new JSONArray();
+ try
+ {
+ String response = account.platform.getAPI(targetURL, urlParameters, headers);
+ if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
+ }
+ catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ catch (JSONException e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ return json;
+
+ }
+
+
+
+}
\ No newline at end of file
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/DI_API.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/DI_API.java
deleted file mode 100644
index 2f5a15e..0000000
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/api/DI_API.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
-
- Adobe AEM Brightcove Connector
-
- Copyright (C) 2017 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
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
- - Additional permission under GNU GPL version 3 section 7
- If you modify this Program, or any covered work, by linking or combining
- it with httpclient 4.1.3, httpcore 4.1.4, httpmine 4.1.3, jsoup 1.7.2,
- 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.
-
- */
-package com.coresecure.brightcove.wrapper.api;
-
-import com.coresecure.brightcove.wrapper.objects.Account;
-import com.coresecure.brightcove.wrapper.objects.Token;
-import com.coresecure.brightcove.wrapper.utils.JsonReader;
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-public class DI_API {
- private Account account;
- private final static int DEFAULT_LIMIT = 20;
- private final static int DEFAULT_OFFSET = 0;
-
- public DI_API(Account aAccount){
- account= aAccount;
- }
- public JSONObject getVideo(String ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String urlParameters = "";
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos/"+ID;
- try {
- String response = account.platform.getAPI(targetURL, urlParameters , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONArray getVideoSources(String ID) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos/"+ID+"/sources";
- try {
- String response = account.platform.getAPI(targetURL, "" , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONObject getVideoImages(String ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String targetURL ="/accounts/"+account.getAccount_ID()+"/videos/"+ID+"/images";
- try {
- String response = account.platform.getAPI(targetURL, "" , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONArray getVideos(String q, int limit, int offset, String sort) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String urlParameters = "q="+q+"&limit="+limit+"&offset="+offset+"&sort="+sort;
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos";
- try {
- String response = account.platform.getAPI(targetURL, urlParameters , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- if (json.length() ==0 && !q.isEmpty()) json.put(getVideo(q));
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- public JSONObject getVideoByRef(String ref_ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos/ref:"+ref_ID;
- try {
- String response = account.platform.getAPI(targetURL, "" , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONArray getVideoSourcesByRef(String ref_ID) {
- JSONArray json = new JSONArray();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos/ref:"+ref_ID+"/sources";
- try {
- String response = account.platform.getAPI(targetURL, "" , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonArrayFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
- public JSONObject getVideoImagesByRef(String ref_ID) {
- JSONObject json = new JSONObject();
- account.login();
- Token authToken = account.getToken();
- if (authToken != null) {
- Map headers = new HashMap();
- headers.put("Authorization", authToken.getTokenType()+" "+authToken.getToken());
- String targetURL = "/accounts/"+account.getAccount_ID()+"/videos/ref:"+ref_ID+"/images";
- try {
- String response = account.platform.getAPI(targetURL, "" , headers);
- if (response != null && !response.isEmpty()) json = JsonReader.readJsonFromString(response);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- }
- return json;
- }
-
- // Command permutations
- public JSONArray getVideos() {
- return getVideos("",DEFAULT_LIMIT,DEFAULT_OFFSET,"");
- }
- public JSONArray getVideos(String q) {
- return getVideos(q,DEFAULT_LIMIT,DEFAULT_OFFSET,"");
- }
- public JSONArray getVideos(String q, String sort) {
- return getVideos(q,DEFAULT_LIMIT,DEFAULT_OFFSET,sort);
- }
- public JSONArray getVideos(String q, int limit) {
- return getVideos(q,limit,DEFAULT_OFFSET,"");
- }
- public JSONArray getVideos(String q, int limit, int offset) {
- return getVideos(q,limit,offset,"");
- }
- public JSONArray getVideos(int limit, int offset, String sort) {
- return getVideos("",limit,offset,sort);
- }
-
-}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/enums/PlaylistFieldEnum.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/enums/PlaylistFieldEnum.java
index 8453865..dae4b55 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/enums/PlaylistFieldEnum.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/enums/PlaylistFieldEnum.java
@@ -36,8 +36,8 @@
public enum PlaylistFieldEnum {
ID("ID", "id"),
- REFERENCEID("REFERENCEID", "referenceId"),
- ACCOUNTID("ACCOUNTID", "accountId"),
+ REFERENCEID("REFERENCEID", "reference_id"),
+ ACCOUNTID("ACCOUNTID", "account_id"),
NAME("NAME", "name"),
SHORTDESCRIPTION("SHORTDESCRIPTION", "shortDescription"),
VIDEOIDS("VIDEOIDS", "video_ids"),
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/filter/CustomAddDialogTabFilter.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/filter/CustomAddDialogTabFilter.java
index 41cffea..68e16ef 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/filter/CustomAddDialogTabFilter.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/filter/CustomAddDialogTabFilter.java
@@ -37,6 +37,7 @@
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.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
import org.apache.sling.commons.json.JSONException;
@@ -44,6 +45,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.annotation.Nonnull;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
@@ -65,7 +67,7 @@
})
public class CustomAddDialogTabFilter extends SlingSafeMethodsServlet implements Filter {
- final private Logger LOGGER = LoggerFactory.getLogger(CustomAddDialogTabFilter.class);
+ final static private Logger LOGGER = LoggerFactory.getLogger(CustomAddDialogTabFilter.class);
@Override
public void init(FilterConfig filterConfig) {
@@ -125,35 +127,18 @@ public void doFilter(ServletRequest pRequest, ServletResponse pResponse, FilterC
String fullRequestPath = slingRequest.getRequestURI();
String componentPath = fullRequestPath.substring(0, fullRequestPath.lastIndexOf("/"));
String dialogPath = getInheritDialog(slingRequest);
-
- Node dialogNode = slingRequest.getResourceResolver().getResource(dialogPath).adaptTo(Node.class);
- TidyJsonItemWriter td = new TidyJsonItemWriter(null);
- StringWriter writer = new StringWriter();
- td.dump(dialogNode, writer, 1000);
- JSONObject originalDialog = new JSONObject(writer.toString());
- JSONObject originalTabs = originalDialog.getJSONObject("items").getJSONObject("tabs").getJSONObject("items");
-
- Resource componentRes = slingRequest.getResourceResolver().getResource(componentPath);
- if (componentRes != null) {
- for (Resource item : getInheritResources(componentRes)) {
-
- NodeIterator additionalTabs = item.adaptTo(Node.class).getNodes("additional_tab_*");
- while (additionalTabs.hasNext()) {
- Node tab = additionalTabs.nextNode();
- String includeURL = tab.getPath() + ".infinity.json";
- LOGGER.trace(includeURL);
-
- JSONObject newTab = new JSONObject();
- newTab.put("xtype", "cqinclude");
- newTab.put("jcr:primaryType", "cq:Widget");
- newTab.put("path", includeURL);
- if (!originalTabs.has(tab.getName())) {
- originalTabs.put(tab.getName(), newTab);
- }
- }
+ if (dialogPath != null) {
+ Resource dialogNodeRes = slingRequest.getResourceResolver().getResource(dialogPath);
+ if (dialogNodeRes != null) {
+ Node dialogNode = dialogNodeRes.adaptTo(Node.class);
+ TidyJsonItemWriter td = new TidyJsonItemWriter(null);
+ StringWriter writer = new StringWriter();
+ td.dump(dialogNode, writer, 1000);
+ JSONObject originalDialog = new JSONObject(writer.toString());
+ JSONObject originalTabs = getOriginalTabs(componentPath, originalDialog, slingRequest);
+ slingResponse.getWriter().write(originalDialog.toString());
}
}
- slingResponse.getWriter().write(originalDialog.toString());
slingResponse.getWriter().close();
} catch (JSONException je) {
LOGGER.error("JE " + je.getMessage());
@@ -168,6 +153,46 @@ public void doFilter(ServletRequest pRequest, ServletResponse pResponse, FilterC
}
}
+ private JSONObject getOriginalTabs(String componentPath, JSONObject originalDialog, final SlingHttpServletRequest slingRequest) throws JSONException, RepositoryException{
+ JSONObject originalTabs = originalDialog.getJSONObject("items").getJSONObject("tabs").getJSONObject("items");
+ Resource componentRes = slingRequest.getResourceResolver().getResource(componentPath);
+ if (componentRes != null) {
+ for (Resource item : getInheritResources(componentRes))
+ {
+ if (item != null)
+ {
+ Node nodeItem = item.adaptTo(Node.class);
+ if(nodeItem!=null)
+ {
+ getOriginalTabsFromRes(nodeItem,originalTabs);
+ }
+ }
+ }
+ }
+ return originalTabs;
+ }
+
+ private void getOriginalTabsFromRes(Node nodeItem, JSONObject originalTabs) throws JSONException, RepositoryException{
+
+ NodeIterator additionalTabs = nodeItem.getNodes("additional_tab_*");
+ while (additionalTabs.hasNext())
+ {
+ Node tab = additionalTabs.nextNode();
+ String includeURL = tab.getPath() + ".infinity.json";
+ LOGGER.trace(includeURL);
+
+ JSONObject newTab = new JSONObject();
+ newTab.put("xtype", "cqinclude");
+ newTab.put("jcr:primaryType", "cq:Widget");
+ newTab.put("path", includeURL);
+ if (!originalTabs.has(tab.getName())) {
+ originalTabs.put(tab.getName(), newTab);
+ }
+ }
+
+ }
+
+
private String getInheritDialog(SlingHttpServletRequest slingRequest) throws RepositoryException {
String fullRequestPath = slingRequest.getRequestURI();
String componentPath = fullRequestPath.substring(0, fullRequestPath.lastIndexOf("/"));
@@ -175,31 +200,47 @@ private String getInheritDialog(SlingHttpServletRequest slingRequest) throws Rep
Resource componentRes = slingRequest.getResourceResolver().getResource(componentPath);
int avoidLoop = 0;
+
+
while (componentRes != null && result == null && avoidLoop < 1000) {
LOGGER.trace("getInheritDialog loop --> " + componentRes.getPath());
-
Resource dialog = componentRes.getChild("dialog");
- if (dialog != null && (!dialog.adaptTo(Node.class).hasProperty("cs_include") || !dialog.adaptTo(Node.class).getProperty("cs_include").getBoolean())) {
- result = componentRes.getChild("dialog").getPath();
- LOGGER.debug("found dialog {}", result);
- break;
- } else {
- componentRes = (componentRes.getResourceSuperType() != null && !componentRes.getResourceSuperType().equals(componentRes.getResourceType())) ? componentRes.getResourceResolver().getResource(componentRes.getResourceSuperType()) : null;
+ if (dialog != null) {
+ ValueMap properties = dialog.getValueMap();
+ if (!properties.containsKey("cs_include") || !properties.get("cs_include",false)) {
+ result = dialog.getPath();
+ LOGGER.debug("found dialog {}", dialog.getPath());
+ break;
+ } else {
+ String resSuperType = componentRes.getResourceSuperType();
+ if ( resSuperType != null && !resSuperType.equals(componentRes.getResourceType())) {
+ componentRes = componentRes.getResourceResolver().getResource(resSuperType);
+ } else {
+ componentRes = null;
+ }
+ }
+
}
avoidLoop++;
}
-
return result;
}
+
private List getInheritResources(Resource res) {
List result = new ArrayList();
Resource temp = res;
while (temp != null) {
if (result.contains(temp)) break; //prevent loop
result.add(temp);
- temp = (temp.getResourceSuperType() != null && !temp.getResourceSuperType().equals(temp.getResourceType())) ? temp.getResourceResolver().getResource(temp.getResourceSuperType()) : null;
+ String resSuperType = temp.getResourceSuperType();
+ if(resSuperType!=null && !resSuperType.equals(temp.getResourceType()))
+ {
+ temp = temp.getResourceResolver().getResource(resSuperType);
+ } else {
+ temp = null;
+ }
}
return result;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/BrightcoveAdminPage.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/BrightcoveAdminPage.java
index 8f64136..5166b5f 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/BrightcoveAdminPage.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/BrightcoveAdminPage.java
@@ -23,7 +23,7 @@
public class BrightcoveAdminPage {
protected final static Logger LOGGER = LoggerFactory.getLogger(BrightcoveAdminPage.class);
- public static final String favIconPath = "/etc/designs/cs/brightcove/favicon.ico";
+ public static final String FAVICONPATH = "/etc/designs/cs/brightcove/favicon.ico";
@Self
private SlingHttpServletRequest slingHttpServletRequest;
@@ -76,37 +76,35 @@ public String getSelectedAccount() {
@PostConstruct
protected void init()
{
- if (cg != null) {
- services = cg.getAvailableServices(slingHttpServletRequest);
- ConfigurationService cs;
- LOGGER.debug("services " + services);
-
- if (services.size() > 0) {
- defaultAccount = (String) services.toArray()[0]; //Set first account as the default
- cookieAccount = ServiceUtil.getAccountFromCookie(slingHttpServletRequest); //If old session holds account in cookie, set that as default
- selectedAccount = (cookieAccount.trim().isEmpty()) ? defaultAccount : cookieAccount; //Only if cookie acct is not empty - else default
-
- cs = cg.getConfigurationService(selectedAccount) != null ? cg.getConfigurationService(selectedAccount) : cg.getConfigurationService(defaultAccount);
- if (cs != null) {
- LOGGER.debug("config service: " + cs.getAccountAlias());
- //Preview location
- previewPlayerLoc = String.format("https://players.brightcove.net/%s/%s_default/index.html?videoId=", cs.getAccountID(), cs.getDefVideoPlayerID());
- previewPlayerListLoc = String.format("https://players.brightcove.net/%s/%s_default/index.html?playlistId=", cs.getAccountID(), cs.getDefPlaylistPlayerID());
- selectedAccountAlias = cs.getAccountAlias();
- //DEBUGGING
- LOGGER.debug(previewPlayerLoc);
- LOGGER.debug(previewPlayerListLoc);
- LOGGER.debug(cs.getAccountID());
- LOGGER.debug(selectedAccountAlias);
- }
+ services = cg.getAvailableServices(slingHttpServletRequest);
+ ConfigurationService cs;
+ LOGGER.debug("services {}", services);
+
+ if (services.size() > 0) {
+ defaultAccount = (String) services.toArray()[0]; //Set first account as the default
+ cookieAccount = ServiceUtil.getAccountFromCookie(slingHttpServletRequest); //If old session holds account in cookie, set that as default
+ selectedAccount = (cookieAccount.trim().isEmpty()) ? defaultAccount : cookieAccount; //Only if cookie acct is not empty - else default
+
+ cs = cg.getConfigurationService(selectedAccount) != null ? cg.getConfigurationService(selectedAccount) : cg.getConfigurationService(defaultAccount);
+ try {
+ LOGGER.debug("config service: " + cs.getAccountAlias());
+ //Preview location
+ previewPlayerLoc = String.format("https://players.brightcove.net/%s/%s_default/index.html?videoId=", cs.getAccountID(), cs.getDefVideoPlayerID());
+ previewPlayerListLoc = String.format("https://players.brightcove.net/%s/%s_default/index.html?playlistId=", cs.getAccountID(), cs.getDefPlaylistPlayerID());
+ selectedAccountAlias = cs.getAccountAlias();
+ //DEBUGGING
+ LOGGER.debug(previewPlayerLoc);
+ LOGGER.debug(previewPlayerListLoc);
+ LOGGER.debug(cs.getAccountID());
+ LOGGER.debug(selectedAccountAlias);
+ } catch (Exception e) {
//OPTIONS RENDER FUNCTION
- for (String service : services) {
- cs = cg.getConfigurationService(service);
- if (cs != null) {
- configurationServices.add(cs);
- }
- }
+ LOGGER.error(e.getClass().getName(),e);
+ }
+ for (String service : services) {
+ configurationServices.add(cg.getConfigurationService(service));
}
}
}
+
}
\ No newline at end of file
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/VideoPlayer.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/VideoPlayer.java
index 33ec787..f6a8d94 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/VideoPlayer.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/models/VideoPlayer.java
@@ -4,6 +4,7 @@
import com.adobe.granite.license.ProductInfoService;
import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber;
import com.coresecure.brightcove.wrapper.sling.ConfigurationService;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.TextUtil;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
@@ -18,6 +19,8 @@
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;
import org.apache.sling.models.annotations.injectorspecific.Self;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,9 +68,6 @@ public class VideoPlayer {
protected final static Logger LOGGER = LoggerFactory.getLogger(VideoPlayer.class);
-
-
-
String componentID;
String videoID;
String playlistID;
@@ -88,6 +88,7 @@ public class VideoPlayer {
Resource playerPageResource;
ValueMap playerProperties;
String inlineCSS;
+ String bundleVersion;
public String getComponentID() {
return componentID;
@@ -173,24 +174,28 @@ public String getDropTargetPrefix() {
return DropTarget.CSS_CLASS_PREFIX;
}
+ public String getBundleVersion() {
+ return bundleVersion;
+ }
public String getInlineCSS() {
- return properties.get("inlineCSS", String.class);
+ return inlineCSS;
}
@PostConstruct
protected void init(){
- LOGGER.info(this.getClass().getName() + "INITAAAA");
+ LOGGER.info(this.getClass().getName());
+ Version bundle_version = FrameworkUtil.getBundle(getClass()).getVersion();
+ bundleVersion = String.format("%s.%s.%s", bundle_version.getMajor(), bundle_version.getMinor(), bundle_version.getMicro());
try {
LOGGER.info(resource.getName() + "INIT");
- if (productInfo != null) {
- ProductInfo[] productInfos = productInfo.getInfos();
- if (productInfos.length > 0) {
- version = productInfos[0].getShortVersion();
- }
-
+ ProductInfo[] productInfos = productInfo.getInfos();
+ if (productInfos.length > 0) {
+ version = productInfos[0].getShortVersion();
}
- LOGGER.info("version");
+
+
+ LOGGER.info("current AEM Version : " + version);
//cg = ServiceUtil.getConfigurationGrabber();
componentID = Text.md5(currentNode.getPath());
@@ -204,6 +209,7 @@ protected void init(){
playerID = "";
playerKey = "";
playerDataEmbed = "";
+ inlineCSS = properties.get("inlineCSS","");
containerID = properties.get("containerID", "");
containerClass = properties.get("containerClass", "");
@@ -216,52 +222,44 @@ protected void init(){
//fallback to default
- if (TextUtil.notEmpty(account)) {
- cs = cg.getConfigurationService(account);
- if (cs != null) {
- playerID = cs.getDefVideoPlayerID();
- playerDataEmbed = cs.getDefVideoPlayerDataEmbedded();
- playerKey = cs.getDefVideoPlayerKey();
+ try {
+ if (TextUtil.notEmpty(account)) {
+ cs = cg.getConfigurationService(account);
+
+ playerID = cs.getDefVideoPlayerID();
+ playerDataEmbed = cs.getDefVideoPlayerDataEmbedded();
+ playerKey = cs.getDefVideoPlayerKey();
+
}
+ } catch (NullPointerException e) {
+ LOGGER.error(e.getClass().getName(),e);
}
playerID = properties.get("playerID", playerID).trim();
playerKey = properties.get("playerKey", playerKey).trim();
- ;
+
playerDataEmbed = playerDataEmbed.isEmpty() ? "default" : playerDataEmbed;
// Load Player Configuration
+ Page playerPage = pageManager.getPage(playerPath);
+ if (playerPage != null) {
- if (!playerPath.isEmpty()) {
-
- playerPageResource = resourceResolver.resolve(playerPath);
-
- if (playerPageResource != null) {
-
- Page playerPage = playerPageResource.adaptTo(Page.class);
-
- if (playerPage != null) {
+ playerProperties = playerPage.getProperties();
- playerProperties = playerPage.getProperties();
+ playerID = playerProperties.get("playerID", playerID);
+ playerKey = playerProperties.get("playerKey", playerKey);
+ playerDataEmbed = playerProperties.get("data_embedded", playerDataEmbed);
- playerID = playerProperties.get("playerID", playerID);
- playerKey = playerProperties.get("playerKey", playerKey);
- playerDataEmbed = playerProperties.get("data_embedded", playerDataEmbed);
+ align = playerProperties.get("align", align);
+ width = playerProperties.get(Constants.WIDTH, width);
+ height = playerProperties.get(Constants.HEIGHT, height);
- align = playerProperties.get("align", align);
- width = playerProperties.get("width", width);
- height = playerProperties.get("height", height);
-
- //append the class to the container wrap
- containerClass += " " + playerProperties.get("containerClass", "");
-
- ignoreComponentProperties = playerProperties.get("ignoreComponentProperties", ignoreComponentProperties);
- }
-
- }
+ //append the class to the container wrap
+ containerClass += " " + playerProperties.get("containerClass", "");
+ ignoreComponentProperties = playerProperties.get("ignoreComponentProperties", ignoreComponentProperties);
}
// Override with local component properties IF enabled
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 1ed56c8..39f9a92 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
@@ -32,9 +32,11 @@
*/
package 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.JsonReader;
import org.apache.jackrabbit.util.Base64;
+import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
@@ -45,11 +47,11 @@
import java.util.Map;
public class Account {
- private String client_id;
- private String client_secret;
- private String account_id;
- private Token authToken;
- public Platform platform;
+ private final String client_id;
+ private final String client_secret;
+ private final String account_id;
+ private TokenObj authToken;
+ 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) {
@@ -68,30 +70,38 @@ public boolean login() {
authToken = null;
LOGGER.debug("getAccount_ID");
String token = Base64.encode(client_id + ":" + client_secret);
- LOGGER.debug("token: "+token);
+ LOGGER.debug("token: {}", token);
Map headers = new HashMap();
- headers.put("Authorization", "Basic " + token);
+ headers.put(DavConstants.HEADER_AUTHORIZATION, "Basic " + token);
String urlParameters = "grant_type=client_credentials";
String targetURL = platform.getOAUTH_Url() + "/access_token";
try {
- JSONObject response = JsonReader.readJsonFromString(HttpServices.executePost(targetURL, urlParameters, headers));
- LOGGER.debug("response: "+response.toString());
+ String loginResponse = HttpServices.executePost(targetURL, urlParameters, headers);
+ if (loginResponse == null) return false;
+ JSONObject response = JsonReader.readJsonFromString(loginResponse);
+ LOGGER.debug(Constants.RESPONSE ,response);
- if (response.getString("access_token") != null && response.getString("token_type") != null) {
- authToken = new Token(response.getString("access_token"), response.getString("token_type"), response.getInt("expires_in"));
+ if (response.getString(Constants.ACCESS_TOKEN) != null && response.getString("token_type") != null) {
+ authToken = new TokenObj(response.getString(Constants.ACCESS_TOKEN), response.getString("token_type"), response.getInt("expires_in"));
result = true;
}
} catch (IOException e) {
- e.printStackTrace();
+ LOGGER.error(e.getClass().getName(), e);
} catch (JSONException e) {
- e.printStackTrace();
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
- public Token getToken() {
+ public TokenObj getToken() {
return authToken;
}
+ public TokenObj getLoginToken() {
+ this.login();
+ return getToken();
+ }
+
+
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Binary.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/BinaryObj.java
similarity index 87%
rename from current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Binary.java
rename to current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/BinaryObj.java
index e249b81..43b60a6 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Binary.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/BinaryObj.java
@@ -38,20 +38,17 @@
import java.io.InputStream;
-public class Binary {
+public class BinaryObj {
- public InputStream binary;
+ public final InputStream binary;
+ public final String mime_type;
+ private static final Logger LOGGER = LoggerFactory.getLogger(BinaryObj.class);
- public String mime_type;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(Binary.class);
-
- public Binary()
+ public BinaryObj()
{
- binary = null;
- mime_type = null;
+ this(null,null);
}
- public Binary(InputStream aBinary, String aType)
+ public BinaryObj(InputStream aBinary, String aType)
{
binary = aBinary;
mime_type = aType;
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Geo.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Geo.java
index 13a609f..de7bc43 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Geo.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Geo.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
import com.coresecure.brightcove.wrapper.enums.GeoFilterCodeEnum;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -43,9 +44,9 @@
import java.util.Collection;
public class Geo {
- public boolean exclude_countries;
- public boolean restricted;
- public Collection countries;
+ public final boolean exclude_countries;
+ public final boolean restricted;
+ public final Collection countries;
private static final Logger LOGGER = LoggerFactory.getLogger(Geo.class);
public Geo(boolean aExclude_countries, boolean aRestricted, Collection aCountries) {
@@ -55,26 +56,27 @@ public Geo(boolean aExclude_countries, boolean aRestricted, Collection();
- for (int i = 0; i < aGeo.getJSONArray("countries").length(); i++) {
- countries.add(GeoFilterCodeEnum.lookupByCode(aGeo.getJSONArray("countries").getString(i)));
+ for (int i = 0; i < aGeo.getJSONArray(Constants.COUNTRIES).length(); i++) {
+ countries.add(GeoFilterCodeEnum.lookupByCode(aGeo.getJSONArray(Constants.COUNTRIES).getString(i)));
}
}
public JSONObject toJSON() throws JSONException {
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"exclude_countries", "restricted", "countries"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.EXCLUDE_COUNTRIES, Constants.RESTRICTED, Constants.COUNTRIES});
return json;
}
public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Images.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Images.java
index 2ba4572..4af0344 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Images.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Images.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -42,44 +43,40 @@
public class Images {
- public Thumbnail thumbnail;
- public Poster poster;
+ public final Thumbnail thumbnail;
+ public final Poster poster;
private static final Logger LOGGER = LoggerFactory.getLogger(Images.class);
- public Images() {
-
+ public Images(Poster aPoster, Thumbnail aThumbnail)
+ {
+ thumbnail = aThumbnail;
+ poster = aPoster;
}
+
public Images(JSONObject aImagesObj) throws JSONException
{
-
- thumbnail = new Thumbnail(aImagesObj.getJSONObject("thumbnail"));
- poster = new Poster(aImagesObj.getJSONObject("poster"));
+ this(new Poster(aImagesObj.getJSONObject(Constants.POSTER)),new Thumbnail(aImagesObj.getJSONObject(Constants.THUMBNAIL)));
}
- public Images(Poster aPoster, Thumbnail aThumbnail)
- {
- thumbnail = aThumbnail;
- poster = aPoster;
- }
public JSONObject toJSON() throws JSONException
{
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"poster","thumbnail"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.POSTER,Constants.THUMBNAIL});
return json;
}
- public String toString()
- {
+ public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Ingest.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Ingest.java
index 1371251..32f43ed 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Ingest.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Ingest.java
@@ -32,6 +32,7 @@
*/
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -44,8 +45,8 @@
public class Ingest {
private static final Logger LOGGER = LoggerFactory.getLogger(Ingest.class);
- public String profile;
- public Map master;
+ public final String profile;
+ public final Map master;
public Ingest(String aProfile, Map aMaster) {
profile = aProfile;
@@ -55,7 +56,7 @@ public Ingest(String aProfile, Map aMaster) {
public Ingest(String aProfile, String aUrl) {
master = new HashMap();
- master.put("url", aUrl);
+ master.put(Constants.URL, aUrl);
profile = aProfile;
}
@@ -65,11 +66,12 @@ public JSONObject toJSON() throws JSONException {
}
public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
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 3762503..6f938c6 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
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
import com.coresecure.brightcove.wrapper.utils.HttpServices;
+import org.apache.sling.servlets.post.JSONResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,18 +46,18 @@ public class Platform {
private final static String DEFAULT_PLAYERS_API_URL = "https://players.api.brightcove.com/v2";
private final static String DEFAULT_API_URL = "https://cms.api.brightcove.com/v1";
private final static String DEFAULT_DI_API_URL = "https://ingest.api.brightcove.com/v1";
- private static String OAUTH_Url;
- private static String PLAYERS_API_Url;
- private static String API_Url;
- private static String DI_API_Url;
- private static Proxy PROXY = Proxy.NO_PROXY;
+ private final String OAUTH_Url;
+ 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() {
-
+ public Platform()
+ {
+ this(null,null,null,null);
}
-
public Platform(String aOAUTH_Url, String aAPI_Url, String aDI_API_Url, String aPLAYERS_API_Url) {
OAUTH_Url = aOAUTH_Url;
API_Url = aAPI_Url;
@@ -80,18 +81,6 @@ public String getDI_API_Url() {
return (DI_API_Url != null && !DI_API_Url.isEmpty()) ? DI_API_Url : DEFAULT_DI_API_URL;
}
- public void setOAUTH_Url(String aOAUTH_Url) {
- OAUTH_Url = aOAUTH_Url;
- }
-
- public void setAPI_Url(String aAPI_Url) {
- API_Url = aAPI_Url;
- }
-
- public void setDI_API_Url(String aDI_API_Url) {
- DI_API_Url = aDI_API_Url;
- }
-
public String getAPI(String targetURL, String urlParameters, Map headers) {
String URL = getAPI_Url() + targetURL;
String response = HttpServices.executeGet(URL, urlParameters, headers);
@@ -140,7 +129,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);
- String response = HttpServices.executePost(URL, payload, headers,"application/json");
+ String response = HttpServices.executePost(URL, payload, headers, JSONResponse.RESPONSE_CONTENT_TYPE);
LOGGER.trace(response);
return response;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Playlist.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Playlist.java
index fcf0343..9061336 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Playlist.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Playlist.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
import com.coresecure.brightcove.wrapper.enums.PlaylistTypeEnum;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -125,14 +126,15 @@
*
*/
public class Playlist {
- private Long id;
- private String referenceId;
- private Long accountId;
- private String name;
- private String description;
-
- private List video_ids;
-
+ private String id;
+ private String created_at;
+ private String updated_at;
+ private Boolean favorite;
+ private String reference_id;
+ private String account_id;
+ private String name;
+ private String description;
+ private List video_ids;
private PlaylistTypeEnum type;
/**
@@ -141,9 +143,7 @@ public class Playlist {
* All fields set to null to start - required fields must be set before calling Write Media API.
*
*/
- public Playlist(){
- initAll();
- }
+ public Playlist(){/* default */}
/**
* Constructor using JSON string.
@@ -152,8 +152,6 @@ public Playlist(){
*
*/
public Playlist(String json) throws JSONException {
- initAll();
-
if(json == null){
throw new JSONException("[ERR] Playlist can not be parsed from null JSON string.");
}
@@ -181,82 +179,48 @@ public Playlist(JSONObject jsonObj) throws JSONException {
*/
private void finishConstruction(JSONObject jsonObj) throws JSONException {
Iterator rootKeys = jsonObj.keys();
-
- while(rootKeys.hasNext()) {
- String rootKey = rootKeys.next();
- Object rootValue = jsonObj.get(rootKey);
-
- if((rootValue == null) || ("null".equals(rootValue.toString()))){
- // Don't bother setting the attribute, it should already be null
- }
- else if("name".equals(rootKey)){
- name = (String)rootValue;
- }
- else if("id".equals(rootKey)){
- id = (Long)rootValue;
- }
- else if("accountId".equals(rootKey)){
- Long rootLong = jsonObj.getLong(rootKey);
- accountId = rootLong;
- }
- else if("referenceId".equals(rootKey)){
- referenceId = rootValue.toString();
- }
- else if("shortDescription".equals(rootKey)){
- description = rootValue.toString();
- }
- else if("video_ids".equals(rootKey)){
- video_ids = new ArrayList();
-
- JSONArray idsArray = jsonObj.getJSONArray(rootKey);
- for(int idIdx=0;idIdx();
+ JSONArray idsArray = jsonObj.getJSONArray(Constants.VIDEO_IDS);
+ for(int idIdx=0;idIdxFully initializes the playlist object by setting all fields to null
- */
- public void initAll() {
- id = null;
- referenceId = null;
- accountId = null;
- name = null;
- description = null;
- video_ids = null;
- type = null;
+ private PlaylistTypeEnum getType(String value) throws JSONException{
+ PlaylistTypeEnum type = null;
+ if(value.equals("OLDEST_TO_NEWEST")){
+ type = PlaylistTypeEnum.OLDEST_TO_NEWEST;
+ }
+ else if(value.equals("NEWEST_TO_OLDEST")){
+ type = PlaylistTypeEnum.NEWEST_TO_OLDEST;
+ }
+ else if(value.equals("ALPHABETICAL")){
+ type = PlaylistTypeEnum.ALPHABETICAL;
+ }
+ else if(value.equals("PLAYSTOTAL")){
+ type = PlaylistTypeEnum.PLAYSTOTAL;
+ }
+ else if(value.equals("PLAYS_TRAILING_WEEK")){
+ type = PlaylistTypeEnum.PLAYS_TRAILING_WEEK;
+ }
+ else if(value.equals("EXPLICIT")){
+ type = PlaylistTypeEnum.EXPLICIT;
+ }
+ else{
+ throw new JSONException("[ERR] Media API specified invalid value for playlist type '" + value + "'. Acceptable values are 'OLDEST_TO_NEWEST', 'NEWEST_TO_OLDEST', 'ALPHABETICAL', 'PLAYSTOTAL', 'PLAYS_TRAILING_WEEK', 'EXPLICIT'.");
+ }
+ return type;
}
/**
@@ -266,7 +230,7 @@ public void initAll() {
*
* @return The id for this Playlist
*/
- public Long getId(){
+ public String getId(){
return id;
}
@@ -278,7 +242,7 @@ public Long getId(){
* @return Reference id for this Playlist
*/
public String getReferenceId(){
- return referenceId;
+ return reference_id;
}
/**
@@ -288,8 +252,8 @@ public String getReferenceId(){
*
* @return Account id for this Playlist
*/
- public Long getAccountId(){
- return accountId;
+ public String getAccountId(){
+ return account_id;
}
/**
@@ -321,7 +285,7 @@ public String getDescription(){
*
* @return Video Ids for this Playlist
*/
- public List getVideoIds(){
+ public List getVideoIds(){
return video_ids;
}
@@ -345,7 +309,7 @@ public PlaylistTypeEnum getPlaylistType(){
*
* @param id The id for this Playlist
*/
- public void setId(Long id){
+ public void setId(String id){
this.id = id;
}
@@ -357,7 +321,7 @@ public void setId(Long id){
* @param referenceId Reference id for this Playlist
*/
public void setReferenceId(String referenceId){
- this.referenceId = referenceId;
+ this.reference_id = referenceId;
}
/**
@@ -365,10 +329,10 @@ public void setReferenceId(String referenceId){
*
* A number that uniquely identifies the account to which this Playlist belongs, assigned by Brightcove.
*
- * @param accountId Account id for this Playlist
+ * @param account_id Account id for this Playlist
*/
- public void setAccountId(Long accountId){
- this.accountId = accountId;
+ public void setAccountId(String account_id){
+ this.account_id = account_id;
}
/**
@@ -400,7 +364,7 @@ public void setDescription(String shortDescription){
*
* @param video_ids Video Ids for this Playlist
*/
- public void setVideoIds(List video_ids){
+ public void setVideoIds(List video_ids){
this.video_ids = video_ids;
}
@@ -429,19 +393,29 @@ public JSONObject toJSON() throws JSONException {
if(id != null){
json.put("id", id);
}
- if(referenceId != null){
- json.put("referenceId", referenceId);
+ if(reference_id != null){
+ json.put("reference_id", reference_id);
+ }
+ if(account_id != null){
+ json.put("account_id", account_id);
+ }
+ if(favorite != null){
+ json.put("favorite", favorite);
+ }
+ if(created_at != null){
+ json.put("created_at", created_at);
}
- if(accountId != null){
- json.put("accountId", accountId);
+ if(updated_at != null){
+ json.put("updated_at", updated_at);
}
+
if(description != null){
json.put("description", description);
}
if(video_ids != null){
JSONArray idArray = new JSONArray();
- for(Long videoId : video_ids){
- idArray.put(String.valueOf(videoId));
+ for(String videoId : video_ids){
+ idArray.put(videoId);
}
json.put("video_ids", idArray);
}
@@ -453,20 +427,4 @@ public JSONObject toJSON() throws JSONException {
return json;
}
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString(){
- String ret = "[com.brightcove.proserve.mediaapi.wrapper.apiobjects.Playlist (\n" +
- "\tname:'" + name + "'\n" +
- "\tid:'" + id + "'\n" +
- "\treferenceId:'" + referenceId + "'\n" +
- "\taccountId:'" + accountId + "'\n" +
- "\tdescription:'" + description + "'\n" +
- "\tvideo_ids:'" + video_ids + "'\n" +
- "\ttype:'" + type + "'\n" +
- ")]";
-
- return ret;
- }
}
\ No newline at end of file
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Poster.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Poster.java
index 3e6aded..80ef32b 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Poster.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Poster.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -42,43 +43,35 @@
public class Poster {
- public String url;
+ public final String url;
private static final Logger LOGGER = LoggerFactory.getLogger(Poster.class);
public Poster(String aSrc)
{
-
url = aSrc;
-
- //sources = aText_track.getString("id");;
-
}
+
public Poster(JSONObject aPoster) throws JSONException
{
-
- url = aPoster.getString("src");
-
- //sources = aText_track.getString("id");;
-
+ this(aPoster.getString(Constants.SRC));
}
public JSONObject toJSON() throws JSONException
{
-
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"url"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.URL});
return json;
}
- public String toString()
- {
+ public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Projection.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Projection.java
index dcd67d4..f0d0628 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Projection.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Projection.java
@@ -38,18 +38,13 @@
public class Projection {
- public String type;
-
+ public final String type;
private static final Logger LOGGER = LoggerFactory.getLogger(Projection.class);
-
public Projection(String aType)
{
-
type = aType;
-
}
-
public String toString()
{
return type;
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/RelatedLink.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/RelatedLink.java
index ab26509..29061c2 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/RelatedLink.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/RelatedLink.java
@@ -42,9 +42,8 @@
import java.util.Collection;
public class RelatedLink {
- public String text;
- public String url;
- public Collection countries;
+ public final String text;
+ public final String url;
private static final Logger LOGGER = LoggerFactory.getLogger(RelatedLink.class);
public RelatedLink(String aText, String aUrl) {
@@ -53,8 +52,7 @@ public RelatedLink(String aText, String aUrl) {
}
public RelatedLink(JSONObject aLink) throws JSONException {
- text = aLink.getString("text");
- url = aLink.getString("url");
+ this(aLink.getString("text"), aLink.getString("url"));
}
public JSONObject toJSON() throws JSONException {
@@ -63,12 +61,13 @@ public JSONObject toJSON() throws JSONException {
}
public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Schedule.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Schedule.java
index 76a575b..41deffd 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Schedule.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Schedule.java
@@ -32,39 +32,40 @@
*/
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.annotation.Nonnull;
public class Schedule {
private static final Logger LOGGER = LoggerFactory.getLogger(Schedule.class);
-
- public String starts_at;
- public String ends_at;
+ public final String starts_at;
+ public final String ends_at;
public Schedule(String aStarts_at, String aEnds_at) {
starts_at = aStarts_at;
ends_at = aEnds_at;
}
- public Schedule(JSONObject aSchedule) throws JSONException {
- starts_at = aSchedule.getString("starts_at");
- ends_at = aSchedule.getString("ends_at");
+ public Schedule(@Nonnull JSONObject aSchedule) throws JSONException {
+ this(aSchedule.getString(Constants.STARTS_AT),aSchedule.getString(Constants.ENDS_AT));
}
public JSONObject toJSON() throws JSONException {
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"starts_at", "ends_at"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.STARTS_AT, Constants.ENDS_AT});
return json;
}
public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Text_track.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Text_track.java
index fb7d4cf..9054d94 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Text_track.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Text_track.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
@@ -43,71 +44,95 @@
public class Text_track {
- public String id;
- public String account_id;
- public String src;
- public String srclang;
- public String label;
- public String kind;
- public String mime_type;
- public String asset_id;
- public Boolean _default;
- public JSONArray sources;
+ public final String id;
+ public final String account_id;
+ public final String src;
+ public final String srclang;
+ public final String label;
+ public final String kind;
+ public final String mime_type;
+ public final String asset_id;
+ public final Boolean _default;
+ public final JSONArray sources;
private static final Logger LOGGER = LoggerFactory.getLogger(Text_track.class);
+ public Text_track(String id, String account_id, String src, String srclang, String label, String kind, String mime_type, String asset_id, Boolean _default, JSONArray sources)
+ {
+ this.id = id;
+ this.account_id = account_id;
+ this.src = src;
+ this.srclang = srclang;
+ this.label = label;
+ this.kind = kind;
+ this.mime_type = mime_type;
+ this.asset_id = asset_id;
+ this._default = _default;
+ this.sources = sources;
+ }
+
+
public Text_track(JSONObject aText_track)
{
-
+ String localid = null;
+ String localaccount_id = null;
+ String localsrc = null;
+ String localsrclang = null;
+ String locallabel = null;
+ String localkind = null;
+ String localmime_type = null;
+ String localasset_id = null;
+ Boolean local_default = null;
+ JSONArray localsources = null;
try
{
- if(!aText_track.isNull("id")) id = aText_track.getString("id");
- if(!aText_track.isNull("account_id"))account_id = aText_track.getString("account_id");
- if(!aText_track.isNull("src"))src = aText_track.getString("src");
- if(!aText_track.isNull("srclang"))srclang = aText_track.getString("srclang");
- if(!aText_track.isNull("label"))label = aText_track.getString("label");
- if(!aText_track.isNull("kind"))kind = aText_track.getString("kind");
- if(!aText_track.isNull("mime_type"))mime_type = aText_track.getString("mime_type");
- if(!aText_track.isNull("asset_id"))asset_id = aText_track.getString("asset_id");
- if(!aText_track.isNull("sources"))sources = aText_track.getJSONArray("sources");
- if(!aText_track.isNull("default"))_default = aText_track.getBoolean("default");
-
+ if(!aText_track.isNull(Constants.ID)) localid = aText_track.getString(Constants.ID);
+ if(!aText_track.isNull(Constants.ACCOUNT_ID))localaccount_id = aText_track.getString(Constants.ACCOUNT_ID);
+ if(!aText_track.isNull(Constants.SRC))localsrc = aText_track.getString(Constants.SRC);
+ if(!aText_track.isNull(Constants.SRCLANG))localsrclang = aText_track.getString(Constants.SRCLANG);
+ if(!aText_track.isNull(Constants.LABEL))locallabel = aText_track.getString(Constants.LABEL);
+ if(!aText_track.isNull(Constants.KIND))localkind = aText_track.getString(Constants.KIND);
+ if(!aText_track.isNull(Constants.MIME_TYPE))localmime_type = aText_track.getString(Constants.MIME_TYPE);
+ if(!aText_track.isNull(Constants.ASSET_ID))localasset_id = aText_track.getString(Constants.ASSET_ID);
+ if(!aText_track.isNull(Constants.SOURCES))localsources = aText_track.getJSONArray(Constants.SOURCES);
+ if(!aText_track.isNull(Constants.DEFAULT))local_default = aText_track.getBoolean(Constants.DEFAULT);
}
catch (JSONException e)
{
- LOGGER.error("JSON TEXT TRACK EXCEPTION " ,e );
+ LOGGER.error(e.getClass().getName(),e );
} catch (Exception e )
{
- LOGGER.error("EXCEPTION TEXT TRACK");
+ LOGGER.error(e.getClass().getName(), e);
+ } finally {
+ this.id = localid;
+ this.account_id = localaccount_id;
+ this.src = localsrc;
+ this.srclang = localsrclang;
+ this.label = locallabel;
+ this.kind = localkind;
+ this.mime_type = localmime_type;
+ this.asset_id = localasset_id;
+ this._default = local_default;
+ this.sources = localsources;
}
-
- //sources = aText_track.getString("id");;
-
}
public JSONObject toJSON() throws JSONException
{
-
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"id", "account_id" , "src", "srclang", "label","kind","mime_type","asset_id","sources", "_default"});
-
-
-
-
-
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.ID, Constants.ACCOUNT_ID , Constants.SRC, Constants.SRCLANG, Constants.LABEL,Constants.KIND,Constants.MIME_TYPE,Constants.ASSET_ID,Constants.SOURCES, Constants.UNDERSCORE_DEFAULT});
return json;
}
- public String toString()
- {
+ public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
-
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Thumbnail.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Thumbnail.java
index 81f2f36..99e7b70 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Thumbnail.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Thumbnail.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
@@ -42,31 +43,22 @@
public class Thumbnail {
- public String url;
+ public final String url;
private static final Logger LOGGER = LoggerFactory.getLogger(Thumbnail.class);
public Thumbnail(String aSrc)
{
-
url = aSrc;
-
- //sources = aText_track.getString("id");;
-
}
public Thumbnail(JSONObject aPoster) throws JSONException
{
-
- url = aPoster.getString("src");
-
- //sources = aText_track.getString("id");;
-
+ this(aPoster.getString(Constants.SRC));
}
public JSONObject toJSON() throws JSONException
{
-
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"url"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.URL});
return json;
}
@@ -75,9 +67,8 @@ public String toString()
try {
return toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
+ return new String();
}
}
-
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Token.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/TokenObj.java
similarity index 84%
rename from current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Token.java
rename to current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/TokenObj.java
index 41d9a69..52a94ec 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Token.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/TokenObj.java
@@ -32,12 +32,15 @@
*/
package com.coresecure.brightcove.wrapper.objects;
-public class Token {
- private static String token_type;
- private static String token;
- private static int expire_in;
+import org.apache.sling.commons.json.JSONException;
+import org.apache.sling.commons.json.JSONObject;
- public Token(String aToken, String aToken_type, int aExpire_in) {
+public class TokenObj {
+ private final String token_type;
+ private final String token;
+ private final int expire_in;
+
+ public TokenObj(String aToken, String aToken_type, int aExpire_in) {
token = aToken;
token_type = aToken_type;
expire_in = aExpire_in;
@@ -54,4 +57,6 @@ public String getTokenType() {
public int getExpire_in() {
return expire_in;
}
+
+
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Video.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Video.java
index 39ae970..f2039fd 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Video.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/objects/Video.java
@@ -33,6 +33,7 @@
package com.coresecure.brightcove.wrapper.objects;
import com.coresecure.brightcove.wrapper.enums.EconomicsEnum;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.ObjectSerializer;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
@@ -47,106 +48,57 @@
public class Video {
private static final Logger LOGGER = LoggerFactory.getLogger(Video.class);
- public String name;
- public String id;
- public String account_id;
- public Projection projection;
- public String reference_id;
- public String description;
- public String long_description;
- public String state;
- public Collection tags;
- public Map custom_fields;
- public Geo geo;
- public RelatedLink link;
- public Schedule schedule;
- public boolean complete;
- public EconomicsEnum economics;
- public JSONArray text_tracks;
- public Images images;
+ public final String name;
+ public final String id;
+ public final String account_id;
+ public final Projection projection;
+ public final String reference_id;
+ public final String description;
+ public final String long_description;
+ public final String state;
+ public final Collection tags;
+ public final Map custom_fields;
+ public final Geo geo;
+ public final RelatedLink link;
+ public final Schedule schedule;
+ public final boolean complete;
+ public final EconomicsEnum economics;
+ public final JSONArray text_tracks;
+ public final Images images;
+
+
+
+ public Video(String aName) {
+ this( aName, null, null, null, null, null, null, null, false, null);
+ }
public Video(String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink) {
- name = aName;
- reference_id = aReference_id;
- description = aDescription;
- long_description = aLong_description;
- state = aState;
- tags = aTags;
- geo = aGeo;
- schedule = aSchedule;
- link = aLink;
- complete = aComplete;
+ this(null, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink);
}
public Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink) {
- id = aId;
- name = aName;
- reference_id = aReference_id;
- description = aDescription;
- long_description = aLong_description;
- state = aState;
- tags = aTags;
- geo = aGeo;
- schedule = aSchedule;
- link = aLink;
- complete = aComplete;
+ this(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, null, null);
}
-
public Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink, Map aCustom_fields, EconomicsEnum aEconomics) {
- id = aId;
- name = aName;
- reference_id = aReference_id;
- description = aDescription;
- long_description = aLong_description;
- state = aState;
- tags = aTags;
- geo = aGeo;
- schedule = aSchedule;
- link = aLink;
- complete = aComplete;
- custom_fields = aCustom_fields;
- economics = aEconomics;
+ this(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, aEconomics, null);
}
public Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink, Map aCustom_fields, EconomicsEnum aEconomics, String aProjection) {
- id = aId;
- name = aName;
- reference_id = aReference_id;
- description = aDescription;
- long_description = aLong_description;
- state = aState;
- tags = aTags;
- geo = aGeo;
- schedule = aSchedule;
- link = aLink;
- complete = aComplete;
- custom_fields = aCustom_fields;
- economics = aEconomics;
- projection = new Projection(aProjection);
+ this(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, aEconomics, aProjection, null);
}
public Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink, Map aCustom_fields, EconomicsEnum aEconomics, String aProjection, JSONArray aText_tracks) {
- id = aId;
- name = aName;
- reference_id = aReference_id;
- description = aDescription;
- long_description = aLong_description;
- state = aState;
- tags = aTags;
- geo = aGeo;
- schedule = aSchedule;
- link = aLink;
- complete = aComplete;
- custom_fields = aCustom_fields;
- economics = aEconomics;
- projection = new Projection(aProjection);
- text_tracks = aText_tracks;
-
+ this(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, aEconomics, aProjection, aText_tracks, null);
}
public Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink, Map aCustom_fields, EconomicsEnum aEconomics, String aProjection, JSONArray aText_tracks, Images aImages) {
+ this(aId, aName, aReference_id, aDescription, aLong_description, aState, aTags, aGeo, aSchedule, aComplete, aLink, aCustom_fields, aEconomics, aProjection, aText_tracks, null, null);
+ }
+
+ private Video(String aId, String aName, String aReference_id, String aDescription, String aLong_description, String aState, Collection aTags, Geo aGeo, Schedule aSchedule, boolean aComplete, RelatedLink aLink, Map aCustom_fields, EconomicsEnum aEconomics, String aProjection, JSONArray aText_tracks, Images aImages, String aAccountId) {
id = aId;
+ account_id = aAccountId;
name = aName;
reference_id = aReference_id;
description = aDescription;
@@ -162,57 +114,91 @@ public Video(String aId, String aName, String aReference_id, String aDescription
projection = new Projection(aProjection);
text_tracks = aText_tracks;
images = aImages;
-
}
-
-
-
-
+ private Object getNotNull(JSONObject video, String key) throws JSONException{
+ return !video.isNull(key) ? video.get(key) : null;
+ }
public Video(JSONObject video) throws JSONException {
- if (!video.isNull("id")) id = video.getString("id");
- if (!video.isNull("account_id")) account_id = video.getString("account_id");
- if (!video.isNull("name")) name = video.getString("name");
- if (!video.isNull("reference_id")) reference_id = video.getString("reference_id");
- if (!video.isNull("description")) description = video.getString("description");
- if (!video.isNull("long_description")) long_description = video.getString("long_description");
- if (!video.isNull("state")) state = video.getString("state");
- if (!video.isNull("projection")) projection = new Projection(video.getString("projection"));
- if (!video.isNull("tags")) {
- tags = new ArrayList();
- for (int i = 0; i < video.getJSONArray("tags").length(); i++) {
- tags.add(video.getJSONArray("tags").getString(i));
+ String localname = null;
+ String localid = null;
+ String localaccount_id = null;
+ Projection localprojection = null;
+ String localreference_id = null;
+ String localdescription = null;
+ String locallong_description = null;
+ String localstate = null;
+ Collection localtags = null;
+ Map localcustom_fields = null;
+ Geo localgeo = null;
+ RelatedLink locallink = null;
+ Schedule localschedule = null;
+ boolean localcomplete = false;
+ EconomicsEnum localeconomics = null;
+ JSONArray localtext_tracks = null;
+ Images localimages = null;
+ try {
+ localid = (String) getNotNull(video, Constants.ID);
+ localaccount_id = (String) getNotNull(video, Constants.ACCOUNT_ID);
+ localname = (String) getNotNull(video, Constants.NAME);
+ localreference_id = (String) getNotNull(video, Constants.REFERENCE_ID);
+ localdescription = (String) getNotNull(video, Constants.DESCRIPTION);
+ locallong_description = (String) getNotNull(video, Constants.LONG_DESCRIPTION);
+ localstate = (String) getNotNull(video, Constants.STATE);
+ localprojection = (Projection) getNotNull(video, Constants.PROJECTION);
+ localgeo = (Geo) getNotNull(video, Constants.GEO);
+ localschedule = (Schedule) getNotNull(video, Constants.SCHEDULE);
+ locallink = (RelatedLink) getNotNull(video, Constants.LINK);
+ localtext_tracks = (JSONArray) getNotNull(video, Constants.TEXT_TRACKS);
+ localcomplete = (Boolean) getNotNull(video, Constants.COMPLETE);
+ if (!video.isNull(Constants.TAGS))
+ {
+ localtags = new ArrayList();
+ for (int i = 0; i < video.getJSONArray(Constants.TAGS).length(); i++)
+ {
+ localtags.add(video.getJSONArray(Constants.TAGS).getString(i));
+ }
}
}
- if (!video.isNull("geo")) geo = new Geo(video.getJSONObject("geo"));
- if (!video.isNull("schedule")) schedule = new Schedule(video.getJSONObject("schedule"));
- if (!video.isNull("link")) link = new RelatedLink(video.getJSONObject("link"));
-
- if(!video.isNull("text_tracks")) text_tracks = video.getJSONArray("text_tracks");
-
-
-
-
-
- complete = video.getBoolean("complete");
- }
-
- public Video(String aName) {
- name = aName;
+ catch(Exception e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ finally
+ {
+ this.name = localname;
+ this.id = localid;
+ this.account_id = localaccount_id;
+ this.projection = localprojection;
+ this.reference_id = localreference_id;
+ this.description = localdescription;
+ this.long_description = locallong_description;
+ this.state = localstate;
+ this.tags = localtags;
+ this.custom_fields = localcustom_fields;
+ this.geo = localgeo;
+ this.link = locallink;
+ this.schedule = localschedule;
+ this.complete = localcomplete;
+ this.economics = localeconomics;
+ this.text_tracks = localtext_tracks;
+ this.images = localimages;
+ }
}
public JSONObject toJSON() throws JSONException {
- JSONObject json = ObjectSerializer.toJSON(this, new String[]{"id", "account_id", "name", "reference_id", "description", "long_description", "state", "tags", "custom_fields", "geo", "schedule", "link", "economics","projection", "text_tracks"});
+ JSONObject json = ObjectSerializer.toJSON(this, new String[]{Constants.ID, Constants.ACCOUNT_ID, Constants.NAME, Constants.REFERENCE_ID, Constants.DESCRIPTION, Constants.LONG_DESCRIPTION, Constants.STATE, Constants.TAGS, Constants.CUSTOM_FIELDS, Constants.GEO, Constants.SCHEDULE, Constants.LINK, Constants.ECONOMICS,Constants.PROJECTION, Constants.TEXT_TRACKS});
return json;
}
public String toString() {
+ String result = new String();
try {
- return toJSON().toString();
+ result = toJSON().toString();
} catch (JSONException e) {
- LOGGER.error("JsonException",e);
- return null;
+ LOGGER.error(e.getClass().getName(),e);
}
+ return result;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/callables/VideoImportCallable.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/callables/VideoImportCallable.java
index b0dd4f2..81335a9 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/callables/VideoImportCallable.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/callables/VideoImportCallable.java
@@ -32,12 +32,14 @@
*/
package com.coresecure.brightcove.wrapper.schedulers.asset_integrator.callables;
-import com.coresecure.brightcove.wrapper.objects.Binary;
+import com.coresecure.brightcove.wrapper.objects.BinaryObj;
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.HttpServices;
import com.coresecure.brightcove.wrapper.utils.ImageUtil;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetManager;
+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.commons.json.JSONException;
@@ -51,10 +53,7 @@
import javax.jcr.RepositoryException;
import java.awt.*;
import java.awt.image.BufferedImage;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
+import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
@@ -86,228 +85,216 @@ public VideoImportCallable(JSONObject innerObj, String confPath, String requeste
this.resourceResolverFactory = resourceResolverFactory;
}
- public String call(){
- // Get the Service resource resolver
-
- try {
- final Map authInfo = Collections.singletonMap(
- ResourceResolverFactory.SUBSERVICE,
- (Object) SERVICE_ACCOUNT_IDENTIFIER);
- resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
- //FOR EACH VIDEO COMING BACK FROM THE QUERY
-
+ private String getItemFromJson(JSONObject innerObj, String key) throws JSONException{
+ return innerObj.has(key) && innerObj.get(key)!=null ? innerObj.getString(key) : "";
+ }
- //CHECK IF VIDEO'S STATE IS SET TO ACTIVE - CONDITION ONE
- Boolean active = false;
- if (innerObj.has("state") && !innerObj.get("state").equals(null)) {
- active = "ACTIVE".equals(innerObj.getString("state"));
+ private Asset createAsset(String localpath, String id, String brightcove_filename) throws JSONException, IOException, RepositoryException {
+ Asset newAsset = null;
+
+ String mime_type = "";
+ InputStream binary = null;
+
+ //GET THUMBNAIL - SOURCE CHECK? - CONDITION THREE? WHy?
+ String thumbnail_src =getItemFromJson(innerObj,Constants.THUMBNAIL_URL);
+
+ BinaryObj binaryRes = null;
+
+ if (HttpServices.isLocalPath(thumbnail_src)) //HAS LOCAL THUMB PATH
+ {
+ //IF THE THUMBNAIL SOURCE IST /CONTENT/DAM/ IT IS LOCAL - IF LOCAL >>
+ LOGGER.trace("->>Pulling local image as this video's thumbnail image binary");
+ LOGGER.trace("->>Thumbnail Source is/: " + thumbnail_src);
+ LOGGER.trace("->>Looking for local thumbnail source at [INTERNAL]: " + localpath);
+ binaryRes = com.coresecure.brightcove.wrapper.utils.JcrUtil.getLocalBinary(resourceResolver, thumbnail_src, mType);
+ } else {
+ LOGGER.trace("->>Pulling external image as this video's thumbnail image binary - Must do a GET");
+ LOGGER.trace("->>Thumbnail Source is/: " + thumbnail_src + " DESTINATION >> " + localpath);
+ binaryRes = HttpServices.getRemoteBinary(thumbnail_src, "", null);
+ LOGGER.trace("->>[PULLING THUMBNAIL] : " + thumbnail_src);
+ }
+ if (binaryRes.binary != null) {
+ binary = binaryRes.binary;
+ mime_type = binaryRes.mime_type;
+ } else {
+ binaryRes = com.coresecure.brightcove.wrapper.utils.JcrUtil.getLocalBinary(resourceResolver, "/etc/designs/cs/brightcove/shared/img/noThumbnail.jpg", mType);
+ if (binaryRes.binary != null) {
+ binary = binaryRes.binary;
+ mime_type = binaryRes.mime_type;
+ } else {
+ LOGGER.trace("FAIL EXTERNAL");
+ return null;
}
+ }
- //CONDITIONN TWO - MUST HAVE AN ID
- Boolean hasID = innerObj.has("id") && !innerObj.get("id").equals(null);
- String ID = innerObj.has("id") ? innerObj.getString("id") : null;
-
-
- LOGGER.trace(">>>>START>>>>>{" + ID + "}>> " + (active && hasID) + ">>>>>");
-
- //TODO: CHECK IF VIDEO COMING INTO DAM (1) IS ACTIVE (2) HAS AN ID + SRC IMAGE??
- if (active && hasID) {
- String name = innerObj.getString("name");
- String brightcove_filename = ID + ".mp4"; //BRIGHTCOVE FILE NAME IS ID + . MP4 <-
- String original_filename = innerObj.getString("original_filename") != null ? innerObj.getString("original_filename").replaceAll("%20", " ") : null;
-
- LOGGER.trace("SYNCING VIDEO>>[" + name + "\tSTATE:ACTIVE\tTO BE:" + original_filename + "]");
-
- //INITIALIZING ASSET SEARCH // INITIALIZATION
- Asset newAsset = null;
- InputStream binary = null;
-
- //TODO: PRINTING DEBUGGER (ENABLE TO DEBUG)
-
- //USNIG THE CONFIGURATION - BUILD THE DIRECTORY TO SEARCH FOR THE LOCAL ASSETS OR BUILD INTO
- String localpath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedServiceAccount + "/").concat(brightcove_filename);
- String oldpath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedServiceAccount + "/").concat(original_filename);
-
- LOGGER.trace("SEARCHING FOR LOCAL ASSET");
- LOGGER.trace(">>ORIGINAL: " + oldpath);
- LOGGER.trace(">>PATH: " + localpath);
-
-
- //TRY TO GET THIS ASSET IN THE CONFIGURED BC NODE PATH - IF IT IS NULL - IT MUST BE CREATED
- newAsset = resourceResolver.getResource(oldpath) != null ? resourceResolver.getResource(oldpath).adaptTo(Asset.class) : resourceResolver.getResource(localpath) != null ? resourceResolver.getResource(localpath).adaptTo(Asset.class) : null;
-
- if (newAsset == null) {
- //IF NEW ASSET IS NULL MEANS THAT - IT MUST BE CREATED
-
+ //CALL ASSET MANAGER
+ AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);
+ if (assetManager == null) {
+ return null;
+ }
+ BufferedImage image = ImageIO.read(binary);
- String mime_type = "";
+ //CRATE TEMPORARY MP4 FILE
+ String prefix = id + "-";
+ String suffix = ".mp4";
+ File tempFile2 = File.createTempFile(prefix, suffix);
+ tempFile2.deleteOnExit();
- //GET THUMBNAIL - SOURCE CHECK? - CONDITION THREE? WHy?
- String thumbnail_src = innerObj.has("thumbnailURL") && !innerObj.get("thumbnailURL").equals(null) ? innerObj.getString("thumbnailURL") : "";
+ AWTSequenceEncoder enc = AWTSequenceEncoder.createSequenceEncoder(tempFile2, 30);
+ LOGGER.trace("ENCODING PROCESS");
+ LOGGER.trace("height: {}" ,image.getType());
+ LOGGER.trace("height: {}" ,image.getHeight());
+ LOGGER.trace("width: {}" ,image.getWidth());
- Binary remoteBinary = null;
- Binary binaryRes = null;
+ if (image.getHeight() % 2 != 0) {
+ image = ImageUtil.cropImage(image, new Rectangle(image.getWidth(), image.getHeight() - (image.getHeight() % 2)));
+ }
+ if (image.getWidth() % 2 != 0) {
+ image = ImageUtil.cropImage(image, new Rectangle(image.getWidth() - (image.getWidth() % 2), image.getHeight()));
+ }
- if (HttpServices.isLocalPath(thumbnail_src)) //HAS LOCAL THUMB PATH
- {
- //IF THE THUMBNAIL SOURCE IST /CONTENT/DAM/ IT IS LOCAL - IF LOCAL >>
+ enc.encodeImage(image);
+ enc.finish();
- LOGGER.trace("->>Pulling local image as this video's thumbnail image binary");
- LOGGER.trace("->>Thumbnail Source is/: " + thumbnail_src);
- LOGGER.trace("->>Looking for local thumbnail source at [INTERNAL]: " + localpath);
+ InputStream in = null;
+ FileInputStream fis = null;
+ try {
+ fis = new FileInputStream(tempFile2);
+ in = new BufferedInputStream(fis);
- binaryRes = com.coresecure.brightcove.wrapper.utils.JcrUtil.getLocalBinary(resourceResolver, thumbnail_src, mType);
- if (binaryRes.binary != null) {
- binary = binaryRes.binary;
- mime_type = binaryRes.mime_type;
- if (binary == null) //IF REMOTE IMAGE LOAD UNSUCCESSFUL - LOAD DEFAULT
- {
- LOGGER.error("External thumbnail could not be read");
- LOGGER.error("FAILURE TO LOAD THUMBNAIL SOURCE FOR VIDEO " + newAsset.getPath());
+ LOGGER.trace("***IMAGE->VIDEO: " + localpath + " {}", mType.getMimeType(brightcove_filename));
- LOGGER.trace("FAIL INTERNAL");
- //failure++;
- return Thread.currentThread().getName();
- }
- }
- } else {
- LOGGER.trace("->>Pulling external image as this video's thumbnail image binary - Must do a GET");
- LOGGER.trace("->>Thumbnail Source is/: " + thumbnail_src + " DESTINATION >> " + localpath);
- remoteBinary = HttpServices.getRemoteBinary(thumbnail_src, "", null);
- LOGGER.trace("->>[PULLING THUMBNAIL] : " + thumbnail_src);
+ //CREATE ASSET - NEEDS BINARY OF THUMBNAIL IN ORDER TO SET IT FOR THE NEW ASSET
+ newAsset = assetManager.createAsset(localpath, in, mType.getMimeType(brightcove_filename), true);
- if (remoteBinary.binary != null) {
- binary = remoteBinary.binary;
- mime_type = remoteBinary.mime_type;
- } else {
- binaryRes = com.coresecure.brightcove.wrapper.utils.JcrUtil.getLocalBinary(resourceResolver, "/etc/designs/cs/brightcove/shared/img/noThumbnail.jpg", mType);
- if (binaryRes.binary != null) {
- binary = binaryRes.binary;
- mime_type = binaryRes.mime_type;
- } else {
- LOGGER.trace("FAIL EXTERNAL");
- //failure++;
- return Thread.currentThread().getName();
- }
- }
- }
+ }
+ catch (Exception e)
+ {
+ LOGGER.error("VideoImportCallable {}",e);
+ }
+ finally {
+ //Close binary
+ if (in != null) in.close();
+ if (fis != null) fis.close();
+ if (tempFile2 != null && tempFile2.delete()) {
+ LOGGER.trace("Temp File Removed");
+ }
+ }
- //CALL ASSET MANAGER
- AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);
- BufferedImage image = ImageIO.read(binary);
+ //SAVE CHANGES
+ resourceResolver.commit();
+ return newAsset;
+ }
- //CRATE TEMPORARY MP4 FILE
- String prefix = ID + "-";
- String suffix = ".mp4";
- File tempFile2 = File.createTempFile(prefix, suffix);
- tempFile2.deleteOnExit();
+ private String cleanPath(String confPath, String filename){
+ return (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedServiceAccount + "/").concat(filename);
+ }
+ private String cleanFilename(JSONObject innerObj) throws JSONException{
+ return innerObj.getString(Constants.ORIGINAL_FILENAME) != null ? innerObj.getString(Constants.ORIGINAL_FILENAME).replaceAll("%20", " ") : null;
+ }
+ private Asset getAsset(String oldpath, String localpath ){
+ Resource resource = resourceResolver.getResource(oldpath);
+ if(resource != null) {
+ return resource.adaptTo(Asset.class);
+ }
+ resource = resourceResolver.getResource(localpath);
+ if(resource != null) {
+ return resource.adaptTo(Asset.class);
+ }
+ return null;
+ }
+ public String call(){
+ // Get the Service resource resolver
+ try {
+ final Map authInfo = Collections.singletonMap(
+ ResourceResolverFactory.SUBSERVICE,
+ (Object) SERVICE_ACCOUNT_IDENTIFIER);
+ resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
+ //FOR EACH VIDEO COMING BACK FROM THE QUERY
- AWTSequenceEncoder enc = AWTSequenceEncoder.createSequenceEncoder(tempFile2, 30);
- LOGGER.trace("ENCODING PROCESS");
+ //CHECK IF VIDEO'S STATE IS SET TO ACTIVE - CONDITION ONE
+ Boolean active = innerObj.has(Constants.STATE) && innerObj.get(Constants.STATE) != null && "ACTIVE".equals(innerObj.getString(Constants.STATE)) && innerObj.has(Constants.ID) && innerObj.get(Constants.ID) != null;
+ //CONDITIONN TWO - MUST HAVE AN ID
+ String id = getItemFromJson(innerObj,Constants.ID);
- LOGGER.trace("height" + image.getType());
- LOGGER.trace("height" + image.getHeight());
- LOGGER.trace("width" + image.getWidth());
+ LOGGER.trace(">>>>START>>>>> {} >> {}", id ,active);
- if (image.getHeight() % 2 != 0) {
- image = ImageUtil.cropImage(image, new Rectangle(image.getWidth(), image.getHeight() - (image.getHeight() % 2)));
- }
- if (image.getWidth() % 2 != 0) {
- image = ImageUtil.cropImage(image, new Rectangle(image.getWidth() - (image.getWidth() % 2), image.getHeight()));
- }
+ //TODO: CHECK IF VIDEO COMING INTO DAM (1) IS ACTIVE (2) HAS AN ID + SRC IMAGE??
+ if (!active) {
+ LOGGER.warn("VIDEO INITIALIZATION FAILED - NOT ACTIVE / NO ID - skipping: " + innerObj.toString(1));
+ if (resourceResolver != null) {
+ resourceResolver.close();
+ }
+ return Thread.currentThread().getName();
+ }
- enc.encodeImage(image);
- enc.finish();
+ String name = innerObj.getString(Constants.NAME);
+ String brightcove_filename = id + ".mp4"; //BRIGHTCOVE FILE NAME IS ID + . MP4 <-
+ String original_filename = cleanFilename(innerObj);
+ LOGGER.trace("SYNCING VIDEO>>[" + name + "\tSTATE:ACTIVE\tTO BE:" + original_filename + "]");
- InputStream in = new BufferedInputStream(new FileInputStream(tempFile2));
+ //INITIALIZING ASSET SEARCH // INITIALIZATION
+ Asset newAsset = null;
+ //TODO: PRINTING DEBUGGER (ENABLE TO DEBUG)
- LOGGER.trace("***IMAGE->VIDEO: " + "video/mp4");
+ //USNIG THE CONFIGURATION - BUILD THE DIRECTORY TO SEARCH FOR THE LOCAL ASSETS OR BUILD INTO
+ String localpath = cleanPath(confPath,brightcove_filename);
+ String oldpath = cleanPath(confPath,original_filename);
+ LOGGER.trace("SEARCHING FOR LOCAL ASSET");
+ LOGGER.trace(">>ORIGINAL: " + oldpath);
+ LOGGER.trace(">>PATH: " + localpath);
- //CREATE ASSET - NEEDS BINARY OF THUMBNAIL IN ORDER TO SET IT FOR THE NEW ASSET
- newAsset = assetManager.createAsset(localpath, in, "video/mp4", true);
+ //TRY TO GET THIS ASSET IN THE CONFIGURED BC NODE PATH - IF IT IS NULL - IT MUST BE CREATED
+ newAsset = getAsset(oldpath,localpath);
+ if (newAsset == null) {
+ newAsset = createAsset(localpath,id,brightcove_filename);
+ if (newAsset != null) serviceUtil.updateAsset(newAsset, innerObj, resourceResolver, requestedServiceAccount);
+ } else {
+ //START CASE - ASSET HAS BEEN FOUND LOCALLY - CAN BE UPDATED
+ LOGGER.trace("ASSET FOUND - UPDATING");
- //SAVE CHANGES
- resourceResolver.commit();
+ //DATE COMPARISON TO MAKE SURE IT MUST BE UPDATED
+ Date local_mod_date = new Date(newAsset.getLastModified());
- //Close binary
- in.close();
- tempFile2.delete();
+ SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
+ Date remote_date = sdf.parse(innerObj.getString(Constants.UPDATED_AT));
- //AFTER ASSET HAS BEEN CREATED --> UPDATE THE ASSET WITH THE INNER OBJ WE ARE STiLL PROCESSING
+ //LOCAL COMPARISON DATE TO SEE IF IT NEEDS TO UPDATE
+ if (local_mod_date.compareTo(remote_date) < 0) {
+ LOGGER.trace("OLDERS-DATE>>>>>" + local_mod_date);
+ LOGGER.trace("PARSED-DATE>>>>>" + remote_date);
+ LOGGER.trace(local_mod_date + " < " + remote_date);
+ LOGGER.trace("MODIFICATION DETECTED");
serviceUtil.updateAsset(newAsset, innerObj, resourceResolver, requestedServiceAccount);
- //END CASE - ASSET NOT FOUND - MUST BE CREATED
- //success++;
-
-
} else {
-
- //START CASE - ASSET HAS BEEN FOUND LOCALLY - CAN BE UPDATED
- LOGGER.trace("ASSET FOUND - UPDATING");
-
- //DATE COMPARISON TO MAKE SURE IT MUST BE UPDATED
- Date local_mod_date = new Date(newAsset.getLastModified());
-
- SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
- Date remote_date = sdf.parse(innerObj.getString("updated_at"));
-
- //LOCAL COMPARISON DATE TO SEE IF IT NEEDS TO UPDATE
- if (local_mod_date.compareTo(remote_date) < 0) {
- LOGGER.trace("OLDERS-DATE>>>>>" + local_mod_date);
- LOGGER.trace("PARSED-DATE>>>>>" + remote_date);
- LOGGER.trace(local_mod_date + " < " + remote_date);
- LOGGER.trace("MODIFICATION DETECTED");
- serviceUtil.updateAsset(newAsset, innerObj, resourceResolver, requestedServiceAccount);
- //success++;
- } else {
- LOGGER.trace("No Changes to be Made = Asset is equivalent");
- //equal++;
- }
-
+ LOGGER.trace("No Changes to be Made = Asset is equivalent");
}
- } else {
- LOGGER.warn("VIDEO INITIALIZATION FAILED - NOT ACTIVE / NO ID - skipping: " + innerObj.toString(1));
- LOGGER.trace("");
- //failure++;
+
}
- LOGGER.trace(">>>>>>>>>{" + ID + "}>>>>>END>>>>");
+ LOGGER.trace(">>>>>>>>>{" + id + "}>>>>>END>>>>");
//MAIN VIDEO ARRAY TRAVERSAL LOOP
- } catch (JSONException e) {
- LOGGER.error("JSON EXCEPTION", e);
- //failure++;
- } catch (IllegalArgumentException e) {
- LOGGER.error("IllegalArgumentException", e);
- //failure++;
- } catch (RepositoryException e) {
- LOGGER.error("RepositoryException", e);
- //failure++;
- } catch (RuntimeException e) {
- LOGGER.error("RuntimeException", e);
- //failure++;
- } catch (ParseException e) {
- LOGGER.error("ParseException", e);
- //failure++;
} catch (Exception e) {
- LOGGER.error("Exception", e);
+ LOGGER.error(e.getClass().getName(), e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/runnables/AssetPropertyIntegratorRunnable.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/runnables/AssetPropertyIntegratorRunnable.java
index 7d970e1..83cb661 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/runnables/AssetPropertyIntegratorRunnable.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/schedulers/asset_integrator/runnables/AssetPropertyIntegratorRunnable.java
@@ -39,6 +39,7 @@
import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber;
import com.coresecure.brightcove.wrapper.sling.ConfigurationService;
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.day.cq.commons.jcr.JcrUtil;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
@@ -86,8 +87,16 @@ public void run()
LOGGER.trace("BRIGHTCOVE ASSET INTEGRATION - SYNCHRONIZING DATABASE");
try
{
-
-
+ //IF ACCOUNT IS VALID - INITIATE SYNC CONFIGURATION
+ final Map authInfo = Collections.singletonMap(
+ ResourceResolverFactory.SUBSERVICE,
+ (Object) SERVICE_ACCOUNT_IDENTIFIER);
+ ResourceResolverFactory rrf = resourceResolverFactory;
+ final ResourceResolver resourceResolver = rrf.getServiceResourceResolver(authInfo);
+ Session session = resourceResolver.adaptTo(Session.class); //GET CURRENT SESSION
+ if (session == null) {
+ return;
+ }
//MAIN TRY - CONFIGURATION GRAB SERVICE
ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber(); //GETCONFIG SERVICE
Set services = cg.getAvailableServices(); //BUILD SERVICES
@@ -97,51 +106,37 @@ public void run()
//GET CURRENT CONFIGURATION
ConfigurationService cs = cg.getConfigurationService(requestedAccount);
- if (cs != null)
- {
- //IF ACCOUNT IS VALID - INITIATE SYNC CONFIGURATION
- final Map authInfo = Collections.singletonMap(
- ResourceResolverFactory.SUBSERVICE,
- (Object) SERVICE_ACCOUNT_IDENTIFIER);
- ResourceResolverFactory rrf = resourceResolverFactory;
- final ResourceResolver resourceResolver = rrf.getServiceResourceResolver(authInfo);
- synchronized (resourceResolver) {
- Session session = resourceResolver.adaptTo(Session.class); //GET CURRENT SESSION
- final String confPath = cs.getAssetIntegrationPath(); //GET PRECONFIGURED SYNC DAM TARGET PATH
- final String basePath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedAccount).concat("/"); //CREATE BASE PATH
- //CREATE AND NAME BRIGHTCOVE ASSET FOLDERS PER ACCOUNT
- Node accountFolder = JcrUtil.createPath(basePath, "sling:OrderedFolder", session);
- accountFolder.setProperty("jcr:title", cs.getAccountAlias());
- session.save();
- final ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
-
- //GET VIDEOS
- int startOffset = 0;
- JSONObject jsonObject = new JSONObject(serviceUtil.searchVideo("", startOffset, 0)); //QUERY<------
- final JSONArray itemsArr = jsonObject.getJSONArray("items");
-
- int success = 0;
- int failure = 0;
- int equal = 0;
-
- LOGGER.trace("<<< " + itemsArr.length() + " INCOMING VIDEOS");
-
- //FOR EACH VIDEO IN THE ITEMS ARRAY
- for (int i = 0; i < itemsArr.length(); i++) {
- final JSONObject innerObj = itemsArr.getJSONObject(i);
-
- Callable callable = new VideoImportCallable(innerObj,confPath,requestedServiceAccount, resourceResolverFactory, mType, serviceUtil);
- Future future = executor.submit(callable);
- //add Future to the list, we can get return value using Future
- list.add(future);
- }
-
- LOGGER.trace(">>>>FINISHED BRIGHTCOVE SYNC PAYLOAD TRAVERSAL>>>>");
- LOGGER.warn(">>>> SYNC DATA: nochange: " + equal + " success: " + success + " skipped or failed: " + failure + " >>>>");
- }
- } else {
+ if (cs == null) {
throw new Exception("[Invalid or missing Brightcove configuration]");
}
+ final String confPath = cs.getAssetIntegrationPath(); //GET PRECONFIGURED SYNC DAM TARGET PATH
+ final String basePath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedAccount).concat("/"); //CREATE BASE PATH
+ //CREATE AND NAME BRIGHTCOVE ASSET FOLDERS PER ACCOUNT
+ Node accountFolder = JcrUtil.createPath(basePath, "sling:OrderedFolder", session);
+ accountFolder.setProperty("jcr:title", cs.getAccountAlias());
+ session.save();
+ final ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
+
+ //GET VIDEOS
+ int startOffset = 0;
+ JSONObject jsonObject = new JSONObject(serviceUtil.searchVideo("", startOffset, 0, Constants.NAME, true)); //QUERY<------
+ final JSONArray itemsArr = jsonObject.getJSONArray("items");
+
+
+ LOGGER.trace("<<< " + itemsArr.length() + " INCOMING VIDEOS");
+
+ //FOR EACH VIDEO IN THE ITEMS ARRAY
+ for (int i = 0; i < itemsArr.length(); i++) {
+ final JSONObject innerObj = itemsArr.getJSONObject(i);
+
+ Callable callable = new VideoImportCallable(innerObj, confPath, requestedServiceAccount, resourceResolverFactory, mType, serviceUtil);
+ Future future = executor.submit(callable);
+ //add Future to the list, we can get return value using Future
+ list.add(future);
+ }
+
+ LOGGER.trace(">>>>FINISHED BRIGHTCOVE SYNC PAYLOAD TRAVERSAL>>>>");
+
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/CertificateListServiceImpl.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/CertificateListServiceImpl.java
index 6543c7f..909c568 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/CertificateListServiceImpl.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/CertificateListServiceImpl.java
@@ -50,7 +50,7 @@
"https://cms.api.brightcove.com/v1:::D:/cert/cms_api.cer",
"https://ingest.api.brightcove.com/v1:::D:/cert/ingest_api.cer",
"https://oauth.brightcove.com/v4/access_token:::D:/cert/oath_brightcove.cer" }),
- @Property(name = "enable-trusted-certificate", label = "Enable Trusted Certificate", description = "To Enable Enable Trusted Certificate, Value should be YES else NO", value = { "YES" }) })
+ @Property(name = "enable-trusted-certificate", label = "Enable Trusted Certificate", description = "To Enable Enable Trusted Certificate, Value should be YES else NO", value = { "NO" }) })
/**
* This class is used to get the certificate per domain. These certificate
* is used to fix the Fortify scan issue.
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationGrabberImpl.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationGrabberImpl.java
index 54915d2..5ce27c7 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationGrabberImpl.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationGrabberImpl.java
@@ -38,6 +38,7 @@
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.resource.ResourceResolver;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
@@ -76,31 +77,40 @@ public Set getAvailableServices(SlingHttpServletRequest request) {
Set result = new HashSet();
boolean is_authorized = false;
try {
- Session session = request.getResourceResolver().adaptTo(Session.class);
- UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
- /* to get the current user */
+
+ ResourceResolver resourceResolver = request.getResourceResolver();
+
+ Session session = resourceResolver.adaptTo(Session.class);
+ UserManager userManager = resourceResolver.adaptTo(UserManager.class);
+
+ if (session == null || userManager == null) {
+ return null;
+ }
Authorizable auth = userManager.getAuthorizable(session.getUserID());
- if (auth != null) {
- List memberOf = new ArrayList();
- Iterator groups = auth.memberOf();
- while (groups.hasNext() && !is_authorized) {
- Group group = groups.next();
- memberOf.add(group.getID());
- }
- int i = 0;
- for (String account : getAvailableServices()) {
- ConfigurationService cs = getConfigurationService(account);
- List allowedGroups = new ArrayList(cs.getAllowedGroupsList());
- allowedGroups.retainAll(memberOf);
- if (allowedGroups.size() > 0) {
- result.add(account);
- i++;
- }
+ if (auth == null) {
+ return null;
+ }
+
+ List memberOf = new ArrayList();
+ Iterator groups = auth.memberOf();
+ while (groups.hasNext() && !is_authorized) {
+ Group group = groups.next();
+ memberOf.add(group.getID());
+ }
+ int i = 0;
+ for (String account : getAvailableServices()) {
+ ConfigurationService cs = getConfigurationService(account);
+ List allowedGroups = new ArrayList(cs.getAllowedGroupsList());
+ allowedGroups.retainAll(memberOf);
+ if (allowedGroups.size() > 0) {
+ result.add(account);
+ i++;
}
}
- } catch (RepositoryException e) {
- LOGGER.error("RepositoryException",e);
+
+ } catch(RepositoryException e){
+ LOGGER.error("RepositoryException", e);
}
return result;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationService.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationService.java
index 906132d..ed76fe4 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationService.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/sling/ConfigurationService.java
@@ -68,4 +68,6 @@ public interface ConfigurationService {
String getProxy();
+ String getIngestProfile();
+
}
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 2fe62ab..5815fe8 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
@@ -65,7 +65,8 @@
@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 = {""}),
- @Property(name = "asset_integration_path", label = "Dam Integration Path", description = "Remote Asset Metadata Storage Path", value = "/content/dam/brightcove_assets")
+ @Property(name = "asset_integration_path", label = "Dam Integration Path", description = "Remote Asset Metadata Storage Path", value = "/content/dam/brightcove_assets"),
+ @Property(name = "ingest_profile", label = "Ingest Profile", description = "Configure default Ingest Profile", value = "")
})
@@ -153,6 +154,11 @@ public String getProxy() {
return (String) getProperties().get("proxy");
}
+ public String getIngestProfile() {
+ return (String) getProperties().get("ingest_profile");
+ }
+
+
private String[] cleanStringArray(String[] input) {
String[] result = input;
List list = new ArrayList();
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 542457c..8544634 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
@@ -35,13 +35,19 @@
import com.coresecure.brightcove.wrapper.BrightcoveAPI;
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.JcrUtil;
import com.coresecure.brightcove.wrapper.utils.S3UploadUtil;
+import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.dam.api.Asset;
+import com.day.cq.dam.api.DamConstants;
import com.day.cq.dam.api.Rendition;
+import com.day.cq.dam.commons.handler.StandardImageHandler;
import com.day.cq.tagging.InvalidTagFormatException;
import com.day.cq.tagging.Tag;
+import com.day.cq.tagging.TagConstants;
import com.day.cq.tagging.TagManager;
+import com.day.cq.wcm.api.NameConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.*;
import org.apache.sling.commons.json.JSONArray;
@@ -52,6 +58,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.annotation.Nonnull;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.servlet.http.Cookie;
@@ -66,10 +73,10 @@
public class ServiceUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceUtil.class);
private static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
- private static final String[] fields = {"name", "created_at" , "duration", "complete", "id", "account_id" ,"description" , "link", "tags","long_description", "reference_id", "economics", "updated_at" , "schedule", "state", "geo" , "custom_fields","text_tracks" , "images" ,"projection"};
+ private static final String[] fields = {Constants.NAME, Constants.CREATED_AT , Constants.DURATION, Constants.COMPLETE, Constants.ID, Constants.ACCOUNT_ID ,Constants.DESCRIPTION , Constants.LINK, Constants.TAGS, Constants.LONG_DESCRIPTION, Constants.REFERENCE_ID, Constants.ECONOMICS, Constants.UPDATED_AT , Constants.SCHEDULE, Constants.STATE, Constants.GEO , Constants.CUSTOM_FIELDS, Constants.TEXT_TRACKS , Constants.IMAGES ,Constants.PROJECTION};
private String account_id;
- public static int DEFAULT_LIMIT = 100;
+ public static final int DEFAULT_LIMIT = 100;
private BrightcoveAPI brAPI = null;
public ServiceUtil(String aAccount_id) {
@@ -145,14 +152,14 @@ public int compare(Object o1, Object o2) {
private String getLength(String videoId, String accountKeyStr) {
String result = "";
try {
- long millis = brAPI.cms.getVideoByRef(videoId).getLong("duration");
+ long millis = brAPI.cms.getVideoByRef(videoId).getLong(Constants.DURATION);
result = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
} catch (JSONException je) {
- //todo log
+ LOGGER.error(je.getClass().getName(), je);
}
return result;
}
@@ -160,9 +167,9 @@ private String getLength(String videoId, String accountKeyStr) {
public String getName(String videoId, String accountKeyStr) {
String result = "";
try {
- result = brAPI.cms.getVideoByRef(videoId).getString("name");
+ result = brAPI.cms.getVideoByRef(videoId).getString(Constants.NAME);
} catch (JSONException je) {
- //todo log
+ LOGGER.error(je.getClass().getName(), je);
}
return result;
}
@@ -182,13 +189,18 @@ public String getList(Boolean exportCSV, String query) {
}
public String getList(Boolean exportCSV, int offset, int limit, boolean full_scroll, String query) {
- return getList(exportCSV, offset, limit, full_scroll, query, "name");
+ return getList(exportCSV, offset, limit, full_scroll, query, Constants.NAME);
}
public JSONArray getVideoSources(String videoID) {
return brAPI.cms.getVideoSources(videoID);
}
public String getList(Boolean exportCSV, int offset, int limit, boolean full_scroll, String query, String sort) {
+ return getList(exportCSV, offset, limit, full_scroll, query, sort, false);
+ }
+ public String getList(Boolean exportCSV, int offset, int limit, boolean full_scroll, String query, String sort, boolean dam_only) {
LOGGER.debug("getList: " + query);
+
+
JSONObject items = new JSONObject();
String result = "";
limit = limit > 0 ? limit : 100;
@@ -201,7 +213,7 @@ public String getList(Boolean exportCSV, int offset, int limit, boolean full_scr
totalItems = brAPI.cms.getVideosCount(query).getLong("count");
while (offset < totalItems && full_scroll) {
- JSONArray videos_page = brAPI.cms.addThumbnail(brAPI.cms.getVideos(query, limit, offset, sort));
+ JSONArray videos_page = brAPI.cms.addThumbnail(brAPI.cms.getVideos(query, limit, offset, sort, dam_only));
for (int i = 0; i < videos_page.length(); i++) {
JSONObject video = videos_page.getJSONObject(i);
videos.put(video);
@@ -218,7 +230,7 @@ public String getList(Boolean exportCSV, int offset, int limit, boolean full_scr
for (int key = 0; key < videos.length(); key++) {
tempJSON = videos.getJSONObject(key);
- csvString += "\"" + tempJSON.getString("name") + "\",\"" + tempJSON.getString("id") + "\"\r\n";
+ csvString += "\"" + tempJSON.getString(Constants.NAME) + "\",\"" + tempJSON.getString(Constants.ID) + "\"\r\n";
}
result = csvString;
} else {
@@ -227,10 +239,7 @@ public String getList(Boolean exportCSV, int offset, int limit, boolean full_scr
result = items.toString(1);
}
} catch (JSONException e) {
- LOGGER.error("JSONException", e);
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -253,22 +262,23 @@ public String searchVideo(String querystr, int offset, int limit) {
return result;
}
- public String searchVideo(String querystr, int offset, int limit, String sort) {
+ public String searchVideo(String querystr, int offset, int limit, String sort, boolean dam_only) {
//Fixed the performance issue at the component authoring side.
//String result = getList(false, offset, limit, true, querystr);
boolean fullscroll = !(limit > 0);
- String result = getList(false, offset, limit, fullscroll, querystr, sort);
+ String result = getList(false, offset, limit, fullscroll, querystr, sort, dam_only);
return result;
}
+ public String searchVideo(String querystr, int offset, int limit, String sort) {
+ return searchVideo(querystr, offset, limit, sort, false);
+ }
public JSONObject getSelectedVideo(String videoIdstr) {
JSONObject result = new JSONObject();
try {
result = brAPI.cms.getVideo(videoIdstr);
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -278,9 +288,7 @@ public JSONObject getCustomFields() {
try {
result = brAPI.cms.getCustomFields();
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -292,9 +300,7 @@ public String getVideoByRefID(String videoIdstr) {
JSONObject video = brAPI.cms.getVideoByRef(videoIdstr);
result = video.toString();
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -306,14 +312,14 @@ public String getListSideMenu(String limits) {
int limit = DEFAULT_LIMIT;
int firstElement = 0;
int lastElement = limit;
- if (limits != null && !limits.trim().isEmpty() && limits.split("\\.\\.")[0] != null) {
- firstElement = Integer.parseInt(limits.split("\\.\\.")[0]);
- lastElement = Integer.parseInt(limits.split("\\.\\.")[1]);
+ if (limits != null && !limits.trim().isEmpty() && limits.split(Constants.DELIMETER_STRING_DOUBLE)[0] != null) {
+ firstElement = Integer.parseInt(limits.split(Constants.DELIMETER_STRING_DOUBLE)[0]);
+ lastElement = Integer.parseInt(limits.split(Constants.DELIMETER_STRING_DOUBLE)[1]);
limit = lastElement - firstElement;
}
result = getList(false, firstElement, limit, false, "");
} catch (Exception e) {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -328,9 +334,7 @@ public JSONObject getPlayers() {
try {
result = brAPI.cms.getPlayers();
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -341,9 +345,7 @@ public JSONObject getPlaylistByID(String id) {
try {
result = brAPI.cms.getPlaylist(id);
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
@@ -359,15 +361,15 @@ public String getPlaylists(String q, int offset, int limit, boolean exportCSV, b
try {
int pageNumber = 0;
long totalItems = 0;
- JSONArray playlists = brAPI.cms.getPlaylists(q, limit, offset, "name");
+ JSONArray playlists = brAPI.cms.getPlaylists(q, limit, offset, Constants.NAME);
offset = offset + limit;
if (playlists.length() > 0) {
totalItems = brAPI.cms.getPlaylistsCount().getLong("count");
- double totalPages = Math.floor(totalItems / limit);
+ double totalPages = Math.floor((double)totalItems / limit);
while (offset < totalItems && full_scroll) {
- JSONArray videos_page = brAPI.cms.getPlaylists(q, limit, offset, "name");
+ JSONArray videos_page = brAPI.cms.getPlaylists(q, limit, offset, Constants.NAME);
for (int i = 0; i < videos_page.length(); i++) {
playlists.put(videos_page.get(i));
}
@@ -383,19 +385,16 @@ public String getPlaylists(String q, int offset, int limit, boolean exportCSV, b
for (int key = 0; key < playlists.length(); key++) {
tempJSON = playlists.getJSONObject(key);
- csvString += "\"" + tempJSON.getString("name") + "\",\"" + tempJSON.getString("id") + "\"\r\n";
+ csvString += "\"" + tempJSON.getString(Constants.NAME) + "\",\"" + tempJSON.getString(Constants.ID) + "\"\r\n";
}
result = csvString;
} else {
items.put("items", playlists);
items.put("totals", totalItems);
-
result = items.toString(1);
}
} catch (JSONException e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -409,9 +408,7 @@ public JSONArray getVideosJsonByIds(String videoIds, String videoProperties) {
jsa.put(brAPI.cms.getVideo(id));
}
} catch (Exception e) {
- e.printStackTrace();
- } finally {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return jsa;
}
@@ -423,23 +420,23 @@ public JSONObject updateVideo(Video aVideo) {
try {
JSONObject videoItem = brAPI.cms.updateVideo(aVideo);
try {
- if (videoItem != null && videoItem.has("id")) {
- String newVideoId = videoItem.getString("id");
- LOGGER.info("New video id: '" + newVideoId + "'.");
- result.put("videoid", newVideoId);
- result.put("sent", true);
+ if (videoItem != null && videoItem.has(Constants.ID)) {
+ String newVideoId = videoItem.getString(Constants.ID);
+ LOGGER.info(Constants.RESULT_LOG_NEW_VIDEO_TMPL, newVideoId);
+ result.put(Constants.VIDEOID, newVideoId);
+ result.put(Constants.SENT, true);
} else {
- result.put("error", "updateVideo Error");
- result.put("sent", false);
+ result.put(Constants.ERROR, "updateVideo Error");
+ result.put(Constants.SENT, false);
}
- } catch (Exception exIngest) {
- LOGGER.error("updateVideo", exIngest);
- result.put("error", "updateVideo Exception");
- result.put("sent", false);
+ } catch (Exception e) {
+ LOGGER.error(e.getClass().getName(), e);
+ result.put(Constants.ERROR, "updateVideo Exception");
+ result.put(Constants.SENT, false);
}
} catch (JSONException e) {
- LOGGER.error("updateVideo", e);
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
@@ -449,27 +446,27 @@ public JSONObject createVideo(Video aVideo, String ingestURL, String ingestProfi
JSONObject result = new JSONObject();
try {
JSONObject videoItem = brAPI.cms.createVideo(aVideo);
- String newVideoId = videoItem.getString("id");
+ String newVideoId = videoItem.getString(Constants.ID);
JSONObject videoIngested = new JSONObject();
try {
com.coresecure.brightcove.wrapper.objects.Ingest ingest = new com.coresecure.brightcove.wrapper.objects.Ingest(ingestProfile, ingestURL);
videoIngested = brAPI.cms.createIngest(new com.coresecure.brightcove.wrapper.objects.Video(videoItem), ingest);
- if (videoIngested != null && videoIngested.has("id")) {
- LOGGER.info("New video id: '" + newVideoId + "'.");
- result.put("videoid", newVideoId);
+ if (videoIngested != null && videoIngested.has(Constants.ID)) {
+ LOGGER.info(Constants.RESULT_LOG_NEW_VIDEO_TMPL, newVideoId);
+ result.put(Constants.VIDEOID, newVideoId);
result.put("output", videoIngested);
} else {
- result.put("error", "createIngest Error");
+ result.put(Constants.ERROR, "createIngest Error");
brAPI.cms.deleteVideo(newVideoId);
}
} catch (Exception exIngest) {
LOGGER.error("createVideo", exIngest);
- result.put("error", "createIngest Exception");
+ result.put(Constants.ERROR, "createIngest Exception");
brAPI.cms.deleteVideo(newVideoId);
}
} catch (JSONException e) {
- LOGGER.error("JSON Error - createVideo", e);
+ LOGGER.error(e.getClass().getName() + "Create Video", e);
}
return result;
}
@@ -478,75 +475,62 @@ public JSONObject createVideoS3(Video aVideo, String filename, InputStream is) {
JSONObject result = new JSONObject();
try {
JSONObject videoItem = brAPI.cms.createVideo(aVideo);
- String newVideoId = videoItem.getString("id");
+ String newVideoId = videoItem.getString(Constants.ID);
JSONObject videoIngested = new JSONObject();
try {
videoIngested = brAPI.cms.getIngestURL(newVideoId, filename);
- if (videoIngested != null && videoIngested.has("bucket")) {
- LOGGER.info("New video id: '" + newVideoId + "'.");
- result.put("bucket", videoIngested.get("bucket"));
- result.put("videoid", newVideoId);
- result.put("object_key", videoIngested.get("object_key"));
- result.put("api_request_url", videoIngested.get("api_request_url"));
- result.put("signed_url", videoIngested.get("signed_url"));
- boolean sent = S3UploadUtil.uploadToUrl(new URL(videoIngested.getString("signed_url")), is);
-
- result.put("sent", sent);
- if (!sent) {
- brAPI.cms.deleteVideo(newVideoId);
- } else {
- result.put("job", brAPI.cms.requestIngestURL(newVideoId, "high-resolution", videoIngested.getString("api_request_url"), true));
- }
- } else {
- LOGGER.trace("createIngest: " + videoIngested.toString(1));
-
- result.put("error", "createIngest Error");
+ LOGGER.info(Constants.RESULT_LOG_NEW_VIDEO_TMPL, newVideoId);
+ result.put(Constants.BUCKET, videoIngested.get(Constants.BUCKET));
+ result.put(Constants.VIDEOID, newVideoId);
+ 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);
+ result.put(Constants.SENT, sent);
+ if (!sent) {
brAPI.cms.deleteVideo(newVideoId);
}
-
- } catch (Exception exIngest) {
- LOGGER.error("createIngest", exIngest);
- result.put("error", "createIngest Exception");
+ else
+ {
+ ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
+ ConfigurationService 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));
+ }
+ } catch (Exception e) {
+ LOGGER.error(e.getClass().getName(), e);
+ result.put(Constants.ERROR, e.getStackTrace()[0].getMethodName());
brAPI.cms.deleteVideo(newVideoId);
}
- LOGGER.trace("result: " + result.toString(1));
+ LOGGER.trace(Constants.RESULT_LOG_TMPL, result.toString(1));
} catch (JSONException e) {
- LOGGER.error("createVideo", e);
+ LOGGER.error(e.getClass().getName(), e);
}
-
return result;
}
public JSONObject createAssetS3(String newVideoId, String filename, InputStream is) {
JSONObject result = new JSONObject();
try {
- JSONObject assetIngested = new JSONObject();
try {
- assetIngested = brAPI.cms.getIngestURL(newVideoId, filename);
- if (assetIngested != null && assetIngested.has("bucket")) {
- LOGGER.info("New video id: '" + newVideoId + "'.");
- result.put("bucket", assetIngested.get("bucket"));
- result.put("videoid", newVideoId);
- result.put("object_key", assetIngested.get("object_key"));
- result.put("api_request_url", assetIngested.get("api_request_url"));
- result.put("signed_url", assetIngested.get("signed_url"));
- boolean sent = S3UploadUtil.uploadToUrl(new URL(assetIngested.getString("signed_url")), is);
- result.put("sent", sent);
- } else {
- LOGGER.trace("createIngest: " + assetIngested.toString(1));
- result.put("error", "createIngest Error");
- }
-
- } catch (Exception exIngest) {
- LOGGER.error("createIngest", exIngest);
- result.put("error", "createIngest Exception");
+ JSONObject assetIngested = brAPI.cms.getIngestURL(newVideoId, filename);
+ LOGGER.info(Constants.RESULT_LOG_NEW_VIDEO_TMPL,newVideoId);
+ result.put(Constants.BUCKET, assetIngested.get(Constants.BUCKET));
+ result.put(Constants.VIDEOID, newVideoId);
+ 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);
+ result.put(Constants.SENT, sent);
+ } catch (Exception e) {
+ LOGGER.error(e.getClass().getName(), e);
+ result.put(Constants.ERROR, e.getStackTrace()[0].getMethodName());
brAPI.cms.deleteVideo(newVideoId);
}
- LOGGER.trace("result: " + result.toString(1));
-
+ LOGGER.trace(Constants.RESULT_LOG_TMPL, result.toString(1));
} catch (JSONException e) {
- LOGGER.error("createAssetS3", e);
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
@@ -559,456 +543,418 @@ public String getListPlaylistsSideMenu(String limits) {
int limit = DEFAULT_LIMIT;
int firstElement = 0;
int lastElement = limit;
- if (limits != null && !limits.trim().isEmpty() && limits.split("\\.\\.")[0] != null) {
- firstElement = Integer.parseInt(limits.split("\\.\\.")[0]);
- lastElement = Integer.parseInt(limits.split("\\.\\.")[1]);
+ if (limits != null && !limits.trim().isEmpty() && limits.split(Constants.DELIMETER_STRING_DOUBLE)[0] != null) {
+ firstElement = Integer.parseInt(limits.split(Constants.DELIMETER_STRING_DOUBLE)[0]);
+ lastElement = Integer.parseInt(limits.split(Constants.DELIMETER_STRING_DOUBLE)[1]);
limit = lastElement - firstElement;
}
result = getPlaylists(firstElement, limit, false, false);
} catch (Exception e) {
-
+ LOGGER.error(e.getClass().getName(), e);
}
return result;
}
- public void updateAsset(Asset newAsset, JSONObject innerObj, ResourceResolver resourceResolver, String requestedAccount) throws JSONException, RepositoryException, PersistenceException {
+ private String getKey(String x){
+ String key = x;
+ if (x.equals(Constants.TAGS))
+ {
+ key = NameConstants.PN_TAGS;
+ }
+ else if (Constants.NAME.equals(x))
+ {
+ key = DamConstants.DC_TITLE; //NAME -> ASSET TITLE
+ }
+ else
+ {
+ key = "brc_".concat(x); //ALL ELSE -> BRC_KEYNAME
+ }
+ return key;
+ }
+ private void setMapJSONArray(String key, JSONArray objArray, ResourceResolver resourceResolver, ModifiableValueMap map) {
+ TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
+ if (tagManager == null) return;
try {
- if (newAsset != null)
+ if (key.equals(NameConstants.PN_TAGS)) {
+ List tags = new ArrayList();
+ for (int cnt = 0; cnt < objArray.length(); cnt++) {
+ String tagValue = objArray.getString(cnt);
+
+ String tagKey = tagValue.replaceAll(": ", ":").trim();
+
+
+ try {
+ if (tagManager.canCreateTag(tagKey)) {
+
+ Tag tag = tagManager.createTag(tagKey, tagValue, "");
+
+ //Tag tag = tagManager.createTagByTitle(tagValue, Locale.US);
+ resourceResolver.commit();
+ LOGGER.trace("tag created > {}", tagValue);
+ //tagManager.setTags(assetRes, new Tag[]{tag}, true);
+ } else {
+ //Tag[] tags = tagManager.findTagsByTitle(tagValue, Locale.US);
+ //tagManager.setTags(assetRes, tags, true);
+ LOGGER.warn("tag create failed [exists] > added > {}", tagValue);
+
+ }
+ tags.add(tagKey);
+ } catch (InvalidTagFormatException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ resourceResolver.commit();
+ map.put(key, tags.toArray());
+ } else {
+ map.put(key, objArray.join("#@#").split("#@#"));
+ }
+ }catch (Exception e) {
+ LOGGER.error(e.getClass().getName(),e);
+ }
+ }
+
+ private void setImages(JSONObject objObject, Asset newAsset) {
+ try {
+ if (objObject.has(Constants.POSTER)) {
+ JSONObject images_poster_obj = objObject.getJSONObject(Constants.POSTER);
+ String src = images_poster_obj.getString(Constants.SRC);
+ //DO GET FOR RENDITION -> TO ASSET "brc_poster"
+ URL srcURL = new URL(src);
+ InputStream ris = srcURL.openStream();
+ //Map rendition_map = new HashMap();
+ newAsset.addRendition(Constants.BRC_POSTER_PNG, ris, StandardImageHandler.PNG1_MIMETYPE);
+ } else {
+ newAsset.removeRendition(Constants.BRC_POSTER_PNG);
+ }
+ if (objObject.has(Constants.THUMBNAIL))
{
+ JSONObject images_poster_obj = objObject.getJSONObject(Constants.THUMBNAIL);
+ String src = images_poster_obj.getString(Constants.SRC);
+ //DO GET FOR RENDITION -> TO ASSET "brc_thumbnail"
+
+ InputStream ris = new URL(src).openStream();
+ //Map rendition_map = new HashMap();
+ newAsset.addRendition(Constants.BRC_THUMBNAIL_PNG, ris, StandardImageHandler.PNG1_MIMETYPE);
+ } else {
+ newAsset.removeRendition(Constants.BRC_THUMBNAIL_PNG);
+ }
+ }
+ catch (Exception e)
+ {
+ LOGGER.error("Failure to initialize remote source for {0}", newAsset.getPath(), e);
+ }
+ }
+ private void setSchedule(JSONObject objObject, ModifiableValueMap assetmap){
+ try {
+ SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
+ String starts_at = objObject.getString(Constants.STARTS_AT);
+ if (starts_at != null && !starts_at.toString().equals(Constants.NULLSTRING)) {
+ assetmap.put(DamConstants.PN_ON_TIME, starts_at);
+ } else {
+ if (assetmap.containsKey(DamConstants.PN_ON_TIME)) assetmap.remove(DamConstants.PN_ON_TIME);
+ }
+ String ends_at = objObject.getString(Constants.ENDS_AT);
+ if (ends_at != null && !ends_at.toString().equals(Constants.NULLSTRING)) {
+ assetmap.put(DamConstants.PN_OFF_TIME, ends_at);
+ } else {
+ if (assetmap.containsKey(DamConstants.PN_OFF_TIME)) assetmap.remove(DamConstants.PN_OFF_TIME);
+ }
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+
+ private void setLink(JSONObject objObject, ModifiableValueMap map) {
+ try {
+ String link_url = objObject.getString(Constants.URL);
+ if (link_url != null && !link_url.toString().equals(Constants.NULLSTRING)) {
+ map.put(Constants.BRC_LINK_URL, link_url);
+ } else {
+ if (map.containsKey(Constants.BRC_LINK_URL)) map.remove(Constants.BRC_LINK_URL);
+ }
+ String link_text = objObject.getString(Constants.TEXT);
+ if (link_text != null && !link_text.toString().equals(Constants.NULLSTRING)) {
+ map.put(Constants.BRC_LINK_TEXT, link_text);
+ } else {
+ if (map.containsKey(Constants.BRC_LINK_TEXT)) map.remove(Constants.BRC_LINK_TEXT);
+ }
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+ private void setObject(JSONObject objObject, Resource metadataRes, String key) {
+ try {
+ Node metadataNode = metadataRes.adaptTo(Node.class);
+ if (metadataNode == null) return;
+
+ Node subNode;
+ if (metadataRes.getChild(key) == null) {
+ subNode = metadataNode.addNode(key);
+ } else {
+ subNode = metadataNode.getNode(key);
+ }
+ if (subNode == null) return;
+ Resource subResource = metadataRes.getChild(key);
+ if (subResource == null) return;
+ ModifiableValueMap submap = subResource.adaptTo(ModifiableValueMap.class);
+ if(submap==null) return;
+
+ Iterator itrObj = objObject.keys();
+ while (itrObj.hasNext()) {
+ String selectorKey = itrObj.next();
+ submap.put(selectorKey, objObject.get(selectorKey));
+ }
+ } catch (RepositoryException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ } catch (JSONException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
+ }
+
+ private void removeObject(String key, String x, ModifiableValueMap map, Asset newAsset, ModifiableValueMap assetmap ) {
+ if (x.equals(Constants.IMAGES)) {
+ //NULL ON IMAGES MEANS NULL SOURCES OF IMAGES
+ newAsset.removeRendition(Constants.BRC_POSTER_PNG);
+ newAsset.removeRendition(Constants.BRC_THUMBNAIL_PNG);
+ } else if (x.equals(Constants.SCHEDULE)) {
+ //NULL OBJECT OF SCHEDULE = EMPTY SCHEDULE METADATA
+ if (assetmap.containsKey(DamConstants.PN_ON_TIME))
+ assetmap.remove(DamConstants.PN_ON_TIME);
+ if (assetmap.containsKey(DamConstants.PN_OFF_TIME))
+ assetmap.remove(DamConstants.PN_OFF_TIME);
+ } else if (x.equals(Constants.LINK)) {
+ //NULL LINK OBJECT MEANS EMPTY URL + TEXT METADATA
+ if (map.containsKey(Constants.BRC_LINK_TEXT)) map.remove(Constants.BRC_LINK_TEXT);
+ if (map.containsKey(Constants.BRC_LINK_URL)) map.remove(Constants.BRC_LINK_URL);
+ } else {
+ //IF ANY OTHER ARE NULL AND WERE ACTIVE - ARE NOW EQUIVALENT
+ if (map.containsKey(key)) map.remove(key);
+ }
+ }
- // LOGGER.trace(innerObj.toString(1));//TODO: Debugger print statement
+ private void setObject(Object obj, String key, String x, ModifiableValueMap map, Asset newAsset, ModifiableValueMap assetmap) {
+ if (obj != null && !obj.toString().toString().equals(Constants.NULLSTRING)) {
+ if (key.equals(Constants.BRC_DURATION)) {
+ int input = Integer.parseInt(obj.toString());
+ input = input / 1000;
+ obj = String.format("%02d:%02d:%02d", input / 3600, (input % 3600) / 60, (input % 3600) % 60);
+ }
+ map.put(key, obj); //MAIN SET OF THE KEYS->VALUES FOR THIS VIDEO OBJECT
+ } else {
+
+ //Improve this check, this is the handle for null object / string
+ //WE TAKE THESE NULL VALUES AS ACTUAL VALUES AND EXECUTE
+ removeObject(key, x, map, newAsset, assetmap );
+ }
+ }
+
+ public void updateAsset(@Nonnull Asset newAsset, JSONObject innerObj, ResourceResolver resourceResolver, String requestedAccount) throws JSONException, RepositoryException, PersistenceException {
+
+ try {
+
+ // LOGGER.trace(innerObj.toString(1));
LOGGER.trace("UPDATING ASSET>>: " + newAsset.getPath());
Resource assetRes = newAsset.adaptTo(Resource.class); //INITIALIZE THE ASSET RESOURCE
- ModifiableValueMap assetmap = assetRes.getChild("jcr:content").adaptTo(ModifiableValueMap.class);
+ ModifiableValueMap assetmap = assetRes.getChild(NameConstants.NN_CONTENT).adaptTo(ModifiableValueMap.class);
- Resource metadataRes = assetRes.getChild("jcr:content/metadata"); //INITIALIZE THE ASSET BC METADATA MAP RESOURCE
+ Resource metadataRes = assetRes.getChild(Constants.ASSET_METADATA_PATH); //INITIALIZE THE ASSET BC METADATA MAP RESOURCE
ModifiableValueMap map = metadataRes.adaptTo(ModifiableValueMap.class);
//SET FIRST PIECE OF METADATA
- map.put("brc_account_id", requestedAccount);
+ map.put(Constants.BRC_ACCOUNTID, requestedAccount);
//HANDLE TAG S
TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
List tags = new ArrayList();
- map.put("cq:tags", tags.toArray());
+ map.put(TagConstants.PN_TAGS, tags.toArray());
- for (String x : fields)
- {
-
- if(innerObj.has(x))
- {
- LOGGER.trace("[X] {} " + innerObj.getString(x), x);
- }
+ for (String x : fields) {
//ADAPT NAME OF METADATA COMPING IN -> AEM PROPERTIES TO BE STORED
- if (innerObj.has(x))
- {
- String key = x;
- if (x.equals("tags"))
- {
- key = "cq:".concat(x); //TAGS -> CQ TAGS
- }
- else if ("name".equals(x))
- {
- key = "dc:title"; //NAME -> ASSET TITLE
- }
- else
- {
- key = "brc_".concat(x); //ALL ELSE -> BRC_KEYNAME
- }
- // SECOND PRINT STATEMNT - LOGGER.trace("" + x + " -> " + "[" + innerObj.get(x) + "] is null? -> " + innerObj.get(x).equals(null));
-
- Object obj = innerObj.get(x);
-
- //IF THE CURRENT METADATA IS AN ARRAY
- if (obj instanceof JSONArray)
- {
- JSONArray objArray = (JSONArray) obj;
- if (x.equals("tags")) {
-
-
- //LOGGER.trace("TAG ARRAY "+objArray.toString(1));
-
- for (int cnt = 0; cnt < objArray.length(); cnt++)
- {
- String tagValue = objArray.getString(cnt);
+ if (!innerObj.has(x)) {
+ LOGGER.trace("##HAS KEY BUT OBJECT IT LEADS TO IS NULL!");
+ LOGGER.trace("## HAS OBJECT WITH KEY : " + x +" ? "+innerObj.has(x) + " isnull? : "+ (innerObj.get(x)==null));
+ break;
+ }
- String tagKey = tagValue.replaceAll(": ",":").trim();
+ String key = getKey(x);
- try {
- if (tagManager.canCreateTag(tagKey)) {
+ Object obj = innerObj.get(x);
- Tag tag = tagManager.createTag(tagKey, tagValue, "");
+ LOGGER.trace("[X] {} {}", obj, key);
- //Tag tag = tagManager.createTagByTitle(tagValue, Locale.US);
- resourceResolver.commit();
- LOGGER.trace("tag created > " + tagValue);
- //tagManager.setTags(assetRes, new Tag[]{tag}, true);
- } else {
- //Tag[] tags = tagManager.findTagsByTitle(tagValue, Locale.US);
- //tagManager.setTags(assetRes, tags, true);
- LOGGER.warn("tag create failed [exists] > added > ", tagValue);
+ //IF THE CURRENT METADATA IS AN ARRAY
+ if (obj instanceof JSONArray) {
+ JSONArray objArray = (JSONArray) obj;
+ setMapJSONArray(key, objArray, resourceResolver, map);
+ } else if (obj instanceof JSONObject) {
- }
- tags.add(tagKey);
- } catch (InvalidTagFormatException e) {
- LOGGER.error("Invalid Tag Format", e);
- }
- }
- resourceResolver.commit();
- map.put(key, tags.toArray());
- } else {
- map.put(key, objArray.join("#@#").split("#@#"));
- }
- }
- else if (obj instanceof JSONObject)
- {
-
- //ELSE IF IT IS AN OBJECT
- JSONObject objObject = (JSONObject) obj;
-
- //CASE IMAGES
- if (x.equals("images"))
- {
- if (objObject != null) {
-
- try {
-
- //LOGGER.trace(objObject.toString());
- if (objObject.has("poster")) {
- JSONObject images_poster_obj = objObject.getJSONObject("poster");
- String src = images_poster_obj.getString("src");
- //DO GET FOR RENDITION -> TO ASSET "brc_poster"
- URL srcURL = new URL(src);
- InputStream ris = srcURL.openStream();
- //Map rendition_map = new HashMap();
- newAsset.addRendition("brc_poster.png", ris, "image/jpeg");
- }
-
- if (objObject.has("thumbnail"))
- {
- JSONObject images_poster_obj = objObject.getJSONObject("thumbnail");
- String src = images_poster_obj.getString("src");
- //DO GET FOR RENDITION -> TO ASSET "brc_thumbnail"
-
- InputStream ris = new URL(src).openStream();
- //Map rendition_map = new HashMap();
- newAsset.addRendition("brc_thumbnail.png", ris, "image/jpeg");
- }
- }
- catch (Exception e)
- {
- LOGGER.error("Failure to initialize remote source for "+ newAsset.getPath(), e);
- }
-
-
- } else {
- newAsset.removeRendition("brc_poster.png");
- newAsset.removeRendition("brc_thumbnail.png");
- }
- } //CASE SCHEDULE
- else if (x.equals("schedule"))
- {
- if (objObject != null) {
-
-
- LOGGER.trace("PRE-PARSE>>>>>>>");
- SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
-
-
- String starts_at = objObject.getString("starts_at");
- if (starts_at != null && !starts_at.equals("null")) {
- assetmap.put("onTime", starts_at);
- } else {
- if (assetmap.containsKey("onTime")) assetmap.remove("onTime");
- }
- String ends_at = objObject.getString("ends_at");
- if (ends_at != null && !ends_at.equals("null")) {
- assetmap.put("offTime", ends_at);
- } else {
- if (assetmap.containsKey("offTime")) assetmap.remove("offTime");
- }
- } else {
- LOGGER.trace("PRE-REMOVE>>>>>>>");
- if (assetmap.containsKey("onTime")) assetmap.remove("onTime");
- if (assetmap.containsKey("offTime")) assetmap.remove("offTime");
- }
- } //ELSE - LINK
- else if (x.equals("link"))
- {
-
- //"link":{"text":"Sample related link","url":"www.brightcove.com"},"
- if (objObject != null)
- {
- String link_url = objObject.getString("url");
- if (link_url != null && !link_url.equals("null")) {
- map.put("brc_link_url", link_url);
- } else {
- if (map.containsKey("brc_link_url")) map.remove("brc_link_url");
- }
- String link_text = objObject.getString("text");
- if (link_text != null && !link_text.equals("null")) {
- map.put("brc_link_text", link_text);
- } else {
- if (map.containsKey("brc_link_text")) map.remove("brc_link_text");
- }
- }
- else
- {
- if (map.containsKey("brc_link_text")) map.remove("brc_link_text");
- if (map.containsKey("brc_link_url")) map.remove("brc_link_url");
- }
- }
- else
- {
-
- //TODO: CHECK - SUBMODULE NECESSARY ? This is else JSON Object Case
-
- Node subNode;
- Resource subResource;
- if (metadataRes.getChild(key) == null) {
- subNode = metadataRes.adaptTo(Node.class).addNode(key);
- } else {
- subNode = metadataRes.adaptTo(Node.class).getNode(key);
- }
-
- if (subNode != null) {
- subResource = metadataRes.getChild(key);
- ModifiableValueMap submap = subResource.adaptTo(ModifiableValueMap.class);
- Iterator itrObj = objObject.keys();
- while (itrObj.hasNext()) {
- String selectorKey = itrObj.next();
- submap.put(selectorKey, objObject.get(selectorKey));
- }
- }
-
-
-
- }
+ JSONObject objObject = (JSONObject) obj;
+ //CASE IMAGES
+ if (x.equals(Constants.IMAGES)) {
+ setImages(objObject, newAsset);
+ } //CASE SCHEDULE
+ else if (x.equals(Constants.SCHEDULE)) {
+ setSchedule(objObject, assetmap);
+ } //ELSE - LINK
+ else if (x.equals(Constants.LINK)) {
+ setLink(objObject, map);
+ } else {
+ setObject(objObject, metadataRes, key);
}
- else //NOT ARRAY NOR OBJECT
- {
- //DURATION SETTING AND CHECK
- try {
- //Check format of brc_duration
- if (key.equals("brc_duration") && obj!=null)
- {
- //LOGGER.trace("*!*!*! current key : " + key.toString() + " value: " + obj.toString());
- //conditional conversion
- int input = Integer.parseInt(obj.toString());
- input = input / 1000 ;
- obj = String.format("%02d:%02d:%02d", input/3600,(input % 3600) / 60,(input % 3600) % 60);
- //LOGGER.trace("*!*!*! is now :" + obj.toString());
- }
- }
- catch (IllegalStateException e)
- {
- LOGGER.warn("Duration Check Error! Invalid / empty video duration");
- }
- catch (NumberFormatException e)
- {
- LOGGER.warn("Duration Check Error! Invalid / empty video duration");
- }
- catch (Exception e)
- {
- LOGGER.warn("Duration Check Error!", e);
- }
- //END DURATION CHECK AND SET
-
-
-
- //THIS HANDLES REST OF NULL SET KEYS WHICH MAP TO PROPERTY VALUES
- if (obj != null && !obj.equals(null) && !obj.equals("null"))
- {
- map.put(key, obj); //MAIN SET OF THE KEYS->VALUES FOR THIS VIDEO OBJECT
- }
- else
- {
-
- //TODO: Improvie this check, this is the handle for null object / string
- //WE TAKE THESE NULL VALUES AS ACTUAL VALUES AND EXECUTE
- if (x.equals("images"))
- {
- //NULL ON IMAGES MEANS NULL SOURCES OF IMAGES
- newAsset.removeRendition("brc_poster.png");
- newAsset.removeRendition("brc_thumbnail.png");
- }
- else if (x.equals("schedule"))
- {
- //NULL OBJECT OF SCHEDULE = EMPTY SCHEDULE METADATA
- if (assetmap.containsKey("onTime")) assetmap.remove("onTime");
- if (assetmap.containsKey("offTime")) assetmap.remove("offTime");
- }
- else if (x.equals("link"))
- {
- //NULL LINK OBJECT MEANS EMPTY URL + TEXT METADATA
- if (map.containsKey("brc_link_text")) map.remove("brc_link_text");
- if (map.containsKey("brc_link_url")) map.remove("brc_link_url");
- }
- else
- {
- //IF ANY OTHER ARE NULL AND WERE ACTIVE - ARE NOW EQUIVALENT
- if (map.containsKey(key)) map.remove(key);
- }
- }
- }
- }
- else
+ } else //NOT ARRAY NOR OBJECT
{
- LOGGER.trace("##HAS KEY BUT OBJECT IT LEADS TO IS NULL!");
- LOGGER.trace("## HAS OBJECT WITH KEY : " + x +" ? "+innerObj.has(x) + " isnull? : "+ innerObj.get(x).equals(null));
+
+ //THIS HANDLES REST OF NULL SET KEYS WHICH MAP TO PROPERTY VALUES
+ setObject(obj, key, x, map, newAsset, assetmap);
}
}
-
-
-
//AFTER SETTING ALL THE METADATA - SET THE LAST UPDATE TIME
-
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
+ map.put(Constants.BRC_LASTSYNC, com.coresecure.brightcove.wrapper.utils.JcrUtil.now2calendar());
+ resourceResolver.commit();
+ LOGGER.trace(">>UPDATED METADATA FOR VIDEO : [{}]",map.get(Constants.BRC_ID));
+ //MAIN TRY
+ } catch (IOException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ }
- map.put("brc_lastsync", com.coresecure.brightcove.wrapper.utils.JcrUtil.now2calendar());
- resourceResolver.commit();
+ }
+ private JSONObject setOriginalRendition(Rendition original_rendition, Date brc_lastsync_time, Asset _asset, ServiceUtil serviceUtil, Video currentVideo) throws JSONException{
+ JSONObject master = new JSONObject();
+ ValueMap original_map = original_rendition.getProperties();
+ Date orig_lastmod_time = original_map.get(JcrConstants.JCR_LASTMODIFIED,new Date(0));
+ LOGGER.trace("ORGINAL RENDITION : [Rendition Last Mod: {}] VS [Last Sync: {} ]" ,orig_lastmod_time, brc_lastsync_time);
+ //LOGGER.trace("{}",original_map);
- LOGGER.trace(">>UPDATED METADATA FOR VIDEO : [" + map.get("brc_id")+ "]");
- }
- else
- {
- LOGGER.error("BC ASSET UPDATE FAILED - ASSET IS NULL ! ERROR");
+ if(orig_lastmod_time.compareTo(brc_lastsync_time) > 0)
+ {
+ LOGGER.trace("UPLOADING ORIGINAL");
+ //CHECK FOR Null BRC _ ID?
+ InputStream original_rendition_is = _asset.getRendition(DamConstants.ORIGINAL_FILE) != null ? _asset.getRendition(DamConstants.ORIGINAL_FILE).getStream() : null;
+ JSONObject s3_url_resp_original = serviceUtil.createAssetS3(currentVideo.id, _asset.getName() ,original_rendition_is);
+
+ LOGGER.trace("S3RESP : " + s3_url_resp_original);
+ LOGGER.trace("##CURRENT VIDEO " + currentVideo.toJSON());
+ if (s3_url_resp_original != null && s3_url_resp_original.getBoolean(Constants.SENT)) {
+ master = new JSONObject("{'master': {'url': '" + s3_url_resp_original.getString(Constants.API_REQUEST_URL) + "'},'profile': 'high-resolution','capture-images': false}");
}
- //MAIN TRY
}
- catch (JSONException e)
+ else
{
- LOGGER.error("JSON EXCEPTION", e);
- } catch (NullPointerException e) {
- LOGGER.error("NULL POINTER", e);
- } catch (IOException e)
- {
- LOGGER.error("FILE NOT FOUND", e);
+ LOGGER.trace("Original Rendition Update Skipped");
}
+ return master;
+ }
+
+ private void addPoster(Rendition poster_rendition, Date brc_lastsync_time, Asset _asset, ServiceUtil serviceUtil, Video currentVideo, JSONObject master) throws JSONException {
+ ValueMap poster_map = poster_rendition.getProperties();
+ Date poster_lastmod_time = poster_map.get(JcrConstants.JCR_LASTMODIFIED,new Date(0));
+ LOGGER.trace("POSTER RENDITION : [Rendition Last Mod: {}] VS [Last Sync: {} ]" ,poster_lastmod_time, brc_lastsync_time);
+
+ if(poster_lastmod_time.compareTo(brc_lastsync_time) > 0)
+ {
+ LOGGER.trace("UPLOADING POSTER");
+ //CHECK FOR Null BRC _ ID?
+ InputStream poster_rendition_is = _asset.getRendition(Constants.BRC_POSTER_PNG) != null ? _asset.getRendition(Constants.BRC_POSTER_PNG).getStream() : null;
+ JSONObject s3_url_resp_poster = serviceUtil.createAssetS3(currentVideo.id,Constants.BRC_POSTER_PNG,poster_rendition_is);
+
+ LOGGER.trace("S3RESP : " + s3_url_resp_poster);
+ LOGGER.trace("##CURRENT VIDEO " + currentVideo.toJSON());
+ //POSTER
+ if (s3_url_resp_poster != null && s3_url_resp_poster.getBoolean(Constants.SENT)) {
+ //IF SUCCESS - PUT
+ Poster poster = new Poster(s3_url_resp_poster.getString(Constants.API_REQUEST_URL));
+ master.put(Constants.POSTER, poster.toJSON());
+ }
+ }
+ else
+ {
+ LOGGER.trace("Poster Rendition Update Skipped");
+ }
}
+
+ private void addThumb(Rendition thumb_rendition, Date brc_lastsync_time, Asset _asset, ServiceUtil serviceUtil, Video currentVideo, JSONObject master) throws JSONException {
+ ValueMap thumbnail_map = thumb_rendition.getProperties(); //RETURNED NULL EACH TIME
+ Date thumbnail_lastmod_time = thumbnail_map.get(JcrConstants.JCR_LASTMODIFIED, new Date(0));
+ LOGGER.trace("THUMBNAIL RENDITION : [Rendition Last Mod: {}] VS [Last Sync: {} ]" ,thumbnail_lastmod_time, brc_lastsync_time);
+ if (thumbnail_lastmod_time.compareTo(brc_lastsync_time) > 0)
+ {
+ LOGGER.trace("UPLOADING THUMBNAIL");
+ InputStream thumbnail_rendition = _asset.getRendition(Constants.BRC_THUMBNAIL_PNG) != null ? _asset.getRendition(Constants.BRC_THUMBNAIL_PNG).getStream() : null;
+ JSONObject s3_url_resp_thumbnail = serviceUtil.createAssetS3(currentVideo.id, Constants.BRC_THUMBNAIL_PNG, thumbnail_rendition);
+
+ if (s3_url_resp_thumbnail != null && s3_url_resp_thumbnail.getBoolean(Constants.SENT)) {
+ //IF SUCCESS - PUT
+ Thumbnail thumbnail = new Thumbnail(s3_url_resp_thumbnail.getString(Constants.API_REQUEST_URL));
+ master.put(Constants.THUMBNAIL, thumbnail.toJSON());
+ }
+ }
+ else
+ {
+ LOGGER.trace("Thumbnail Rendition Update Skipped");
+ }
+ }
public boolean updateRenditions(Asset _asset, Video currentVideo) throws JSONException
{
boolean result = false;
Long asset_lastmod = _asset.getLastModified();
- Resource metadataRes = _asset.adaptTo(Resource.class).getChild("jcr:content/metadata");
- ModifiableValueMap brc_lastsync_map = metadataRes.adaptTo(ModifiableValueMap.class);
- Date brc_lastsync_time = brc_lastsync_map.get("brc_lastsync",new Date(0));
-
+ Resource assetRes = _asset.adaptTo(Resource.class);
+ if (assetRes == null) return false;
+ Resource metadataRes = assetRes.getChild(Constants.ASSET_METADATA_PATH);
+ if (metadataRes == null) return false;
+ ValueMap brc_lastsync_map = metadataRes.adaptTo(ValueMap.class);
+ if (brc_lastsync_map == null) return false;
+ Date brc_lastsync_time = brc_lastsync_map.get(Constants.BRC_LASTSYNC,new Date(0));
+ if (brc_lastsync_time == null) return false;
ServiceUtil serviceUtil = new ServiceUtil(account_id);
- Rendition poster_rendition = _asset.getRendition("brc_poster.png");
- Rendition thumb_rendition = _asset.getRendition("brc_thumbnail.png");
- Rendition original_rendition = _asset.getRendition("original");
+ Rendition poster_rendition = _asset.getRendition(Constants.BRC_POSTER_PNG);
+ Rendition thumb_rendition = _asset.getRendition(Constants.BRC_THUMBNAIL_PNG);
+ Rendition original_rendition = _asset.getRendition(DamConstants.ORIGINAL_FILE);
JSONObject master = new JSONObject();
-
+ if (currentVideo.id == null) return false;
//ORGINAL RENDITION - REPLACE CHECK - RENDITION PROCESS
- if (currentVideo.id != null && original_rendition != null)
+ if (original_rendition != null)
{
-
- ValueMap original_map = original_rendition.getProperties();
- Date orig_lastmod_time = original_map.get("jcr:lastModified",new Date(0));
- LOGGER.trace("ORGINAL RENDITION LASTMOD: " + orig_lastmod_time + " VS LASTSYNC " + brc_lastsync_time);
- LOGGER.trace(""+original_map);
-
- if(orig_lastmod_time.compareTo(brc_lastsync_time) > 0)
- {
- LOGGER.trace("UPLOADING ORIGINAL");
- //CHECK FOR Null BRC _ ID?
- InputStream original_rendition_is = _asset.getRendition("original") != null ? _asset.getRendition("original").getStream() : null;
- JSONObject s3_url_resp_original = serviceUtil.createAssetS3(currentVideo.id, _asset.getName() ,original_rendition_is);
-
- LOGGER.trace("S3RESP : " + s3_url_resp_original);
- LOGGER.trace("##CURRENT VIDEO " + currentVideo.toJSON());
- if (s3_url_resp_original != null && s3_url_resp_original.getBoolean("sent")) {
- master = new JSONObject("{'master': {'url': '" + s3_url_resp_original.getString("api_request_url") + "'},'profile': 'high-resolution','capture-images': false}");
- }
-
- }
-
+ master = setOriginalRendition(original_rendition, brc_lastsync_time, _asset, serviceUtil, currentVideo);
}
//POSTER RENDITION PROCESS
if (poster_rendition != null)
{
- ValueMap poster_map = poster_rendition.getProperties();
- Date poster_lastmod_time = poster_map.get("jcr:lastModified",new Date(0));
- LOGGER.trace("POSTER RENDITION LASTMOD: " + poster_lastmod_time);
-
-
- if(poster_lastmod_time.compareTo(brc_lastsync_time) > 0)
- {
- LOGGER.trace("UPLOADING POSTER");
- //CHECK FOR Null BRC _ ID?
- InputStream poster_rendition_is = _asset.getRendition("brc_poster.png") != null ? _asset.getRendition("brc_poster.png").getStream() : null;
- JSONObject s3_url_resp_poster = serviceUtil.createAssetS3(currentVideo.id,"brc_poster.png",poster_rendition_is);
-
- LOGGER.trace("S3RESP : " + s3_url_resp_poster);
- LOGGER.trace("##CURRENT VIDEO " + currentVideo.toJSON());
- //POSTER
- if (s3_url_resp_poster != null && s3_url_resp_poster.getBoolean("sent"))
- {
- //IF SUCCESS - PUT
- Poster poster = new Poster(s3_url_resp_poster.getString("api_request_url"));
- master.put("poster", poster.toJSON());
-
- }
- }
-
+ addPoster(poster_rendition, brc_lastsync_time, _asset, serviceUtil, currentVideo, master);
}
//THUMBNAIL RENDITION PROCESS
if (thumb_rendition != null) {
-
- LOGGER.trace("ASSET LASTMOD: " + asset_lastmod);
-
- ValueMap thumbnail_map = thumb_rendition.getValueMap(); //RETURNED NULL EACH TIME
-
-
- Date thumbnail_lastmod_time = thumbnail_map.get("jcr:lastModified", new Date(0));
- LOGGER.trace("THUMBNAIL RENDITION LASTMOD: " + thumbnail_lastmod_time);
-
- if (thumbnail_lastmod_time.compareTo(brc_lastsync_time) > 0)
- {
- LOGGER.trace("UPLOADING THUMBNAIL");
- InputStream thumbnail_rendition = _asset.getRendition("brc_thumbnail.png") != null ? _asset.getRendition("brc_thumbnail.png").getStream() : null;
- JSONObject s3_url_resp_thumbnail = serviceUtil.createAssetS3(currentVideo.id, "brc_thumbnail.png", thumbnail_rendition);
-
- if (s3_url_resp_thumbnail != null && s3_url_resp_thumbnail.getBoolean("sent")) {
- //IF SUCCESS - PUT
- Thumbnail thumbnail = new Thumbnail(s3_url_resp_thumbnail.getString("api_request_url"));
- master.put("thumbnail", thumbnail.toJSON());
- }
- }
+ addThumb(thumb_rendition, brc_lastsync_time, _asset, serviceUtil, currentVideo, master);
}
//UPLOAD INJEST SENDS THE IMAGE OBJECT TO THE API - UPDATES THE METADATA TO POINT TO THE NEW URLS
- if (master.has("poster") || master.has("thumbnail") || master.has("master") ) {
-
- LOGGER.trace("master OBJ ECT : " + master.toString());
+ if (master.has(Constants.POSTER) || master.has(Constants.THUMBNAIL) || master.has(Constants.MASTER) ) {
+ LOGGER.trace("master OBJ ECT : {}" , master);
JSONObject response = brAPI.cms.uploadInjest(currentVideo.id, master);
-
- LOGGER.trace("response: " + response.toString());
-
- JSONObject api_resp = new JSONObject(response.getString("response"));
- if (api_resp.has("id")) {
+ LOGGER.trace(Constants.RESPONSE , response);
+ JSONObject api_resp = new JSONObject(response.getString(Constants.RESPONSE));
+ if (api_resp.has(Constants.ID)) {
result = true;
}
} else {
@@ -1020,45 +966,60 @@ public boolean updateRenditions(Asset _asset, Video currentVideo) throws JSONExc
return result;
}
+
+ private Schedule getSchedule(ValueMap assetMap) {
+ //SCHEDULE
+ SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
+
+ Date sched_start = assetMap.get(DamConstants.PN_ON_TIME, Date.class);
+ Date sched_ends = assetMap.get(DamConstants.PN_OFF_TIME, Date.class);
+ Schedule schedule = null;
+ String start = sched_start != null ? sdf.format(sched_start): null;
+ String end = sched_ends != null ? sdf.format(sched_ends): null;
+
+ if(sched_start!=null || sched_ends != null)
+ {
+ schedule = new Schedule(start,end );
+ }
+ return schedule;
+ }
+
+
+
public Video createVideo(String request, Asset asset, String aState)
{
- LOGGER.trace("VIDEO CREATION CALLED FOR" + asset.getName() + " req? : " + request);
+
+
+
+ LOGGER.trace("VIDEO CREATION CALLED FOR {} req: {}", asset.getName() , request);
Resource assetRes = asset.adaptTo(Resource.class);
- LOGGER.trace("assetRes: " + assetRes.getPath());
+ LOGGER.trace("assetRes: {}" , assetRes.getPath());
- Resource metadataRes = assetRes.getChild("jcr:content/metadata");
+ Resource metadataRes = assetRes.getChild(Constants.ASSET_METADATA_PATH);
//SUB ASSETS
- Resource custom_node = metadataRes.getChild("brc_custom_fields")!= null ? metadataRes.getChild("brc_custom_fields") : null;
+ Resource custom_node = metadataRes.getChild(Constants.BRC_CUSTOM_FIELDS)!= null ? metadataRes.getChild(Constants.BRC_CUSTOM_FIELDS) : null;
//MAIN MAP
- ValueMap assetMap = assetRes.getChild("jcr:content").adaptTo(ValueMap.class);
+ ValueMap assetMap = assetRes.getChild(NameConstants.NN_CONTENT).adaptTo(ValueMap.class);
ValueMap map = metadataRes.adaptTo(ValueMap.class);
//SUBMAPS
ValueMap custom_node_map = custom_node != null ? custom_node.adaptTo(ValueMap.class) : null;
//RELATED LINK
- String aUrl = map.get("brc_link_url", null);
- String aText = map.get("brc_link_text", null);
+ String aUrl = map.get(Constants.BRC_LINK_URL, String.class);
+ String aText = map.get(Constants.BRC_LINK_TEXT, String.class);
RelatedLink alink = new RelatedLink( (aUrl != null ? (aText != null ? aText : "" ) : null), (aText != null ? (aUrl != null ? aUrl : "" ): null));
- //SCHEDULE
- SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
+ //Schedule
+ Schedule schedule = getSchedule(assetMap);
- Date sched_start = assetMap.get("onTime", Date.class);
- Date sched_ends = assetMap.get("offTime", Date.class);
- Schedule schedule = null;
- if(sched_start!=null || sched_ends != null)
- {
-
- schedule = new Schedule(sdf.format(sched_start), sdf.format(sched_ends) );
- }
-
- Geo geo = null; //NOT SUPPORTED
+ //Geo
+ Geo geo = null;
//TAGS
- String[] tagsList = metadataRes.getValueMap().get("cq:tags",new String[]{});
+ String[] tagsList = metadataRes.getValueMap().get(TagConstants.PN_TAGS,new String[]{});
List list = new ArrayList(Arrays.asList(tagsList));
tagsList = list.toArray(new String[0]);
//REMOVE BRIGHTCOVE TAG BEFORE PUSH
@@ -1067,42 +1028,40 @@ public Video createVideo(String request, Asset asset, String aState)
//STO FROM LOCAL VIDEOS INITIALIZE THESE SO THAT YOU CAN SEND -- COULD COME FROM PROPERTIES VALUE MAP
- String name = map.get("dc:title", asset.getName());
- String id = map.get("brc_id", null);
- String referenceId = map.get("brc_reference_id", "");
- String shortDescription = map.get("brc_description","");
- String longDescription = map.get("brc_long_description","");
- String projection = "equirectangular".equals(map.get("brc_projection",""))? "equirectangular" : "";
+ String name = map.get(DamConstants.DC_TITLE, asset.getName());
+ String id = map.get(Constants.BRC_ID, String.class);
+ String referenceId = map.get(Constants.BRC_REFERENCE_ID, "");
+ String shortDescription = map.get(Constants.BRC_DESCRIPTION,"");
+ String longDescription = map.get(Constants.BRC_LONG_DESCRIPTION,"");
+ String projection = "equirectangular".equals(map.get(Constants.BRC_PROJECTION,""))? Constants.EQUIRECTANGULAR : "";
Map custom_fields = new HashMap();
LOGGER.trace("###CUSTOM NODEMAP###");
-
-
try
{
JSONObject custom_fields_obj = getCustomFields();
- JSONArray custom_fields_arr = custom_fields_obj.getJSONArray("custom_fields");
+ JSONArray custom_fields_arr = custom_fields_obj.getJSONArray(Constants.CUSTOM_FIELDS);
for(int z = 0 ; z < custom_fields_arr.length() ; z ++ )
{
JSONObject current = custom_fields_arr.getJSONObject(z);
- custom_fields.put( current.getString("id"), custom_node_map.get(current.getString("id"),""));
+ custom_fields.put( current.getString(Constants.ID), custom_node_map.get(current.getString(Constants.ID),""));
}
}
catch (Exception e)
{
- LOGGER.error("REPO EXCEPTION " + e);
+ LOGGER.error("REPO EXCEPTION {}" , e);
}
//economics enum initialization
- EconomicsEnum economics = EconomicsEnum.valueOf(map.get("brc_economics", "AD_SUPPORTED"));
+ EconomicsEnum economics = EconomicsEnum.valueOf(map.get(Constants.BRC_ECONOMICS, "AD_SUPPORTED"));
//ININTIALIZING WRAPPER OBJECTS
//COMPLETE
- Boolean complete = map.get("brc_complete",false);
+ Boolean complete = map.get(Constants.BRC_COMPLETE,false);
//THIS VIDEO
Video video;
@@ -1123,9 +1082,8 @@ public Video createVideo(String request, Asset asset, String aState)
economics,
projection
);
- LOGGER.trace("Video "+video.toString());
+ LOGGER.trace("Video {}", video);
LOGGER.trace(">>>>>>>>>>///>>>>>>>>>>");
-
return video;
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/AccountUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/AccountUtil.java
index 04f12d2..1ed7d17 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/AccountUtil.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/AccountUtil.java
@@ -39,6 +39,7 @@
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -53,9 +54,11 @@ public class AccountUtil
{
private static final Logger LOGGER = LoggerFactory.getLogger(AccountUtil.class);
+ private AccountUtil(){/* default implementation ignored */}
+
public static String getSelectedAccount(SlingHttpServletRequest req)
{
- String accountParam = req.getParameter("account_id");
+ String accountParam = req.getParameter(Constants.ACCOUNT_ID);
String selectedaccount = accountParam != null && !accountParam.isEmpty() ? accountParam : ServiceUtil.getAccountFromCookie(req);
return selectedaccount;
}
@@ -85,8 +88,12 @@ public static Set getSelectedServices(SlingHttpServletRequest req) {
public static boolean isAuthorized(SlingHttpServletRequest req, ConfigurationService service) {
boolean is_authorized = false;
- Session session = req.getResourceResolver().adaptTo(Session.class); //GET CURRENT SESSION
- UserManager userManager = req.getResourceResolver().adaptTo(UserManager.class);
+ ResourceResolver resourceResolver = req.getResourceResolver();
+ Session session = resourceResolver.adaptTo(Session.class); //GET CURRENT SESSION
+ if (session == null) return false;
+ UserManager userManager = resourceResolver.adaptTo(UserManager.class);
+ if(userManager==null) return false;
+
List allowedGroups = service.getAllowedGroupsList();
try {
Authorizable auth = userManager.getAuthorizable(session.getUserID());
@@ -100,6 +107,7 @@ public static boolean isAuthorized(SlingHttpServletRequest req, ConfigurationSer
} catch (RepositoryException re) {
LOGGER.error("executeRequest", re);
}
+
return is_authorized;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/Constants.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/Constants.java
new file mode 100644
index 0000000..7ff7fc2
--- /dev/null
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/Constants.java
@@ -0,0 +1,182 @@
+package com.coresecure.brightcove.wrapper.utils;
+
+import com.day.cq.dam.api.DamConstants;
+import com.day.cq.wcm.api.NameConstants;
+
+/**
+ * Created by pablo.kropilnicki on 12/18/17.
+ */
+public class Constants {
+
+ public Constants(){/* default implementation ignored */}
+ public static final String EMPTY_URLPARAMS = "";
+ public static final String EMPTY_Q_PARAM = "";
+ public static final String EMPTY_SORT_PARAM = "";
+
+ public static final String AUTHENTICATION_HEADER = "Authorization";
+ public static final String ACCOUNTS_API_PATH = "/accounts/";
+ public static final String VIDEOS_API_PATH = "/videos/";
+ public static final String WHITESPACE_FIX = "%20%2B";
+ public static final String REFERENCE_SEARCH_FIELD_TAG = "ref:";
+ public static final String INGEST_REQUEST = "/ingest-requests";
+
+ //JSON KEY CONSTANTS
+ public static final String ID = "id";
+ public static final String ACCOUNT_ID = "account_id";
+ public static final String NAME = "name";
+ public static final String REFERENCE_ID = "reference_id";
+ public static final String DESCRIPTION = "description";
+ public static final String LONG_DESCRIPTION = "long_description";
+ public static final String STATE = "state";
+ public static final String PROJECTION = "projection";
+
+ public static final String TAGS = "tags";
+ public static final String GEO = "geo";
+ public static final String SCHEDULE = "schedule";
+ public static final String LINK = "link";
+ public static final String COMPLETE = "complete";
+
+ public static final String TEXT_TRACKS = "text_tracks";
+ public static final String TRACK_LANG = "track_lang";
+ public static final String TRACK_KIND = "track_kind";
+ public static final String TRACK_LABEL = "track_label";
+ public static final String TRACK_MIME_TYPE = "track_mime_type";
+ public static final String TRACK_DEFAULT = "track_default";
+ public static final String TRACK_SOURCE = "track_source";
+ public static final String TRACK_FILEPATH = "track_filepath";
+
+
+
+ public static final String IMAGES = "images";
+ public static final String THUMBNAIL = "thumbnail";
+ public static final String POSTER = "poster";
+ public static final String SRC = "src";
+ public static final String URL = "url";
+
+ public static final String CREATED_AT = "created_at";
+ public static final String STARTS_AT = "starts_at";
+ public static final String ENDS_AT = "ends_at";
+ public static final String CUE_POINTS = "cue_points";
+ public static final String UPDATED_AT = "updated_at";
+
+ public static final String BRC_LINK_URL = "brc_link_url";
+ public static final String BRC_LINK_TEXT = "brc_link_text";
+
+ public static final String BRC_LASTSYNC = "brc_lastsync";
+ public static final String BRC_ID = "brc_id";
+ public static final String BRC_COMPLETE = "brc_complete";
+ public static final String BRC_ECONOMICS = "brc_economics";
+ public static final String BRC_PROJECTION = "brc_projection";
+ public static final String BRC_ACCOUNTID = "brc_account_id";
+ public static final String BRC_CUSTOM_FIELDS = "brc_custom_fields";
+ public static final String BRC_REFERENCE_ID = "brc_reference_id";
+ public static final String BRC_DESCRIPTION = "brc_description";
+ public static final String BRC_LONG_DESCRIPTION = "brc_long_description";
+ public static final String BRC_DURATION = "brc_duration";
+ public static final String BRC_STATE = "brc_state";
+
+
+ public static final String EQUIRECTANGULAR = "equirectangular";
+
+
+
+ public static final String CUSTOM_FIELDS = "custom_fields";
+ public static final String DURATION = "duration";
+ public static final String ECONOMICS = "economics";
+
+ public static final String DIGITAL_MASTER_ID = "digital_master_id";
+ public static final String FOLDER_ID = "folder_id";
+
+ public static final String WIDTH = "width";
+ public static final String HEIGHT = "height";
+ public static final String ALIGN = "align";
+
+ public static final String COUNTRIES = "countries";
+ public static final String EXCLUDE_COUNTRIES = "exclude_countries";
+ public static final String RESTRICTED = "restricted";
+
+
+ public static final String ACCESS_TOKEN = "access_token";
+ public static final String API_REQUEST_URL = "api_request_url";
+ public static final String SIGNED_URL = "signed_url";
+ public static final String OBJECT_KEY = "object_key";
+ public static final String BUCKET = "bucket";
+
+
+ public static final String BRC_POSTER_PNG = "brc_poster.png";
+ public static final String BRC_THUMBNAIL_PNG = "brc_thumbnail.png";
+
+ public static final String SENT = "sent";
+ public static final String MASTER = "master";
+ public static final String RESPONSE = "response";
+
+ public static final String NULLSTRING = "null";
+ public static final String SRCLANG = "srclang";
+
+
+ public static final String LABEL = "label";
+ public static final String KIND = "kind";
+ public static final String MIME_TYPE = "mime_type";
+ public static final String ASSET_ID = "asset_id";
+ public static final String SOURCES = "sources";
+ public static final String UNDERSCORE_DEFAULT = "_default";
+ public static final String DEFAULT = "default";
+
+ public static final String BINARY = "binary";
+ public static final String ITEMS = "items";
+ public static final String TOTALS = "totals";
+ public static final String QUERY = "query";
+ public static final String SORT = "sort";
+ public static final String VALUE = "value";
+ public static final String TEXT = "text";
+ public static final String START = "start";
+ public static final String LIMIT = "limit";
+ public static final String PLST = "playlist";
+ public static final String PLST_NAME = "plst.name";
+ public static final String PLST_REFERENCE_ID = "plst.referenceId";
+ public static final String PLST_SHORT_DESC = "plst.shortDescription";
+
+
+ public static final String ORIGINAL_FILENAME = "original_filename";
+ public static final String THUMBNAIL_URL = "thumbnailURL";
+ public static final String DEFAULT_THUMBNAIL_LOCATION = "/etc/designs/cs/brightcove/shared/img/noThumbnail.jpg";
+ public static final String THUMBNAIL_SOURCE = "thumbnail_source";
+ public static final String POSTER_SOURCE = "poster_source";
+
+
+
+ public static final String DELIMETER_STRING_DOUBLE = "\\.\\.";
+ public static final String ERROR = "error";
+ public static final String VIDEOID = "videoid";
+ public static final String RESULT_LOG_TMPL = "Result: {}";
+ public static final String RESULT_LOG_NEW_VIDEO_TMPL = "New video id: {} ";
+ public static final String ERROR_LOG_TMPL = "Error! {}";
+ public static final String REP_ERROR_LOG_TMPL = "Replication failed: {} ";
+ public static final String REP_FAILED_ERROR = "Replication failed: ";
+ public static final String REP_ACTION_TYPE_TMPL = "Replication action type {} ";
+ public static final String REP_ACTIVATION_SUCCESS_TMPL = "BC: ACTIVATION SUCCESSFUL >> {} ";
+ public static final String REP_ACTIVATION_FAILED_TMPL = "BC: ACTIVATION FAILED >> {} ";
+
+ public static final String CONTENT_TYPE_HEADER = "Content-Type";
+ public static final String CONTENT_LENGTH_HEADER = "Content-Length";
+ public static final String CONTENT_LANGUAGE_HEADER = "Content-Language";
+ public static final String CONTENT_LANGUAGE_LOCALITY = "en-US";
+
+
+ public final static String DEFAULT_OAUTH_URL = "https://oauth.brightcove.com/v4";
+ public final static String DEFAULT_PLAYERS_API_URL = "https://players.api.brightcove.com/v2";
+ public final static String DEFAULT_API_URL = "https://cms.api.brightcove.com/v1";
+ public final static String DEFAULT_DI_API_URL = "https://ingest.api.brightcove.com/v1";
+
+
+
+ public static final String ASSET_METADATA_PATH = NameConstants.NN_CONTENT+"/"+DamConstants.ACTIVITY_TYPE_METADATA;
+
+ public static final String FAVORITE = "favorite";
+
+ public static final String VIDEO_IDS = "video_ids";
+
+ public static final String PLAYLIST_TYPE = "type";
+
+
+}
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 686d2bc..02f8399 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
@@ -32,11 +32,14 @@
*/
package com.coresecure.brightcove.wrapper.utils;
-import com.coresecure.brightcove.wrapper.objects.Binary;
+import com.coresecure.brightcove.wrapper.objects.BinaryObj;
import com.coresecure.brightcove.wrapper.sling.CertificateListService;
+import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.jackrabbit.webdav.DavMethods;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
+import org.apache.sling.servlets.post.JSONResponse;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
@@ -70,6 +73,7 @@ public class HttpServices {
private static final String TLS = "TLS";
private static final Logger LOGGER = LoggerFactory.getLogger(HttpServices.class);
+
public static void setProxy(Proxy proxy) {
if (proxy == null) {
PROXY = Proxy.NO_PROXY;
@@ -90,11 +94,11 @@ public static String executeDelete(String targetURL,
// Create connection
url = new URL(targetURL.replaceAll(" ", "%20"));
connection = getSSLConnection(url, targetURL);
- connection.setRequestMethod("DELETE");
- connection.setRequestProperty("Content-Type", "application/json");
- connection.setRequestProperty("Content-Length",
+ connection.setRequestMethod(DavMethods.METHOD_DELETE);
+ connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER, JSONResponse.RESPONSE_CONTENT_TYPE);
+ connection.setRequestProperty(Constants.CONTENT_LENGTH_HEADER,
"" + Integer.toString(payload.getBytes().length));
- connection.setRequestProperty("Content-Language", "en-US");
+ connection.setRequestProperty(Constants.CONTENT_LANGUAGE_HEADER, Constants.CONTENT_LANGUAGE_LOCALITY);
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
@@ -123,7 +127,7 @@ public static String executeDelete(String targetURL,
delResponse= "{'error_code':"+connection.getResponseCode()+",'message':'"+connection.getResponseMessage()+"'}";
}
} catch (Exception e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
delResponse= "{'error_code':-1,'message':'Exception in executeDelete'}";
} finally {
@@ -135,7 +139,7 @@ public static String executeDelete(String targetURL,
try {
rd.close();
} catch (IOException e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
}
}
if (null != wr) {
@@ -143,7 +147,7 @@ public static String executeDelete(String targetURL,
wr.flush();
wr.close();
} catch (IOException e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
}
}
@@ -166,7 +170,6 @@ public static String executePost(String targetURL, String payload,
BufferedReader rd = null;
DataOutputStream wr = null;
try {
-
// Create connection
url = new URL(targetURL.replaceAll(" ", "%20"));
LOGGER.debug("URL :"+targetURL);
@@ -175,12 +178,12 @@ public static String executePost(String targetURL, String payload,
connection = getSSLConnection(url, targetURL);
connection = (HttpsURLConnection) url.openConnection(PROXY);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type",
+ connection.setRequestMethod(DavMethods.METHOD_POST);
+ connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER,
contentType);
- connection.setRequestProperty("Content-Length",
+ connection.setRequestProperty(Constants.CONTENT_LENGTH_HEADER,
"" + Integer.toString(payload.getBytes().length));
- connection.setRequestProperty("Content-Language", "en-US");
+ connection.setRequestProperty(Constants.CONTENT_LANGUAGE_HEADER, Constants.CONTENT_LANGUAGE_LOCALITY);
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
@@ -188,12 +191,16 @@ public static String executePost(String targetURL, String payload,
connection.setDoInput(true);
connection.setDoOutput(true);
+
// Send request
wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
+
+
// Get Response
- if (connection.getResponseCode() < 400) {
+ if (connection.getResponseCode() < 400)
+ {
InputStream is = connection.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
@@ -204,13 +211,21 @@ public static String executePost(String targetURL, String payload,
}
exPostResponse = response.toString();
- } else {
- LOGGER.debug("getResponseCode: " + connection.getResponseCode() + " getResponseMessage: " + connection.getResponseMessage());
+ }
+ 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());
}
} catch (Exception e) {
- LOGGER.error("error! ",e);
-
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
} finally {
if (connection != null) {
@@ -221,7 +236,7 @@ public static String executePost(String targetURL, String payload,
try {
rd.close();
} catch (IOException e) {
- e.printStackTrace();
+ LOGGER.error(e.getClass().getName(),e);
}
}
if (null != wr) {
@@ -229,12 +244,11 @@ public static String executePost(String targetURL, String payload,
wr.flush();
wr.close();
} catch (IOException e) {
-
- e.printStackTrace();
+ LOGGER.error(e.getClass().getName(),e);
}
}
}
- LOGGER.debug("exPostResponse[1]: " + exPostResponse);
+ LOGGER.debug("exPostResponse[1]: {}", exPostResponse);
return exPostResponse;
}
@@ -257,7 +271,7 @@ public static String executePatch(String targetURL, String payload,
connection = (HttpsURLConnection) url.openConnection(PROXY);
connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
setRequestMethod(connection,"PATCH");
- connection.setRequestProperty("Content-Type", "application/json");
+ connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER, JSONResponse.RESPONSE_CONTENT_TYPE);
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
@@ -281,14 +295,12 @@ public static String executePatch(String targetURL, String payload,
exPostResponse = response.toString();
} else {
- LOGGER.debug("getResponseCode: " + connection.getResponseCode());
- LOGGER.debug("getResponseCode: " + connection.getResponseMessage());
-
+ LOGGER.debug("getResponseCode: {} {}",connection.getResponseCode() ,connection.getResponseMessage());
}
- LOGGER.debug("exPostResponse[2]: " + exPostResponse);
+ LOGGER.debug("exPostResponse[2]: {}" , exPostResponse);
} catch (Exception e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL,e);
} finally {
@@ -300,7 +312,7 @@ public static String executePatch(String targetURL, String payload,
try {
rd.close();
} catch (IOException e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL,e);
}
}
if (null != wr) {
@@ -309,7 +321,7 @@ public static String executePatch(String targetURL, String payload,
wr.close();
} catch (IOException e) {
- LOGGER.error("error! ",e);
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
}
}
}
@@ -339,12 +351,10 @@ public static String executeGet(String targetURL, String urlParameters,
String exGetResponse = null;
try {
JSONObject response = executeFullGet(targetURL, urlParameters, headers);
- exGetResponse = response.has("response") ? response.getString("response") : null;
+ exGetResponse = response.has(Constants.RESPONSE) ? response.getString(Constants.RESPONSE) : null;
} catch (Exception e) {
- e.printStackTrace();
- LOGGER.error("error! ",e);
-
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
}
return exGetResponse;
}
@@ -364,11 +374,11 @@ public static JSONObject executeFullGet(String targetURL, String urlParameters,
connection = getSSLConnection(url, targetURL, HttpsURLConnection.class);
}
- connection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- connection.setRequestProperty("Content-Length",
+ connection.setRequestProperty(Constants.CONTENT_TYPE_HEADER,
+ com.adobe.granite.rest.Constants.CT_WWW_FORM_URLENCODED);
+ connection.setRequestProperty(Constants.CONTENT_LENGTH_HEADER,
"" + Integer.toString(urlParameters.getBytes().length));
- connection.setRequestProperty("Content-Language", "en-US");
+ 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)+"\"");
@@ -390,13 +400,11 @@ public static JSONObject executeFullGet(String targetURL, String urlParameters,
}
LOGGER.trace("response committed!");
- exGetResponse.put("response",new String(response.toByteArray(), "UTF-8"));
- exGetResponse.put("binary",response.toByteArray());
- exGetResponse.put("mime_type", connection.getContentType());
+ 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) {
- e.printStackTrace();
- LOGGER.error("error! ",e);
-
+ LOGGER.error(Constants.ERROR_LOG_TMPL, e);
} finally {
if (connection != null) {
@@ -421,26 +429,33 @@ private static HttpsURLConnection getSSLConnection(URL url, String targetURL) th
private static T getSSLConnection(URL url, String targetURL, Class classType)
throws IOException {
+ T connection = (T) url.openConnection(PROXY);
+
+ try {
- T connection = (T) url
- .openConnection(PROXY);
- if ("HttpsURLConnection".equals(classType.getClass().getName())) {
- CertificateListService certificateListService = getServiceReference();
- if (null != certificateListService) {
- String enableCert = certificateListService
- .getEnableTrustedCertificate();
- String certPath = getCertificatePath(targetURL);
-
- if (null != enableCert && "YES".equalsIgnoreCase(enableCert)) {
- SSLContext context = getSSlContext(certPath);
- if (null != context) {
- HttpsURLConnection sslConn = (HttpsURLConnection) connection;
- sslConn.setSSLSocketFactory(context.getSocketFactory());
- return (T) sslConn;
+ if (classType.getClass().isInstance(HttpsURLConnection.class)) {
+ CertificateListService certificateListService = getServiceReference();
+ if (null != certificateListService) {
+ String enableCert = certificateListService
+ .getEnableTrustedCertificate();
+ String certPath = getCertificatePath(targetURL);
+
+ if (null != enableCert && "YES".equalsIgnoreCase(enableCert)) {
+ SSLContext context = getSSlContext(certPath);
+ if (null != context) {
+ HttpsURLConnection sslConn = (HttpsURLConnection) connection;
+ sslConn.setSSLSocketFactory(context.getSocketFactory());
+ return (T) sslConn;
+ }
}
}
}
+
+ } catch (Exception e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
}
+
return connection;
}
@@ -476,17 +491,23 @@ private static String getCertificatePath(String targetURL) {
*/
private static CertificateListService getServiceReference() {
CertificateListService serviceRef = null;
- BundleContext bundleContext = FrameworkUtil.getBundle(
- CertificateListService.class).getBundleContext();
- if (null != bundleContext) {
- ServiceReference osgiRef = bundleContext
- .getServiceReference(CertificateListService.class.getName());
- if (null != osgiRef) {
- serviceRef = (CertificateListService) bundleContext
- .getService(osgiRef);
+ try {
+
+ BundleContext bundleContext = FrameworkUtil.getBundle(
+ CertificateListService.class).getBundleContext();
+ if (null != bundleContext) {
+ ServiceReference osgiRef = bundleContext
+ .getServiceReference(CertificateListService.class.getName());
+ if (null != osgiRef) {
+ serviceRef = (CertificateListService) bundleContext
+ .getService(osgiRef);
+ }
}
}
-
+ catch (Exception e)
+ {
+ LOGGER.error(e.getClass().getName(), e);
+ }
return serviceRef;
}
@@ -526,23 +547,21 @@ private static SSLContext getSSlContext(String certPath) {
}
} catch (IOException ioe) {
- ioe.printStackTrace();
+ LOGGER.error(ioe.getClass().getName(), ioe);
} catch (NoSuchAlgorithmException nae) {
- nae.printStackTrace();
+ LOGGER.error(nae.getClass().getName(),nae);
} catch (KeyStoreException kse) {
- kse.printStackTrace();
- }
-
- catch (CertificateException ce) {
- ce.printStackTrace();
+ LOGGER.error(kse.getClass().getName(),kse);
+ } catch (CertificateException ce) {
+ LOGGER.error(ce.getClass().getName(),ce);
} catch (KeyManagementException ke) {
- ke.printStackTrace();
+ LOGGER.error(ke.getClass().getName(),ke);
} finally {
if (null != caInput) {
try {
caInput.close();
} catch (IOException ioe) {
- ioe.printStackTrace();
+ LOGGER.error(ioe.getClass().getName(),ioe);
}
}
}
@@ -554,19 +573,13 @@ public static boolean isLocalPath(String path){
return path.startsWith("/") && !path.startsWith("//");
}
- public static Binary getRemoteBinary(String path, String urlParameters, Map headers) throws JSONException {
- Binary binary = new Binary();
+ public static BinaryObj getRemoteBinary(String path, String urlParameters, Map headers) throws JSONException {
+ BinaryObj binary = new BinaryObj();
JSONObject get_response = HttpServices.executeFullGet(path, urlParameters, headers!= null ? headers :new HashMap());
- if (get_response != null && get_response.has("binary")) {
- InputStream binarystream = new ByteArrayInputStream((byte[]) get_response.get("binary"));
- String mime_type = get_response.getString("mime_type"); //< SET MIME TYPE
-
- if (binarystream == null) //IF REMOTE IMAGE LOAD UNSUCCESSFUL - LOAD DEFAULT
- {
- LOGGER.error("External thumbnail could not be read");
- } else {
- binary = new Binary(binarystream,mime_type);
- }
+ 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);
}
return binary;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ImageUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ImageUtil.java
index fe3b201..a0d5313 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ImageUtil.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ImageUtil.java
@@ -37,6 +37,8 @@
public class ImageUtil {
+ private ImageUtil(){/* default implementation ignored */}
+
public static BufferedImage cropImage(BufferedImage src, Rectangle rect) {
BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
return dest;
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JcrUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JcrUtil.java
index 1b1bc19..a25203b 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JcrUtil.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JcrUtil.java
@@ -32,7 +32,7 @@
*/
package com.coresecure.brightcove.wrapper.utils;
-import com.coresecure.brightcove.wrapper.objects.Binary;
+import com.coresecure.brightcove.wrapper.objects.BinaryObj;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
@@ -45,6 +45,9 @@
import java.util.*;
public class JcrUtil {
+
+ private JcrUtil(){/* default implementation ignored */}
+
private static final Logger LOGGER = LoggerFactory.getLogger(JcrUtil.class);
public static Calendar now2calendar() {
@@ -53,12 +56,11 @@ public static Calendar now2calendar() {
return calendar;
}
- public static Binary getLocalBinary(ResourceResolver resourceResolver, String path, MimeTypeService mType) throws RepositoryException{
- Binary binary = new Binary();
+ public static BinaryObj getLocalBinary(ResourceResolver resourceResolver, String path, MimeTypeService mType) throws RepositoryException{
+
Resource thumbRes = resourceResolver.resolve(path); //RESOLVE TO IMAGE
//READ THUMBNAIL FROM LOCAL ADDRESS
- binary.mime_type = mType.getMimeType(thumbRes.getName()); //MATCH TO THUMBNAIL SOURCE MIME TYPE
- binary.binary = JcrUtils.readFile(thumbRes.adaptTo(Node.class));
+ BinaryObj binary = new BinaryObj(JcrUtils.readFile(thumbRes.adaptTo(Node.class)), mType.getMimeType(thumbRes.getName()));
LOGGER.trace("MIME TYPE COMING IN:\t" + binary.mime_type + " NEW THUMBNAIL RESOURCE: " + path);
return binary;
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JsonReader.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JsonReader.java
index 7a953e9..25fbfef 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JsonReader.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/JsonReader.java
@@ -40,6 +40,8 @@
public class JsonReader {
+ private JsonReader(){/* default implementation ignored */};
+
public static JSONObject readJsonFromString(String jsonText) throws IOException, JSONException {
JSONObject json = new JSONObject(jsonText);
return json;
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ObjectSerializer.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ObjectSerializer.java
index 3840c5a..02189eb 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ObjectSerializer.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/ObjectSerializer.java
@@ -47,90 +47,140 @@
public class ObjectSerializer {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectSerializer.class);
+ public ObjectSerializer(){/* default implementation ignored */};
+
+ private static String cleanFilterName(String name){
+ return (name.startsWith("_")) ? name.substring(1) : name;
+ }
+ private static void addAsCollection(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Collection value = (Collection) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ JSONArray itemCollection = new JSONArray(value);
+ json.put(json_key, itemCollection);
+ }
+ }
+ private static void addAsString(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ String value = (String) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) json.put(json_key, value);
+ }
+ private static void addAsMap(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Map value = (Map) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ JSONObject itemObj = new JSONObject((Map) f.get(obj));
+ json.put(json_key, itemObj);
+ }
+ }
+ private static void addAsBoolean(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Boolean value = (Boolean) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) json.put(json_key, value);
+ }
+ private static void addAsRelatedLink(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ RelatedLink value = (RelatedLink) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsGeo(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Geo value = (Geo) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsSchedule(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Schedule value = (Schedule) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsEconomicsEnum(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ EconomicsEnum value = (EconomicsEnum) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.name());
+ }
+ }
+ private static void addAsText_track(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Text_track value = (Text_track) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsJSONArray(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ JSONArray value = (JSONArray) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value);
+ }
+ }
+ private static void addAsImages(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ JSONArray value = (JSONArray) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value);
+ }
+ }
+ private static void addAsPoster(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Poster value = (Poster) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsThumbnail(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Thumbnail value = (Thumbnail) f.get(obj);
+ if (value != null && !value.toString().equals(Constants.NULLSTRING)) {
+ json.put(json_key, value.toJSON());
+ }
+ }
+ private static void addAsProjection(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException{
+ Projection value = (Projection) f.get(obj);
+ if (value.type != null) {
+ if (value.type.isEmpty()) {
+ json.put(json_key, JSONObject.NULL);
+ } else {
+ json.put(json_key, value.type);
+ }
+ }
+ }
+ private static void addFieldToJson(Field f, Object obj, JSONObject json, String json_key) throws JSONException, IllegalAccessException {
+ if (f.getType().equals(Collection.class)) {
+ addAsCollection(f, obj, json, json_key);
+ } else if (f.getType().equals(String.class)) {
+ addAsString(f, obj, json, json_key);
+ } else if (f.getType().equals(Map.class)) {
+ addAsMap(f, obj, json, json_key);
+ } else if (f.getType().equals(Boolean.class)) {
+ addAsBoolean(f, obj, json, json_key);
+ } else if (f.getType().equals(RelatedLink.class)) {
+ addAsRelatedLink(f, obj, json, json_key);
+ } else if (f.getType().equals(Geo.class)) {
+ addAsGeo(f, obj, json, json_key);
+ } else if (f.getType().equals(Schedule.class)) {
+ addAsSchedule(f, obj, json, json_key);
+ } else if (f.getType().equals(EconomicsEnum.class)) {
+ addAsEconomicsEnum(f, obj, json, json_key);
+ } else if (f.getType().equals(Text_track.class)) {
+ addAsText_track(f, obj, json, json_key);
+ } else if (f.getType().equals(JSONArray.class)) {
+ addAsJSONArray(f, obj, json, json_key);
+ } else if (f.getType().equals(Images.class)) {
+ addAsImages(f, obj, json, json_key);
+ }else if (f.getType().equals(Poster.class)) {
+ addAsPoster(f, obj, json, json_key);
+ }else if (f.getType().equals(Thumbnail.class)) {
+ addAsThumbnail(f, obj, json, json_key);
+ } else if (f.getType().equals(Projection.class)) {
+ addAsProjection(f, obj, json, json_key);
+ }
+ }
public static JSONObject toJSON(Object obj, String[] fields) throws JSONException {
JSONObject json = new JSONObject();
- for (String field : fields) {
+ for (String field_name : fields) {
try {
Class> c = obj.getClass();
- Field f = c.getDeclaredField(field);
- if (field.startsWith("_")) field = field.substring(1);
+ Field f = c.getDeclaredField(field_name);
+ String json_key = cleanFilterName(field_name);
f.setAccessible(true);
- if (f.getType().equals(Collection.class)) {
- Collection value = (Collection) f.get(obj);
- if (value != null) {
- JSONArray itemCollection = new JSONArray(value);
- json.put(field, itemCollection);
- }
- } else if (f.getType().equals(String.class)) {
- String value = (String) f.get(obj);
- if (value != null) json.put(field, value);
- } else if (f.getType().equals(Map.class)) {
- Map value = (Map) f.get(obj);
- if (value != null) {
- JSONObject itemObj = new JSONObject((Map) f.get(obj));
- json.put(field, itemObj);
- }
- } else if (f.getType().equals(Boolean.class)) {
- Boolean value = (Boolean) f.get(obj);
- if (value != null) json.put(field, value);
- } else if (f.getType().equals(RelatedLink.class)) {
- RelatedLink value = (RelatedLink) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- } else if (f.getType().equals(Geo.class)) {
- Geo value = (Geo) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- } else if (f.getType().equals(Schedule.class)) {
- Schedule value = (Schedule) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- } else if (f.getType().equals(EconomicsEnum.class)) {
- EconomicsEnum value = (EconomicsEnum) f.get(obj);
- if (value != null) {
- json.put(field, value.name());
- }
- } else if (f.getType().equals(Text_track.class)) {
- Text_track value = (Text_track) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- } else if (f.getType().equals(JSONArray.class)) {
- JSONArray value = (JSONArray) f.get(obj);
- if (value != null) {
- json.put(field, value);
- }
- } else if (f.getType().equals(Images.class)) {
- Images value = (Images) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- }else if (f.getType().equals(Poster.class)) {
- Poster value = (Poster) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- }else if (f.getType().equals(Thumbnail.class)) {
- Thumbnail value = (Thumbnail) f.get(obj);
- if (value != null) {
- json.put(field, value.toJSON());
- }
- } else if (f.getType().equals(Projection.class)) {
- Projection value = (Projection) f.get(obj);
- if (value.type != null) {
- if (value.type.isEmpty()) {
- json.put(field, JSONObject.NULL);
- } else {
- json.put(field, value.type);
- }
- }
- }
+ addFieldToJson(f, obj, json, json_key);
} catch (Exception e) {
- LOGGER.error("Exception",e);
+ LOGGER.error(e.getClass().getName(), e);
}
}
return json;
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 8d5b449..f305b84 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
@@ -45,6 +45,9 @@
* Created by alessandro.bonfatti on 7/14/17.
*/
public class S3UploadUtil {
+
+ public S3UploadUtil() {/* default implementation ignored */}
+
static int BUFFER_SIZE = 4096;
private static final Logger LOGGER = LoggerFactory.getLogger(S3UploadUtil.class);
@@ -56,8 +59,7 @@ public static boolean uploadToUrl(URL url, InputStream inputStream) {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
- OutputStream out =
- connection.getOutputStream();
+ OutputStream out = connection.getOutputStream();
byte[] buf = new byte[1024];
int count;
@@ -67,7 +69,7 @@ public static boolean uploadToUrl(URL url, InputStream inputStream) {
{
if (Thread.interrupted())
{
- throw new InterruptedException();
+ throw new IOException();
}
out.write(buf, 0, count);
total += count;
@@ -85,8 +87,6 @@ public static boolean uploadToUrl(URL url, InputStream inputStream) {
}
} catch (IOException e) {
LOGGER.error("IOException",e);
- } catch (InterruptedException e) {
- LOGGER.error("InterruptedException",e);
}
return responseCode == 200;
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/TextUtil.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/TextUtil.java
index 7df4311..e4fb27f 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/TextUtil.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/utils/TextUtil.java
@@ -37,6 +37,9 @@
public class TextUtil {
+
+ public TextUtil(){/* default implementation ignored */}
+
private static final Logger LOGGER = LoggerFactory.getLogger(TextUtil.class);
public static boolean isEmpty(final String str) {
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 cbe0fd3..97184ef 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
@@ -78,13 +78,13 @@ public class AssetPropertyIntegrator extends SlingAllMethodsServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(AssetPropertyIntegrator.class);
@Reference
- MimeTypeService mType;
+ private transient MimeTypeService mType;
@Reference
- ResourceResolverFactory resourceResolverFactory;
+ private transient ResourceResolverFactory resourceResolverFactory;
@Reference
- AssetIntegratorCronBundle assetIntegratorCronBundle;
+ private transient AssetIntegratorCronBundle assetIntegratorCronBundle;
@Override
protected void doPost(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException {
@@ -110,50 +110,48 @@ private void executeRequest(final SlingHttpServletRequest req, final SlingHttpSe
//GET CURRENT CONFIGURATION
ConfigurationService cs = cg.getConfigurationService(requestedAccount);
- if (cs != null)
- {
- //IF ACCOUNT IS VALID - INITIATE SYNC CONFIGURATION
- final Map authInfo = Collections.singletonMap(
- ResourceResolverFactory.SUBSERVICE,
- (Object) SERVICE_ACCOUNT_IDENTIFIER);
- ResourceResolverFactory rrf = resourceResolverFactory;
- final ResourceResolver resourceResolver = rrf.getServiceResourceResolver(authInfo);
- synchronized (resourceResolver) {
- Session session = resourceResolver.adaptTo(Session.class); //GET CURRENT SESSION
- final String confPath = cs.getAssetIntegrationPath(); //GET PRECONFIGURED SYNC DAM TARGET PATH
- final String basePath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedAccount).concat("/"); //CREATE BASE PATH
- //CREATE AND NAME BRIGHTCOVE ASSET FOLDERS PER ACCOUNT
- Node accountFolder = JcrUtil.createPath(basePath, "sling:OrderedFolder", session);
- accountFolder.setProperty("jcr:title", cs.getAccountAlias());
- session.save();
- final ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
-
- //GET VIDEOS
- int startOffset = 0;
- JSONObject jsonObject = new JSONObject(serviceUtil.searchVideo("", startOffset, 0)); //QUERY<------
- final JSONArray itemsArr = jsonObject.getJSONArray("items");
-
- int success = 0;
- int failure = 0;
- int equal = 0;
-
- LOGGER.trace("<<< " + itemsArr.length() + " INCOMING VIDEOS");
-
- //FOR EACH VIDEO IN THE ITEMS ARRAY
- for (int i = 0; i < itemsArr.length(); i++) {
- final JSONObject innerObj = itemsArr.getJSONObject(i);
-
- Callable callable = new VideoImportCallable(innerObj,confPath,requestedServiceAccount, resourceResolverFactory, mType, serviceUtil);
- Future future = executor.submit(callable);
- //add Future to the list, we can get return value using Future
- list.add(future);
- }
-
- LOGGER.trace(">>>>FINISHED BRIGHTCOVE SYNC PAYLOAD TRAVERSAL>>>>");
- LOGGER.warn(">>>> SYNC DATA: nochange: " + equal + " success: " + success + " skipped or failed: " + failure + " >>>>");
+ if (cs == null) throw new Exception("[Invalid or missing Brightcove configuration]");
+
+ //IF ACCOUNT IS VALID - INITIATE SYNC CONFIGURATION
+ final Map authInfo = Collections.singletonMap(
+ ResourceResolverFactory.SUBSERVICE,
+ (Object) SERVICE_ACCOUNT_IDENTIFIER);
+ ResourceResolverFactory rrf = resourceResolverFactory;
+ final ResourceResolver resourceResolver = rrf.getServiceResourceResolver(authInfo);
+
+ if (resourceResolver == null) break;
+ synchronized (resourceResolver) {
+ Session session = resourceResolver.adaptTo(Session.class); //GET CURRENT SESSION
+ if (session == null) break;
+ final String confPath = cs.getAssetIntegrationPath(); //GET PRECONFIGURED SYNC DAM TARGET PATH
+
+ final String basePath = (confPath.endsWith("/") ? confPath : confPath.concat("/")).concat(requestedAccount).concat("/"); //CREATE BASE PATH
+ //CREATE AND NAME BRIGHTCOVE ASSET FOLDERS PER ACCOUNT
+ Node accountFolder = JcrUtil.createPath(basePath, "sling:OrderedFolder", session);
+ accountFolder.setProperty("jcr:title", cs.getAccountAlias());
+ session.save();
+ final ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
+
+ //GET VIDEOS
+ int startOffset = 0;
+ JSONObject jsonObject = new JSONObject(serviceUtil.searchVideo("", startOffset, 0)); //QUERY<------
+ final JSONArray itemsArr = jsonObject.getJSONArray("items");
+
+
+ LOGGER.trace("<<< " + itemsArr.length() + " INCOMING VIDEOS");
+
+ //FOR EACH VIDEO IN THE ITEMS ARRAY
+ for (int i = 0; i < itemsArr.length(); i++) {
+ final JSONObject innerObj = itemsArr.getJSONObject(i);
+
+ Callable callable = new VideoImportCallable(innerObj, confPath, requestedServiceAccount, resourceResolverFactory, mType, serviceUtil);
+ Future future = executor.submit(callable);
+ //add Future to the list, we can get return value using Future
+ list.add(future);
}
- } else {
- throw new Exception("[Invalid or missing Brightcove configuration]");
+
+ LOGGER.trace(">>>>FINISHED BRIGHTCOVE SYNC PAYLOAD TRAVERSAL>>>>");
+
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccounts.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccounts.java
index 3287171..ccc8dcd 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccounts.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccounts.java
@@ -99,7 +99,6 @@ public void api(final SlingHttpServletRequest request,
PrintWriter outWriter = response.getWriter();
response.setContentType("application/json");
JSONObject root = new JSONObject();
- boolean is_authorized = false;
JSONArray accounts = new JSONArray();
LOGGER.debug("get account");
@@ -111,7 +110,7 @@ public void api(final SlingHttpServletRequest request,
if (auth != null) {
List memberOf = new ArrayList();
Iterator groups = auth.memberOf();
- while (groups.hasNext() && !is_authorized) {
+ while (groups.hasNext()) {
Group group = groups.next();
memberOf.add(group.getID());
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccountsUI.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccountsUI.java
index 1067dda..4b48a4b 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccountsUI.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcAccountsUI.java
@@ -39,6 +39,7 @@
import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber;
import com.coresecure.brightcove.wrapper.sling.ConfigurationService;
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.TextUtil;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.iterators.TransformIterator;
@@ -52,6 +53,7 @@
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceMetadata;
+import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.wrappers.ValueMapDecorator;
@@ -97,62 +99,67 @@ protected void doGet(final SlingHttpServletRequest request,
routeUIrequest(request, response);
}
-
- public void api(final SlingHttpServletRequest request,
- final SlingHttpServletResponse response) throws ServletException,
- IOException {
-
-
+ private List buildList(SlingHttpServletRequest request) {
boolean is_authorized = false;
-
List accountsList = new ArrayList();
- LOGGER.debug("get account");
try {
- Session session = request.getResourceResolver().adaptTo(Session.class);
- UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
- /* to get the current user */
+ ResourceResolver resourceResolver = request.getResourceResolver();
+ Session session = resourceResolver.adaptTo(Session.class);
+ UserManager userManager = resourceResolver.adaptTo(UserManager.class);
+
+ if(session==null || userManager == null) return accountsList;
+
Authorizable auth = userManager.getAuthorizable(session.getUserID());
- if (auth != null) {
- List memberOf = new ArrayList();
- Iterator groups = auth.memberOf();
- while (groups.hasNext() && !is_authorized) {
- Group group = groups.next();
- memberOf.add(group.getID());
+ if (auth == null) {
+ LOGGER.debug("Not authorized");
+ return accountsList;
+ }
+ List memberOf = new ArrayList();
+ Iterator groups = auth.memberOf();
+ while (groups.hasNext() && !is_authorized) {
+ Group group = groups.next();
+ memberOf.add(group.getID());
+ }
+ ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
+
+ int i = 0;
+ for (String account : cg.getAvailableServices()) {
+ LOGGER.debug("get account: " + account);
+ ConfigurationService cs = cg.getConfigurationService(account);
+ List allowedGroups = new ArrayList();
+ allowedGroups.addAll(cs.getAllowedGroupsList());
+ allowedGroups.retainAll(memberOf);
+
+ String optionText = account;
+ String alias = cs.getAccountAlias();
+ if (TextUtil.notEmpty(alias)) {
+ optionText = String.format("%s [%s]", alias, account);
}
- ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
-
- int i = 0;
- for (String account : cg.getAvailableServices()) {
- LOGGER.debug("get account: " + account);
- ConfigurationService cs = cg.getConfigurationService(account);
- List allowedGroups = new ArrayList();
- allowedGroups.addAll(cs.getAllowedGroupsList());
- allowedGroups.retainAll(memberOf);
-
- String optionText = account;
- String alias = cs.getAccountAlias();
- if (TextUtil.notEmpty(alias)) {
- optionText = String.format("%s [%s]", alias, account);
- }
- if (allowedGroups.size() > 0) {
- JSONObject accountJson = new JSONObject();
- accountJson.put("text", optionText);
- accountJson.put("value", account);
- accountJson.put("id", i);
- i++;
- accountsList.add(accountJson);
- }
+ if (allowedGroups.size() > 0) {
+ JSONObject accountJson = new JSONObject();
+ accountJson.put("text", optionText);
+ accountJson.put("value", account);
+ accountJson.put("id", i);
+ i++;
+ accountsList.add(accountJson);
}
-
- } else {
- LOGGER.debug("not authorized");
}
} catch (JSONException e) {
- LOGGER.error("JSONException", e);
+ LOGGER.error(e.getClass().getName(), e);
} catch (RepositoryException e) {
- LOGGER.error("RepositoryException", e);
+ LOGGER.error(e.getClass().getName(), e);
}
+ return accountsList;
+ }
+ public void api(final SlingHttpServletRequest request,
+ final SlingHttpServletResponse response) throws ServletException,
+ IOException {
+
+
+ boolean is_authorized = false;
+
+ List accountsList = buildList(request);
DataSource ds = new SimpleDataSource(new TransformIterator(accountsList.iterator(), new Transformer() {
@@ -161,9 +168,9 @@ public Object transform(Object input) {
JSONObject item = (JSONObject) input;
ValueMap vm = new ValueMapDecorator(new HashMap());
- vm.put("value", item.getString("value"));
- vm.put("text", item.getString("text"));
- vm.put("id", item.getString("id"));
+ vm.put(Constants.VALUE, item.getString(Constants.VALUE));
+ vm.put(Constants.TEXT, item.getString(Constants.TEXT));
+ vm.put(Constants.ID, item.getString(Constants.ID));
return new ValueMapResource(request.getResourceResolver(), new ResourceMetadata(), "nt:unstructured", vm);
} catch (Exception e) {
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 b6a2ef1..eeb081a 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
@@ -41,6 +41,7 @@
import com.coresecure.brightcove.wrapper.sling.ConfigurationService;
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
import com.coresecure.brightcove.wrapper.utils.AccountUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.TextUtil;
import com.day.cq.wcm.api.Page;
import org.apache.felix.scr.annotations.Component;
@@ -52,6 +53,7 @@
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
+import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
@@ -67,6 +69,7 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
import java.util.*;
@Service
@@ -78,8 +81,11 @@
public class BrcApi extends SlingAllMethodsServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(BrcApi.class);
- private ServiceUtil serviceUtil = null;
+ 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;
@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
executeRequest(request, response);
@@ -89,465 +95,536 @@ protected void doPost(final SlingHttpServletRequest request, final SlingHttpServ
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
executeRequest(request,response);
}
+
+ private boolean getServices( SlingHttpServletRequest request) {
+ 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);
+ serviceUtil = new ServiceUtil(requestedAccount);
+ if (cs.getProxy() != null && cs.getProxy().length() > 0) {
+ brAPI.setProxy(cs.getProxy());
+ }
+ result = true;
+ }
+ return result;
+ }
+
+ private JSONObject getLocalPlayers(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ JSONArray players = new JSONArray();
+ String playersPath = cs.getPlayersLoc();
+ ResourceResolver resourceResolver = request.getResourceResolver();
+ Resource res = resourceResolver.resolve(playersPath);
+ Iterator playersItr = res.listChildren();
+ String selectedAccount = request.getParameter("account_id");
+ if (TextUtil.notEmpty(selectedAccount)) {
+ while (playersItr.hasNext()) {
+ Page playerRes = playersItr.next().adaptTo(Page.class);
+ if (playerRes != null && "brightcove/components/page/brightcoveplayer".equals(playerRes.getContentResource().getResourceType())) {
+ JSONObject item = new JSONObject();
+ String path = playerRes.getPath();
+ String title = playerRes.getTitle();
+ String account = playerRes.getProperties().get("account", "");
+ if (TextUtil.notEmpty(account) && account.equals(selectedAccount)) {
+ item.put("id", path);
+ item.put("name", title);
+ players.put(item);
+ }
+ }
+ }
+ }
+ result.put(Constants.ITEMS, players);
+ return result;
+ }
+
+ private JSONObject getPlayers() throws JSONException {
+ return serviceUtil.getPlayers();
+ }
+
+ private JSONObject getListVideos(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ LOGGER.debug("query: " + request.getParameter(Constants.QUERY));
+ if (request.getParameter(Constants.QUERY) != null && !request.getParameter(Constants.QUERY).trim().isEmpty()) {
+ int start = 0;
+ try {
+ start = Integer.parseInt(request.getParameter(Constants.START));
+ } catch (NumberFormatException e) {
+ LOGGER.error("NumberFormatException", e);
+
+ }
+ int limit = ServiceUtil.DEFAULT_LIMIT;
+ try {
+ limit = Integer.parseInt(request.getParameter(Constants.LIMIT));
+ } catch (NumberFormatException e) {
+ LOGGER.error("NumberFormatException", e);
+
+ }
+ result = new JSONObject(serviceUtil.getList(false, start, limit, false, request.getParameter(Constants.QUERY)));
+ } else {
+ LOGGER.debug("getListSideMenu");
+ result = new JSONObject(serviceUtil.getListSideMenu(request.getParameter(Constants.LIMIT)));
+ }
+ return result;
+ }
+
+ private JSONObject getListPlaylists(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ if (request.getParameter(Constants.QUERY) != null && !request.getParameter(Constants.QUERY).trim().isEmpty()) {
+ result = new JSONObject(serviceUtil.getPlaylistByID(request.getParameter(Constants.QUERY)).toString());
+ } else {
+ result = new JSONObject(serviceUtil.getListPlaylistsSideMenu(request.getParameter(Constants.LIMIT)));
+ }
+ return result;
+ }
+ private JSONObject searchVideos(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ LOGGER.debug("query: " + request.getParameter(Constants.QUERY));
+ if ("true".equals(request.getParameter("isID"))) {
+ LOGGER.debug("isID");
+
+ JSONArray videos = new JSONArray();
+ try {
+ JSONObject video = serviceUtil.getSelectedVideo(request.getParameter(Constants.QUERY));
+
+ long totalItems = 0;
+ if (video.has("id")) {
+ totalItems = 1;
+ videos.put(video);
+ }
+ result.put(Constants.ITEMS, videos);
+ result.put(Constants.TOTALS, totalItems);
+
+ } catch (JSONException je) {
+ LOGGER.error("search_videos", je);
+ }
+ } else {
+ LOGGER.debug("NOT isID");
+ result = new JSONObject(serviceUtil.searchVideo(request.getParameter(Constants.QUERY), Integer.parseInt(request.getParameter(Constants.START)), Integer.parseInt(request.getParameter(Constants.LIMIT)), request.getParameter(Constants.SORT)));
+ }
+ return result;
+ }
+ private JSONObject searchPlaylist(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ if ("true".equals(request.getParameter("isID"))) {
+ JSONArray playlists = new JSONArray();
+ try {
+ JSONObject playlist = serviceUtil.getPlaylistByID(request.getParameter(Constants.QUERY));
+
+ long totalItems = 0;
+ if (playlist.has("id")) {
+ totalItems = 1;
+ playlists.put(playlist);
+ }
+ result.put(Constants.ITEMS, playlists);
+ result.put(Constants.TOTALS, totalItems);
+
+ } catch (JSONException je) {
+ LOGGER.error("search_playlists", je);
+ }
+ } else {
+ result = new JSONObject(serviceUtil.getPlaylists(request.getParameter(Constants.QUERY), Integer.parseInt(request.getParameter(Constants.START)), Integer.parseInt(request.getParameter(Constants.LIMIT)), false, false));
+ }
+ return result;
+ }
+ private JSONObject deleteVideo(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ String[] ids = request.getParameter(Constants.QUERY).split(",");
+ for (String id : ids) {
+ if (!TextUtil.isEmpty(id)) {
+
+ boolean resultDelete = serviceUtil.deleteVideo(id);
+ LOGGER.debug(id + " " + resultDelete);
+
+ }
+ }
+ 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);
+ if (requestParameter == null) {
+ result.put(Constants.ERROR, 500);
+ return result;
+ }
+ String[] ids = requestParameter.getString().split(",");
+
+ LOGGER.info("Creating a Playlist");
+ Playlist playlist = new Playlist();
+ // Required fields
+ playlist.setName(request.getParameter(Constants.PLST_NAME));
+ playlist.setDescription(request.getParameter(Constants.PLST_SHORT_DESC));
+ playlist.setPlaylistType(PlaylistTypeEnum.EXPLICIT);
+ // Optional Fields
+ if (request.getParameter(Constants.PLST_REFERENCE_ID) != null && request.getParameter(Constants.PLST_REFERENCE_ID).trim().length() > 0)
+ playlist.setReferenceId(request.getParameter(Constants.PLST_REFERENCE_ID));
+
+ List videoIDs = new ArrayList();
+ for (String idStr : ids) {
+ LOGGER.info("Video ID: " + idStr);
+ videoIDs.add(idStr);
+ }
+ LOGGER.info("Writing Playlist to Media API");
+
+ playlist.setVideoIds(videoIDs);
+ JSONObject videoItem = brAPI.cms.createPlaylist(playlist);
+ LOGGER.info("New Playlist id: " + videoItem.toString(1));
+ if (!videoItem.has(Constants.ID))
+ {
+ result.put(Constants.ERROR, 409);
+ }
+ else
+ {
+ result = null;
+ }
+ return result;
+ }
+ private JSONObject createVideo(SlingHttpServletRequest request) throws JSONException {
+ JSONObject result = new JSONObject();
+ RequestParameter requestParameter = request.getRequestParameter(Constants.PLST);
+ if (requestParameter == null) {
+ result.put(Constants.ERROR, 500);
+ return result;
+ }
+ String ingestURL = requestParameter.getString();
+
+ String ingestProfile = "balanced-high-definition";
+ RequestParameter requestIngestParameter = request.getRequestParameter("profile_Ingest");
+ if (requestIngestParameter != null) {
+ ingestProfile = requestIngestParameter.getString();
+ }
+
+ Collection tagsToAdd = new ArrayList();
+ if (request.getParameter("tags") != null) {
+
+ List tags = Arrays.asList(request.getParameterValues("tags"));
+ for (String tag : tags) {
+ if (tag.startsWith("+")) tagsToAdd.add(tag.substring(1));
+ }
+
+ }
+ com.coresecure.brightcove.wrapper.objects.RelatedLink link = new com.coresecure.brightcove.wrapper.objects.RelatedLink(request.getParameter("linkText"), request.getParameter("linkURL"));
+ com.coresecure.brightcove.wrapper.objects.Ingest ingest = new com.coresecure.brightcove.wrapper.objects.Ingest(ingestProfile, ingestURL);
+ com.coresecure.brightcove.wrapper.objects.Video video = new com.coresecure.brightcove.wrapper.objects.Video(
+ request.getParameter(Constants.NAME),
+ request.getParameter(Constants.REFERENCE_ID),
+ request.getParameter(Constants.DESCRIPTION),
+ request.getParameter(Constants.LONG_DESCRIPTION),
+ "",
+ tagsToAdd,
+ null,
+ null,
+ false,
+ link
+ );
+ JSONObject videoItem = brAPI.cms.createVideo(video);
+ String newVideoId = videoItem.getString(Constants.ID);
+ JSONObject videoIngested = new JSONObject();
+ try {
+ videoIngested = brAPI.cms.createIngest(new com.coresecure.brightcove.wrapper.objects.Video(videoItem), ingest);
+ if (videoIngested != null && videoIngested.has(Constants.ID)) {
+ LOGGER.info("New video id: {}", newVideoId);
+ result.put(Constants.VIDEOID, newVideoId);
+ result.put("output", videoIngested);
+ } else {
+ result.put(Constants.ERROR, "createIngest Error");
+ brAPI.cms.deleteVideo(newVideoId);
+ }
+
+ } catch (Exception exIngest) {
+ result.put(Constants.ERROR, "createIngest Exception");
+ brAPI.cms.deleteVideo(newVideoId);
+ }
+ return result;
+ }
+ private JSONObject updateVideo(SlingHttpServletRequest request) throws JSONException {
+ Collection tagsToAdd = new ArrayList();
+ if (request.getParameter("tags") != null) {
+
+ List tags = Arrays.asList(request.getParameterValues("tags"));
+ for (String tag : tags) {
+ if (tag.startsWith("+")) tagsToAdd.add(tag.substring(1));
+ }
+
+ }
+ com.coresecure.brightcove.wrapper.objects.RelatedLink link = new com.coresecure.brightcove.wrapper.objects.RelatedLink(request.getParameter("linkText"), request.getParameter("linkURL"));
+ com.coresecure.brightcove.wrapper.objects.Video video = new com.coresecure.brightcove.wrapper.objects.Video(
+ request.getParameter(Constants.ID),
+ request.getParameter(Constants.NAME),
+ request.getParameter("referenceId"),
+ request.getParameter(Constants.DESCRIPTION),
+ request.getParameter(Constants.LONG_DESCRIPTION),
+ "",
+ tagsToAdd,
+ null,
+ null,
+ false,
+ link
+ );
+ JSONObject videoItem = brAPI.cms.updateVideo(video);
+ //LOGGER.debug("videoItem", videoItem);
+
+ 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);
+
+ //GET VIDEO FOR THIS VIDEO ID - REMOVE FORM THE JSON OBJECT AND RESEND UP
+ //GET VIDEO AND UPDATE TEXT TRACKS JSON
+ JSONObject down_video = brAPI.cms.getVideo(request.getParameter(Constants.ID));
+
+ //DELETE THE TRACK
+ JSONArray trackslist = down_video.has(Constants.TEXT_TRACKS) ? down_video.getJSONArray(Constants.TEXT_TRACKS) : new JSONArray();
+ String curID = "";
+
+ //CONSTRUCTED CORRECTLY
+ JSONArray updated_tracks = new JSONArray();
+
+ LOGGER.trace("OLD TRACKS LIST {}", trackslist.length());
+ for(int x = 0 ; x < trackslist.length(); x++)
+ {
+ JSONObject track = trackslist.getJSONObject(x);
+ curID = track.getString(Constants.ID);
+ if(!trackID.equals(curID))
+ {
+ Text_track currentTrack = new Text_track(track);
+ updated_tracks.put(currentTrack.toJSON());
+ }
+ }
+ LOGGER.trace("UPDATED TRACKS LIST {}", updated_tracks.length());
+
+ com.coresecure.brightcove.wrapper.objects.Video video = new Video(
+ request.getParameter(Constants.ID),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ false,
+ null,
+ null,
+ null,
+ null,
+ updated_tracks
+ );
+
+ //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.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();
+ JSONObject text_track = new JSONObject();
+
+ text_track.put(Constants.SRCLANG, request.getParameter(Constants.TRACK_LANG));
+ text_track.put(Constants.KIND, request.getParameter(Constants.TRACK_KIND));
+ String label = request.getParameter(Constants.TRACK_LABEL);
+ String filename;
+ if (label!= null && !label.isEmpty()) {
+ text_track.put(Constants.LABEL, label);
+ filename = label.replaceAll(" ","_")+".vtt";
+ } else {
+ filename = "no_label.vtt";
+ }
+ text_track.put(Constants.DEFAULT, "true".equals(request.getParameter(Constants.TRACK_DEFAULT)));
+ text_track.put(Constants.MIME_TYPE, request.getParameter(Constants.TRACK_MIME_TYPE));
+ //LOGGER.trace(text_track.toString(1));
+
+
+ //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)) )
+ {
+ 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" ));
+
+ //REQUEST INGEST URL
+ 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))
+ {
+ //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
+ {
+ LOGGER.error("FAILED TO INITIALIZE BUCKET");
+ }
+
+ }
+ 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));
+
+ }
+
+ text_track_arr.put(text_track);
+ text_track_payload.put(Constants.TEXT_TRACKS, text_track_arr);
+
+
+ JSONObject videoItem = brAPI.cms.uploadInjest(request.getParameter(Constants.ID), text_track_payload);
+ //DEBUGGER PRINT - LOGGER.trace("**:" + videoItem.toString(1));
+
+ if(videoItem.has(Constants.RESPONSE))
+ {
+ JSONObject responseOBJ = new JSONObject(videoItem.getString(Constants.RESPONSE));
+ LOGGER.trace("**has id object: {}", responseOBJ.has(Constants.ID) );
+ //response.sendError(422, "Incompatible Payload for Audio Track");
+ LOGGER.trace("Text Track Upload Complete");
+
+ } else {
+ response.sendError(500, "Check logs");
+ }
+ return null;
+ }
+ private JSONObject uploadImage(SlingHttpServletRequest request) throws JSONException {
+ LOGGER.trace("upload_thumbnail");
+
+
+ JSONObject images_payload = new JSONObject();
+
+ if (request.getParameter(Constants.THUMBNAIL_SOURCE) != null) {
+ JSONObject thumbnail = new JSONObject();
+ thumbnail.put(Constants.URL, request.getParameter(Constants.THUMBNAIL_SOURCE));
+ images_payload.put(Constants.THUMBNAIL, thumbnail);
+ }
+ if (request.getParameter(Constants.POSTER_SOURCE) != null) {
+ JSONObject poster = new JSONObject();
+ poster.put(Constants.URL, request.getParameter(Constants.POSTER_SOURCE));
+ images_payload.put(Constants.POSTER, poster);
+ }
+
+ LOGGER.trace("UploadImagesPayload>> {}", images_payload.toString(1));
+
+ JSONObject videoItem = brAPI.cms.uploadInjest(request.getParameter(Constants.ID), images_payload);
+ LOGGER.trace(videoItem.toString(1));
+
+ return null;
+ }
+
+ private JSONObject apiLogic(SlingHttpServletRequest request, SlingHttpServletResponse response, JSONObject jsonObject) throws JSONException, IOException {
+ JSONObject result = jsonObject;
+ String requestedAPI = request.getParameter("a");
+ if ("local_players".equals(requestedAPI)) { //getPlayers
+ result = getLocalPlayers(request);
+ } else if ("players".equals(requestedAPI)) { //getPlayers
+ result = getPlayers();
+ } else if ("list_videos".equals(requestedAPI)) {
+ result = getListVideos(request);
+ } else if ("export".equals(requestedAPI)) {
+ response.setHeader("Content-type", "application/xls");
+ response.setHeader("Content-disposition", "inline; filename=Brightcove_Library_Export.csv");
+ result = new JSONObject(serviceUtil.getList(true, Integer.parseInt(request.getParameter(Constants.START)), Integer.parseInt(request.getParameter(Constants.LIMIT)), true, request.getParameter(Constants.QUERY)));
+ } else if ("list_playlists".equals(requestedAPI)) {
+ result = getListPlaylists(request);
+ } else if ("search_videos".equals(requestedAPI)) {
+ result = searchVideos(request);
+ } else if ("search_playlists".equals(requestedAPI)) {
+ result = searchPlaylist(request);
+ } else if ("delete_video".equals(requestedAPI)) {
+ result = deleteVideo(request);
+ } else if ("create_playlist".equals(requestedAPI)) {
+ result = createPlaylist(request);
+ } else if ("create_video".equals(requestedAPI)) {
+ result = createVideo(request);
+ } else if ("update_video".equals(requestedAPI)) {
+ result = updateVideo(request);
+ } else if("remove_text_track".equals(requestedAPI)) {
+ result = removeTextTrack(request);
+ } else if ("upload_text_track".equals(requestedAPI)) {
+ result = uploadTextTrack(request, response);
+ } else if ("upload_image".equals(requestedAPI)) {
+ result = uploadImage(request);
+ } else {
+ result.put(Constants.ERROR, 404);
+ }
+ return result;
+ }
+
private void executeRequest(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException, IOException {
+ cg = ServiceUtil.getConfigurationGrabber();
String extension = request.getRequestPathInfo().getExtension();
+ LOGGER.debug("executeRequest");
+ int error_code = 0;
boolean js = "js".equals(extension);
+ boolean hasError = false;
JSONObject result = new JSONObject();
- String resultstr="";
- try {
+ String resultstr="{\""+Constants.ITEMS+"\":[],\""+Constants.TOTALS+"\":0,\""+Constants.ERROR+"\":"+error_code+"}";
+
+ try_loop: try {
result.put("items", new JSONArray());
- result.put("totals", 0);
+ result.put(Constants.TOTALS, 0);
result.put("error", JSONObject.NULL);
- if (request.getParameter("a") != null) {
- String requestedAccount = AccountUtil.getSelectedAccount(request);
- ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
- ConfigurationService cs = cg.getConfigurationService(requestedAccount);
-
- Set services = cg.getAvailableServices();
- if (services.contains(requestedAccount)) {
- com.coresecure.brightcove.wrapper.BrightcoveAPI brAPI = new com.coresecure.brightcove.wrapper.BrightcoveAPI(cs.getClientID(), cs.getClientSecret(), requestedAccount);
- if (cs.getProxy() != null && cs.getProxy().length() > 0) {
- brAPI.setProxy(cs.getProxy());
- }
+ if (request.getParameter("a") == null) break try_loop;
- allowedGroups = cs.getAllowedGroupsList();
- serviceUtil = new ServiceUtil(requestedAccount);
- String requestedAPI = "";
- boolean is_authorized = false;
- Session session = request.getResourceResolver().adaptTo(Session.class);
- UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
- try {
- Authorizable auth = userManager.getAuthorizable(session.getUserID());
-
- if (auth != null) {
- Iterator groups = auth.memberOf();
- while (groups.hasNext() && !is_authorized) {
- Group group = groups.next();
- if (allowedGroups.contains(group.getID())) is_authorized = true;
- }
- }
- } catch (RepositoryException re) {
- LOGGER.error("executeRequest", re);
- }
- if (is_authorized) {
- requestedAPI = request.getParameter("a");
- if ("test".equals(requestedAPI)) { //no commands
- result.put("mode", "test");
- } else if ("local_players".equals(requestedAPI)) { //getPlayers
- JSONArray players = new JSONArray();
- String playersPath = cs.getPlayersLoc();
- ResourceResolver resourceResolver = request.getResourceResolver();
- Resource res = resourceResolver.resolve(playersPath);
- Iterator playersItr = res.listChildren();
- String selectedAccount = request.getParameter("account_id");
- if (TextUtil.notEmpty(selectedAccount)) {
- while (playersItr.hasNext()) {
- Page playerRes = playersItr.next().adaptTo(Page.class);
- if (playerRes != null && "brightcove/components/page/brightcoveplayer".equals(playerRes.getContentResource().getResourceType())) {
- JSONObject item = new JSONObject();
- String path = playerRes.getPath();
- String title = playerRes.getTitle();
- String account = playerRes.getProperties().get("account", "");
- if (TextUtil.notEmpty(account) && account.equals(selectedAccount)) {
- item.put("id", path);
- item.put("name", title);
- players.put(item);
- }
- }
- }
- }
-
- result.put("items", players);
- } else if ("players".equals(requestedAPI)) { //getPlayers
- JSONObject players = null;
- String type = request.getParameter("players_type");
- result = serviceUtil.getPlayers();
- } else if ("list_videos".equals(requestedAPI)) {
- LOGGER.debug("query: " + request.getParameter("query"));
- if (request.getParameter("query") != null && !request.getParameter("query").trim().isEmpty()) {
- int start = 0;
- try {
- start = Integer.parseInt(request.getParameter("start"));
- } catch (NumberFormatException e) {
- LOGGER.error("NumberFormatException", e);
-
- }
- int limit = ServiceUtil.DEFAULT_LIMIT;
- try {
- limit = Integer.parseInt(request.getParameter("limit"));
- } catch (NumberFormatException e) {
- LOGGER.error("NumberFormatException", e);
-
- }
- result = new JSONObject(serviceUtil.getList(false, start, limit, false, request.getParameter("query")));
- } else {
- LOGGER.debug("getListSideMenu");
- result = new JSONObject(serviceUtil.getListSideMenu(request.getParameter("limit")));
- }
- } else if ("export".equals(requestedAPI)) {
- response.setHeader("Content-type", "application/xls");
- response.setHeader("Content-disposition", "inline; filename=Brightcove_Library_Export.csv");
- result = new JSONObject(serviceUtil.getList(true, Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), true, request.getParameter("query")));
- } else if ("list_playlists".equals(requestedAPI)) {
- if (request.getParameter("query") != null && !request.getParameter("query").trim().isEmpty()) {
- result = new JSONObject(serviceUtil.getPlaylistByID(request.getParameter("query")).toString());
- } else {
- result = new JSONObject(serviceUtil.getListPlaylistsSideMenu(request.getParameter("limit")));
- }
- } else if ("search_videos".equals(requestedAPI)) {
- LOGGER.debug("query: " + request.getParameter("query"));
- if ("true".equals(request.getParameter("isID"))) {
- LOGGER.debug("isID");
-
- JSONArray videos = new JSONArray();
- try {
- JSONObject video = serviceUtil.getSelectedVideo(request.getParameter("query"));
-
- long totalItems = 0;
- if (video.has("id")) {
- totalItems = 1;
- videos.put(video);
- }
- result.put("items", videos);
- result.put("totals", totalItems);
-
- } catch (JSONException je) {
- LOGGER.error("search_videos", je);
- }
- } else {
- LOGGER.debug("NOT isID");
- result = new JSONObject(serviceUtil.searchVideo(request.getParameter("query"), Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), request.getParameter("sort")));
- }
- } else if ("search_playlists".equals(requestedAPI)) {
- if ("true".equals(request.getParameter("isID"))) {
- JSONArray playlists = new JSONArray();
- try {
- JSONObject playlist = serviceUtil.getPlaylistByID(request.getParameter("query"));
-
- long totalItems = 0;
- if (playlist.has("id")) {
- totalItems = 1;
- playlists.put(playlist);
- }
- result.put("items", playlists);
- result.put("totals", totalItems);
-
- } catch (JSONException je) {
- LOGGER.error("search_playlists", je);
- }
- } else {
- result = new JSONObject(serviceUtil.getPlaylists(request.getParameter("query"), Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), false, false));
- }
- } else if ("delete_video".equals(requestedAPI)) {
- String[] ids = request.getParameter("query").split(",");
- for (String id : ids) {
- if (!TextUtil.isEmpty(id)) {
-
- boolean resultDelete = serviceUtil.deleteVideo(id);
- LOGGER.debug(id + " " + resultDelete);
-
- }
- }
- result = new JSONObject(serviceUtil.searchVideo("", Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), request.getParameter("sort")));
- } else if ("create_playlist".equals(requestedAPI)) {
- String[] ids = request.getRequestParameter("playlist").getString().split(",");
-
- LOGGER.info("Creating a Playlist");
- Playlist playlist = new Playlist();
- // Required fields
- playlist.setName(request.getParameter("plst.name"));
- playlist.setDescription(request.getParameter("plst.shortDescription"));
- playlist.setPlaylistType(PlaylistTypeEnum.EXPLICIT);
- // Optional Fields
- if (request.getParameter("plst.referenceId") != null && request.getParameter("plst.referenceId").trim().length() > 0)
- playlist.setReferenceId(request.getParameter("plst.referenceId"));
-
- List videoIDs = new ArrayList();
- for (String idStr : ids) {
- Long id = Long.parseLong(idStr);
- LOGGER.info("Video ID: " + idStr);
- videoIDs.add(id);
- }
- LOGGER.info("Writing Playlist to Media API");
-
- playlist.setVideoIds(videoIDs);
- JSONObject videoItem = brAPI.cms.createPlaylist(playlist);
- LOGGER.info("New Playlist id: " + videoItem.toString(1));
-
- } else if ("create_video".equals(requestedAPI)) {
- String ingestURL = request.getRequestParameter("filePath_Ingest").getString();
- String ingestProfile = request.getRequestParameter("profile_Ingest") != null ? request.getRequestParameter("profile_Ingest").getString() : "balanced-high-definition";
-
- Collection tagsToAdd = new ArrayList();
- if (request.getParameter("tags") != null) {
-
- List tags = Arrays.asList(request.getParameterValues("tags"));
- for (String tag : tags) {
- if (tag.startsWith("+")) tagsToAdd.add(tag.substring(1));
- }
-
- }
- com.coresecure.brightcove.wrapper.objects.RelatedLink link = new com.coresecure.brightcove.wrapper.objects.RelatedLink(request.getParameter("linkText"), request.getParameter("linkURL"));
- com.coresecure.brightcove.wrapper.objects.Ingest ingest = new com.coresecure.brightcove.wrapper.objects.Ingest(ingestProfile, ingestURL);
- com.coresecure.brightcove.wrapper.objects.Video video = new com.coresecure.brightcove.wrapper.objects.Video(
- request.getParameter("name"),
- request.getParameter("referenceId"),
- request.getParameter("shortDescription"),
- request.getParameter("longDescription"),
- "",
- tagsToAdd,
- null,
- null,
- false,
- link
- );
- JSONObject videoItem = brAPI.cms.createVideo(video);
- String newVideoId = videoItem.getString("id");
- JSONObject videoIngested = new JSONObject();
- try {
- videoIngested = brAPI.cms.createIngest(new com.coresecure.brightcove.wrapper.objects.Video(videoItem), ingest);
- if (videoIngested != null && videoIngested.has("id")) {
- LOGGER.info("New video id: '" + newVideoId + "'.");
- result.put("videoid", newVideoId);
- result.put("output", videoIngested);
- } else {
- result.put("error", "createIngest Error");
- brAPI.cms.deleteVideo(newVideoId);
- }
-
- } catch (Exception exIngest) {
- result.put("error", "createIngest Exception");
- brAPI.cms.deleteVideo(newVideoId);
- }
-
- //result = new JSONObject(serviceUtil.searchVideo("", Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), request.getParameter("sort")));
- } else if ("update_video".equals(requestedAPI)) {
-
- Collection tagsToAdd = new ArrayList();
- if (request.getParameter("tags") != null) {
-
- List tags = Arrays.asList(request.getParameterValues("tags"));
- for (String tag : tags) {
- if (tag.startsWith("+")) tagsToAdd.add(tag.substring(1));
- }
-
- }
- com.coresecure.brightcove.wrapper.objects.RelatedLink link = new com.coresecure.brightcove.wrapper.objects.RelatedLink(request.getParameter("linkText"), request.getParameter("linkURL"));
- com.coresecure.brightcove.wrapper.objects.Video video = new com.coresecure.brightcove.wrapper.objects.Video(
- request.getParameter("id"),
- request.getParameter("name"),
- request.getParameter("referenceId"),
- request.getParameter("shortDescription"),
- request.getParameter("longDescription"),
- "",
- tagsToAdd,
- null,
- null,
- false,
- link
- );
- JSONObject videoItem = brAPI.cms.updateVideo(video);
- //LOGGER.debug("videoItem", videoItem);
-
- result = null;
-
- }
- else if("remove_text_track".equals(requestedAPI))
- {
-
-
- try {
- String trackID = request.getParameter("track");
- String videoID = request.getParameter("id");
- LOGGER.trace("TRACK DELETION ACTIVATED FOR TRACK " + trackID);
- //PUT TOGETHER THE TEXT TRACKS JSON OBJECT IN ORDER TO SEND
- 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
- JSONObject down_video = brAPI.cms.getVideo(request.getParameter("id"));
-
- //DELETE THE TRACK
- JSONArray trackslist = down_video.has("text_tracks") ? down_video.getJSONArray("text_tracks") : null;
- String curID = "";
-
- //CONSTRUCTED CORRECTLY
- JSONArray updated_tracks = new JSONArray();
-
- LOGGER.trace("OLD TRACKS LIST " + trackslist.length());
- for(int x = 0 ; x < trackslist.length(); x++)
- {
- JSONObject track = trackslist.getJSONObject(x);
- curID = track.getString("id");
- if(!trackID.equals(curID))
- {
- Text_track currentTrack = new Text_track(track);
- updated_tracks.put(currentTrack.toJSON());
- }
- }
- LOGGER.trace("UPDATED TRACKS LIST " + updated_tracks.length());
-
- com.coresecure.brightcove.wrapper.objects.Video video = new Video(
- request.getParameter("id"),
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- false,
- null,
- null,
- null,
- null,
- updated_tracks
- );
-
- //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.error("ERROR! JSON WTF", e);
- }
-
- result = null;
- }
- else if ("upload_text_track".equals(requestedAPI))
- {
-
- JSONObject text_track_payload = new JSONObject();
- JSONArray text_track_arr = new JSONArray();
- JSONObject text_track = new JSONObject();
-
- text_track.put("srclang", request.getParameter("track_lang"));
- text_track.put("kind", request.getParameter("track_kind"));
- String label = request.getParameter("track_label");
- if (label!= null && !label.isEmpty()) text_track.put("label", label);
- text_track.put("default", "true".equals(request.getParameter("track_default")));
- text_track.put("mime_type", request.getParameter("track_mime_type"));
- //LOGGER.trace(text_track.toString(1));
-
-
- //FILE UPLOAD CASE***
- //HERE IT GETS THE TRACK SOURCE - HANDLE CASE OF FILE UPLOAD
- if("".equals(request.getParameter("track_source")) && !"".equals(request.getParameter("track_filepath")) )
- {
- LOGGER.trace("FILEPATH: " + request.getParameter("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("track_filepath").getBytes("UTF-8" ));
-
- //REQUEST INGEST URL
- JSONObject s3_url_resp = serviceUtil.createAssetS3(request.getParameter("id"),label.replaceAll(" ","_")+".vtt", is);
- //IF SUCCESS
- if (s3_url_resp != null && s3_url_resp.has("sent") && s3_url_resp.getBoolean("sent"))
- {
- //text_track.put("url", s3_url_resp.getString("signed_url"));
- text_track.put("url", s3_url_resp.getString("api_request_url"));
- LOGGER.trace("S3URLRESP: " + s3_url_resp.toString(1));
- }
- else
- {
- LOGGER.error("FAILED TO INITIALIZE BUCKET");
- }
-
- }
- else if (!"".equals(request.getParameter("track_source")))
- {
- LOGGER.trace("SOURCEPATH: " +request.getParameter("track_source"));
-
- text_track.put("url", request.getParameter("track_source"));
-
- }
-
- text_track_arr.put(text_track);
- text_track_payload.put("text_tracks", text_track_arr);
-
-
- JSONObject videoItem = brAPI.cms.uploadInjest(request.getParameter("id"), text_track_payload);
- //DEBUGGER PRINT - LOGGER.trace("**:" + videoItem.toString(1));
-
- if(videoItem.has("response"))
- {
- JSONObject responseOBJ = new JSONObject(videoItem.getString("response"));
- LOGGER.trace("**has id object: " + responseOBJ.has("id") );
- //response.sendError(422, "Incompatible Payload for Audio Track");
-
-
- LOGGER.trace("Text Track Upload Complete");
-
- } else {
- response.sendError(500, "Check logs");
- }
- result = null;
-
-
-
- } else if ("upload_image".equals(requestedAPI)) {
- LOGGER.trace("upload_thumbnail");
-
-
- JSONObject images_payload = new JSONObject();
-
- if (request.getParameter("thumbnail_source") != null) {
- JSONObject thumbnail = new JSONObject();
- thumbnail.put("url", request.getParameter("thumbnail_source"));
- images_payload.put("thumbnail", thumbnail);
- }
- if (request.getParameter("poster_source") != null) {
- JSONObject poster = new JSONObject();
- poster.put("url", request.getParameter("poster_source"));
- images_payload.put("poster", poster);
- }
-
- LOGGER.trace("UploadImagesPayload>>" + images_payload.toString(1));
- JSONObject videoItem = brAPI.cms.uploadInjest(request.getParameter("id"), images_payload);
- LOGGER.trace(videoItem.toString(1));
+ if (!getServices(request)) {
+ result.put(Constants.ERROR, 403);
+ break try_loop;
+ }
- result = null;
+ result = apiLogic(request, response, result);
+ 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");
+ break try_loop;
+ }
+ resultstr = result.toString();
- } else {
- result.put("error", 404);
- }
- } else {
- result.put("error", 403);
- }
- } else {
- result.put("error", 404);
- }
- } else {
- result.put("error", 400);
+ String callback = request.getParameter("callback");
+ if (callback == null || callback.isEmpty() || callback.matches("[^0-9a-zA-Z\\$_]|^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|volatile|void|while|with|NaN|Infinity|undefined)$")) {
+ callback = "callback";
}
- resultstr = result != null ? result.toString(): "";
- } catch (JSONException je) {
- LOGGER.error("JSONException", je);
- resultstr = "{\"items\":[],\"totals\":0,\"error\":500}";
- }
- if (result!= null) {
+
if (js) {
response.setContentType("text/javascript;charset=UTF-8");
- String callback = request.getParameter("callback");
- if (callback == null || callback.isEmpty() || callback.matches("[^0-9a-zA-Z\\$_]|^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|volatile|void|while|with|NaN|Infinity|undefined)$")) {
- callback = "callback";
- }
response.getWriter().write(callback + "(" + resultstr + ");");
- } else {
- response.setContentType("application/json;charset=UTF-8");
- response.getWriter().write(resultstr);
+ break try_loop;
}
- } else {
- //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");
+
+ response.setContentType("application/json;charset=UTF-8");
+ response.getWriter().write(resultstr);
+
+ if (result.has(Constants.ERROR) && result.getInt(Constants.ERROR) >= 400) {
+ error_code = result.getInt(Constants.ERROR);
+ }
+ } catch (JSONException je) {
+ LOGGER.error(je.getClass().getName(), je);
+ error_code = 500;
+ }
+
+ if (error_code >= 400)
+ {
+ response.setStatus(error_code);
}
+
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcImageApi.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcImageApi.java
index 6c0cc12..081e5e8 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcImageApi.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcImageApi.java
@@ -33,12 +33,14 @@
package com.coresecure.brightcove.wrapper.webservices;
import com.coresecure.brightcove.wrapper.BrightcoveAPI;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
+import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,6 +67,25 @@ protected void doPost(final SlingHttpServletRequest request,
}
+ private String getPoster(String accountKeyStr, String VideoIDStr) throws JSONException {
+ String urlStr = null;
+ BrightcoveAPI brAPI = new BrightcoveAPI(accountKeyStr);
+
+ JSONObject video = brAPI.cms.getVideoImages(VideoIDStr);
+
+
+ //TODO: MODULARIZE
+
+ // Find a single video
+ if (video != null && video.has(Constants.POSTER)) {
+ JSONObject poster = video.getJSONObject(Constants.POSTER);
+ urlStr = poster.getString(Constants.SRC);
+ }
+
+
+ return urlStr;
+ }
+
@Override
protected void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException,
@@ -74,114 +95,38 @@ protected void doGet(final SlingHttpServletRequest request,
String requestedToken = "";
Logger logger = LoggerFactory.getLogger(BrcImageApi.class);
logger.debug("request image:");
+ try {
+ String VideoIDStr = "";
+ String accountKeyStr = "";
+ if (request.getParameter("id") != null) {
+ VideoIDStr = request.getParameter("id");
+ accountKeyStr = request.getParameter("key");
+ } else if (request.getRequestPathInfo().getSuffix() != null) {
+ String suffix = request.getRequestPathInfo().getSuffix();
+ if (suffix != null) {
+ logger.debug("suffix:" + suffix);
+ String[] sections = suffix.split("/");
+ if (sections.length == 3) {
+ VideoIDStr = sections[2];
+ VideoIDStr = VideoIDStr.substring(0, VideoIDStr.indexOf("."));
+ accountKeyStr = sections[1];
+ logger.debug("VideoIDStr:" + VideoIDStr);
+ logger.debug("accountKeyStr:" + accountKeyStr);
- if (request.getParameter("id") != null) {
- String VideoIDStr = request.getParameter("id");
- String accountKeyStr = request.getParameter("key");
- try {
- BrightcoveAPI brAPI = new BrightcoveAPI(accountKeyStr);
-
- JSONObject video = brAPI.cms.getVideoImages(VideoIDStr);
-
-
- //TODO: MODULARIZE
-
- // Find a single video
- if (video != null && video.has("poster")) {
- JSONObject poster = video.getJSONObject("poster");
- String urlStr = poster.getString("src");
-
- URL url = new URL(urlStr);
- BufferedImage img = null;
- try {
- img = ImageIO.read(url);
- //out.println(" READ SUCCESS" + "
");
- } catch (Exception e) {
- response.setStatus(404);
- PrintWriter outWriter = response.getWriter();
- outWriter.println("READ ERROR " + "
");
}
- if (img != null) {
- try {
- response.setContentType("image/jpeg");
- ImageIO.write(img, "jpeg", response.getOutputStream());
- } catch (Exception ee) {
- response.setStatus(404);
- response.setContentType("text/html");
- PrintWriter outWriter = response.getWriter();
- outWriter.println("ENCODING ERROR " + "
");
- }
- }
- } else {
- response.setStatus(404);
-
}
- } catch (Exception e) {
- //System.out.println("Exception caught: '" + e + "'.");
- //System.exit(1);
- response.setStatus(404);
}
- } else {
- if (request.getRequestPathInfo().getSuffix() != null) {
- String suffix = request.getRequestPathInfo().getSuffix();
- logger.debug("suffix:" + suffix);
- String[] sections = suffix.split("/");
- if (sections.length == 3) {
- String VideoIDStr = sections[2];
- VideoIDStr = VideoIDStr.substring(0, VideoIDStr.indexOf("."));
- String accountKeyStr = sections[1];
- logger.debug("VideoIDStr:" + VideoIDStr);
- logger.debug("accountKeyStr:" + accountKeyStr);
-
- try {
- BrightcoveAPI brAPI = new BrightcoveAPI(accountKeyStr);
-
- JSONObject video = brAPI.cms.getVideoImages(VideoIDStr);
- logger.debug("video:" + video.toString(1));
-
-
- // Find a single video
- if (video != null && video.has("poster")) {
- JSONObject poster = video.getJSONObject("poster");
- String urlStr = poster.getString("src");
-
- URL url = new URL(urlStr);
- BufferedImage img = null;
- try {
- img = ImageIO.read(url);
- //out.println(" READ SUCCESS" + "
");
- } catch (Exception e) {
- response.setStatus(404);
- PrintWriter outWriter = response.getWriter();
- outWriter.println("READ ERROR " + "
");
- }
- if (img != null) {
- try {
- response.setContentType("image/jpeg");
- ImageIO.write(img, "jpeg", response.getOutputStream());
- } catch (Exception ee) {
- response.setStatus(404);
- response.setContentType("text/html");
- PrintWriter outWriter = response.getWriter();
- outWriter.println("ENCODING ERROR " + "
");
- }
- }
- } else {
- response.setStatus(404);
-
- }
- } catch (Exception e) {
- //System.out.println("Exception caught: '" + e + "'.");
- //System.exit(1);
- logger.error("Exception:",e);
-
- response.setStatus(404);
- }
-
- //out.write(vidID);
- }
- //{out.write("{\"items\":[],\"results\":0}");}
+ String urlStr = getPoster(accountKeyStr, VideoIDStr);
+ URL url = new URL(urlStr);
+ BufferedImage img = ImageIO.read(url);
+ if (img == null) {
+ response.setStatus(404);
+ return;
}
+ response.setContentType("image/jpeg");
+ ImageIO.write(img, "jpeg", response.getOutputStream());
+ } catch (Exception e) {
+ response.setStatus(500);
}
}
}
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcReplicationHandler.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcReplicationHandler.java
index a1e2183..3c569a8 100644
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcReplicationHandler.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcReplicationHandler.java
@@ -36,8 +36,10 @@
import com.coresecure.brightcove.wrapper.sling.ConfigurationGrabber;
import com.coresecure.brightcove.wrapper.sling.ConfigurationService;
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
import com.coresecure.brightcove.wrapper.utils.JcrUtil;
import com.day.cq.dam.api.Asset;
+import com.day.cq.dam.api.DamConstants;
import com.day.cq.replication.*;
import org.apache.felix.scr.annotations.*;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -49,6 +51,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import java.io.InputStream;
import java.util.*;
@@ -63,7 +66,7 @@ public class BrcReplicationHandler implements TransportHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BrcReplicationHandler.class);
/** Protocol for replication agent transport URI that triggers this transport handler. */
- private static Map properties;
+ private Map properties;
private static final String DEFAULT_BRIGHTCOVE_PROTOCOL = "brightcove://";
@Property(label = "Brightcove Replication Protocol", value = DEFAULT_BRIGHTCOVE_PROTOCOL)
@@ -110,7 +113,6 @@ private Map getProperties() {
if (properties == null) {
return new Hashtable();
}
-
return properties;
}
@@ -128,171 +130,182 @@ public boolean canHandle(AgentConfig agentConfig)
final String transportURI = agentConfig.getTransportURI();
return ((agentConfig.isEnabled() && (transportURI != null)) && transportURI.toLowerCase().startsWith(getBrightcoveProtocol()));
}
+ private boolean isAuthorized(ResourceResolver rr, ReplicationAction replicationAction, List allowedGroups) throws RepositoryException {
+ boolean is_authorized = false;
+ UserManager userManager = rr.adaptTo(UserManager.class);
+ if (userManager == null) {
+ is_authorized = false;
+ return is_authorized;
+ }
+ Authorizable auth = userManager.getAuthorizable(replicationAction.getUserId());
+
+ if (auth == null) {
+ is_authorized = false;
+ return is_authorized;
+ }
+ Iterator groups = auth.memberOf();
+ while (groups.hasNext() && !is_authorized) {
+ Group group = groups.next();
+ if (allowedGroups.contains(group.getID()))
+ is_authorized = true; //<-Authorization
+ }
+
+ return is_authorized;
+ }
+
+ private ReplicationResult execAction(ReplicationActionType replicationType, Asset _asset, String account_id) throws ReplicationException{
+ //ACTION SWITCH
+ ReplicationResult result = ReplicationResult.OK;
+ if (replicationType == ReplicationActionType.TEST) {
+ result = testVideo();
+ } else if (replicationType == ReplicationActionType.ACTIVATE) {
+ //TESTING
+ result = activateVideo(_asset, account_id);
+ } else if (replicationType == ReplicationActionType.DEACTIVATE) {
+ result = deactivateVideo(_asset, account_id);
+ } else {
+ throw new ReplicationException("Replication action type " + replicationType + " not supported.");
+ }
+ return result;
+ }
+
+ private ReplicationResult replicateAssets(ResourceResolver rr, String current_path, ReplicationAction replicationAction, ReplicationActionType replicationType) throws RepositoryException, ReplicationException{
+ Resource asset_res = rr.getResource(current_path);
+ ReplicationResult result = ReplicationResult.OK;
+ if (asset_res == null) {
+ return result;
+ }
+ Resource parent = asset_res.getParent();
+ if (parent == null) {
+ return result;
+ }
+ String account_id = parent.getName();
+ Asset _asset = asset_res.adaptTo(Asset.class);
+ if (_asset == null){
+ LOGGER.warn("Asset removed or not existing");
+ return result;
+ }
+ LOGGER.trace(account_id);
+
+ cs = configurationGrabber.getConfigurationService(account_id);
+ if (cs == null) {
+ LOGGER.warn("Account not existing");
+ result = ReplicationResult.OK;
+ return result;
+ }
+ List allowedGroups = cs.getAllowedGroupsList();
+
+ //AUTHORIZATION CHECK
+ boolean is_authorized = isAuthorized(rr, replicationAction, allowedGroups);
+ //tag amanger
+ //get tags
+ //do check of funciton allreayd implemented
+
+ if (!is_authorized) {
+ LOGGER.debug("Not authorized");
+ return result;
+ }
+ Resource metadataRes = asset_res.getChild(Constants.ASSET_METADATA_PATH);
+
+ if (asset_res.getPath().startsWith(cs.getAssetIntegrationPath())) {
+
+ result = execAction(replicationType, _asset, account_id);
+
+ }
+ return result;
+ }
@Override
public ReplicationResult deliver(TransportContext ctx, ReplicationTransaction tx) throws ReplicationException
{
replicationLog = tx.getLog();
- ReplicationResult result = null;
+ ReplicationResult result = ReplicationResult.OK;
//Global Assignments
ReplicationAction replicationAction = tx.getAction();
- if (replicationAction != null)
+ if (replicationAction == null) {
+ LOGGER.trace("REPLICATION ACTION IS NULL");
+ return ReplicationResult.OK;
+ }
+
+ final ReplicationActionType replicationType = replicationAction.getType();
+ if (replicationType == ReplicationActionType.DELETE)
{
- final ReplicationActionType replicationType = replicationAction.getType();
- if (replicationType != ReplicationActionType.DELETE)
- {
- final String[] assetPaths = replicationAction.getPaths();
+ LOGGER.trace("DELETE REPLICATION NOT SUPPORTED");
+ return ReplicationResult.OK;
+ }
+ final String[] assetPaths = replicationAction.getPaths();
- //REPLOGS
- replicationLog.debug("Deliver Method Successfully Called");
- replicationLog.debug(ctx.getName() + tx.toString());
- replicationLog.debug(ctx.getConfig().toString() + " " + ctx.getConfig().getTransportUser() + " " + replicationAction.getUserId());
- replicationLog.debug("Action: " + replicationAction.getType().toString());
- replicationLog.debug("Path: " + replicationAction.getPath().toString());
- replicationLog.debug("Time: " + replicationAction.getTime());
- replicationLog.debug(Arrays.toString(assetPaths));
+ //REPLOGS
+ replicationLog.debug("Deliver Method Successfully Called");
+ replicationLog.debug(ctx.getName() + tx.toString());
+ replicationLog.debug(ctx.getConfig().toString() + " " + ctx.getConfig().getTransportUser() + " " + replicationAction.getUserId());
+ replicationLog.debug("Action: " + replicationAction.getType().toString());
+ replicationLog.debug("Path: " + replicationAction.getPath().toString());
+ replicationLog.debug("Time: " + replicationAction.getTime());
+ replicationLog.debug(Arrays.toString(assetPaths));
- //SERVICELOGS
- LOGGER.debug("Deliver Method Successfully Called");
- LOGGER.debug(ctx.getName() + tx.toString());
- LOGGER.debug(ctx.getConfig().toString() + " " + ctx.getConfig().getTransportUser() + " " + replicationAction.getUserId());
- LOGGER.debug("Action: " + replicationAction.getType().toString());
- LOGGER.debug("Path: " + replicationAction.getPath().toString());
- LOGGER.debug("Time: " + replicationAction.getTime());
- LOGGER.debug(Arrays.toString(assetPaths));
+ //SERVICELOGS
+ LOGGER.debug("Deliver Method Successfully Called");
+ LOGGER.debug(ctx.getName() + tx.toString());
+ LOGGER.debug(ctx.getConfig().toString() + " " + ctx.getConfig().getTransportUser() + " " + replicationAction.getUserId());
+ LOGGER.debug("Action: " + replicationAction.getType().toString());
+ LOGGER.debug("Path: " + replicationAction.getPath().toString());
+ LOGGER.debug("Time: " + replicationAction.getTime());
+ LOGGER.debug(Arrays.toString(assetPaths));
- //GET ACTION TYPE
- LOGGER.trace("ACTION-TYPE: " + replicationType + " @ " + assetPaths);
+ //GET ACTION TYPE
+ LOGGER.trace("ACTION-TYPE: " + replicationType + " @ " + assetPaths);
- //GET VIDEOS FOR ACTION - (ERASE MIGHT BE NO VIDEO AT ALL?)
+ //GET VIDEOS FOR ACTION - (ERASE MIGHT BE NO VIDEO AT ALL?)
- String path = replicationAction.getPath();
- String targetDirectory = getTargetDirectory();
+ String path = replicationAction.getPath();
+ String targetDirectory = getTargetDirectory();
- if (!path.startsWith(targetDirectory))
- {
- LOGGER.debug(String.format("SKIP -- Asset: %s is not in Target Directory: %s ", path, targetDirectory));
- return ReplicationResult.OK;
+ if (!path.startsWith(targetDirectory))
+ {
+ LOGGER.debug(String.format("SKIP -- Asset: %s is not in Target Directory: %s ", path, targetDirectory));
+ return ReplicationResult.OK;
+ }
+ else {
+ LOGGER.debug("READY TO REPLICATE! RESOURCE IS A BRIGHTCOVE RESOURCE");
+ try {
+
+ final Map authInfo = Collections.singletonMap(
+ ResourceResolverFactory.SUBSERVICE,
+ (Object) SERVICE_ACCOUNT_IDENTIFIER);
+
+ // Get the Service resource resolver
+ ResourceResolver rr = resourceResolverFactory.getServiceResourceResolver(authInfo);
+ Resource asset_res;
+ for (String current_path : assetPaths) {
+ result = replicateAssets(rr, current_path, replicationAction, replicationType);
}
- else {
- LOGGER.debug("READY TO REPLICATE! RESOURCE IS A BRIGHTCOVE RESOURCE");
- try {
+ rr.commit();
+ } catch (LoginException e) {
+ LOGGER.error(e.getClass().getName(), e);
+ replicationLog.error(Constants.REP_ACTION_TYPE_TMPL+"LoginException." ,replicationType);
+ throw new ReplicationException(Constants.REP_ACTION_TYPE_TMPL + replicationType + " LoginException.");
+ } catch (NullPointerException e) {
+ LOGGER.error(e.getClass().getName()+" RepHandler", e);
+ replicationLog.error(Constants.REP_ACTION_TYPE_TMPL+"NullPointer RepHandler." , replicationType);
+ throw new ReplicationException(Constants.REP_ACTION_TYPE_TMPL + replicationType + " NullPointer RepHandler.");
+
+ } catch (ReplicationException e) {
+ LOGGER.error("ReplicationException - RepHandler", e);
+ replicationLog.error(Constants.REP_ACTION_TYPE_TMPL+"RepHandler", replicationType);
+ throw new ReplicationException(Constants.REP_ACTION_TYPE_TMPL + replicationType + " ReplicationException - RepHandler.");
+ } catch (Exception e) {
+ LOGGER.error("Exception RepHandler", e);
+ replicationLog.error("Replication action type {} Exception RepHandler.", replicationType);
+ throw new ReplicationException("Replication action type" + replicationType + " Exception RepHandler.");
+ }
+ //END FORLOOP
+ }
- final Map authInfo = Collections.singletonMap(
- ResourceResolverFactory.SUBSERVICE,
- (Object) SERVICE_ACCOUNT_IDENTIFIER);
-
- // Get the Service resource resolver
- ResourceResolver rr = resourceResolverFactory.getServiceResourceResolver(authInfo);
- Resource asset_res;
- for (String current_path : assetPaths) {
- asset_res = rr.getResource(current_path);
- if (asset_res != null) {
- String account_id = asset_res.getParent().getName();
- Asset _asset = asset_res.adaptTo(Asset.class);
-
- LOGGER.trace(account_id);
-
- cs = configurationGrabber.getConfigurationService(account_id);
- if (cs != null) {
- List allowedGroups = cs.getAllowedGroupsList();
-
- //AUTHORIZATION CHECK
- boolean is_authorized = false;
- UserManager userManager = rr.adaptTo(UserManager.class);
- try {
- Authorizable auth = userManager.getAuthorizable(replicationAction.getUserId());
-
- if (auth != null) {
- Iterator groups = auth.memberOf();
- while (groups.hasNext() && !is_authorized) {
- Group group = groups.next();
- if (allowedGroups.contains(group.getID()))
- is_authorized = true; //<-Authorization
- }
- }
- } catch (RepositoryException e) {
- LOGGER.error("executeRequest", e);
- result = new ReplicationResult(false, 0, "Replication error: " + e.getMessage());
-
- }
- //tag amanger
- //get tags
- //do check of funciton allreayd implemented
-
- if (is_authorized) {
- Resource metadataRes = asset_res.getChild("jcr:content/metadata");
-
- String[] tagsList = metadataRes.getValueMap().get("cq:tags", String[].class);
- Collection tags = JcrUtil.tagsToCollection(tagsList);
-
- if (assetPaths != null && _asset != null && path.startsWith(cs.getAssetIntegrationPath())) {//isBrightcoveAsset(tags)) {
-
- //ACTION SWITCH
- if (replicationType == ReplicationActionType.TEST) {
- return testVideo();
- } else if (replicationType == ReplicationActionType.ACTIVATE) {
- //TESTING
- result = activateVideo(_asset, account_id);
- } else if (replicationType == ReplicationActionType.DEACTIVATE) {
- result = deactivateVideo(_asset, account_id);
- } else {
- //return ReplicationResult.OK;
- throw new ReplicationException("Replication action type " + replicationType + " not supported.");
- }
-
- } else {
- LOGGER.debug("No Brightcove Tag in cq:tags", Arrays.toString(tagsList));
-
- }
- } else {
- LOGGER.debug("Not authorized");
- }
- }
- else
- {
-
- LOGGER.debug("Not Brightcove - Asset Is Outside the Configuration Scope");
- return ReplicationResult.OK;
- }
- } else {
- LOGGER.warn("Asset removed or not existing");
- result = ReplicationResult.OK;
- }
- }
- rr.commit();
- } catch (LoginException e) {
- LOGGER.error("LoginException: ", e);
- replicationLog.error("Replication action type " + replicationType + " LoginException.");
- throw new ReplicationException("Replication action type " + replicationType + " LoginException.");
- } catch (NullPointerException e) {
- LOGGER.error("NullPointer RepHandler", e);
- replicationLog.error("Replication action type " + replicationType + " NullPointer RepHandler.");
- throw new ReplicationException("Replication action type " + replicationType + " NullPointer RepHandler.");
-
- } catch (ReplicationException e) {
- LOGGER.error("ReplicationException - RepHandler", e);
- replicationLog.error("Replication action type " + replicationType + " ReplicationException - RepHandler.");
- throw new ReplicationException("Replication action type " + replicationType + " ReplicationException - RepHandler.");
- } catch (Exception e) {
- LOGGER.error("Exception RepHandler", e);
- replicationLog.error("Replication action type " + replicationType + " Exception RepHandler.");
- throw new ReplicationException("Replication action type " + replicationType + " Exception RepHandler.");
- }
- //END FORLOOP
- }
- }
- else
- {
- LOGGER.trace("DELETE REPLICATION NOT SUPPORTED");
- result = ReplicationResult.OK;
- }
- //END MAIN
- }
replicationLog.info("REPLICATION STATUS >> Code: %s Message: %s Success: %s", result.getCode(), result.getMessage(), result.isSuccess());
return result;
@@ -300,7 +313,7 @@ public ReplicationResult deliver(TransportContext ctx, ReplicationTransaction tx
private ReplicationResult doTest(TransportContext ctx, ReplicationTransaction tx, String accountId) throws ReplicationException
{
- replicationLog.debug("TEST");
+ replicationLog.debug("Replication Test");
return new ReplicationResult(false, 0, "Replication test not available");
}
@@ -318,14 +331,14 @@ private ReplicationResult doActivate(TransportContext ctx, ReplicationTransactio
}
catch (Exception e)
{
- replicationLog.error("Replication Failed" , e );
- result = new ReplicationResult(false, 0, "Replication failed: "+e.getMessage());
+ replicationLog.error(Constants.REP_ERROR_LOG_TMPL , e );
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR+e.getMessage());
}
return result;
}
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, String accountId, Map propertiesMap) throws ReplicationException {
- ReplicationResult result = null;
+ ReplicationResult result = ReplicationResult.OK;
String path = tx.getAction().getPath();
String activatorUserID=tx.getAction().getUserId();
replicationLog.info("DE-ACTIVATING[account:"+accountId+"]>>%s" ,path );
@@ -336,7 +349,7 @@ private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransact
}
catch (Exception e) {
replicationLog.error("Deactivation Failed" , e );
- result = new ReplicationResult(false, 0, "Replication failed: "+e.getMessage());
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR+e.getMessage());
}
return result;
}
@@ -344,133 +357,146 @@ private ReplicationResult doDelete(TransportContext ctx, ReplicationTransaction
throws ReplicationException {
return doDeactivate(ctx, tx, accountId, propertiesMap);
}
+ private ReplicationResult activateNew(Asset _asset, ServiceUtil serviceUtil, Video video, ModifiableValueMap brc_lastsync_map) {
+ ReplicationResult result = ReplicationResult.OK;
+ LOGGER.trace("brc_lastsync was null or zero : asset should be initialized");
+ try {
+ InputStream is = _asset.getOriginal().getStream(); //VIDEO ORIGINAL BINARY FOR BC DATABASE
- private ReplicationResult activateVideo(Asset _asset, String account_id)
+ JSONObject api_resp = serviceUtil.createVideoS3(video, _asset.getName(), is); //ACTUAL VIDEO UPLOAD CALL - WITH METADATA
+
+ //LOGGER.trace("API-RESP >>" + api_resp.toString(1));
+ boolean sent = api_resp.getBoolean(Constants.SENT);
+ if (sent) {
+ brc_lastsync_map.put(Constants.BRC_ID, api_resp.getString(Constants.VIDEOID));
+
+ LOGGER.trace("UPDATING RENDITIONS FOR THIS ASSET");
+ serviceUtil.updateRenditions(_asset, video);
+
+
+ replicationLog.info("BC: ACTIVATION SUCCESSFUL >> {}" , _asset.getPath());
+ result = ReplicationResult.OK;
+ brc_lastsync_map.put(DamConstants.DC_TITLE, video.name);
+ brc_lastsync_map.put(Constants.BRC_LASTSYNC, JcrUtil.now2calendar());
+ } else {
+ replicationLog.error(Constants.REP_ACTIVATION_SUCCESS_TMPL, _asset.getName());
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR+" S3UploadUtil.uploadFile");
+ }
+ } catch (Exception e) {
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR + e.getMessage());
+ }
+ return result;
+ }
+ private ReplicationResult activateModified(Asset _asset, ServiceUtil serviceUtil, Video video, ModifiableValueMap brc_lastsync_map) {
+ ReplicationResult result = ReplicationResult.OK;
+ try {
+ LOGGER.trace("CREATE VIDEO - THUMBNAIL / POSTER TEST>>");
+ LOGGER.trace(video.toJSON().toString(1));
+
+ //do update video
+ JSONObject api_resp = serviceUtil.updateVideo(video); //ONLY UPDATE METADATA - DO NOT SEND BINARY
+ boolean sent = api_resp.getBoolean(Constants.SENT);
+ if (sent) {
+ //REPLICATION - AFTER METADATA HAS BEEN UPDATED - TRY TO UPDATE THE RENDITIONS
+ LOGGER.trace("UPDATING RENDITIONS FOR THIS ASSET");
+ serviceUtil.updateRenditions(_asset, video);
+
+ replicationLog.info(Constants.REP_ACTIVATION_SUCCESS_TMPL, _asset.getPath());
+ long current_time_millisec = new Date().getTime();
+ brc_lastsync_map.put(Constants.BRC_LASTSYNC, current_time_millisec);
+ result = ReplicationResult.OK;
+ } else {
+ replicationLog.error(Constants.REP_ACTIVATION_SUCCESS_TMPL , _asset.getName());
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR + "S3UploadUtil.uploadFile");
+ }
+ } catch (Exception e) {
+ result = new ReplicationResult(false, 0, "Replication failed: " + e.getMessage());
+ }
+ return result;
+ }
+ private ReplicationResult activateVideo(@Nonnull Asset _asset, String account_id)
{
+
replicationLog.info("ACTIVATING >> "+_asset.getName());
ServiceUtil serviceUtil = new ServiceUtil(account_id);
- ReplicationResult result = null;
+ ReplicationResult result = ReplicationResult.OK;
String path = _asset.getPath();
Video video = serviceUtil.createVideo(path, _asset, "ACTIVE");
+ Resource assetRes = _asset.adaptTo(Resource.class);
+ if(assetRes==null) {
+ return result;
+ }
+ Resource metadataRes = assetRes.getChild(Constants.ASSET_METADATA_PATH);
+ if(metadataRes==null) {
+ return result;
+ }
- Resource metadataRes = _asset.adaptTo(Resource.class).getChild("jcr:content/metadata");
ModifiableValueMap brc_lastsync_map = metadataRes.adaptTo(ModifiableValueMap.class); //RETURNED NULL EACH TIME
- Long jcr_lastmod = _asset.getLastModified();
- Long brc_lastsync_time = brc_lastsync_map.get("brc_lastsync",Long.class);
- brc_lastsync_map.put("brc_state","ACTIVE");
-
- if (brc_lastsync_time == null)
- {
- LOGGER.trace("brc_lastsync was null or zero : asset should be initialized");
- try {
- InputStream is = _asset.getOriginal().getStream(); //VIDEO ORIGINAL BINARY FOR BC DATABASE
-
- JSONObject api_resp = serviceUtil.createVideoS3(video, _asset.getName(), is); //ACTUAL VIDEO UPLOAD CALL - WITH METADATA
-
- //LOGGER.trace("API-RESP >>" + api_resp.toString(1));
- boolean sent = api_resp.getBoolean("sent");
- if (sent) {
- brc_lastsync_map.put("brc_id", api_resp.getString("videoid"));
+ if(brc_lastsync_map==null) {
+ return result;
+ }
- LOGGER.trace("UPDATING RENDITIONS FOR THIS ASSET");
- serviceUtil.updateRenditions( _asset, video);
+ Long jcr_lastmod = _asset.getLastModified();
+ Long brc_lastsync_time = brc_lastsync_map.get(Constants.BRC_LASTSYNC, Long.class);
+ brc_lastsync_map.put(Constants.BRC_STATE, "ACTIVE");
+ if (brc_lastsync_time == null) {
+ result = activateNew(_asset, serviceUtil, video, brc_lastsync_map);
+ } else if (jcr_lastmod > brc_lastsync_time) {
+ result = activateModified(_asset, serviceUtil, video, brc_lastsync_map);
+ }
- replicationLog.info("BC: ACTIVATION SUCCESSFUL >> " + _asset.getPath());
- result = ReplicationResult.OK;
- brc_lastsync_map.put("dc:title",video.name);
- brc_lastsync_map.put("brc_lastsync", JcrUtil.now2calendar());
- } else {
- replicationLog.error("BC: ACTIVATION FAILED >> " + _asset.getName());
- result = new ReplicationResult(false, 0, "Replication failed: S3UploadUtil.uploadFile");
- }
- } catch (Exception e) {
- result = new ReplicationResult(false, 0, "Replication failed: " + e.getMessage());
- }
- }
- else if(jcr_lastmod > brc_lastsync_time)
- {
- //https://cms.api.brightcove.com/v1/accounts/:account_id/videos/:video_id/assets/poster
- try
- {
- LOGGER.trace("CREATE VIDEO - THUMBNAIL / POSTER TEST>>");
- LOGGER.trace(video.toJSON().toString(1));
-
- //do update video
- JSONObject api_resp = serviceUtil.updateVideo(video); //ONLY UPDATE METADATA - DO NOT SEND BINARY
- boolean sent = api_resp.getBoolean("sent");
- if (sent)
- {
- //REPLICATION - AFTER METADATA HAS BEEN UPDATED - TRY TO UPDATE THE RENDITIONS
- LOGGER.trace("UPDATING RENDITIONS FOR THIS ASSET");
- serviceUtil.updateRenditions( _asset, video);
-
- replicationLog.info("BC: ACTIVATION SUCCESSFUL >> "+_asset.getPath());
- long current_time_millisec = new Date().getTime();
- brc_lastsync_map.put("brc_lastsync", current_time_millisec);
- result = ReplicationResult.OK;
- }
- else
- {
- replicationLog.error("BC: ACTIVATION FAILED >> "+_asset.getName());
- result = new ReplicationResult(false, 0, "Replication failed: S3UploadUtil.uploadFile");
- }
- }
- catch (Exception e)
- {
- result = new ReplicationResult(false, 0, "Replication failed: "+e.getMessage());
- }
- }
return result;
}
- private ReplicationResult deactivateVideo(Asset _asset, String account_id)
+ private ReplicationResult deactivateVideo(@Nonnull Asset _asset, String account_id)
{
-
ServiceUtil serviceUtil = new ServiceUtil(account_id);
- ReplicationResult result = null;
-
- Resource metadataRes = _asset.adaptTo(Resource.class).getChild("jcr:content/metadata");
- ModifiableValueMap brc_lastsync_map = metadataRes.adaptTo(ModifiableValueMap.class); //RETURNED NULL EACH TIME
-
- brc_lastsync_map.put("brc_state","INACTIVE");
+ ReplicationResult result = ReplicationResult.OK;
+ Resource assetRes = _asset.adaptTo(Resource.class);
+ if(assetRes!=null)
+ {
+ Resource metadataRes = assetRes.getChild(Constants.ASSET_METADATA_PATH);
+ if (metadataRes!=null)
+ {
+ ModifiableValueMap brc_lastsync_map = metadataRes.adaptTo(ModifiableValueMap.class); //RETURNED NULL EACH TIME
+ if(brc_lastsync_map!=null) {
+ brc_lastsync_map.put(Constants.BRC_STATE, "INACTIVE");
- replicationLog.info("DEACTIVATING >> "+_asset.getName() +" ");
- String path = _asset.getPath();
+ replicationLog.info("DEACTIVATING >> {}" , _asset.getName());
+ String path = _asset.getPath();
- Video video = serviceUtil.createVideo(path, _asset,"INACTIVE");
+ Video video = serviceUtil.createVideo(path, _asset, "INACTIVE");
- LOGGER.trace("VIDEO GOING TO API CALL>>>>>>>"+video.toString());
+ LOGGER.trace("VIDEO GOING TO API CALL>>>>>>> {}" , video.toString());
- //UPDATE VIDEO CREATES A NEW VIDEO CORRECTLY INACTIVE AS THE ONE ABOVE
- //JSONObject update_resp = serviceUtil.updateVideo(video); //
+ //UPDATE VIDEO CREATES A NEW VIDEO CORRECTLY INACTIVE AS THE ONE ABOVE
+ //JSONObject update_resp = serviceUtil.updateVideo(video); //
- //MUST BE DEACTIVATION CALL
- try
- {
- LOGGER.trace("DEACTIVATION");
- LOGGER.trace(video.toString());
- JSONObject update_resp = serviceUtil.updateVideo(video);
- boolean sent = update_resp.getBoolean("sent");
- if (sent)
- {
- replicationLog.info("BC: ACTIVATION SUCCESSFUL >> "+_asset.getPath());
- result = ReplicationResult.OK;
- }
- else
- {
- replicationLog.error("BC: ACTIVATION FAILED >> "+_asset.getName());
- result = new ReplicationResult(false, 0, "Replication failed: S3UploadUtil.uploadFile");
+ //MUST BE DEACTIVATION CALL
+ try {
+ LOGGER.trace("DEACTIVATION");
+ LOGGER.trace(video.toString());
+ JSONObject update_resp = serviceUtil.updateVideo(video);
+ boolean sent = update_resp.getBoolean(Constants.SENT);
+ if (sent) {
+ replicationLog.info("BC: ACTIVATION SUCCESSFUL >> {}" , _asset.getPath());
+ result = ReplicationResult.OK;
+ } else {
+ replicationLog.error(Constants.REP_ACTIVATION_SUCCESS_TMPL , _asset.getName());
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR+": S3UploadUtil.uploadFile");
+ }
+ } catch (Exception e) {
+ result = new ReplicationResult(false, 0, Constants.REP_FAILED_ERROR+ e.getMessage());
+ LOGGER.error("Error!: {} {}" ,result, e.getMessage());
+ }
+ }
}
}
- catch (Exception e)
- {
- result = new ReplicationResult(false, 0, "Replication failed: "+e.getMessage());
- LOGGER.error("error!: " + result + ":" + e.getMessage());
- }
return result;
+
}
private ReplicationResult testVideo()
diff --git a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcSuggestions.java b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcSuggestions.java
index 73e9d6f..5a4f3a9 100755
--- a/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcSuggestions.java
+++ b/current/core/src/main/java/com/coresecure/brightcove/wrapper/webservices/BrcSuggestions.java
@@ -34,12 +34,15 @@
import com.coresecure.brightcove.wrapper.sling.ServiceUtil;
import com.coresecure.brightcove.wrapper.utils.AccountUtil;
+import com.coresecure.brightcove.wrapper.utils.Constants;
+import com.day.cq.security.util.RequestConstants;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONObject;
+import org.apache.sling.servlets.post.JSONResponse;
import javax.servlet.ServletException;
import java.io.IOException;
@@ -58,21 +61,21 @@ protected void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException,
IOException {
PrintWriter outWriter = response.getWriter();
- response.setContentType("application/json");
+ response.setContentType(JSONResponse.RESPONSE_CONTENT_TYPE);
JSONObject root = new JSONObject();
int requestedAPI = 0;
String requestedAccount = "";
- if (request.getParameter("query") != null && request.getParameter("account_id") != null) {
+ if (request.getParameter(Constants.QUERY) != null && request.getParameter(Constants.ACCOUNT_ID) != null) {
requestedAccount = AccountUtil.getSelectedAccount(request);
ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
response.setContentType("application/json");
if ("playlist".equalsIgnoreCase(request.getParameter("type"))) {
- outWriter.write(serviceUtil.getPlaylistByID(request.getParameter("query")).toString());
+ outWriter.write(serviceUtil.getPlaylistByID(request.getParameter(Constants.QUERY)).toString());
} else {
- outWriter.write(serviceUtil.getList(false, request.getParameter("query")));
+ outWriter.write(serviceUtil.getList(false, request.getParameter(Constants.QUERY)));
}
} else {
diff --git a/current/pom.xml b/current/pom.xml
index c873108..91f3b77 100644
--- a/current/pom.xml
+++ b/current/pom.xml
@@ -50,7 +50,7 @@
com.coresecure.brightcove.cq5
brightcove_connector
pom
- 5.3.1
+ 5.5.0
Parent Maven POM for the 'Adobe CQ5 Brightcove Connector API' project.
@@ -69,6 +69,7 @@
admin
admin
admin
+ true
@@ -200,7 +201,7 @@
- ${project.build.directory}/classes
+ ${project.build.directory}/classes
@@ -326,7 +327,7 @@
-
+
@@ -353,7 +354,7 @@
-
+
@@ -477,8 +478,15 @@
cq-wcm-taglib
5.7.4
provided
-
+
+
+
+ org.apache.sling
+ org.apache.sling.testing.sling-mock
+ 1.0.0
+ test
+
junit
junit
diff --git a/current/ui.apps/pom.xml b/current/ui.apps/pom.xml
index 8b78bee..3c3f376 100644
--- a/current/ui.apps/pom.xml
+++ b/current/ui.apps/pom.xml
@@ -54,7 +54,7 @@
com.coresecure.brightcove.cq5
brightcove_connector
- 5.3.1
+ 5.5.0
../pom.xml
@@ -192,8 +192,8 @@
true
true
-
-
+
+
@@ -219,8 +219,8 @@
true
true
-
-
+
+
@@ -232,7 +232,7 @@
com.coresecure.brightcove.cq5
brightcove-services
- 5.3.1
+ 5.5.0
diff --git a/current/ui.apps/src/main/content/META-INF/vault/filter-vlt.xml b/current/ui.apps/src/main/content/META-INF/vault/filter-vlt.xml
new file mode 100644
index 0000000..da66c21
--- /dev/null
+++ b/current/ui.apps/src/main/content/META-INF/vault/filter-vlt.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/current/ui.apps/src/main/content/META-INF/vault/filter.xml b/current/ui.apps/src/main/content/META-INF/vault/filter.xml
index ac7b2e6..da66c21 100644
--- a/current/ui.apps/src/main/content/META-INF/vault/filter.xml
+++ b/current/ui.apps/src/main/content/META-INF/vault/filter.xml
@@ -19,15 +19,17 @@
-
-
+
+
+
+
-
+
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/js.txt b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/js.txt
index 7830a7b..7e8c0e8 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/js.txt
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/js.txt
@@ -5,4 +5,4 @@ brightcoveUpload.js
brc_util.js
brc_account.js
-brc_combobox.js
\ No newline at end of file
+brc_combobox.js
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/source/js/brc_combobox.js b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/source/js/brc_combobox.js
index 2390f51..9f9a46b 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/source/js/brc_combobox.js
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/clientlibs/cq-widgets/source/js/brc_combobox.js
@@ -138,10 +138,12 @@ Brightcove.ComboBox = CQ.Ext.extend(CQ.Ext.form.ComboBox, {
brcAccountFieldName = combobox.initialConfig['brcAccountFieldName'],
accountField = dialogObject.getField(brcAccountFieldName),
value = CQ.Ext.isEmpty(v) ? '' : v;
+ brcApiCommand = combobox.initialConfig['brcApiCommand'],
combobox.store.baseParams[this.queryParam] = value;
combobox.store.baseParams['isID'] = !CQ.Ext.isEmpty(value);
combobox.store.baseParams['account_id'] = accountField.getValue();
+ if (brcApiCommand) combobox.store.baseParams['a'] = brcApiCommand;
//console.log('asyncSetDisplayValue', combobox, v);
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer-playlist/player-embed.html b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer-playlist/player-embed.html
index c7d8892..ba7a88c 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer-playlist/player-embed.html
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer-playlist/player-embed.html
@@ -46,6 +46,7 @@
data-player="${player.playerID}"
data-embed="${player.playerDataEmbed}"
data-playlist-id="${player.playlistID}"
+ data-usage="cms:aem:${player.version}:${player.bundleVersion}:javascript"
width="${player.width}"
height="${player.height}"
class="video-js"
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/inline-styles.html b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/inline-styles.html
index 1255587..5ac9d04 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/inline-styles.html
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/inline-styles.html
@@ -74,7 +74,7 @@
overflow-x: hidden;
overflow-y: hidden;
width: 100%;
- text-align: ${player.align @context='unsafe'};
+ text-align: left;
}
#component-wrap-${player.componentID @context='unsafe'}.brc-align-left .player-embed-wrap {
@@ -85,10 +85,25 @@
margin-right: 0;
}
- #component-wrap-${player.componentID @context='unsafe'} .brightcove-container {
+ #component-wrap-${player.componentID @context='unsafe'}.brc-align-center .brightcove-container {
width: 100%;
}
+ #component-wrap-${player.componentID @context='unsafe'}.brc-align-left .player-embed-wrap .brightcove-container{
+ margin-left: 0;
+ float:left;
+ }
+
+ #component-wrap-${player.componentID @context='unsafe'}.brc-align-center .player-embed-wrap .brightcove-container .video-js{
+ display:block;
+ }
+
+ #component-wrap-${player.componentID @context='unsafe'}.brc-align-right .player-embed-wrap .brightcove-container{
+ margin-right: 0;
+ float:right;
+ }
+
+
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/player-embed.html b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/player-embed.html
index 4800be7..c466e8d 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/player-embed.html
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/content/brightcoveplayer/player-embed.html
@@ -34,7 +34,7 @@
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/_cq_dialog/.content.xml b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/_cq_dialog/.content.xml
index 252f314..1346ee8 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/_cq_dialog/.content.xml
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/_cq_dialog/.content.xml
@@ -87,6 +87,7 @@
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/select"
emptyText="Select"
+ emptyOption="{Boolean}true"
fieldDescription="When configuring an HTML5 Playlist the following rules apply: Left: Playlist appears after the Video element. Center: Playlist appears after the Video element. Right: Playlist appears before the Video element. Update your CSS accordingly."
fieldLabel="Player Alignment:"
name="./align"
@@ -119,15 +120,15 @@
sling:resourceType="granite/ui/components/foundation/form/numberfield"
emptyText="Width"
name="./width"
- >
-
+ min="0"
+ defaultValue=""/>
-
+ min="0"
+ defaultValue=""/>
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/brightcoveIframe.html b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/brightcoveIframe.html
index d081ad1..8f54474 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/brightcoveIframe.html
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveIframe/brightcoveIframe.html
@@ -49,10 +49,11 @@
-
+
@@ -61,6 +62,7 @@
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveplayer/_cq_dialog/.content.xml b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveplayer/_cq_dialog/.content.xml
index e66c1e8..7b78dc0 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveplayer/_cq_dialog/.content.xml
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/page/brightcoveplayer/_cq_dialog/.content.xml
@@ -115,7 +115,6 @@
/>
-
-
+ min="0"
+ defaultValue=""/>
-
+ min="0"
+ defaultValue=""/>
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/shared/dialog/field_playerPath.xml b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/shared/dialog/field_playerPath.xml
index 55900a9..e1163cd 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/shared/dialog/field_playerPath.xml
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/shared/dialog/field_playerPath.xml
@@ -4,9 +4,10 @@
allowBlank="{Boolean}true"
brcAccountFieldName="./account"
fieldDescription=""
+ brcApiCommand="local_players"
fieldLabel="Player:"
fieldSubLabel=""
forceSelection="{Boolean}true"
hiddenName="./playerPath"
- storePath="/apps/brightcove/components/tools/players.html"
+ storePath="/bin/brightcove/api.json"
xtype="brc_combobox"/>
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcAdmin.js b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcAdmin.js
index 4eee6f4..dcd916e 100644
--- a/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcAdmin.js
+++ b/current/ui.apps/src/main/content/jcr_root/apps/brightcove/components/tools/brightcoveadmin/clientlibs/js/brcAdmin.js
@@ -312,15 +312,49 @@ function startVideoImageUpload() {
}
//See createPlaylistBox for more info
function createPlaylistSubmit() {
- var form = document.getElementById("createPlaylistForm");
+ var formObject = document.getElementById("createPlaylistForm");
- form.action = apiLocation+"?account_id="+$("#selAccount").val();
- form.submit();
- $('#createPlstVideoTable').empty();
- loadStart();
- //noWrite();
- closeBox('createPlaylistDiv', form);
- Load(getAllPlaylistsURL());
+ formObject.action = apiLocation+"?account_id="+$("#selAccount").val();
+ //form.submit();
+
+ var id = $("#selAccount").val();
+ var datap = formObject.getElementsByTagName("input");
+ if(datap!=undefined)
+ {
+ $.ajax({
+ url: formObject.action, //give your url here
+ type: 'GET',
+ data: {
+ "a": "create_playlist",
+ "account_id": id,
+ "id": id,
+ "plst.name": datap["plst.name"].value,
+ "plst.shortDescription": datap["plst.shortDescription"].value,
+ "plst.referenceId": datap["plst.referenceId"].value,
+ "playlist": datap["playlist"].value,
+ },
+ success: function ( data ){
+ // alert(data); do your stuff
+ $('#createPlstVideoTable').empty();
+ closeBox('createPlaylistDiv', formObject);
+ Load(getAllPlaylistsURL());
+ loadEnd();
+ },
+ error: function ( data )
+ {
+ if(data.status==409)
+ {
+ window.alert("Invalid Playlist Reference ID");
+ }
+ else
+ {
+ window.alert("Error Creating Playlist - Check Logs");
+ }
+ }
+ });
+
+
+ }
}
function modPlstSubmit() {
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 519e8af..424655b 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
@@ -331,7 +331,7 @@ function showMetaData(idx) {
$("#tbData>tr:eq(" + idx + ")").addClass("select");
- //TODO: CURRENTLY
+ //CURRENTLY
var v = oCurrentVideoList[idx];
@@ -523,6 +523,7 @@ function openBox(id) {
.css("left", ($(window).width() / 4))
.css("top", ($(window).height() / 6))
.draggable();
+
//TODO: replace jquery ui with extjs for consistency
if (!$.browser.msie) {
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/.content.xml b/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/.content.xml
old mode 100755
new mode 100644
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/formitems/.content.xml b/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/formitems/.content.xml
old mode 100755
new mode 100644
index c2c8cfb..db27224
--- a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/formitems/.content.xml
+++ b/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/video/formitems/.content.xml
@@ -1,6 +1,4 @@
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/.content.xml
deleted file mode 100755
index 54084a8..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/.content.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/.content.xml
deleted file mode 100755
index 54084a8..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/.content.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/.content.xml
deleted file mode 100755
index 54084a8..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/.content.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/.content.xml
deleted file mode 100755
index bc2a53d..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/.content.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/.content.xml
deleted file mode 100755
index 46e8a39..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/.content.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/.content.xml
deleted file mode 100755
index 491392d..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/.content.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/.content.xml
similarity index 63%
rename from current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/.content.xml
rename to current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/.content.xml
index 491392d..aba872a 100755
--- a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/asseteditors/.content.xml
+++ b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/.content.xml
@@ -1,3 +1,6 @@
+ jcr:primaryType="sling:OrderedFolder">
+
+
+
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/items/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/items/.content.xml
new file mode 100755
index 0000000..f6e6310
--- /dev/null
+++ b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/items/.content.xml
@@ -0,0 +1,71 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/current/ui.apps/src/main/content/jcr_root/apps/dam/content/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/video/.content.xml
similarity index 100%
rename from current/ui.apps/src/main/content/jcr_root/apps/dam/content/.content.xml
rename to current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/video/.content.xml
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/video/items/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/video/items/.content.xml
new file mode 100755
index 0000000..7c25f41
--- /dev/null
+++ b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/brightcove/video/items/.content.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/default/video/.content.xml b/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/default/video/.content.xml
deleted file mode 100755
index 2f7ae99..0000000
--- a/current/ui.apps/src/main/content/jcr_root/conf/global/settings/dam/adminui-extension/metadataschema/default/video/.content.xml
+++ /dev/null
@@ -1,321 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/current/ui.apps/src/main/content/jcr_root/etc/designs/cs/brightcove/players/html5-player/js/BrightcoveExperiences.js b/current/ui.apps/src/main/content/jcr_root/etc/designs/cs/brightcove/players/html5-player/js/BrightcoveExperiences.js
index 8af5bc5..ef61ff5 100644
--- a/current/ui.apps/src/main/content/jcr_root/etc/designs/cs/brightcove/players/html5-player/js/BrightcoveExperiences.js
+++ b/current/ui.apps/src/main/content/jcr_root/etc/designs/cs/brightcove/players/html5-player/js/BrightcoveExperiences.js
@@ -53,11 +53,12 @@ function createPlayers() {
var dataVideoId= selected_element.getAttribute("data-video-id");
var dataWidth= selected_element.getAttribute("data-width");
var dataHeight= selected_element.getAttribute("data-height");
+ var dataUsage = selected_element.getAttribute("data-usage");
var s = document.createElement('script');
s.src = "//players.brightcove.net/" + dataAccount + "/" + dataPlayer + "_"+dataEmbed+"/index.min.js";
s.onload = (function(playerID,dataVideoId,dataAccount,dataPlayer,dataEmbed,dataWidth,dataHeight,selected_element) {
return function() {
- playerHTML = '';
+ playerHTML = '';
selected_element.innerHTML = playerHTML;
bc(document.getElementById(playerID));
videojs(playerID).ready(function () {
diff --git a/current/ui.apps/src/main/content/jcr_root/libs/foundation/global.jsp b/current/ui.apps/src/main/content/jcr_root/libs/foundation/global.jsp
deleted file mode 100644
index 95c031a..0000000
--- a/current/ui.apps/src/main/content/jcr_root/libs/foundation/global.jsp
+++ /dev/null
@@ -1,66 +0,0 @@
-<%--
- Copyright 1997-2008 Day Management AG
- Barfuesserplatz 6, 4001 Basel, Switzerland
- All Rights Reserved.
-
- This software is the confidential and proprietary information of
- Day Management AG, ("Confidential Information"). You shall not
- disclose such Confidential Information and shall use it only in
- accordance with the terms of the license agreement you entered into
- with Day.
-
- ==============================================================================
-
- Global WCM script.
-
- This script can be used by any other script in order to get the default
- tag libs, sling objects and CQ objects defined.
-
- the following page context attributes are initialized via the
- tag:
-
- @param slingRequest SlingHttpServletRequest
- @param slingResponse SlingHttpServletResponse
- @param resource the current resource
- @param currentNode the current node
- @param log default logger
- @param sling sling script helper
-
- @param componentContext component context of this request
- @param editContext edit context of this request
- @param properties properties of the addressed resource (aka "localstruct")
- @param pageManager page manager
- @param currentPage containing page addressed by the request (aka "actpage")
- @param resourcePage containing page of the addressed resource (aka "myPage")
- @param pageProperties properties of the containing page
- @param component current CQ5 component
- @param designer designer
- @param currentDesign design of the addressed resource (aka "actdesign")
- @param resourceDesign design of the addressed resource (aka "myDesign")
- @param currentStyle style of the addressed resource (aka "actstyle")
-
- ==============================================================================
-
---%><%@page session="false" import="javax.jcr.*,
- org.apache.sling.api.resource.Resource,
- org.apache.sling.api.resource.ValueMap,
- com.day.cq.commons.inherit.InheritanceValueMap,
- com.day.cq.wcm.commons.WCMUtils,
- com.day.cq.wcm.api.Page,
- com.day.cq.wcm.api.NameConstants,
- com.day.cq.wcm.api.PageManager,
- com.day.cq.wcm.api.designer.Designer,
- com.day.cq.wcm.api.designer.Design,
- com.day.cq.wcm.api.designer.Style,
- com.day.cq.wcm.api.components.ComponentContext,
- com.day.cq.wcm.api.components.EditContext"
-%><%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0" %><%
-%><%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %><%
-%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%
-%><%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%
-%><%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><%
-%><%
-
- // add more initialization code here
-
-%>
\ No newline at end of file