Commit 1cbca8c0 by Adi Amir

support grouped cameras

parent 4d2d253f
{
"config": {
"metaDataConfig": "logic.adapter.HttpAdapter.model.HttpAdapterConfig",
"configHttpRequestParams": {
"baseUrl": "ie-parking.run.aws-usw02-pr.ice.predix.io/",
"basePath": "v1/",
"headers": [{
"name": "predix-zone-id",
"value": "c54e3e63-8dc6-425e-a533-64e061f64023"
}]
},
"authentication": {
"type": "oauth2",
"credential": {
"uaa": "9deacc64-7c53-4790-9a6c-c9de0fdebcdf.predix-uaa.run.aws-usw02-pr.ice.predix.io/oauth/token",
"clientId": "ipgallery",
"clientSecret": "1PGall3ry"
}
}
},
"flows": [{
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "GetAllParkingSpots",
"httpMethod": "GET",
"path": "locations/search",
"queryParams": [{
"name": "bbox",
"value": "32.123:-117,32.723179:-117.172655"
}, {
"name": "q",
"value": "location-type:PARKING_SPOT"
}, {
"name": "size",
"value": "30"
}],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": [
{
"metaDataActionClass": "logic.adapter.action.ExtractValueAction",
"params": {
"path": "/_embedded/locations",
"valueType": "ARRAY-NODE"
}
}, {
"metaDataActionClass": "logic.adapter.action.JsonConvertAction",
"params": {
"intermediateOperations": [{
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"variables": {
"id": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/_links/self/href",
"valueType": "STRING"
},
"subString": {
"from": {
"str": "/",
"location": "LAST",
"index": null
},
"to": null
}
}
}},
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": null,
"headers": [],
"content": null
}
}
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapJsonToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.JsonPatchAction",
"params": {
"variables": {
"mdeKey": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/_embedded/assets/0/_links/self/href",
"valueType": "STRING"
},
"subString": {
"from": {
"str": "/",
"location": "LAST",
"index": null
},
"to": null
}
}
}
},
"fileInput": null,
"filePatch": "parkingSpotJsonPatch.json"
}
}
}
}],
"terminateOperation": null
}
}]
},
"onError": null
}
}, {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": [],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": []
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}, {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "subscribe",
"httpMethod": "GET",
"path": "assets/$mdeKey/live-events",
"queryParams": [{
"name": "event-types",
"value": "PKIN,PKOUT"
}],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": [{
"metaDataActionClass": "logic.adapter.HttpAdapter.action.WebSocketAction",
"params": {
"variables": {
"webSocket": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/url",
"valueType": "STRING"
},
"subString": {
"from": null,
"to": null
}
}
}
},
"headers": [{
"name": "predix-zone-id",
"value": "c54e3e63-8dc6-425e-a533-64e061f64023"
}],
"webSocket": "$webSocket",
"mdeKey": "$mdeKey",
"uid": "$uid"
}
}]
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}
]
}
\ No newline at end of file
{
"config": {
"metaDataConfig": "logic.adapter.HttpAdapter.model.HttpAdapterConfig",
"configHttpRequestParams": {
"baseUrl": "ie-parking.run.aws-usw02-pr.ice.predix.io/",
"basePath": "v1/",
"headers": [{
"name": "predix-zone-id",
"value": "c54e3e63-8dc6-425e-a533-64e061f64023"
}]
},
"authentication": {
"type": "oauth2",
"credential": {
"uaa": "9deacc64-7c53-4790-9a6c-c9de0fdebcdf.predix-uaa.run.aws-usw02-pr.ice.predix.io/oauth/token",
"clientId": "ipgallery",
"clientSecret": "1PGall3ry"
}
}
},
"flows": [{
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "GetAllParkingSpots",
"httpMethod": "GET",
"path": "locations/search",
"queryParams": [{
"name": "bbox",
"value": "32.123:-117,32.723179:-117.172655"
}, {
"name": "q",
"value": "location-type:PARKING_SPOT"
}, {
"name": "size",
"value": "30"
}],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": [
{
"metaDataActionClass": "logic.adapter.action.ExtractValueAction",
"params": {
"path": "/_embedded/locations",
"valueType": "ARRAY-NODE"
}
}, {
"metaDataActionClass": "logic.adapter.action.JsonConvertAction",
"params": {
"intermediateOperations": [{
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"variables": {
"id": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/_links/self/href",
"valueType": "STRING"
},
"subString": {
"from": {
"str": "/",
"location": "LAST",
"index": null
},
"to": null
}
}
}},
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": null,
"headers": [],
"content": null
}
}
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapJsonToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.JsonPatchAction",
"params": {
"variables": {
"mdeKey": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/_embedded/assets/0/_links/self/href",
"valueType": "STRING"
},
"subString": {
"from": {
"str": "/",
"location": "LAST",
"index": null
},
"to": null
}
}
}
},
"fileInput": null,
"filePatch": "parkingSpotJsonPatch.json"
}
}
}
}],
"terminateOperation": null
}
}]
},
"onError": null
}
}, {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": [],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": []
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}, {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "subscribe",
"httpMethod": "GET",
"path": "assets/$mdeKey/live-events",
"queryParams": [{
"name": "event-types",
"value": "PKIN,PKOUT"
}],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": [{
"metaDataActionClass": "logic.adapter.HttpAdapter.action.WebSocketAction",
"params": {
"variables": {
"webSocket": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.ExtractSubStringAction",
"extract": {
"path": "/url",
"valueType": "STRING"
},
"subString": {
"from": null,
"to": null
}
}
}
},
"headers": [{
"name": "predix-zone-id",
"value": "c54e3e63-8dc6-425e-a533-64e061f64023"
}],
"webSocket": "$webSocket",
"mdeKey": "$mdeKey",
"uid": "$uid"
}
}]
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}
]
}
\ No newline at end of file
{
"api": [{
"id": "getCameraList",
"request": {
"method": "GET",
"path": "v2/ge/media/cameras",
"params": [{
"bbox": "{quuery.bbox}[GEO]/mandatory"
}]
},
"actions": [{
"type": "CALL_ADAPTER",
"adapterId": "ge-v1",
"apiId": "getCameraList",
"params": [{
"bbox": "${request.query.bbox}[GEO]"
}],
"OnResponse": {
"$CAMERA_ARRAY": "response.content.content[JSON_ARRAY]"
}
}, {
"type": "CALL_ADAPTER",
"rule": {
"callEachEntryInArray": "${CAMERA_ARRAY}"
}
},
"adapterId": "ge-v1",
"apiId": "getCameraDetails",
"params": [{
"cameraId": "${CAMERA_ARRAY}.assetUid}}"
}]
}, {
"type": "CONVERT",
"converterId": "J2J/parking-spot",
"input": "$content/spot"
}]
}]
}
\ No newline at end of file
...@@ -31,7 +31,7 @@ response: ...@@ -31,7 +31,7 @@ response:
getLatestImage getLatestImage
************** **************
public-safety ==> GET 172.16.1.72:50005/public-safety/media/api/v2/san-diego/camera/CAMERA-STG-HYP1052-CAM-L/latestImage public-safety ==> GET 172.16.1.72:50005/public-safety/media/api/v2/san-diego/camera/CAMERA-STG-HYP1052-CAM-L/latestImage?views=CAMERA-STG-HYP1017-CAM-L,CAMERA-STG-HYP1017-CAM-R,CAMERA-STG-HYP1017-CAM-F
response: response:
{ {
"success": true, "success": true,
......
...@@ -11,7 +11,6 @@ import microservice.RequestContext; ...@@ -11,7 +11,6 @@ import microservice.RequestContext;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import microservice.types.BaseRestResponse; import microservice.types.BaseRestResponse;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
...@@ -24,7 +23,6 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; ...@@ -24,7 +23,6 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
...@@ -41,13 +39,15 @@ public class GEManager { ...@@ -41,13 +39,15 @@ public class GEManager {
public static String AUTH_PARAMS = "grant_type=client_credentials&client_id=ipgallery"; public static String AUTH_PARAMS = "grant_type=client_credentials&client_id=ipgallery";
public static String METADATA_URL = "ie-cities-metadata.run.asv-pr-pub.ice.predix.io"; public static String METADATA_URL = "ie-cities-metadata.run.asv-pr-pub.ice.predix.io";
public static String MEDIA_URL = "ie-cities-media.run.asv-pr-pub.ice.predix.io"; public static String MEDIA_URL = "ie-cities-media.run.asv-pr-pub.ice.predix.io";
public static String ASSET_LIST_URL = "v2/assets/search"; public static String ASSET_LIST_URL = "/v2/assets/search";
public static String ASSETS_URL = "/v2/assets";
public static String PARKING_ZONE_ID = "ics-IE-PARKING"; public static String PARKING_ZONE_ID = "ics-IE-PARKING";
public static String PS_ZONE_ID = "ics-IE-PUBLIC-SAFETY"; public static String PS_ZONE_ID = "ics-IE-PUBLIC-SAFETY";
public static String TOKEN = "NOT_VALID"; public static String TOKEN = "NOT_VALID";
private SimpleHttpClient httpClient = null; private SimpleHttpClient httpClient = null;
private ILogger logger; private ILogger logger;
private ObjectMapper objMapper = new ObjectMapper();
public GEManager(ILogger logger) throws Exception { public GEManager(ILogger logger) throws Exception {
this.logger = logger; this.logger = logger;
...@@ -55,148 +55,206 @@ public class GEManager { ...@@ -55,148 +55,206 @@ public class GEManager {
httpClient.Initialize(100); httpClient.Initialize(100);
} }
public BaseRestResponse executeRequest(String serviceId, String[] apiIdAsParams, RequestContext requestContext, JsonNode content, boolean isMaintenanceRequest) { public BaseRestResponse executeRequest(String serviceId, String[] apiIdAsParams, RequestContext requestContext) {
String error = null; String error = null;
BaseRestResponse brr = new BaseRestResponse(false,null); BaseRestResponse brr = new BaseRestResponse(false,null);
switch(apiIdAsParams[0]) { if (apiIdAsParams.length == 1 && apiIdAsParams[0].equals("cameras")) {
case "cameras": brr = getCameraList(requestContext);
brr = getCamerasList(serviceId,apiIdAsParams,requestContext,content,isMaintenanceRequest); }
break; else if (apiIdAsParams.length == 3 && apiIdAsParams[0].equals("camera") && apiIdAsParams[2].equals("latestImage")) {
case "camera": brr = getLatestMediaFile(apiIdAsParams[1] /*camId*/, "IMAGE", requestContext);
brr = getCamera(serviceId,apiIdAsParams,requestContext,content,isMaintenanceRequest); }
//brr = testGetImage(requestContext, apiIdAsParams); else {
break; String err = "executeRequest() failed. Unknown api: " + getApiIdString(apiIdAsParams);
default: return errorResponse(err);
} }
// if the request failed due to invalid token - fetch a new one & try again
if (isAccessDenied(brr)) {
logger.info("executeRequest() - access denied. fetch a new token & try again");
if (getNewAccessToken() == true) {
brr = executeRequest(serviceId, apiIdAsParams, requestContext);
}
else {
return errorResponse("executeRequest() failed to obtain access token");
}
}
return brr; return brr;
} }
private BaseRestResponse getCamera(String serviceId, String[] apiIdAsParams, RequestContext requestContext, JsonNode content, boolean isMaintenanceRequest) { private BaseRestResponse getLatestMediaFile(String camId, String mediaType, RequestContext requestContext) {
SimpleHttpRequest req = null;
SimpleHttpResponse resp = null; SimpleHttpResponse httpResp = null;
BaseRestResponse brr = new BaseRestResponse(false,null); BaseRestResponse brr = null;
JsonNode contentObj = null;
String api = ""; logger.info("getLatestMediaFile() activated. camId=" + camId);
for (String tk: apiIdAsParams)
api += tk + "."; // execute the request
logger.info("received getCamera() serviceId=" + serviceId + " api=" + api); // example: ie-cities-media.run.asv-pr-pub.ice.predix.io/assets/{camId}/media/latest?mediaType=IMAGE
req = buildCameraHttpRequest(requestContext,content,apiIdAsParams);
try { try {
resp = httpClient.processRequest(req); // step 1: get the latest file URL to retreive (e.g: {{mediaurl}}/assets/CAMERA-STG-HYP1072-CAM-R/media/latest?mediaType=IMAGE)
SimpleHttpRequest httpRequest = buildLatestMediaFileUrlRequest(camId, mediaType);
SimpleHttpResponse httpFileUrlResp = httpClient.processRequest(httpRequest);
if (httpFileUrlResp.getStatusCode() != 200) {
logHttpError("getLatestMediaFile/getLatestMediaURL", httpFileUrlResp);
return errorHttpResponse(httpFileUrlResp);
}
contentObj = objMapper.readTree(httpFileUrlResp.getContent());
JsonNode arrNode = contentObj.get("content");
String url = arrNode.get(0).get("url").asText();
} catch (UnsupportedEncodingException e) { // step 2: get/download latest media file data (e.g: https://ie-cities-media.run.asv-pr-pub.ice.predix.io/v2/file/CAMERA-STG-HYP1052-CAM-L_1487807853000_0_IMAGE.JPG)
e.printStackTrace(); httpRequest = buildDownloadLatestMediaFileRequest(url);
} SimpleHttpResponse httpFileDataResp = httpClient.processRequest(httpRequest);
if(resp.getStatusCode() == 200) if (httpFileDataResp.getStatusCode() != 200) {
return buildCameraResp(resp); logHttpError("getLatestMediaFile/downloadLatestMediaFile", httpFileDataResp);
else if (resp.getStatusCode() == 403 || resp.getStatusCode() == 401) { return errorHttpResponse(httpFileDataResp);
logger.info("no valid token - obtain a new token ..."); }
if(getNewToken()) String fileData = httpFileDataResp.getContent();
brr = executeRequest(serviceId,apiIdAsParams,requestContext,content,isMaintenanceRequest);
else // step 3: get the view direction for this camera (e.g: {{metadataurl}}/assets/CAMERA-STG-HYP1066-CAM-R)
brr.setError("failed to retrieve a valid token"); httpRequest = buildGetCameraDetailsRequest(camId);
SimpleHttpResponse httpCameraDetailsResp = httpClient.processRequest(httpRequest);
if (httpCameraDetailsResp.getStatusCode() != 200) {
logHttpError("getLatestMediaFile/getCameraDetails", httpCameraDetailsResp);
return errorHttpResponse(httpFileDataResp);
}
contentObj = objMapper.readTree(httpCameraDetailsResp.getContent());
String viewDir = contentObj.at("/properties/VIEW").asText();
// build the final response
brr = buildLatestMediaFileResp(httpFileDataResp.getContent(), url, viewDir);
} catch (Exception e) {
String err = "getLatestMediaFile() failed with exception. camId=" + camId + " e=" + e.toString();
logger.error(err);
return errorResponse(err);
} }
else {
brr.setError("processRequest() failed. path: " + req.getPath() + " resp: " + resp.toString()); return brr;
}
private SimpleHttpRequest buildLatestMediaFileUrlRequest(String camId, String mediaType) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setProtocol("https");
request.setDomain(MEDIA_URL);
request.setPort(443);
request.setMethod(SimpleHttpRequest.Method.GET);
String path = "/v2/assets/" + camId + "/media/latest";
request.setQueryString("mediaType=" + mediaType);
request.setPath(path);
request.addHeader("Authorization", "Bearer " + TOKEN);
request.addHeader("Predix-Zone-Id", PS_ZONE_ID);
return request;
}
private BaseRestResponse buildLatestMediaFileResp(String fileData, String url, String viewDir) {
BaseRestResponse brr = new BaseRestResponse(true,null);
try {
ObjectNode dataObj = objMapper.createObjectNode();
// parse file url
// String[0]: cameraId
// String[1]: timestamp
// String[2]: media type (IMAGE/VIDEO)
// String[3]: fileName
String[] urlParts = getMediaFileName(url, "latest");
if (urlParts == null) {
String err = "buildLatestMediaFileResp() - failed to parse file url: " + url;
logger.error(err);
return new BaseRestResponse(false, err);
}
dataObj.put("cameraId", urlParts[0]);
dataObj.put("timestamp", Long.valueOf(urlParts[1]));
dataObj.put("mediaType", urlParts[2]);
dataObj.put("fileName", urlParts[3]);
dataObj.put("viewDir", viewDir);
dataObj.put("fileData", fileData);
brr.objectNode = dataObj;
} catch (Exception e) {
String err = "buildLatestMediaFileResp() failed with exception. e: " + e.toString();
logger.error(err);
return new BaseRestResponse(false, err);
} }
return brr; return brr;
} }
private BaseRestResponse getCamerasList(String serviceId, String[] apiIdAsParams, RequestContext requestContext, JsonNode content, boolean isMaintenanceRequest) { private SimpleHttpRequest buildGetCameraDetailsRequest(String camId) {
SimpleHttpRequest request = new SimpleHttpRequest();
request.setProtocol("https");
request.setDomain(METADATA_URL);
request.setPort(443);
request.setMethod(SimpleHttpRequest.Method.GET);
String path = ASSETS_URL + "/" + camId;
request.setPath(path);
request.addHeader("Authorization", "Bearer " + TOKEN);
request.addHeader("Predix-Zone-Id", PARKING_ZONE_ID);
return request;
}
private BaseRestResponse getCameraList(RequestContext requestContext) {
SimpleHttpRequest req = null; SimpleHttpRequest req = null;
SimpleHttpResponse resp = null; SimpleHttpResponse httpResp = null;
BaseRestResponse brr = new BaseRestResponse(false,null); BaseRestResponse brr = new BaseRestResponse(false,null);
String api = ""; logger.info("getCamerasList() activated.");
for (String tk: apiIdAsParams)
api += tk + ".";
logger.info("received getCamerasList() serviceId=" + serviceId + " api=" + api);
req = buildCamerasHttpRequest(requestContext,content); // execute the request ...
req = buildCameraListHttpRequest(requestContext);
try { try {
resp = httpClient.processRequest(req); httpResp = httpClient.processRequest(req);
} catch (UnsupportedEncodingException e) { if(httpResp.getStatusCode() == 200)
e.printStackTrace(); brr = buildCameraListResp(httpResp);
} else {
if(resp.getStatusCode() == 200) logHttpError("getCameraList", httpResp);
return buildCameraListResp(resp); return errorHttpResponse(httpResp);
else if (resp.getStatusCode() == 403 || resp.getStatusCode() == 401) { }
logger.info("no valid token - obtain a new token ...");
if(getNewToken()) } catch (Exception e) {
brr = executeRequest(serviceId,apiIdAsParams,requestContext,content,isMaintenanceRequest); String err = "getCameraList() failed with exception. e=" + e.toString();
else logger.error(err);
brr.setError("failed to retrieve a valid token"); return errorResponse(err);
} }
return brr; return brr;
} }
private boolean getNewToken() { private boolean getNewAccessToken() {
SimpleHttpRequest req = null; SimpleHttpRequest req = null;
SimpleHttpResponse resp = null; SimpleHttpResponse httpResp = null;
logger.info("getNewAccessToken() activated.");
req = buildGetTokenRequest(); req = buildGetTokenRequest();
try { try {
resp = httpClient.processRequest(req); httpResp = httpClient.processRequest(req);
if (resp.getStatusCode() == 200) { if (httpResp.getStatusCode() == 200) {
String cont = resp.getContent(); String cont = httpResp.getContent();
ObjectMapper mapper = new ObjectMapper(); JsonNode contObj = objMapper.readTree(cont);
try { TOKEN = contObj.get("access_token").asText();
JsonNode contObj = mapper.readTree(cont); logger.info("getNewAccessToken() succeeded.");
TOKEN = contObj.get("access_token").asText(); return true;
return true;
} catch (IOException e) {
e.printStackTrace();
}
} }
} catch(UnsupportedEncodingException e){ else {
e.printStackTrace(); logHttpError("getNewAccessToken", httpResp);
} return false;
return false;
}
private BaseRestResponse buildCameraResp(SimpleHttpResponse resp) {
BaseRestResponse brr = new BaseRestResponse(true,null);
SimpleHttpRequest req;
String content = resp.getContent();
ObjectMapper mapper = new ObjectMapper();
try {
ObjectNode objectNode = mapper.createObjectNode();
JsonNode contentObj = mapper.readTree(content);
JsonNode arrNode = contentObj.get("content");
String url = arrNode.get(0).get("url").asText();
req = buildOpenCameraLinkRequest(url);
resp = httpClient.processRequest(req);
if (resp.getStatusCode() == 200) {
ObjectNode dataObj = mapper.createObjectNode();
// parse file url
// String[0]: cameraId
// String[1]: timestamp
// String[2]: media type (IMAGE/VIDEO)
// String[3]: fileName
String[] urlParts = getMediaFileName(url, "latest");
if (urlParts == null) {
String err = "buildCameraResp() failed to parse file url: " + url;
logger.error(err);
return new BaseRestResponse(false, err);
}
dataObj.put("cameraId", urlParts[0]);
dataObj.put("timestamp", Long.valueOf(urlParts[1]));
dataObj.put("mediaType", urlParts[2]);
dataObj.put("fileName", urlParts[3]);
dataObj.put("data", resp.getContent());
brr.objectNode = dataObj;
} }
} catch (Exception e) { } catch(Exception e){
String err = "buildCameraResp() failed. e: " + e.toString(); logger.error("getNewAccessToken() failed with exception. e: " + e.toString());
logger.error(err); return false;
e.printStackTrace();
return new BaseRestResponse(false, err);
} }
return brr;
} }
private BaseRestResponse buildCameraListResp(SimpleHttpResponse resp) {
private BaseRestResponse buildCameraListResp(SimpleHttpResponse resp) {
BaseRestResponse brr = new BaseRestResponse(true,null); BaseRestResponse brr = new BaseRestResponse(true,null);
int size; int size;
String content = resp.getContent(); String content = resp.getContent();
...@@ -216,14 +274,6 @@ public class GEManager { ...@@ -216,14 +274,6 @@ public class GEManager {
double lon = Double.parseDouble(latLon[1]); double lon = Double.parseDouble(latLon[1]);
objectNode.put("lat",lat); objectNode.put("lat",lat);
objectNode.put("lon",lon); objectNode.put("lon",lon);
// ArrayNode linksArray = mapper.createArrayNode();
// ObjectNode linksNode = mapper.createObjectNode();
// linksNode.put("latestImage",(JsonNode)null);
// linksArray.add(linksNode);
// linksNode = mapper.createObjectNode();
// linksNode.put("latestVideo",(JsonNode)null);
// linksArray.add(linksNode);
// objectNode.put("links",linksArray);
node.add(objectNode); node.add(objectNode);
} }
brr.objectNode = node; brr.objectNode = node;
...@@ -236,10 +286,10 @@ public class GEManager { ...@@ -236,10 +286,10 @@ public class GEManager {
return brr; return brr;
} }
private SimpleHttpRequest buildOpenCameraLinkRequest(String link) { private SimpleHttpRequest buildDownloadLatestMediaFileRequest(String url) {
SimpleHttpRequest request = new SimpleHttpRequest(); SimpleHttpRequest request = new SimpleHttpRequest();
String[] domainFileUrl = extractDomainFile(link); String[] domainFileUrl = extractDomainFile(url);
if(domainFileUrl != null) { if(domainFileUrl != null) {
request.setProtocol("https"); request.setProtocol("https");
request.setDomain(domainFileUrl[0]); request.setDomain(domainFileUrl[0]);
...@@ -253,7 +303,7 @@ public class GEManager { ...@@ -253,7 +303,7 @@ public class GEManager {
return request; return request;
} }
private SimpleHttpRequest buildCameraHttpRequest(RequestContext requestContext, JsonNode content, String[] apiIdAsParams) { private SimpleHttpRequest buildCameraHttpRequest(RequestContext requestContext, String[] apiIdAsParams) {
switch(apiIdAsParams[2]) { switch(apiIdAsParams[2]) {
case "latestImage": case "latestImage":
SimpleHttpRequest request = new SimpleHttpRequest(); SimpleHttpRequest request = new SimpleHttpRequest();
...@@ -266,15 +316,13 @@ public class GEManager { ...@@ -266,15 +316,13 @@ public class GEManager {
request.setPath(path); request.setPath(path);
request.addHeader("Authorization", "Bearer " + TOKEN); request.addHeader("Authorization", "Bearer " + TOKEN);
request.addHeader("Predix-Zone-Id", PS_ZONE_ID); request.addHeader("Predix-Zone-Id", PS_ZONE_ID);
if(content != null)
request.setContent(content.toString());
return request; return request;
default: default:
} }
return null; return null;
} }
private SimpleHttpRequest buildCamerasHttpRequest(RequestContext requestContext,JsonNode content) { private SimpleHttpRequest buildCameraListHttpRequest(RequestContext requestContext) {
SimpleHttpRequest request = new SimpleHttpRequest(); SimpleHttpRequest request = new SimpleHttpRequest();
request.setProtocol("https"); request.setProtocol("https");
request.setDomain(METADATA_URL); request.setDomain(METADATA_URL);
...@@ -288,8 +336,6 @@ public class GEManager { ...@@ -288,8 +336,6 @@ public class GEManager {
String bbox = "bbox=" + queryParams.get("bbox").peek() + "&page=0&size=500&q=assetType:CAMERA"; String bbox = "bbox=" + queryParams.get("bbox").peek() + "&page=0&size=500&q=assetType:CAMERA";
request.setQueryString(bbox); request.setQueryString(bbox);
} }
if(content != null)
request.setContent(content.toString());
return request; return request;
} }
...@@ -413,5 +459,41 @@ public class GEManager { ...@@ -413,5 +459,41 @@ public class GEManager {
} }
private String getApiIdString(String[] apiIdAsParams) {
String apiString = "";
for (String p: apiIdAsParams)
apiString += p + "\"";
return apiString;
}
private BaseRestResponse errorHttpResponse(SimpleHttpResponse httpResp) {
BaseRestResponse errResp = new BaseRestResponse(false, null);
ObjectNode objectNode = objMapper.createObjectNode();
objectNode.put("statusCode", httpResp.getStatusCode());
objectNode.put("content", httpResp.getContent());
errResp.objectNode = objectNode;
return errResp;
}
private BaseRestResponse errorResponse(String error) {
BaseRestResponse errResp = new BaseRestResponse(false, error);
return errResp;
}
private Boolean isAccessDenied(BaseRestResponse brr) {
if (brr.success == false && brr.objectNode != null) {
int statusCode = brr.objectNode.get("statusCode").asInt();
Boolean bAccessDenied = (statusCode == 403 ||statusCode == 401);
return bAccessDenied;
}
else
return false;
}
private void logHttpError(String funcName, SimpleHttpResponse httpResp) {
logger.error("statusCode=" + httpResp.getStatusCode() + " content=" + httpResp.getContent());
}
} }
...@@ -78,7 +78,7 @@ public class MdeManager { ...@@ -78,7 +78,7 @@ public class MdeManager {
String ver = serviceId.split("\\.")[0]; String ver = serviceId.split("\\.")[0];
if (ver.equals("v2")) if (ver.equals("v2"))
brr = geManager.executeRequest(serviceId,apiIdAsParams,requestContext,null, isMaintenanceRequest); brr = geManager.executeRequest(serviceId,apiIdAsParams,requestContext);
else else
brr = executeRequest(serviceId,apiIdAsParams,requestContext,null,isMaintenanceRequest); brr = executeRequest(serviceId,apiIdAsParams,requestContext,null,isMaintenanceRequest);
return brr; return brr;
...@@ -104,7 +104,7 @@ public class MdeManager { ...@@ -104,7 +104,7 @@ public class MdeManager {
String ver = serviceId.split("\\.")[0]; String ver = serviceId.split("\\.")[0];
if (ver.equals("v2")) if (ver.equals("v2"))
brr = geManager.executeRequest(serviceId,apiIdAsParams,requestContext,content, isMaintenanceRequest); brr = geManager.executeRequest(serviceId,apiIdAsParams,requestContext);
else else
brr = executeRequest(serviceId,apiIdAsParams,requestContext,content, isMaintenanceRequest); brr = executeRequest(serviceId,apiIdAsParams,requestContext,content, isMaintenanceRequest);
return brr; return brr;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment