Commit 81228a97 by Eli Ben Baruch

getAllParkingSpots - working

parent c7023bde
Showing with 4097 additions and 441 deletions
...@@ -14,16 +14,41 @@ repositories { ...@@ -14,16 +14,41 @@ repositories {
dependencies { dependencies {
compile 'com.flipkart.zjsonpatch:zjsonpatch:0.2.1' compile 'com.flipkart.zjsonpatch:zjsonpatch:0.2.1'
compile group:'com.ipgallery.common', name:'microservice', version:'1.2.0' // compile group:'com.ipgallery.common', name:'microservice', version:'1.2.0'
compile group:'com.ipgallery.common', name:'microservice', version:'1.3.2'
compile group:'com.ipgallery.common', name:'itc', version:'1.0.0' compile group:'com.ipgallery.common', name:'itc', version:'1.0.0'
// compile 'com.ipgallery.common:utils:1.1.0' // compile 'com.ipgallery.common:utils:1.1.0'
compile 'io.swagger:swagger-annotations:1.5.7' compile 'io.swagger:swagger-annotations:1.5.7'
compile 'org.slf4j:slf4j-simple:1.7.19' compile 'org.slf4j:slf4j-simple:1.7.19'
compile 'com.javadocmd:simplelatlng:1.3.1' compile 'com.javadocmd:simplelatlng:1.3.1'
compile group: 'org.json', name: 'json', version: '20160212' compile group: 'org.json', name: 'json', version: '20160212'
// https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api
compile group: 'javax.websocket', name: 'javax.websocket-api', version: '1.1'
compile 'com.neovisionaries:nv-websocket-client:1.30'
compile 'org.java-websocket:Java-WebSocket:1.3.0'
// compile 'com.google.oauth-client:google-oauth-client:1.22.0'
// compile 'com.google.api.client:google-api-client-json:1.2.3-alpha'
// compile 'com.google.http-client:google-http-client-jackson:1.15.0-rc'
// <dependency>
// <groupId>com.google.api.client</groupId>
//<artifactId>google-api-client</artifactId>
// <version>1.4.1-beta</version>
//</dependency>
testCompile 'junit:junit:4.12'
// testCompile 'com.neovisionaries:nv-websocket-client:1.30'
testCompile fileTree(dir: '../ds/lib/external/sap', include: '*.jar')
testCompile 'org.java-websocket:Java-WebSocket:1.3.0'
testCompile 'com.google.oauth-client:google-oauth-client:1.22.0'
testCompile 'com.google.api.client:google-api-client-json:1.2.3-alpha'
testCompile 'com.google.http-client:google-http-client-jackson:1.15.0-rc'
testCompile 'com.google.api.client:google-api-client:1.4.1-beta'
testCompile 'junit:junit:4.12'
} }
jar { jar {
......
{
"coordinates": {
"P1": "32.711734697964815,-117.1573294130409",
"P2": "32.711736,-117.15736248188104",
"P3": "32.711858,-117.15736455072118",
"P4": "32.711859,-117.1573304130409"
},
"city": null,
"state": null,
"country": null,
"zipcode": null,
"_links": {
"self": {
"href": "http://ie-parking.run.aws-usw02-pr.ice.predix.io/v1/locations/1000000047"
}
},
"location-uid": "157-parkingspot",
"location-type": "PARKING_SPOT",
"address": null,
"_embedded": {
"container": null,
"locations": [],
"assets": [{
"coordinates": {
"P1": "32.711653,-117.157314"
},
"_links": {
"self": {
"href": "http://ie-parking.run.aws-usw02-pr.ice.predix.io/v1/assets/1000000018"
},
"search-media": {
"href": "http://ie-parking.run.aws-usw02-pr.ice.predix.io/v1/assets/1000000018/media{?media-types,start-ts,end-ts,page,size,locationId}",
"templated": true
},
"search-events": {
"href": "http://ie-parking.run.aws-usw02-pr.ice.predix.io/v1/assets/1000000018/events{?event-types,start-ts,end-ts,size}",
"templated": true
},
"live-events": {
"href": "http://ie-parking.run.aws-usw02-pr.ice.predix.io/v1/assets/1000000018/live-events{?event-types}",
"templated": true
}
},
"device-id": "HYP1040-75",
"event-type": "PKIN;PKOUT;TFEVT",
"media-type": "IMAGE",
"device-type": "DATASIM"
}]
},
"analytic-category": "PARKING"
}
\ 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"
}, {
"name": "Authorization",
"value": "bearer $token"
}]
},
"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"
}],
"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.MapJsonToStringOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.ExtractValueAction",
"params": {
"path": "/_links/self/href",
"valueType": "STRING"
}
}
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": null,
"headers": [],
"content": null
}
},
"id": "lastToken"
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapJsonToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.JsonPatchAction",
"params": {
"fileInput": null,
"filePatch": "parkingSpotJsonPatch.json"
}
}
}
}],
"terminateOperation": null
}
}]
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}, {
"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.action.ExtractValueAction",
"params": {
"path": "/url",
"valueType": "STRING"
}
},
{
"metaDataActionClass": "logic.adapter.HttpAdapter.action.WebSocketAction",
"params": {
"headers":[{
"name": "predix-zone-id",
"value": "c54e3e63-8dc6-425e-a533-64e061f64023"
}]
}
}]
},
"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": "b6fc22b6-ad71-423e-867b-a1b197f6cfc2"
}, {
"name": "Authorization",
"value": "bearer $token"
}]
},
"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": "GetAllTrafficLanes",
"httpMethod": "GET",
"path": "locations/search",
"queryParams": [{
"name": "bbox",
"value": "32.123:-117,32.723179:-117.172655"
}, {
"name": "q",
"value": "location-type:TRAFFIC_LANES"
}],
"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.MapJsonToStringOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.ExtractValueAction",
"params": {
"path": "/_links/self/href",
"valueType": "STRING"
}
}
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.HttpAdapter.action.SimpleHttpAction",
"params": {
"id": "getLocationDetails",
"httpMethod": "GET",
"path": "locations/$id",
"queryParams": null,
"headers": [],
"content": null
}
},
"id": "lastToken"
}
}, {
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapJsonToJsonOperation",
"operationParams": {
"action": {
"metaDataActionClass": "logic.adapter.action.JsonPatchAction",
"params": {
"fileInput": null,
"filePatch": "trafficLaneJsonPatch.json"
}
}
}
}],
"terminateOperation": null
}
}]
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}, {
"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/$id/live-events",
"queryParams": [{
"name": "event-types",
"value": "TFEVT"
}
],
"headers": [],
"content": null
}
},
"onResponse": {
"onSuccess": {
"actionsInput": "CONTENT",
"actions": []
},
"onError": {
"actionsInput": "CONTENT",
"actions": []
}
}
}
]
}
\ No newline at end of file
{ {
"adapters": [{ "adapters": [{
"id": "adapter.chicago.transportation", "id": "adapter.ge.parking",
"type": "HttpAdapter" "type": "HttpAdapter"
}] }]
} }
\ No newline at end of file
123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123123
[
{ "op": "add", "path": "/location-uid", "value": "$uid"}
]
\ No newline at end of file
[
{"op": "move", "from": "/bustime-response", "path": ""}
]
{
"mde": {
"host": "172.16 .1 .56",
"port": 50040,
"base": "mde",
"api":
{
"version": "v1",
"tenant": [
{
"id": "chicago",
"commonTenantFile": null,
"isBasePath": false,
"resourceTypes": null,
"domains": [
{
"name": "transportation",
"service-file": "chicago.transportation.json",
"resources": [ "routes" , "vehicles"],
"resources-file": "resources.chicago.transportation.json"
}
]
},
{
"id": "ge",
"commonTenantFile": "ge.json",
"isBasePath": false,
"domains": ["pedestrian","parking","publicSafety"],
"resources": ["assets","locations"],
{
"name": "pedestrian",
"service-file": "ge.pedestrian.json",
"resources": ["assets","locations"],
"resources-file": "resources.ge.json"
},
{
"name": "parking",
"service-file": "ge.parking.json",
"resources-file": "resources.ge.json"
},
{
"name": "publicSafety",
"service-file": "ge.publicSafety.json",
"resources-file": "resources.ge.json"
}
]
}
]
}
"general-services": {
"path": {
}
}
,
"prov": {}
}
"ge.json": {
"security": {
"client-id": "ipgallery",
"client-secret": "1PGall3ry",
"app-key": null,
}
},
"chicago.transportation.json": {
"security": {
"client-id": null,
"client-secret": null,
"app-key": {
"name": "key",
"type": "queryParam",
"value": "bdfsfbsdfasab"
}
}
}
}
\ No newline at end of file
{ {
"apiList": [{ "apiList": [
{
"apiIn": "routes", "apiIn": "routes",
"actions": [{ "actions": [{
"adapterId": "adapter.chicago.transportation", "adapterId": "adapter.chicago.transportation",
"apiOut": "getroutes" "apiOut": "getroutes"
}] }]
}, { },
{
"apiIn": "directions",
"actions": [{
"adapterId": "adapter.chicago.transportation",
"apiOut": "directions"
}]
},
{
"apiIn": "reports", "apiIn": "reports",
"actions": [{ "actions": [{
"adapterId": "adapter.chicago.public-safety", "adapterId": "adapter.chicago.public-safety",
......
{
"apiList": [
{
"apiIn": "spots",
"method": "GET",
"actions": [{
"adapterId": "adapter.ge.parking",
"apiOut": "GetAllParkingSpots"
}]
},
{
"apiIn": "resources/devices/$id",
"method": "GET",
"actions": [{
"adapterId": "adapter.ge.parking",
"apiOut": "getLastEventDetails"
}]
},
{
"apiIn": "subscribe/$mde-id/$uid",
"method": "POST",
"actions": [{
"adapterId": "adapter.ge.parking",
"apiOut": "subscribe"
}]
}
]
}
{ {
"services": [ { "id": "chicago.transportation" } ] "services": [ { "id": "ge.parking" } ]
} }
\ No newline at end of file
{
"services": [ { "id": "chicago.transportation" } ]
}
\ No newline at end of file
package defs; package defs;
import com.fasterxml.jackson.databind.JsonNode;
import util.Utils;
/** /**
* Created by eli on 6/26/16. * Created by eli on 6/26/16.
*/ */
...@@ -8,4 +11,5 @@ public class Constants { ...@@ -8,4 +11,5 @@ public class Constants {
public static final String SERVICES_PATH = "services.json"; public static final String SERVICES_PATH = "services.json";
public static final String CONFIG_LOCATION = "/opt/mcx/config/"; public static final String CONFIG_LOCATION = "/opt/mcx/config/";
} }
...@@ -4,6 +4,34 @@ package defs; ...@@ -4,6 +4,34 @@ package defs;
* Created by eli on 7/5/16. * Created by eli on 7/5/16.
*/ */
public class Enums { public class Enums {
public enum eNodeType{
ARRAY_NODE("ARRAY-NODE"),
STRING_NODE("STRING");
private String nodeType;
eNodeType(String nodeType) {
this.nodeType = nodeType;
}
public String getNodeType() {
return nodeType;
}
public static eNodeType resolveNodeType(String nodeType){
eNodeType[] types = eNodeType.values();
for (eNodeType type : types)
{
if (type.getNodeType().equals(nodeType))
return type;
}
return null;
}
}
public enum eKeyWord{ public enum eKeyWord{
QUERY("query"), QUERY("query"),
HEADER("header"); HEADER("header");
......
...@@ -27,18 +27,17 @@ public class MdeHandler extends BaseHandler { ...@@ -27,18 +27,17 @@ public class MdeHandler extends BaseHandler {
// public static final Pattern regExCsvParamSeperatorPattern = Pattern.compile(","); // public static final Pattern regExCsvParamSeperatorPattern = Pattern.compile(",");
public MdeHandler(ILogger logger) { public MdeHandler() {
} }
@Override @Override
public void init() { public void init() {
// try { try {
// sleep(10000); sleep(10000);
// } catch (InterruptedException e) { } catch (InterruptedException e) {
// e.printStackTrace(); e.printStackTrace();
// } }
this.mdeManager = new MdeManager(logger); this.mdeManager = new MdeManager(logger);
this.rcc = new RedisCacheClient(this.getConfigValueAsString("redis.host","localhost")); this.rcc = new RedisCacheClient(this.getConfigValueAsString("redis.host","localhost"));
} }
......
...@@ -2,19 +2,21 @@ package logic; ...@@ -2,19 +2,21 @@ package logic;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler; import common.JsonHandler;
import defs.Constants;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.BaseAdapter; import logic.adapter.BaseAdapter;
//import logic.adapter.HttpAdapter.model.DataHttpAdapter; //import logic.adapter.HttpAdapter.model.DataHttpAdapter;
import logic.adapter.HttpAdapter.HttpAdapter; import logic.adapter.HttpAdapter.HttpAdapter;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.repository.AdaptersRepository; import logic.adapter.repository.AdaptersRepository;
import logic.service.model.Action; import logic.service.model.Action;
import logic.service.model.Api; import logic.service.model.Api;
import logic.service.model.Service;
import logic.service.repository.ServicesRepository; import logic.service.repository.ServicesRepository;
import microservice.RequestContext; import microservice.RequestContext;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import microservice.types.BaseRestResponse; import microservice.types.BaseRestResponse;
import rx.functions.Actions; import util.Utils;
import util.MDEResult;
import java.util.List; import java.util.List;
...@@ -24,6 +26,7 @@ import java.util.List; ...@@ -24,6 +26,7 @@ import java.util.List;
public class MdeManager { public class MdeManager {
private static final String DS_IP_ADDRESS = System.getProperty("ds.IpAddress", "localhost:8080"); private static final String DS_IP_ADDRESS = System.getProperty("ds.IpAddress", "localhost:8080");
public static JsonNode jsonPatchAddLocationUID;
private ILogger logger; private ILogger logger;
private AdaptersRepository adaptersRepository; private AdaptersRepository adaptersRepository;
private ServicesRepository servicesRepository; private ServicesRepository servicesRepository;
...@@ -31,6 +34,7 @@ public class MdeManager { ...@@ -31,6 +34,7 @@ public class MdeManager {
public MdeManager(ILogger logger) { public MdeManager(ILogger logger) {
try{ try{
jsonPatchAddLocationUID = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+"jsonPatchAddLocationUid.json");
this.logger = logger; this.logger = logger;
LoadServices(logger); LoadServices(logger);
loadAdapters(logger); loadAdapters(logger);
...@@ -49,42 +53,96 @@ public class MdeManager { ...@@ -49,42 +53,96 @@ public class MdeManager {
this.servicesRepository = servicesRepository; this.servicesRepository = servicesRepository;
} }
// example: GET ../mde/chicago/transportation/routes?key=gT2nciTKwRv6Jy5njqm8fe7LW // example: GET ../mde/api/v1/chicago/transportation/routes?key=gT2nciTKwRv6Jy5njqm8fe7LW
public BaseRestResponse doRead(RequestContext requestContext) { public BaseRestResponse doRead(RequestContext requestContext) {
BaseRestResponse brr=null; BaseRestResponse brr=null;
String serviceId = requestContext.params[0] +"." +requestContext.params[1]; String serviceId = requestContext.params[0] +"." +requestContext.params[1];
String apiId = requestContext.params[2]; String apiId = requestContext.params[2];
String error = null;
SimpleHttpResponse resp=null;
Api api= servicesRepository.getApi(serviceId,apiId); Api api= servicesRepository.getApi(serviceId,apiId);
List<Action> actions = api.getActions(); List<Action> actions = api.getActions();
// TODO: 7/18/16 currently handle one action only // TODO: 7/18/16 currently handle one action only
for(Action action : actions) if (actions.size()==0)
{ error = "failed to find adapter for: "+serviceId+"."+apiId;
BaseAdapter adapter = adaptersRepository.getAdapter(action.getAdapterId()); else {
if (adapter!=null) { for (Action action : actions) {
MDEResult mdeResult = adapter.activateCommand(requestContext,action.getApiOut()); BaseAdapter adapter = adaptersRepository.getAdapter(action.getAdapterId());
if (mdeResult.getSuccess()) { if (adapter != null) {// && adapter.getClass().isInstance(HttpAdapter.class)) {
brr = new BaseRestResponse(true, null); RequestParams requestParams = convertToRequestParams(requestContext);
JsonNode node = mdeResult.getJsonData().get("data"); resp = ((HttpAdapter) adapter).executeFlow(action.getApiOut(), requestParams);
String str = node.asText();
brr.objectNode = JsonHandler.getJsonNodeFromString(str); // else
}else{ // error = "failed to find adapter " + action.getAdapterId();
brr=new BaseRestResponse(false, mdeResult.getError());
break;//currently only one action
} }
} }
else
brr=new BaseRestResponse(false, "failed to find adapter "+ action.getAdapterId());
} }
if (brr==null)
brr=new BaseRestResponse(false, "failed to activate command");
return brr; return convertToBaseRestResponse(resp,error);
}
//one the parameter assumed to be null. if resp has a valid value it is converted,
//else if error is valid new BestRestResponse is created with this error
private BaseRestResponse convertToBaseRestResponse(SimpleHttpResponse resp, String error) {
BaseRestResponse baseRestResponse=null;
String errorContent=null;
if (resp!=null) {
if (resp.getStatusCode() == 200) {
baseRestResponse = new BaseRestResponse(true, null);
String content = resp.getContent();
baseRestResponse.objectNode = JsonHandler.getJsonNodeFromString(content);
} else {
errorContent = resp.getContent();
baseRestResponse = new BaseRestResponse(false, "Error: " + resp.getStatusCode() + ((errorContent != null) ? errorContent : ""));
}
}
else
baseRestResponse=new BaseRestResponse(false,error);
return baseRestResponse;
} }
private RequestParams convertToRequestParams(RequestContext requestContext) {
RequestParams requestParams = new RequestParams();
requestParams.setParams(requestContext.params);
requestParams.setQueryParameters(requestContext.queryParameters);
requestParams.setMethod(requestContext.enumCrudMethod);
return requestParams;
}
public BaseRestResponse doCreate(RequestContext requestContext) { public BaseRestResponse doCreate(RequestContext requestContext) {
return new BaseRestResponse(false, "method " +Thread.currentThread().getStackTrace()[1].getMethodName()+ "not implemented yet"); BaseRestResponse brr=null;
String serviceId = requestContext.params[0] +"." +requestContext.params[1];
String apiId = requestContext.params[2];
String error = null;
SimpleHttpResponse resp=null;
Api api= servicesRepository.getApi(serviceId,apiId);
List<Action> actions = api.getActions();
// TODO: 7/18/16 currently handle one action only
if (actions.size()==0)
error = "failed to find adapter for: "+serviceId+"."+apiId;
else {
for (Action action : actions) {
BaseAdapter adapter = adaptersRepository.getAdapter(action.getAdapterId());
if (adapter != null) {// && adapter.getClass().isInstance(HttpAdapter.class)) {
RequestParams requestParams = convertToRequestParams(requestContext);
resp = ((HttpAdapter) adapter).executeFlow(action.getApiOut(), requestParams);
// else
// error = "failed to find adapter " + action.getAdapterId();
break;//currently only one action
}
}
}
return convertToBaseRestResponse(resp,error);
} }
public BaseRestResponse doUpdate(RequestContext requestContext) { public BaseRestResponse doUpdate(RequestContext requestContext) {
......
package logic.adapter; package logic.adapter;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.loader.IAdapterLoader; import logic.adapter.loader.IAdapterLoader;
import logic.adapter.model.BaseApi; import logic.adapter.model.*;
import logic.adapter.model.DataModel;
import logic.adapter.model.ResponseAction;
import logic.adapter.normalizer.INormalizer;
import logic.adapter.normalizer.JsonConverterNormalizer;
import logic.adapter.normalizer.Xml2jsonNormalizer;
import microservice.MicroserviceClient;
import microservice.RequestContext;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import util.MDEResult;
import util.Utils; import util.Utils;
import java.util.ArrayList; import java.io.IOException;
import java.util.HashMap; import java.lang.reflect.TypeVariable;
import java.util.LinkedHashMap;
import static util.Utils.SORTED_MAPPER;
/** /**
* Created by eli on 13/06/16. * Created by eli on 13/06/16.
*/ */
public abstract class BaseAdapter<T extends BaseApi> { public abstract class BaseAdapter<T extends BaseFlow, TypeIn/*must be as TypeIn of BaseFlow*/,
protected String adapterId = null; TypeOut/*must be as TypeOut of BaseFlow*/> {
protected DataModel<T> dataModel ; private String adapterId = null;
protected ILogger logger = null; private AdapterModel<T> model;
protected IAdapterLoader loader = null;
//iteration - order of insertion
private LinkedHashMap<String, INormalizer> normalizerMap = new LinkedHashMap<>();
protected LinkedHashMap<String, INormalizer> getNormalizerMap() { public ILogger getLogger() {
return normalizerMap; return logger;
} }
//apiClass is "T.class" private ILogger logger = null;
protected BaseAdapter(ILogger logger, String id, IAdapterLoader loader, Class<T> apiClass) throws Exception { private IAdapterLoader loader = null;
//flowClass is "T.class"
protected BaseAdapter(ILogger logger, String id, IAdapterLoader loader, Class<T> flowClass) throws Exception {
this.logger =logger; this.logger =logger;
this.adapterId = id; this.adapterId = id;
this.loader = loader; this.loader = loader;
this.loadDataModel(apiClass); this.loadModel(flowClass);
//foreach api go trough each configured "responseAction" and create one and only one
//instance of normalizer (for this adapter). for the combination "$action.$type"
//for example: for normalize.xml2json create one normalizer (Xml2jsonNormalizer)
for (BaseApi api : dataModel.getApiList()) {
for (ResponseAction action : api.getResponseActions()){
switch(action.getAction()){
case "normalize":
switch (action.getType()){
case "xml2json":
Xml2jsonNormalizer xml2jsonNormalizer = new Xml2jsonNormalizer();
normalizerMap.putIfAbsent("normalize.xml2json", xml2jsonNormalizer);
break;
case "jsonConverter":
JsonConverterNormalizer jsonConverterNormalizer= new JsonConverterNormalizer();
normalizerMap.putIfAbsent("normalize.jsonConverter", jsonConverterNormalizer);
}
break;
}
}
}
}
private void loadDataModel(Class<T> apiClass) {
JsonNode jsonAdapterData = loader.load(adapterId);
this.dataModel = (DataModel<T>) Utils.getNodeAsParametricTypeObject(jsonAdapterData, DataModel.class, apiClass);
} }
public DataModel<T> getDataModel(){ return dataModel;} public AdapterModel<T> getModel() {
return model;
}
abstract public MDEResult activateCommand(RequestContext requestContext, String apiId); private void loadModel(Class<T> flowClass) throws IOException {
protected INormalizer getNormalizer(String actionType){ JsonNode jsonAdapterData = loader.load(adapterId);
return normalizerMap.get(actionType); this.model = (AdapterModel<T>) Utils.getNodeAsParametricTypeObject(jsonAdapterData, AdapterModel.class, flowClass);
if (model.isValid())
buildModel(model);
} }
protected abstract void buildModel(AdapterModel<T> model);
protected abstract TypeOut executeFlow(String flowId, TypeIn input);
} }
package logic.adapter.HttpAdapter;
/**
* Created by eli on 11/7/16.
*/
public class ErrorLoginException extends Exception {
/**
* Constructs a new exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public ErrorLoginException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ErrorLoginException(String message) {
super(message);
}
}
package logic.adapter.HttpAdapter;
import http.simpleHttpClient.SimpleHttpClient;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.model.AuthenticationClient;
import logic.adapter.HttpAdapter.model.CredentialDetails;
import logic.adapter.HttpAdapter.model.CredentialResponse;
import util.Utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
/**
* Created by eli on 11/7/16.
*/
public class OAuth2Client implements AuthenticationClient{
public CredentialDetails getClientSecrets() {
return clientSecrets;
}
public CredentialResponse getCredential() {
return credential;
}
private CredentialDetails clientSecrets = null;
private CredentialResponse credential = null;
private SimpleHttpClient httpClient = null;
private SimpleHttpRequest request = null;
// private SimpleHttpResponse httpResp = null;
OAuth2Client(CredentialDetails credentialDetails) throws UnsupportedEncodingException, ErrorLoginException {
httpClient = new SimpleHttpClient();
httpClient.Initialize(100);
clientSecrets = credentialDetails;
request = createTokenRequest();
SimpleHttpResponse resp = this.login();
if (resp.getStatusCode()!= 200) {
if (resp.getContent()!=null )
throw new ErrorLoginException("status resp code: " + resp.getStatusCode()+", content: "+ resp.getContent());
}
}
public OAuth2Client(CredentialDetails clientSecrets, CredentialResponse credential) throws UnsupportedEncodingException, ErrorLoginException {
SimpleHttpResponse resp=null;
httpClient = new SimpleHttpClient();
httpClient.Initialize(100);
this.clientSecrets = clientSecrets;
this.credential = credential;
request = createTokenRequest();
if (getToken() == null) {
resp = this.login();
if (resp.getContent()!=null )
throw new ErrorLoginException("status resp code: " + resp.getStatusCode()+", content: "+ resp.getContent());
}
}
//if login was succeful (200 ok) and the response parsed successfuly the
// field credential holds a valid token. otherwise credential is null and cant be used
@Override
public SimpleHttpResponse login() throws ErrorLoginException, UnsupportedEncodingException {
SimpleHttpResponse httpResp=null;
try {
httpResp = httpClient.processRequest(request);
System.out.println("status code is: " + httpResp.getStatusCode());
return parseResponse(httpResp);
} catch (UnsupportedEncodingException e) {
if (httpResp != null)
throw new UnsupportedEncodingException("Authentication failed: status code is: " + httpResp.getStatusCode() + "Error message: " + e);
else
throw new UnsupportedEncodingException("Authentication failed, Error message: " + e);
}
}
public String getToken() {
if (credential!= null)
return credential.getToken();
else return null;
}
private SimpleHttpResponse parseResponse(SimpleHttpResponse httpResp) throws ErrorLoginException{
if (httpResp != null ) {
if (httpResp.getStatusCode() == 200) {
try {
credential = (CredentialResponse) Utils.readObjectFromString1(httpResp.getContent(), CredentialResponse.class);
return httpResp;
} catch (IOException e) {
throw new ErrorLoginException("Login failed: authentication response status code is:" + "200", e);
}
}
return httpResp;
}
else
throw new ErrorLoginException("Login failed: authentication response is null");
}
// private final static SimpleHttpRequest getTokenRequest = createTokenRequest();
// private final static String UAA_DOMAIN = "9deacc64-7c53-4790-9a6c-c9de0fdebcdf.predix-uaa.run.aws-usw02-pr.ice.predix.io/oauth/token";
// private final static String CLIENT_ID = "ipgallery";
// private final static String CLIENT_SECRET = "ipgallery";
private SimpleHttpRequest createTokenRequest() {
SimpleHttpRequest request = new SimpleHttpRequest();
String clientId = clientSecrets.getClientId();
String clientSecret = clientSecrets.getClientSecret();
String uaaDomain = clientSecrets.getUaa();
request.setProtocol("https");
request.setMethod(SimpleHttpRequest.Method.POST);
request.setDomain(uaaDomain);
request.addHeader("Pragma", "no-cache");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Cache-Control", "no-cache");
String str = clientId.concat(":").concat(clientSecret);
byte[] encodedBytes = Base64.getEncoder().encode(str.getBytes());
String authorization = "Basic " + new String(encodedBytes);
request.addHeader("Authorization", authorization);
request.setContent("client_id="+clientId+"&grant_type=client_credentials");
return request;
}
}
package logic.adapter.HttpAdapter;
import microservice.defs.Enums;
import java.util.Deque;
import java.util.Map;
/**
* Created by eli on 11/29/16.
*/
public class RequestParams {
public String[] getParams() {
return params;
}
public void setParams(String[] params) {
this.params = params;
}
public Map<String, Deque<String>> getQueryParameters() {
return queryParameters;
}
public void setQueryParameters(Map<String, Deque<String>> queryParameters) {
this.queryParameters = queryParameters;
}
public Enums.EnumCrudMethod getEnumCrudMethod() {
return enumCrudMethod;
}
public void setMethod(Enums.EnumCrudMethod enumCrudMethod) {
this.enumCrudMethod = enumCrudMethod;
}
public Map<String, String> getHeadersMap() {
return headersMap;
}
public void setHeadersMap(Map<String, String> headersMap) {
this.headersMap = headersMap;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
private String[] params = null;
private Map<String, Deque<String>> queryParameters = null;
private Enums.EnumCrudMethod enumCrudMethod;
private Map<String, String> headersMap = null;
private String content;
public RequestParams() {}
public String getQueryParameter(String paramName) {
return (((this.queryParameters != null) && (this.queryParameters.containsKey(paramName)))?
(String)((Deque)this.queryParameters.get(paramName)).getFirst():null);
}
}
package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.HttpAdapter;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.action.ActionsList;
import logic.adapter.action.BaseAction;
import util.Utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by eli on 11/27/16.
*/
public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> {
@JsonProperty("actionsInput")
private String actionsInput;
@JsonProperty("actions")
private List<BaseAction> actions = new ArrayList<>();
@JsonCreator
public HttpContentActions(@JsonProperty("actionsInput") String actionsInput, @JsonProperty("actions") List<BaseAction> actions) {
this.actionsInput = actionsInput;
this.actions = actions;
}
public boolean isEmptyActionsValid() {
return isEmptyActionsValid;
}
public void setEmptyActionsValid(boolean emptyActionsValid) {
isEmptyActionsValid = emptyActionsValid;
}
private boolean isEmptyActionsValid = false;
/**
*
* @return
* The actionsInput
*/
@JsonProperty("actionsInput")
public String getActionsInput() {
return actionsInput;
}
/**
*
* @param actionsInput
* The actionsInput
*/
@JsonProperty("actionsInput")
public void setActionsInput(String actionsInput) {
this.actionsInput = actionsInput;
}
/**
*
* @return
* The actions
*/
@JsonProperty("actions")
public List<BaseAction> getActions() {
return actions;
}
/**
*
* @param actions
* The actions
*/
@JsonProperty("actions")
public void setActions(List<BaseAction> actions) {
this.actions = actions;
}
// @Override
public boolean isValid() {
if (actionsInput.equals("CONTENT")) {
if (actions.size() != 0)
return actions.stream().anyMatch(action -> !action.isValid());
else
return this.isEmptyActionsValid();
}
else
return false;
}
public void setRunTimeHttpRequest(RequestParams inRequestParams) {
this.runTimeHttpRequest = inRequestParams;
}
private RequestParams runTimeHttpRequest;
// @Override
public SimpleHttpResponse executeActions(SimpleHttpResponse input) throws Exception {
String content = input.getContent();
JsonNode node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class);
List<BaseAction> actions=getActions();
for (BaseAction action : actions)
{
if (action.getType().equals(SimpleHttpAction.TYPE)) {
SimpleHttpResponse resp = (SimpleHttpResponse) action.apply(runTimeHttpRequest);
if (resp.getStatusCode()!= 200)
{
return new SimpleHttpResponse(500,"failed onSuccess.executeActions.httpAction with error:" +resp.getStatusCode() );
}
content = resp.getContent();
node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class);
}
//assumed that after extractValueAction
else if (HttpAdapter.myTypeOf(action).equals("WebSocketAction")){
Map<String,String > runTimeParams = new HashMap<>();
if (node!=null && node.isTextual()) runTimeParams.put("webSocket", node.asText());
action.setRunTimeParameters(runTimeParams);
SimpleHttpResponse resp = (SimpleHttpResponse) action.apply(runTimeHttpRequest);
}
else //JsonNodeAction.class
{
node = (JsonNode)action.apply(node);
if (node==null)
return new SimpleHttpResponse(500,"failed onSuccess.executeActions.JsonAction " );
}
}
return new SimpleHttpResponse(200,node.toString());
// return input
}
}
package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.model.OnResponse;
import logic.adapter.action.ActionsList;
import logic.adapter.action.BaseAction;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/27/16.
*/
public class OnHttpResponse{ //extends OnResponse<SimpleHttpResponse> {
public HttpContentActions getOnSuccess() {
return onSuccess;
}
public HttpContentActions getOnError() {
return onError;
}
@JsonProperty("onSuccess")
private HttpContentActions onSuccess;
@JsonProperty("onError")
private HttpContentActions onError;
@JsonCreator
public OnHttpResponse(@JsonProperty("onSuccess") HttpContentActions onSuccess, @JsonProperty("onError") HttpContentActions onError) {
this.onSuccess = onSuccess;
this.onError = onError;
}
public SimpleHttpResponse execute(SimpleHttpResponse actionResp) {
if (actionResp.getStatusCode() == 200) {
try {
return onSuccess.executeActions(actionResp);
} catch (Exception e) {
return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e);
}
} else {
try {
return onError.executeActions(actionResp);
} catch (Exception e) {
return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e);
}
}
}
public boolean isValid() {
return true;
}
}
package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import http.simpleHttpClient.SimpleHttpClient;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams;
import logic.adapter.HttpAdapter.model.HttpRequestActionParams;
import logic.adapter.HttpAdapter.model.NameValueParam;
import logic.adapter.action.BaseAction;
import util.HttpRequestResolver;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;
/**
* Created by eli on 11/17/16.
*/
public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,RequestParams,SimpleHttpResponse>{
public static final String TYPE = "SimpleHttpAction";
// private ConfigHttpRequestParams adapterHttpParams=null;
// private SimpleHttpClient httpClient =null;
// private OAuth2Client oauth2Client =null;
// public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams,
// SimpleHttpClient httpClient,
// OAuth2Client oauth2Client) {
// this.adapterHttpParams = adapterHttpParams;
// this.httpClient = httpClient;
// this.oauth2Client = oauth2Client;
// }
/**
*
* @param params - the type of params is HttpRequestActionParams
*/
@JsonCreator
public SimpleHttpAction(@JsonProperty("params") HttpRequestActionParams params) {
super(params);
}
@Override
public String getType() {
return SimpleHttpAction.TYPE;
}
@Override
public void build() {
}
/**
* Applies this function to the given argument.
*
* @param requestParams the function argument
* @return the function result
*/
@Override
public SimpleHttpResponse apply(RequestParams requestParams) {
//if not null authentication required
SimpleHttpResponse authResp,resp;
SimpleHttpRequest httpRequest;
RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput();
//if authentication not needed or token already exist
httpRequest = buildHttpRequest(inRequestParams);
try {
resp = httpClient.processRequest(httpRequest);
if (resp.getStatusCode()==401 || resp.getStatusCode() == 403){
{
//if authentication required
if (oauth2Client!=null) {
resp = oauth2Client.login();
if (resp.getStatusCode() == 200) {
HttpRequestResolver.replaceToken(httpRequest, oauth2Client.getToken());
resp = httpClient.processRequest(httpRequest);
}
}
}
}
} catch (UnsupportedEncodingException e) {
resp = new SimpleHttpResponse(500, "failed to proccess http request with error: "+e);
} catch (ErrorLoginException e) {
resp = new SimpleHttpResponse(500, "authentication failed with error "+e);
}
return resp;
}
private SimpleHttpRequest buildHttpRequest(RequestParams inRequestParams) {
SimpleHttpRequest request = new HttpRequestResolver().createResolvedRequest(inRequestParams,
adapterHttpParams,
getParams(),
((oauth2Client != null)?oauth2Client.getToken():null),
getRunTimeParameters());
return request;
}
}
package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.neovisionaries.ws.client.WebSocketException;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.model.CredentialResponse;
import logic.adapter.HttpAdapter.model.HttpRequestActionParams;
import logic.adapter.action.BaseAction;
import logic.webSocket.OnEventDetails;
import logic.webSocket.WebSocketManger;
import util.HttpRequestResolver;
import util.Utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by eli on 12/4/16.
*/
/**
* Created by eli on 11/17/16.
*/
public class WebSocketAction extends BaseAction<WebSocketActionParams ,RequestParams,SimpleHttpResponse> {
public static final String TYPE = "WebSocketAction";
@JsonIgnore
private WebSocketManger webSocketManger;
@JsonIgnore
private RequestParams httpRequestParams;
/**
*
* @param params - the type of params is HttpRequestActionParams
*/
@JsonCreator
public WebSocketAction(@JsonProperty("params") WebSocketActionParams params) {
super(params);
}
@Override
public String getType() {
return logic.adapter.HttpAdapter.action.WebSocketAction.TYPE;
}
@Override
public void build() {
}
/**
* Applies this function to the given argument.
*
* @param requestParams the function argument
* @return the function result
*/
@Override
public SimpleHttpResponse apply(RequestParams requestParams) {
OnEventDetails details=null;
RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput();
String[] params = inRequestParams.getParams();
String mdeKey = params[3];//id
String uid = params[4];//uid
String httpPayload = inRequestParams.getContent();
try {
details = (OnEventDetails) Utils.readObjectFromString1(httpPayload, OnEventDetails.class);
} catch (IOException e) {
e.printStackTrace();
return new SimpleHttpResponse(500, "Failed to read Request payload OnEventDetails");
}
Map<String, String> runTimeParameters = getRunTimeParameters();
String webSocket=null;
if (runTimeParameters.containsKey("webSocket")){
webSocket = runTimeParameters.get("webSocket");
}
if (webSocket == null)
return new SimpleHttpResponse(500, "Failed to extract web socket url");
try {
webSocketManger.connect(mdeKey,uid,webSocket,details);
} catch (UnsupportedEncodingException e) {
return new SimpleHttpResponse(500, "failed to connect to webSocket with error: "+e);
} catch (ErrorLoginException e) {
return new SimpleHttpResponse(500, "failed to connect to webSocket with error: "+e);
} catch (WebSocketException e) {
return new SimpleHttpResponse(500, "failed to connect to webSocket with error: "+e);
}
if (webSocketManger.isConnected(mdeKey,uid)){
return new SimpleHttpResponse(200,null);
}
else
return new SimpleHttpResponse(500, "failed to connect to, internal error" );
}
// private SimpleHttpRequest buildHttpRequest(RequestParams inRequestParams) {
//
//
// SimpleHttpRequest request = new HttpRequestResolver().createResolvedRequest(inRequestParams,
// adapterHttpParams,
// getParams(),
// ((oauth2Client != null)?oauth2Client.getToken():null),
// getRunTimeParameters());
//
// return request;
// }
}
package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonProperty;
import logic.adapter.HttpAdapter.model.NameValueParam;
import logic.adapter.model.BaseActionParams;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 12/4/16.
*/
public class WebSocketActionParams extends BaseActionParams{
@JsonProperty("headers")
private List<NameValueParam> headers = new ArrayList<>();
@Override
public String getId() {
return null;
}
@Override
public boolean isValid() {
return true;
}
}
package logic.adapter.HttpAdapter.model;
import http.simpleHttpClient.SimpleHttpResponse;
/**
* Created by eli on 11/7/16.
*/
public interface AuthenticationClient {
SimpleHttpResponse login() throws Exception;
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import logic.adapter.model.ModelValidator;
/**
* Created by eli on 11/16/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"type",
"credential"
})
public class AuthenticationDetails implements ModelValidator{
@JsonProperty("type")
private String type;
@JsonProperty("credential")
private CredentialDetails credential;
/**
*
* @return
* The type
*/
@JsonProperty("type")
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The credential
*/
@JsonProperty("credential")
public CredentialDetails getCredential() {
return credential;
}
/**
*
* @param credential
* The credential
*/
@JsonProperty("credential")
public void setCredential(CredentialDetails credential) {
this.credential = credential;
}
@Override
public boolean isValid() {
return (type.equals("oauth2") && credential.isValid());
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client;
/**
* Created by eli on 11/22/16.
*/
public abstract class BaseOperationParams {
public abstract void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams,
SimpleHttpClient httpClient,
OAuth2Client oauth2Client);
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import logic.adapter.model.BaseAdapterConfig;
import logic.adapter.model.ModelValidator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/16/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"baseUrl",
"basePath",
"headers"
})
public class ConfigHttpRequestParams implements ModelValidator {
@JsonProperty("baseUrl")
private String baseUrl;
@JsonProperty("basePath")
private String basePath;
@JsonProperty("headers")
private List<NameValueParam> headers = new ArrayList<>();
/**
*
* @return
* The baseUrl
*/
@JsonProperty("baseUrl")
public String getBaseUrl() {
return baseUrl;
}
/**
*
* @param baseUrl
* The baseUrl
*/
@JsonProperty("baseUrl")
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
*
* @return
* The basePath
*/
@JsonProperty("basePath")
public String getBasePath() {
return basePath;
}
/**
*
* @param basePath
* The basePath
*/
@JsonProperty("basePath")
public void setBasePath(String basePath) {
this.basePath = basePath;
}
/**
*
* @return
* The headers
*/
@JsonProperty("headers")
public List<NameValueParam> getHeaders() {
return headers;
}
/**
*
* @param headers
* The headers
*/
@JsonProperty("headers")
public void setHeaders(List<NameValueParam> headers) {
this.headers = headers;
}
@Override
public boolean isValid() {
return true;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import logic.adapter.model.ModelValidator;
/**
* Created by eli on 11/16/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"uaa",
"clientId",
"clientSecret"
})
public class CredentialDetails implements ModelValidator{
@JsonProperty("uaa")
private String uaa;
@JsonProperty("clientId")
private String clientId;
@JsonProperty("clientSecret")
private String clientSecret;
/**
*
* @return
* The uaa
*/
@JsonProperty("uaa")
public String getUaa() {
return uaa;
}
/**
*
* @param uaa
* The uaa
*/
@JsonProperty("uaa")
public void setUaa(String uaa) {
this.uaa = uaa;
}
/**
*
* @return
* The clientId
*/
@JsonProperty("clientId")
public String getClientId() {
return clientId;
}
/**
*
* @param clientId
* The clientId
*/
@JsonProperty("clientId")
public void setClientId(String clientId) {
this.clientId = clientId;
}
/**
*
* @return
* The clientSecret
*/
@JsonProperty("clientSecret")
public String getClientSecret() {
return clientSecret;
}
/**
*
* @param clientSecret
* The clientSecret
*/
@JsonProperty("clientSecret")
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public boolean isValid() {
return (uaa != null && !uaa.equals("") &&
clientId != null && !clientId.equals("") &&
clientSecret != null && !clientSecret.equals("")) ? true : false;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import http.simpleHttpClient.SimpleHttpRequest;
import java.util.Base64;
/**
* Created by eli on 11/6/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"access_token",
"token_type",
"expires_in",
"scope",
"jti"
})
public class CredentialResponse {
@JsonProperty("access_token")
private String token = null;
@JsonProperty("token_type")
private String tokenType = null;
@JsonProperty("expires_in")
private Integer expiresInSec = null;
@JsonProperty("scope")
private String scope = null;
@JsonProperty("jti")
private String jti = null;
private int responseCode;
public String getToken() { return token;}
public void setToken(String token) {this.token = token;}
public String getTokenType() { return tokenType;}
public void setTokenType(String tokenType) { this.tokenType = tokenType; }
public Integer getExpiresInSec() {return expiresInSec;}
public void setExpiresInSec(Integer expiresInSec) {this.expiresInSec = expiresInSec;}
public String getScope() {
return scope;
}
public void setScope(String scope) {this.scope = scope;}
public String getJti() {
return jti;
}
public void setJti(String jti) {this.jti = jti;}
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int respCode) {
this.responseCode = respCode;
}
}
package logic.adapter.HttpAdapter.model;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 13/06/16.
*/
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import logic.adapter.model.BaseApi;
import logic.adapter.model.ResponseAction;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"method",
"path",
"queryParams",
"headers",
"content",
"responseActions"})
public class DataHttpApi extends BaseApi{
@JsonProperty
private String method = null;
@JsonProperty
private String path = null;
@JsonProperty
private List<NameValueParam> queryParams = null;
@JsonProperty
private List<NameValueParam> headers = null;
@JsonProperty
private String content = null;
@JsonCreator
public DataHttpApi(@JsonProperty("id") String id,
@JsonProperty("responseActions") ArrayList<ResponseAction> responseActions) {
super(id, responseActions);
}
@Override
protected void setCmd() {
switch (method){
case "POST":
setCmd(eCommand.CREATE);
break;
case "GET":
setCmd(eCommand.READ);
break;
case "PUT":
setCmd(eCommand.UPDATE);
break;
case "DELETE":
setCmd(eCommand.DELETE);
break;
}
}
@JsonIgnore
public String toString() {
StringBuilder sb=new StringBuilder("id="+getId()+", eCmd="+geteCmd().toString()+", method=" + method );
if (path!=null) sb.append(", path=" +path);
if (queryParams!=null) sb.append(", queryParams=" + queryParams.toString());
if (headers!=null) sb.append(", headers=" + headers.toString());
if (content!=null) sb.append(", content=" +content);
return sb.toString();
}
public List<NameValueParam> getHeaders() {
return headers;
}
public void setHeaders(ArrayList<NameValueParam> headers) {
this.headers = headers;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
setCmd();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<NameValueParam> getQueryParams() {
return queryParams;
}
public void setQueryParams(ArrayList<NameValueParam> queryParams) {
this.queryParams = queryParams;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package logic.adapter.HttpAdapter.model;
import java.util.function.Predicate;
/**
* Created by eli on 11/22/16.
*/
public abstract class FilterIntermediateOperation<TypeIn> extends IntermediateOperation<FilterOperationParams, Predicate<TypeIn>> {
public FilterIntermediateOperation(FilterOperationParams operationParams) {
super(operationParams);
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.function.Predicate;
/**
* Created by eli on 11/22/16.
*/
public class FilterJsonOperation extends FilterIntermediateOperation<JsonNode> {
public final static String TYPE="FilterJsonOperation";
@JsonCreator
public FilterJsonOperation(@JsonProperty("operationParams") FilterOperationParams operationParams) {
super(operationParams);
}
@Override
protected Predicate<JsonNode> buildFunc() {
return null;
}
@Override
public String getType() {
return FilterJsonOperation.TYPE;
}
}
package logic.adapter.HttpAdapter.model;
/**
* Created by eli on 11/22/16.
*/
public abstract class FilterOperationParams extends BaseOperationParams{
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.function.Predicate;
/**
* Created by eli on 11/22/16.
*/
public class FilterStringOperation extends FilterIntermediateOperation<String> {
public final static String TYPE="FilterStringOperation";
@JsonCreator
public FilterStringOperation(@JsonProperty FilterOperationParams operationParams) {
super(operationParams);
}
@Override
protected Predicate<String> buildFunc() {
return null;
}
@Override
public String getType() {
return FilterStringOperation.TYPE;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import logic.adapter.model.BaseAdapterConfig;
/**
* Created by eli on 11/16/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"configHttpRequestParams",
"authentication"
})
public class HttpAdapterConfig extends BaseAdapterConfig {
@JsonProperty("configHttpRequestParams")
private ConfigHttpRequestParams configHttpRequestParams;
@JsonProperty("authentication")
private AuthenticationDetails authentication;
public boolean isAuthenticationRequired() { return authentication.isValid(); }
/**
*
* @return
* The configHttpRequestParams
*/
@JsonProperty("configHttpRequestParams")
public ConfigHttpRequestParams getConfigHttpRequestParams() {
return configHttpRequestParams;
}
/**
*
* @param configHttpRequestParams
* The configHttpRequestParams
*/
@JsonProperty("configHttpRequestParams")
public void setConfigHttpRequestParams(ConfigHttpRequestParams configHttpRequestParams) {
this.configHttpRequestParams = configHttpRequestParams;
}
/**
*
* @return
* The authentication
*/
@JsonProperty("authentication")
public AuthenticationDetails getAuthentication() {
return authentication;
}
/**
*
* @param authentication
* The authentication
*/
@JsonProperty("authentication")
public void setAuthentication(AuthenticationDetails authentication) {
this.authentication = authentication;
}
@Override
public boolean isValid() {
return (configHttpRequestParams.isValid() && authentication.isValid());
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import http.simpleHttpClient.SimpleHttpRequest;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.action.OnHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.HttpAdapter.action.WebSocketAction;
import logic.adapter.action.BaseAction;
import logic.adapter.model.BaseFlow;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/17/16.
*/
public class HttpFlow extends BaseFlow{
@JsonIgnore
private List<SimpleHttpAction> httpActions = new ArrayList<>();
@JsonIgnore
private List<WebSocketAction> webSocketActions = new ArrayList<>();
@JsonIgnore
public boolean addHttpAction(SimpleHttpAction action) { return httpActions.add(action);}
@JsonIgnore
public boolean addWebSocketAction(WebSocketAction action) { return webSocketActions.add(action);}
@JsonCreator
public HttpFlow(@JsonProperty("action") SimpleHttpAction action,
@JsonProperty("onResponse") OnHttpResponse onResponse){
super(action, onResponse);
}
public void setRunTimeHttpRequest(RequestParams input) {
for (SimpleHttpAction action : httpActions){
action.setRunTimeInput(input);
}
for (WebSocketAction action : webSocketActions){
action.setRunTimeInput(input);
}
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import logic.adapter.model.BaseActionParams;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/17/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"httpMethod",
"path",
"queryParams",
"headers",
"content"
})
public class HttpRequestActionParams extends BaseActionParams {
@JsonProperty("id")
private String id;
@JsonProperty("httpMethod")
private String httpMethod;
@JsonProperty("path")
private String path;
@JsonProperty("queryParams")
private List<NameValueParam> queryParams = new ArrayList<>();
@JsonProperty("headers")
private List<NameValueParam> headers = new ArrayList<>();
@JsonProperty("content")
private Object content;
public HttpRequestActionParams() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @return The httpMethod
*/
@JsonProperty("httpMethod")
public String getHttpMethod() {
return httpMethod;
}
/**
* @param httpMethod The httpMethod
*/
@JsonProperty("httpMethod")
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
/**
* @return The path
*/
@JsonProperty("path")
public String getPath() {
return path;
}
/**
* @param path The path
*/
@JsonProperty("path")
public void setPath(String path) {
this.path = path;
}
/**
* @return The queryParams
*/
@JsonProperty("queryParams")
public List<NameValueParam> getQueryParams() {
return queryParams;
}
/**
* @param queryParams The queryParams
*/
@JsonProperty("queryParams")
public void setQueryParams(List<NameValueParam> queryParams) {
this.queryParams = queryParams;
}
/**
* @return The headers
*/
@JsonProperty("headers")
public List<NameValueParam> getHeaders() {
return headers;
}
/**
* @param headers The headers
*/
@JsonProperty("headers")
public void setHeaders(List<NameValueParam> headers) {
this.headers = headers;
}
/**
* @return The content
*/
@JsonProperty("content")
public Object getContent() {
return content;
}
/**
* @param content The content
*/
@JsonProperty("content")
public void setContent(Object content) {
this.content = content;
}
@Override
public boolean isValid() {
return true;
}
}
package logic.adapter.HttpAdapter.model;
import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client;
import java.util.function.Function;
/**
* Created by eli on 11/22/16.
*/
public abstract class IntermediateOperation<TypeParams extends BaseOperationParams, TypeFunc>
extends Operation<TypeParams> {
public IntermediateOperation(TypeParams operationParams) {
super(operationParams);
this.func=buildFunc();
}
protected abstract TypeFunc buildFunc();
public abstract String getType();
public TypeFunc getFunc() {
return func;
}
public void setAdapterReferences(ConfigHttpRequestParams configHttpRequestParams,
SimpleHttpClient httpClient,
OAuth2Client oAuth2Client){
getOperationParams().setAdapterReferences(configHttpRequestParams,httpClient,oAuth2Client );
}
private TypeFunc func;
}
package logic.adapter.HttpAdapter.model;
import java.util.function.Function;
import java.util.stream.Stream;
/**
* Created by eli on 11/22/16.
*/
public abstract class MapIntermediateOperation<TypeIn, TypeOut> extends IntermediateOperation<MapOperationParams, Function<TypeIn,TypeOut>>
{
public static final String TYPE = "MapIntermediateOperation";
public MapIntermediateOperation(MapOperationParams operationParams) {
super(operationParams);
}
@Override
public String getType() {
return MapIntermediateOperation.TYPE;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.action.JsonNodeAction;
import util.Utils;
import java.util.function.Function;
/**
* Created by eli on 11/22/16.
*/
public class MapJsonToJsonOperation extends MapIntermediateOperation<JsonNode, JsonNode> {
@JsonCreator
public MapJsonToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams) {
super(operationParams);
}
@Override
protected Function<JsonNode, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (node) -> {
SimpleHttpResponse resp;
try {
int end_index = getOperationParams().getAction().toString().indexOf('@');
String type=getOperationParams().getAction().toString().substring(0,end_index);
int startIndex = type.lastIndexOf(".");
startIndex++;
type = type.substring(startIndex,end_index);
if (type.equals("SimpleHttpAction")) {
SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction();
//assumed that the action holds its input already, and use it
resp = httpAction.apply(null);
if (resp.getStatusCode()!=200)
throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() );
return JsonHandler.getJsonNodeFromObject(resp.getContent());
}
//assumed JsonNodeAction.class
//else if(getOperationParams().getAction().getClass().isInstance(JsonNodeAction.class)) {
else{
JsonNodeAction JsonAction = (JsonNodeAction)getOperationParams().getAction();
return (JsonNode)JsonAction.apply(node);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("MapJsonToJsonOperation failed with error "+ e);
}
return null;
};
return ret;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.action.JsonNodeAction;
import java.util.function.Function;
/**
* Created by eli on 11/22/16.
*/
public class MapJsonToStringOperation extends MapIntermediateOperation<JsonNode, JsonNode> {
@JsonCreator
public MapJsonToStringOperation(@JsonProperty("operationParams") MapOperationParams operationParams) {
super(operationParams);
}
@Override
protected Function<JsonNode, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (node) -> {
SimpleHttpResponse resp;
try {
//in this case assumed that the action get and return JsonNode!!!!! no else section
if(!getOperationParams().getAction().getClass().isInstance(SimpleHttpAction.class)) {
JsonNodeAction JsonAction = (JsonNodeAction)getOperationParams().getAction();
JsonNode transformedNode = (JsonNode)JsonAction.apply(node);
return transformedNode;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("MapJsonToJsonOperation failed with error "+ e);
}
return null;
};
return ret;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.*;
import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.action.BaseAction;
import logic.adapter.model.BaseActionParams;
import java.util.HashMap;
import java.util.Map;
/**
* Created by eli on 11/22/16.
*/
public class MapOperationParams extends BaseOperationParams{
@JsonCreator
public MapOperationParams(@JsonProperty("action") BaseAction action) {
this.action = action;
}
public BaseAction getAction() {
return action;
}
private BaseAction action;
@JsonIgnore
private Map<String, String> additionalProperties = new HashMap<String, String>();
@JsonAnyGetter
public Map<String, String> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
}
@Override
public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams,
SimpleHttpClient httpClient,
OAuth2Client oauth2Client) {
action.setAdapterReferences(adapterHttpParams, httpClient, oauth2Client);
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.action.JsonNodeAction;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* Created by eli on 11/22/16.
*/
public class MapStringToJsonOperation extends MapIntermediateOperation<JsonNode, JsonNode> {
@JsonCreator
public MapStringToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams) {
super(operationParams);
}
@Override
protected Function<JsonNode, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (str) -> {
SimpleHttpResponse resp;
String last;
try {
//currently support only httpAction
if (getOperationParams().getAction().getType().equals(SimpleHttpAction.TYPE)) {
SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction();
Map<String,String> parameters = getOperationParams().getAdditionalProperties();
Map<String,String> convertedParameters = new HashMap<>();
for (Map.Entry<String,String> parameter:
parameters.entrySet()) {
if (parameter.getValue().equals("lastToken")) {
String str1 = str.asText();
last = str1.substring(str1.lastIndexOf('/') + 1);
convertedParameters.put(parameter.getKey(), last);
}
else
convertedParameters.put(parameter.getKey(), parameter.getValue());
}
httpAction.setRunTimeParameters(convertedParameters);
//assumed that the action holds its input already, and use it
resp = httpAction.apply(null);
if (resp.getStatusCode()!=200)
throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() );
return JsonHandler.getJsonNodeFromString(resp.getContent());
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("MapStringToJsonOperation failed with error "+ e);
}
return null;
};
return ret;
}
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import logic.adapter.action.ActionsList;
import logic.adapter.model.BaseActionParams;
import logic.adapter.model.ModelValidator;
/**
* Created by eli on 11/17/16.
*/
public abstract class OnResponse<TypeInOut > implements ModelValidator{
@JsonProperty("onSuccess")
private ActionsList<TypeInOut> onSuccess;
@JsonProperty("onError")
private ActionsList<TypeInOut> onError;
@JsonCreator
public OnResponse(@JsonProperty("onSuccess") ActionsList<TypeInOut> onSuccess, @JsonProperty("onError")ActionsList<TypeInOut> onError) {
this.onSuccess = onSuccess;
this.onError = onError;
}
/**
*
* @return
* The onSuccess
*/
@JsonProperty("onSuccess")
public ActionsList<TypeInOut> getOnSuccess() {
return onSuccess;
}
/**
*
* @param onSuccess
* The onSuccess
*/
@JsonProperty("onSuccess")
public void setOnSuccess(ActionsList<TypeInOut> onSuccess) {
this.onSuccess = onSuccess;
this.onSuccess.setEmptyActionsValid(true);
}
/**
*
* @return
* The onError
*/
@JsonProperty("onError")
public ActionsList<TypeInOut> getOnError() {
return onError;
}
/**
*
* @param onError
* The onError
*/
@JsonProperty("onError")
public void setOnError(ActionsList<TypeInOut> onError) {
this.onError = onError;
this.onError.setEmptyActionsValid(true);
}
@Override
public boolean isValid() {
return (onSuccess.isValid() && onError.isValid());
}
public abstract boolean isRespSuccess(TypeInOut actionResp);
public TypeInOut execute(TypeInOut actionResp) throws Exception {
if (this.isRespSuccess(actionResp))
return onSuccess.executeActions(actionResp);
else
return onError.executeActions(actionResp);
}
public abstract void build();
}
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* Created by eli on 11/22/16.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="metaDataOperationClass")
public abstract class Operation<T extends BaseOperationParams> {
public Operation(T operationParams) {
this.operationParams = operationParams;
}
public T getOperationParams() {
return operationParams;
}
private T operationParams;
}
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonProperty;
import logic.adapter.action.BaseAction;
import logic.adapter.model.BaseActionParams;
import logic.adapter.model.ModelValidator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/17/16.
*/
public abstract class ActionsList<TypeExecuteInOut> implements ModelValidator{
@JsonProperty("actionsInput")
private String actionsInput;
@JsonProperty("actions")
private List<BaseAction> actions = new ArrayList<>();
public ActionsList(String actionsInput, List<BaseAction> actions) {
this.actionsInput = actionsInput;
this.actions = actions;
}
public boolean isEmptyActionsValid() {
return isEmptyActionsValid;
}
public void setEmptyActionsValid(boolean emptyActionsValid) {
isEmptyActionsValid = emptyActionsValid;
}
private boolean isEmptyActionsValid = false;
/**
*
* @return
* The actionsInput
*/
@JsonProperty("actionsInput")
public String getActionsInput() {
return actionsInput;
}
/**
*
* @param actionsInput
* The actionsInput
*/
@JsonProperty("actionsInput")
public void setActionsInput(String actionsInput) {
this.actionsInput = actionsInput;
}
/**
*
* @return
* The actions
*/
@JsonProperty("actions")
public List<BaseAction> getActions() {
return actions;
}
/**
*
* @param actions
* The actions
*/
@JsonProperty("actions")
public void setActions(List<BaseAction> actions) {
this.actions = actions;
}
@Override
public boolean isValid() {
if (actionsInput.equals("CONTENT")) {
if (actions.size() != 0)
return actions.stream().anyMatch(action -> !action.isValid());
else
return this.isEmptyActionsValid();
}
else
return false;
}
public abstract TypeExecuteInOut executeActions(TypeExecuteInOut input) throws Exception;
}
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams;
import logic.adapter.model.BaseActionParams;
import logic.adapter.model.ModelValidator;
import java.util.Map;
import java.util.function.Function;
/**
* Created by eli on 11/17/16.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="metaDataActionClass")
public abstract class BaseAction<T extends BaseActionParams, TypeIn, TypeOut> implements ModelValidator, ThrowableFunction<TypeIn,TypeOut> {
@JsonProperty
T params;
public Map<String, String> getRunTimeParameters() {
return runTimeParameters;
}
private Map<String, String> runTimeParameters;
public BaseAction(T params) {
this.params = params;
}
public T getParams() {return params;}
public TypeIn getRunTimeInput() {
return runTimeInput;
}
public void setRunTimeInput(TypeIn runTimeInput) {
this.runTimeInput = runTimeInput;
}
TypeIn runTimeInput;
@Override
public boolean isValid() {
return params.isValid();
}
abstract public String getType();
public abstract void build();
public void setRunTimeParameters(Map<String, String> convertedParameters) {
this.runTimeParameters = convertedParameters;
}
public ConfigHttpRequestParams getAdapterHttpParams() {
return adapterHttpParams;
}
public SimpleHttpClient getHttpClient() {
return httpClient;
}
public OAuth2Client getOauth2Client() {
return oauth2Client;
}
protected ConfigHttpRequestParams adapterHttpParams;
protected SimpleHttpClient httpClient;
protected OAuth2Client oauth2Client;
public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams,
SimpleHttpClient httpClient,
OAuth2Client oauth2Client) {
this.adapterHttpParams = adapterHttpParams;
this.httpClient = httpClient;
this.oauth2Client = oauth2Client;
}
}
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonPointer;
import com.fasterxml.jackson.databind.JsonNode;
import defs.Enums;
import logic.adapter.model.ExtractValueActionParams;
/**
* Created by eli on 11/17/16.
*/
public class ExtractValueAction extends JsonNodeAction<ExtractValueActionParams> {
public static final String TYPE = "ExtractValueAction";
private JsonPointer pathPointer;
@JsonCreator
public ExtractValueAction(@JsonProperty("params") ExtractValueActionParams params) {
super(params);
pathPointer = JsonPointer.compile(getParams().getPath());
}
@Override
public String getType() {
return ExtractValueAction.TYPE;
}
@Override
public void build() {
}
@Override
public JsonNode apply(JsonNode jsonNode) throws Exception {
Enums.eNodeType eType = getParams().getValueType();
JsonNode transformedNode = jsonNode.at(pathPointer);
switch (eType){
case ARRAY_NODE:
if (!transformedNode.isArray())
throw new Exception("ExtractValueAction expected transformed of type ARRAY-NODE");
break;
case STRING_NODE:
if (!transformedNode.isTextual())
throw new Exception("ExtractValueAction expected transformed of type ARRAY-NODE");
break;
default:
throw new Exception("ExtractValueAction unsupported type");
}
return transformedNode;
}
}
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import logic.adapter.HttpAdapter.model.*;
import logic.adapter.model.JsonConvertActionParams;
import logic.adapter.model.TerminateOperation;
import util.ArrayNodeCollector;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Created by eli on 11/21/16.
*/
/**
* This action used to perform all pre-configured set of supported operations on a given JsonNode.
* in order to change
* @param
*/
public class JsonConvertAction extends JsonNodeAction<JsonConvertActionParams>
{
public static final String TYPE = "JsonConvertAction";
@JsonCreator
public JsonConvertAction(@JsonProperty("params") JsonConvertActionParams params) {
super(params);
}
@Override
public String getType() {
return JsonConvertAction.TYPE;
}
@Override
public void build() {
}
/**
* Applies this function to the given argument.
*
* @param jsonNode the function argument
* @return the function result
*/
@Override
public JsonNode apply(JsonNode jsonNode) throws Exception {
if (jsonNode == null || !jsonNode.isArray())
throw new Exception("JsonConvertAction failed. expected ARRAY-NODE input ");
else{
Stream<JsonNode> streamOfJsonNodes;
streamOfJsonNodes = StreamSupport.stream(jsonNode.spliterator(),false);
JsonConvertActionParams params=getParams();
List<IntermediateOperation> operations = params.getIntermediateOperations();
for (IntermediateOperation operation : operations) {
int end_index = operation.toString().indexOf('@');
String type=operation.toString().substring(0,end_index);
int startIndex = type.lastIndexOf(".");
startIndex++;
type = type.substring(startIndex,end_index);
if (type.equals("MapJsonToJsonOperation")){
Function<JsonNode,JsonNode> func = ((MapJsonToJsonOperation)operation).getFunc();
streamOfJsonNodes=streamOfJsonNodes.map(func);
}
else if (type.equals("MapJsonToStringOperation")) {
Function<JsonNode, JsonNode> func = ((MapJsonToStringOperation) operation).getFunc();
streamOfJsonNodes=streamOfJsonNodes.map(func);
}
else if (type.equals("MapStringToJsonOperation")) {
Function<JsonNode,JsonNode> func = ((MapStringToJsonOperation) operation).getFunc();
streamOfJsonNodes=streamOfJsonNodes.map(func);
}
else if (type.equals("FilterJsonOperation")) {
Predicate<JsonNode> func = (Predicate<JsonNode> )operation.getFunc();
streamOfJsonNodes=streamOfJsonNodes.filter(func);
}
else throw new Exception("JsonConvertAction failed. unsupported intermediate operation");
}
TerminateOperation termOperation = params.getTerminateOperation();
//HandleTerminateOperation
ArrayNodeCollector collector = new ArrayNodeCollector();
return streamOfJsonNodes.collect(collector);
}
}
}
package logic.adapter.action;
import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.model.BaseActionParams;
import java.util.function.Function;
/**
* Created by eli on 11/17/16.
*/
/**
* implement this action for actions that gets JsonNode type Parameter and return the same type
* @param <T>
*/
public abstract class JsonNodeAction<T extends BaseActionParams> extends BaseAction<T, JsonNode, JsonNode> {
public JsonNodeAction(T params) {
super(params);
}
}
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.flipkart.zjsonpatch.JsonPatch;
import logic.adapter.model.JsonPatchActionParams;
import util.Utils;
import java.io.IOException;
import static defs.Constants.CONFIG_LOCATION;
/**
* Created by eli on 12/1/16.
*/
public class JsonPatchAction extends JsonNodeAction<JsonPatchActionParams>{
@JsonCreator
public JsonPatchAction(@JsonProperty("params") JsonPatchActionParams params) {
super(params);
}
@Override
public String getType() {
return null;
}
@Override
public void build() {
}
@Override
public JsonNode apply(JsonNode jsonNode) throws Exception {
JsonNode jsonInput;
JsonPatchActionParams params = getParams();
String JsonPatchFile = params.getFileJsonPatch();
JsonNode jsonPatch = Utils.readJsonNodeFromFile(CONFIG_LOCATION+JsonPatchFile);
if (params.getFileJsonInput() == null)
jsonInput=jsonNode;
else
jsonInput=Utils.readJsonNodeFromFile(CONFIG_LOCATION+JsonPatchFile);
if (jsonPatch!=null && !jsonPatch.isNull() && jsonInput!=null && !jsonInput.isNull()){
return JsonPatch.apply(jsonPatch, jsonInput);
}
else
return null;
}
private JsonNode jsonPatchApply(String jsonPatchfile, String jsonInputfile ) throws IOException {
JsonNode jsonPatch = Utils.readJsonNodeFromFile(jsonPatchfile);
JsonNode jsonInput = Utils.readJsonNodeFromFile(jsonInputfile);
if (jsonPatch!=null && !jsonPatch.isNull() && jsonInput!=null && !jsonInput.isNull()){
return JsonPatch.apply(jsonPatch, jsonInput);
}
return null;
}
}
package logic.adapter.action;
import java.util.function.Function;
/**
* Created by eli on 11/30/16.
*/
public interface ThrowableFunction <TypeIn,TypeOut> {
TypeOut apply(TypeIn typeIn) throws Exception;
}
...@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import util.Utils; import util.Utils;
import java.io.IOException;
import static defs.Constants.ADAPTERS_PATH; import static defs.Constants.ADAPTERS_PATH;
import static defs.Constants.CONFIG_LOCATION; import static defs.Constants.CONFIG_LOCATION;
//import static defs.Constants.CONFIG_LOCATION; //import static defs.Constants.CONFIG_LOCATION;
...@@ -18,7 +20,7 @@ public class FileAdapterLoader implements IAdapterLoader { ...@@ -18,7 +20,7 @@ public class FileAdapterLoader implements IAdapterLoader {
public FileAdapterLoader(ILogger logger) { public FileAdapterLoader(ILogger logger) {
this.logger = logger; this.logger = logger;
} }
public JsonNode load(String adapterId) { public JsonNode load(String adapterId) throws IOException {
String adapterFile = CONFIG_LOCATION+adapterId + ".json"; String adapterFile = CONFIG_LOCATION+adapterId + ".json";
return Utils.readJsonNodeFromFile(adapterFile); return Utils.readJsonNodeFromFile(adapterFile);
} }
......
...@@ -3,10 +3,12 @@ package logic.adapter.loader; ...@@ -3,10 +3,12 @@ package logic.adapter.loader;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import java.io.IOException;
/** /**
* Created by eli on 6/23/16. * Created by eli on 6/23/16.
*/ */
public interface IAdapterLoader { public interface IAdapterLoader {
JsonNode load(String adapterId); JsonNode load(String adapterId) throws IOException;
} }
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
/**
* Created by eli on 11/20/16.
*/
public class AdapterModel<T extends BaseFlow> implements ModelValidator{
@JsonProperty("config")
private BaseAdapterConfig config;
@JsonProperty("flows")
private ArrayList<T> flows = new ArrayList<>();
public BaseAdapterConfig getConfig() {
return config;
}
public void setConfig(BaseAdapterConfig config) {
this.config = config;
}
public ArrayList<T> getFlows() {
return flows;
}
public void setFlows(ArrayList<T> flows) {
this.flows = flows;
}
public T getFlow(String flowId) {
//todo change the list to map for better performance
for(T flow : flows)
{
if (flow.getFlowId().equals(flowId))
return flow;
}
return null;
}
public void buildFlows() {
for (T flow:
flows) {
flow.build();
}
}
@Override
public boolean isValid() {
if ( config == null || !config.isValid() || flows == null )
return false;
for (BaseFlow flow : flows) {
if (!flow.isValid())
return false;
}
return true;
}
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* Created by eli on 11/15/16.
*/
/**
* base class for all the classes used to hold parameters for methods
*/
public abstract class BaseActionParams implements ModelValidator{
abstract public String getId();
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* Created by eli on 11/16/16.
*/
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="metaDataConfig")
public abstract class BaseAdapterConfig implements ModelValidator{
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import microservice.params.CommandParams;
import java.util.ArrayList;
/**
* Created by eli on 6/30/16.
*/
//@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="class")
public abstract class BaseApi {
public enum eCommand { CREATE, READ, UPDATE, DELETE, BAD_COMMAND}
@JsonCreator
protected BaseApi(String id,
ArrayList<ResponseAction> responseActions)
{ this.id=id; this.responseActions = responseActions; eCmd = eCommand.BAD_COMMAND;}
// @JsonCreator
// protected BaseApi(@JsonProperty("id") String id)
// { this.id=id; eCmd = eCommand.BAD_COMMAND;}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonIgnore
public eCommand geteCmd() {
return eCmd;
}
@JsonIgnore
public void setCmd(eCommand eCmd) {
this.eCmd = eCmd;
}
@JsonIgnore
protected abstract void setCmd();
// @JsonIgnore
// public abstract void setCommandParams();
//
// @JsonIgnore
// public CommandParams getCmdParams() {
// return cmdParams;
// }
@JsonProperty
public ArrayList<ResponseAction> getResponseActions() {
return responseActions;
}
@JsonProperty
public void setResponseActions(ArrayList<ResponseAction> responseActions) {
this.responseActions = responseActions;
}
@JsonProperty
private String id;
@JsonProperty
private ArrayList<ResponseAction> responseActions= new ArrayList<ResponseAction>();
@JsonIgnore
private eCommand eCmd;
// @JsonIgnore
// protected CommandParams cmdParams;
}
package logic.adapter.model;
//import com.fasterxml.jackson.annotation.JsonCreator;
//import com.fasterxml.jackson.annotation.JsonIgnore;
//import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.*;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.action.OnHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.HttpAdapter.model.HttpFlow;
import logic.adapter.HttpAdapter.model.HttpRequestActionParams;
import logic.adapter.HttpAdapter.model.OnResponse;
import logic.adapter.action.BaseAction;
import java.util.ArrayList;
/**
* Created by eli on 11/16/16.
*/
//@JsonTypeInfo(
// use = JsonTypeInfo.Id.CLASS,
// include = JsonTypeInfo.As.PROPERTY,
// property = "metaDataClassFlow")
//@JsonSubTypes({
// @JsonSubTypes.Type(value = HttpFlow.class)
//})
//HttpRequestActionParams, RequestParams,SimpleHttpResponse
public abstract class BaseFlow implements ModelValidator{
@JsonProperty("action")
protected SimpleHttpAction action;
@JsonProperty("onResponse")
protected OnHttpResponse onResponse;
public BaseFlow(SimpleHttpAction action,
OnHttpResponse onResponse)
{
this.action = action;
this.onResponse = onResponse;
}
public void build(){
action.build();
// onResponse.build();
}
public SimpleHttpAction getAction() {
return action;
}
public void setAction(SimpleHttpAction action) {
this.action = action;
}
public OnHttpResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(OnHttpResponse onResponse) {
this.onResponse = onResponse;
}
public String getFlowId(){
if (this.action!=null)
return action.getParams().getId();
else
return null;
}
public SimpleHttpResponse execute(RequestParams input) throws Exception {
SimpleHttpResponse actionResp = action.apply(input);
try {
return onResponse.execute(actionResp);
} catch (Exception e) {
e.printStackTrace();
return actionResp;
}
}
@Override
public boolean isValid() {
return (action.isValid() && onResponse.isValid());
}
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.util.ArrayList;
import java.util.List;
import static com.fasterxml.jackson.databind.type.TypeFactory.*;
/**
* Created by eli on 6/30/16.
*/
public class DataModel<T extends BaseApi> {
//private String serviceId = null;
@JsonProperty
private String baseUrl = null;
@JsonProperty
private String basePath;
@JsonProperty
private ArrayList<T> apiList = new ArrayList<>();
@JsonCreator
public DataModel() {
}
@JsonIgnore
public String toString() {
// return new String("serviceId="+serviceId+", baseUri="+baseUrl+"apilist="+ apiList.toString());
return new StringBuilder().append("baseUri=").append(baseUrl).append(", apilist=").append(apiList.toString()).toString();
}
// public void setApisCommandParams() {
// for (T api : apiList){
// api.setCommandParams();
// }
// }
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public ArrayList<T> getApiList() {
return apiList;
}
public void setApiList(ArrayList<T> apiList) {
this.apiList = apiList;
}
public T getApi(String id) {
//todo change the list to map for better performance
for(T api : apiList)
{
if (api.getId().equals(id))
return api;
}
return null;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.*;
import defs.Enums;
/**
* Created by eli on 11/17/16.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"path",
"valueType"
})
public class ExtractValueActionParams extends BaseActionParams {
@JsonCreator
public ExtractValueActionParams(@JsonProperty("path") String path, @JsonProperty("valueType") String valueType) {
this.path = path;
this.valueType = Enums.eNodeType.resolveNodeType(valueType);
}
public String getPath() {
return path;
}
@JsonGetter("valueType")
public String getType() {
return valueType.getNodeType();
}
public Enums.eNodeType getValueType() {
return valueType;
}
private String path;
private Enums.eNodeType valueType;
@Override
public boolean isValid() {
if (path != null && !path.equals("") && valueType!= null )
return true;
else
return false;
}
@Override
public String getId() {
return null;
}
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import logic.adapter.HttpAdapter.model.IntermediateOperation;
import logic.adapter.action.BaseAction;
import java.util.ArrayList;
import java.util.List;
/**
* Created by eli on 11/21/16.
*/
public class JsonConvertActionParams extends BaseActionParams {
@JsonProperty("intermediateOperations")
private List<IntermediateOperation> intermediateOperations= new ArrayList<>();
@JsonProperty("terminateOperation")
private TerminateOperation terminateOperation;
public List<IntermediateOperation> getIntermediateOperations() {
return intermediateOperations;
}
public TerminateOperation getTerminateOperation() {
return terminateOperation;
}
@JsonCreator
public JsonConvertActionParams(@JsonProperty("intermediateOperations") List<IntermediateOperation> intermediateOperations,
@JsonProperty("terminateOperation") TerminateOperation terminateOperation) {
this.terminateOperation = terminateOperation;
this.intermediateOperations = intermediateOperations;
}
@Override
public boolean isValid() {
return true;
}
@Override
public String getId() {
return null;
}
}
//package logic.adapter.model;
//
//
//import com.fasterxml.jackson.annotation.JsonCreator;
//import com.fasterxml.jackson.annotation.JsonIgnore;
//import com.fasterxml.jackson.annotation.JsonProperty;
//import com.fasterxml.jackson.core.JsonPointer;
//import com.fasterxml.jackson.databind.JsonNode;
//import com.google.api.client.json.Json;
//
///**
// * Created by eli on 11/15/16.
// */
//public class JsonExtractFieldValue extends BaseActionParams {
//
// @JsonProperty
// private String path;
// @JsonProperty
// private EnumJsonFieldValueType enumFieldValueType;
//
//
// @JsonIgnore
// private JsonPointer jsonPointer;
//
// @JsonCreator
// public JsonExtractValueParams(String path, String strFieldValueType) throws IllegalArgumentException{
// this.path = path;
// this.jsonPointer= JsonPointer.compile(path);
// //if the string holds non valid string, enumFieldValueType is null
// this.enumFieldValueType = Enum.valueOf(EnumJsonFieldValueType.class, strFieldValueType);
// }
//
// JsonNode activate(JsonNode)
//
//
//
//
// private enum EnumJsonFieldValueType {
// ARRAY_VALUE("ARRAY"),
// STRING_VALUE("STRING");
//
// public String getName() {
// return name;
// }
//
// private final String name;
//
//
// EnumJsonFieldValueType(String name) {
// this.name = name;
// }
//
//// public static EnumJsonFieldValueType resolveEnumField(String name){
//// EnumJsonFieldValueType[] eValueTypes = EnumJsonFieldValueType.values();
//// for (EnumJsonFieldValueType eType : eValueTypes)
//// {
//// if (eType.getName().equals(name))
//// return eType;
//// }
//// return null;
////
//// }
// }
//
//}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by eli on 12/1/16.
*/
public class JsonPatchActionParams extends BaseActionParams{
@JsonProperty("fileInput")
private String fileJsonInput;
@JsonProperty("filePatch")
private String fileJsonPatch;
@JsonCreator
public JsonPatchActionParams(@JsonProperty("fileInput") String fileJsonInput, @JsonProperty("filePatch") String fileJsonPatch) {
this.fileJsonInput = fileJsonInput;
this.fileJsonPatch = fileJsonPatch;
}
public String getFileJsonPatch() {
return fileJsonPatch;
}
public String getFileJsonInput() {
return fileJsonInput;
}
@Override
public boolean isValid() {
return false;
}
@Override
public String getId() {
return null;
}
}
package logic.adapter.model;
/**
* Created by eli on 11/24/16.
*/
public interface ModelValidator {
boolean isValid();
}
package logic.adapter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import logic.adapter.HttpAdapter.model.Operation;
/**
* Created by eli on 11/22/16.
*/
public class TerminateOperation extends Operation<TerminateOperationParams>{
public static final String TYPE = "TerminateOperation";
@JsonCreator
public TerminateOperation(@JsonProperty("operationParams") TerminateOperationParams operationParams) {
super(operationParams);
}
}
package logic.adapter.model;
import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.BaseOperationParams;
import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams;
/**
* Created by eli on 11/22/16.
*/
public class TerminateOperationParams extends BaseOperationParams{
@Override
public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams, SimpleHttpClient httpClient, OAuth2Client oauth2Client) {
}
}
...@@ -8,6 +8,7 @@ import logic.adapter.HttpAdapter.HttpAdapter; ...@@ -8,6 +8,7 @@ import logic.adapter.HttpAdapter.HttpAdapter;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import util.Utils; import util.Utils;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -24,10 +25,14 @@ public class AdaptersRepository { ...@@ -24,10 +25,14 @@ public class AdaptersRepository {
this.logger = logger; this.logger = logger;
adapterList = new HashMap<>(); adapterList = new HashMap<>();
} }
public void load() { public void load() {//have to throw exception
ArrayNode adaptersArray; ArrayNode adaptersArray;
JsonNode jsonNode; JsonNode jsonNode=null;
jsonNode = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+Constants.ADAPTERS_PATH); try {
jsonNode = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+Constants.ADAPTERS_PATH);
} catch (IOException e) {
e.printStackTrace();
}
if (jsonNode!=null) { if (jsonNode!=null) {
adaptersArray = (ArrayNode) jsonNode.get("adapters"); adaptersArray = (ArrayNode) jsonNode.get("adapters");
this.loadAdapters( adaptersArray); this.loadAdapters( adaptersArray);
......
...@@ -10,6 +10,19 @@ import java.util.List; ...@@ -10,6 +10,19 @@ import java.util.List;
*/ */
public class Api { public class Api {
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
@JsonProperty("method")
private String method;
@JsonProperty("apiIn") @JsonProperty("apiIn")
private String apiIn; private String apiIn;
@JsonProperty("actions") @JsonProperty("actions")
......
...@@ -11,6 +11,8 @@ import java.util.List; ...@@ -11,6 +11,8 @@ import java.util.List;
*/ */
public class Service { public class Service {
@JsonProperty("apiList") @JsonProperty("apiList")
private List<Api> apiList = new ArrayList<>(); private List<Api> apiList = new ArrayList<>();
...@@ -36,7 +38,7 @@ public class Service { ...@@ -36,7 +38,7 @@ public class Service {
public Api getApi(String apiId){ public Api getApi(String apiId){
for (Api api : apiList) { for (Api api : apiList) {
if (api.getApiIn().equals(apiId)) if (api.getApiIn().startsWith(apiId))
return api; return api;
} }
return null; return null;
......
...@@ -11,6 +11,7 @@ import logic.service.model.Service; ...@@ -11,6 +11,7 @@ import logic.service.model.Service;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import util.Utils; import util.Utils;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
/** /**
...@@ -28,8 +29,12 @@ public class ServicesRepository { ...@@ -28,8 +29,12 @@ public class ServicesRepository {
} }
public void load() { public void load() {
ArrayNode servicesArray; ArrayNode servicesArray;
JsonNode jsonNode; JsonNode jsonNode=null;
jsonNode = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+Constants.SERVICES_PATH); try {
jsonNode = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+Constants.SERVICES_PATH);
} catch (IOException e) {
e.printStackTrace();
}
if (jsonNode!=null) { if (jsonNode!=null) {
servicesArray = (ArrayNode) jsonNode.get("services"); servicesArray = (ArrayNode) jsonNode.get("services");
this.loadServices( servicesArray); this.loadServices( servicesArray);
...@@ -51,11 +56,15 @@ public class ServicesRepository { ...@@ -51,11 +56,15 @@ public class ServicesRepository {
} }
private void addService(String serviceId) { private void addService(String serviceId) {
JsonNode serviceNode; JsonNode serviceNode=null;
if (serviceId!=null) { if (serviceId!=null) {
StringBuilder serviceFile=new StringBuilder(Constants.CONFIG_LOCATION). StringBuilder serviceFile=new StringBuilder(Constants.CONFIG_LOCATION).
append("service.").append(serviceId).append(".json"); append("service.").append(serviceId).append(".json");
serviceNode = Utils.readJsonNodeFromFile(serviceFile.toString()); try {
serviceNode = Utils.readJsonNodeFromFile(serviceFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
Service service = (Service)JsonHandler.getNodeAsObject(serviceNode,Service.class); Service service = (Service)JsonHandler.getNodeAsObject(serviceNode,Service.class);
if (serviceList.putIfAbsent(serviceId,service) != null) if (serviceList.putIfAbsent(serviceId,service) != null)
logger.debug("service " +serviceId + " was loaded successfully"); logger.debug("service " +serviceId + " was loaded successfully");
......
package logic.webSocket;
/**
* Created by eli on 12/4/16.
*/
public class OnEventDetails {
public String getCallBackUrl() {
return callBackUrl;
}
public String getAppKey() {
return appKey;
}
private String callBackUrl;
private String appKey;
public OnEventDetails(String callBackUrl, String appKey) {
this.callBackUrl = callBackUrl;
this.appKey = appKey;
}
public boolean isValid() {
return callBackUrl!=null;
}
}
package logic.webSocket;
import com.neovisionaries.ws.client.OpeningHandshakeException;
import com.neovisionaries.ws.client.StatusLine;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.NameValueParam;
import org.java_websocket.WebSocket;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
/**
* Created by eli on 12/4/16.
*/
public class WebSocketConnection {
private String connectionId;
private String webSocketUrl;
private OAuth2Client auth2Client;
private com.neovisionaries.ws.client.WebSocket webSocket;
private WebSocketEventListener eventListener;
private WebSocketFactory factory;
public WebSocketConnection(String connectionId,
String webSocketUrl,
OAuth2Client auth2Client,
List<NameValueParam> httpHeaders) throws UnsupportedEncodingException, ErrorLoginException, WebSocketException {
this.factory = new WebSocketFactory();
this.connectionId = connectionId;
this.webSocketUrl = webSocketUrl;
// StatusLine sl;
if (auth2Client!=null) {
this.auth2Client = new OAuth2Client(auth2Client.getClientSecrets(), auth2Client.getCredential());
}
try {
this.createWebSocket(httpHeaders);
}
catch (OpeningHandshakeException e){
// Status line.
StatusLine sl = e.getStatusLine();
if ( (sl.getStatusCode() == 401 || sl.getStatusCode() == 403) && auth2Client!= null){
this.auth2Client.login();
//try again
createWebSocket(httpHeaders);
}
}
}
private void createWebSocket(List<NameValueParam> httpHeaders) throws WebSocketException
{
try {
webSocket = factory.setConnectionTimeout(5000).createSocket(webSocketUrl);
webSocket.setMissingCloseFrameAllowed(false);
if (auth2Client!=null) {
webSocket.addHeader("Authorization", "Bearer " + auth2Client.getToken());
}
if (httpHeaders!=null ) {
for (NameValueParam header :
httpHeaders) {
webSocket.addHeader(header.getName(), header.getValue());
}
}
this.eventListener = new WebSocketEventListener(connectionId, null);
// fileList.add(logFile);
webSocket.addListener(eventListener);
webSocket.setPingInterval(50*1000);
synchronized (eventListener) {
try {
webSocket.connect();
eventListener.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("status of connection: " + connectionId+ ": " +eventListener.getState());
}
} catch (IOException e) {
e.printStackTrace();
}
// catch (WebSocketException e) {
// e.printStackTrace();
// }
// finally {
// try {
// Thread.sleep(3600*23*1000);
// } catch (InterruptedException e) {
//
// e.printStackTrace();
// }
// }
}
}
package logic.webSocket;
import com.neovisionaries.ws.client.WebSocketException;
import io.undertow.websockets.WebSocketConnectionCallback;
import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.NameValueParam;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by eli on 12/4/16.
*/
public class WebSocketManger {
private Map<String, WebSocketConnection> webSocketConnections;
private List<NameValueParam> defaultHeaders;
private OAuth2Client auth2Client;
public WebSocketManger(OAuth2Client oAuth2Client, List<NameValueParam> defaultHeaders)
{
this.webSocketConnections = new HashMap<>();
this.defaultHeaders = defaultHeaders;
this.auth2Client = oAuth2Client;
}
public boolean isConnected( String connectionId, String uid){
StringBuilder sb = new StringBuilder();
sb.append(connectionId).append(":").append(uid);
String key = sb.toString();
return webSocketConnections.containsKey(key);
}
public void connect(String connectionId, String uid, String webSocketUrl, OnEventDetails details) throws UnsupportedEncodingException, ErrorLoginException, WebSocketException {
StringBuilder sb = new StringBuilder();
sb.append(connectionId).append(":").append(uid);
String key = sb.toString();
WebSocketConnection webSocketConnection;
if (!isConnected(connectionId,uid)){
webSocketConnection = new WebSocketConnection(connectionId,webSocketUrl,auth2Client,defaultHeaders);
}
}
}
package util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* Created by eli on 11/30/16.
*/
public class ArrayNodeCollector implements Collector<JsonNode, ArrayNode, ArrayNode> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public Supplier<ArrayNode> supplier() {
return mapper::createArrayNode;
}
@Override
public BiConsumer<ArrayNode, JsonNode> accumulator() {
return ArrayNode::add;
}
@Override
public BinaryOperator<ArrayNode> combiner() {
return (x, y) -> {
x.addAll(y);
return x;
};
}
@Override
public Function<ArrayNode, ArrayNode> finisher() {
return accumulator -> accumulator;
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
}
package util;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import http.simpleHttpClient.SimpleHttpRequest;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams;
import logic.adapter.HttpAdapter.model.HttpRequestActionParams;
import logic.adapter.HttpAdapter.model.NameValueParam;
import microservice.RequestContext;
import microservice.defs.*;
import microservice.defs.Enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static defs.Enums.eKeyWord;
/**
* Created by eli on 11/29/16.
*/
public class HttpRequestResolver {
//this regexQueryParamValue means string starting with '$' followed with word (1-15 chars length) followed by period, ending with
//another word (1-15 chars)
private final static String regexQueryParamValue = "^\\$[a-zA-Z]{1,15}\\.[a-zA-Z]{1,15}$";
private final static Pattern patternFullMatchValue = Pattern.compile(regexQueryParamValue);
private final static String regexPathParamValue = "^\\$[a-zA-Z]{1,15}\\.[a-zA-Z]{1,15}$";
private final static Pattern patternPathParamValue = Pattern.compile(regexPathParamValue);
private final static String regexPathKeyWord= "^\\$[a-zA-Z0-9]{1,15}\\.[a-zA-Z]{1,15}$";
private final static Pattern patternPathKeyWord = Pattern.compile(regexPathKeyWord);
// private final String tokenAccess;
//
// private RequestContext srcRequest;
// //field hold the dst request parameters that added to all request of the given adapter.
// //some of the parameters has to be resolved
// private ConfigHttpRequestParams dstConfigRequestParamsPattern;
// //field hold the dst request parameters that relevant for specific httpRequest
// //some of the parameters has to be resolved
// private HttpRequestActionParams dstRequestParamsPattern;
//GENERAL
// "baseUrl": "ie-parking.run.aws-usw02-pr.ice.predix.io/",
// "basePath": "v1/",
// "headers": [{
// "name": "predix-zone-id",
// "value": "c54e3e63-8dc6-425e-a533-64e061f64023"
// }, {
// "name": "Authorization",
// "value": "bearer $token"
// }]
//GetAllParkingSpots
// "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"
// }],
// "headers": [],
// "content": null
// }
public SimpleHttpRequest createResolvedRequest(RequestParams srcRequest,
ConfigHttpRequestParams dstConfigRequestParamsPattern,
HttpRequestActionParams dstRequestParamsPattern,
String tokenAccess,
Map<String,String> runTimeVariables){
// use it to create JsonNode JsonNodeFactory.instance.arrayNode();
String domain,path;
String name,value;
SimpleHttpRequest request = new SimpleHttpRequest();
if (tokenAccess!=null)
request.setProtocol("https");
else
request.setProtocol("https");
domain = dstConfigRequestParamsPattern.getBaseUrl()+dstConfigRequestParamsPattern.getBasePath();
request.setDomain(domain);
String method = dstRequestParamsPattern.getHttpMethod();
SimpleHttpRequest.Method eMethod;
switch (method){
case "GET":
eMethod= SimpleHttpRequest.Method.GET;
break;
case "POST":
eMethod= SimpleHttpRequest.Method.POST;
break;
case "PUT":
eMethod= SimpleHttpRequest.Method.PUT;
break;
case "DELETE":
eMethod= SimpleHttpRequest.Method.DELETE;
break;
default:
eMethod= SimpleHttpRequest.Method.GET;
break;
}
request.setMethod(eMethod);
List<NameValueParam> headers= dstConfigRequestParamsPattern.getHeaders();
for (NameValueParam header: headers)
{
name = header.getName();
value = header.getValue();
value = value.replaceFirst("\\$token",tokenAccess);
request.addHeader(name,value);
}
Map<String, String> variables;
path = dstRequestParamsPattern.getPath();
Enums.EnumCrudMethod enumCrudMethod = srcRequest.getEnumCrudMethod();
if (enumCrudMethod == Enums.EnumCrudMethod.E_CREATE){
if (dstRequestParamsPattern.getId().equals("subscribe")) {
variables = new HashMap<>();
String[] params = srcRequest.getParams();
if (params.length>3) {
variables.put("mdeKey", (srcRequest.getParams())[3]);
path = replaceMatchedKeysByItsValues(path, variables);
}
}
}
else
path = replaceMatchedKeysByItsValues(path, runTimeVariables);
request.setPath(path);
List<NameValueParam> queryParams = dstRequestParamsPattern.getQueryParams();
if (queryParams!=null) {
request.InitQueryStringBuilder();
for (NameValueParam param : queryParams) {
request.addQueryStringParam(param.getName(), param.getValue());
}
}
return request;
}
//key may include letters and digits till 15 chars length, prefix with '$'
public static String replaceMatchedKeysByItsValues(String target, Map<String, String> keyVals)
{
if (keyVals== null) return target;
final String regex = "\\$[a-zA-Z0-9]{1,15}";
final Pattern compiledRegEx = Pattern.compile(regex);
String result=target;
Matcher matcher = compiledRegEx.matcher(target);
int start, end;
String key,val;
boolean flag = false;
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
//if matched not last portion of the string
key= target.substring(start+1,end);
if (keyVals.containsKey(key))
{
val=keyVals.get(key);
if (target.length() != end)
result = target.substring(0, start ) + val + target.substring(end );
else
result = target.substring(0, start ) + val;
}
}
return result;
}
private static String ResolvePathValue(RequestContext requestContext, String path) {
Matcher matcher = patternPathParamValue.matcher(path);
StringBuffer stringBuffer = new StringBuffer();
String matchedString, replacement;
int start, end;
boolean flag = false;
while (matcher.find()) {
if (!flag) flag = true;
start = matcher.start();
end = matcher.end();
matchedString = path.substring(start, end);
replacement = resolveFullMatchValue(requestContext, matchedString);
matcher.appendReplacement(stringBuffer, replacement);
}
if (flag)
return stringBuffer.toString();
else
return path;
}
private static String resolveQueryParamsToString(RequestContext requestContext, List<NameValueParam> queryParams) {
StringBuilder sbQueryParams = new StringBuilder();
int size;
NameValueParam nameVal;
if (queryParams == null || (size = queryParams.size()) == 0) return null;
for (int i = 0; i < size; i++) {
nameVal = queryParams.get(i);
sbQueryParams.append(nameVal.getName()).append("=");
String value = resolveFullMatchValue(requestContext, nameVal.getValue());
sbQueryParams.append(value);
//if not the last element
if (i < size - 1)
sbQueryParams.append("&");
}
return sbQueryParams.toString();
}
private static String resolveFullMatchValue(RequestContext reqCnt, String value) {
Matcher matcher = patternFullMatchValue.matcher(value);
String resolvedValue = value;
if (matcher.matches()) {
//skip the $ and split to 2 Strings by '.'
String[] keyVal = value.substring(1).split("\\.");
String key = keyVal[0];
String val = keyVal[1];
eKeyWord ekey = eKeyWord.resolveKeyWord(key);
if (ekey!=null) {
switch (ekey) {
case QUERY:
//value contains query parameter
resolvedValue = reqCnt.getParameter(val);
break;
case HEADER:
// todo
break;
}
}
}
return resolvedValue;
}
public static void replaceToken(SimpleHttpRequest httpRequest, String token) {
Map<String,String> headers = httpRequest.getHeaders();
headers.put("Authorization", "bearer "+token);
}
}
//package util;
//
//import http.simpleHttpClient.SimpleHttpClient;
//import http.simpleHttpClient.SimpleHttpRequest;
//import http.simpleHttpClient.SimpleHttpResponse;
////import io.undertow.websockets.core.protocol.version07.Base64;
//import logic.adapter.HttpAdapter.model.DataHttpApi;
//import logic.adapter.loader.FileAdapterLoader;
//import microservice.io.iface.ILogger;
//
//import java.util.Base64;
//
///**
// * Created by eli on 10/31/16.
// */
//public class RestClientAccessToken {
// private static final String UAA_URL = "9deacc64-7c53-4790-9a6c-c9de0fdebcdf.predix-uaa.run.aws-usw02-pr.ice.predix.io/oauth/token?grant_type=client_credentials";
//
//
// private SimpleHttpClient httpClient = null;
// private SimpleHttpRequest request = null;
//
// public RestClientAccessToken(String clientId, String secret) throws Exception {
//
// String clientCredentials = clientId+ ":" +secret;
// String encodedClientCredential = Base64.getEncoder().encodeToString(clientCredentials.getBytes("utf-8"));
// // String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
//
//
// httpClient = new SimpleHttpClient();
// httpClient.Initialize(100);
// request = new SimpleHttpRequest();
//
// request.setProtocol("https");
// request.setMethod(SimpleHttpRequest.Method.GET);
// request.setDomain(UAA_URL);
// request.setPort(443);
//// request.setPath(path);
// // optional
// request.setQueryString("grant_type=client_credentials");
// request.addHeader("Authorization", "Basic "+encodedClientCredential);
//
//
// }
//
// SimpleHttpResponse httpResp = null;
//
//
// request.setProtocol("http");
// request.setMethod(method);
// request.setDomain(domain);
// request.setPort(port);
// request.setPath(path);
// // optional
// request.setQueryString(queryParams);
// request.setContent(content);
//
// try
// {
// httpResp = httpClient.processRequest(request);
// if (httpResp.getStatusCode() == 200) {
// return new MDEResult(true, null, httpResp.getContent());
// }
// else
// return new MDEResult(httpResp.getContent());
// }
// catch(Exception e)
// {
// e.printStackTrace();
// return new MDEResult("doHttp failed with exception. e: " + e.toString());
// }
//
//
//}
package util;
/**
* Created by eli on 10/31/16.
*/
public class TokenResponse {
}
...@@ -12,29 +12,29 @@ public class Utils { ...@@ -12,29 +12,29 @@ public class Utils {
public static final ObjectMapper SORTED_MAPPER = new ObjectMapper(); public static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
public static JsonNode readJsonNodeFromFile(String strFile) { public static Object readObjectFromString1(String jsonStr, Class<?> ObjClass) throws IOException {
Object obj = null;
obj = SORTED_MAPPER.readValue(jsonStr, ObjClass);
return obj;
}
public static JsonNode readJsonNodeFromFile(String strFile) throws IOException {
File file=new File(strFile); File file=new File(strFile);
JsonNode jsonNode = null; JsonNode jsonNode = null;
try { jsonNode = SORTED_MAPPER.readTree(file);
jsonNode = SORTED_MAPPER.readTree(file);
} catch (IOException e) {
e.printStackTrace();
}
return jsonNode; return jsonNode;
} }
public static Object getNodeAsObject(JsonNode jsonNode, TypeReference<?> type) { public static Object getNodeAsObject(JsonNode jsonNode, TypeReference<?> type) throws IOException {
ObjectReader objectReader = SORTED_MAPPER.reader(type); ObjectReader objectReader = SORTED_MAPPER.reader(type);
if(jsonNode != null && !jsonNode.isNull() && !jsonNode.isMissingNode() && objectReader != null) { if(jsonNode != null && !jsonNode.isNull() && !jsonNode.isMissingNode() && objectReader != null)
try { return objectReader.readValue(jsonNode);
return objectReader.readValue(jsonNode);
} catch (Exception var4) {
var4.printStackTrace();
}
}
else
return null;
return null; return null;
} }
...@@ -68,4 +68,12 @@ public class Utils { ...@@ -68,4 +68,12 @@ public class Utils {
SORTED_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SORTED_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} }
public static JsonNode getJsonNodeFromString(String jsonString) throws IOException {
JsonNode node = null;
node = SORTED_MAPPER.readTree(jsonString);
return node;
}
} }
...@@ -21,7 +21,8 @@ public class App { ...@@ -21,7 +21,8 @@ public class App {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ConfigProperties.getInstance().loadProperties(); ConfigProperties.getInstance().loadProperties();
// for testing
Thread.sleep(10000);
// load rest server parameters // load rest server parameters
Long port = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.port","9090", EnumPropertyType.E_LONG); Long port = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.port","9090", EnumPropertyType.E_LONG);
String host = (String) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.host","localhost", EnumPropertyType.E_STRING); String host = (String) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.host","localhost", EnumPropertyType.E_STRING);
...@@ -32,7 +33,7 @@ public class App { ...@@ -32,7 +33,7 @@ public class App {
.withMetrics() .withMetrics()
.withMonitoring() .withMonitoring()
.withPubSub(new IPubSubMQTTImpl("tcp://localhost",0,null,0)) .withPubSub(new IPubSubMQTTImpl("tcp://localhost",0,null,0))
.addHandler("/mde/api/v1", new MdeHandler(null)) .addHandler("/mde/api/v1", new MdeHandler())
//.addMicroserviceClient(new MicroserviceClient(MicroserviceClient.EnumRestClientType.E_HTTP,clientParams)) //.addMicroserviceClient(new MicroserviceClient(MicroserviceClient.EnumRestClientType.E_HTTP,clientParams))
.addRestServer(new IRestServerUndertowImpl(new RestServerParams(port.intValue(), host, workerThreadsNum.intValue()))) .addRestServer(new IRestServerUndertowImpl(new RestServerParams(port.intValue(), host, workerThreadsNum.intValue())))
.build() .build()
......
import logic.adapter.HttpAdapter.model.DataHttpApi; //import com.google.api.client.util.DateTime;
import logic.adapter.model.BaseApi; //import logic.adapter.model.BaseActionApi;
import org.junit.Test; //import org.junit.Test;
//
import java.util.ArrayList; //import java.util.ArrayList;
//import java.util.Date;
/** //
* Created by eli on 7/7/16. ///**
*/ // * Created by eli on 7/7/16.
public class TestArrayList { // */
public class ArrayTest<T extends BaseApi>{ //public class TestArrayList {
public ArrayList<T> getApiList() { // private static String currentDate() {
return apiList; // Date date = new Date(System.currentTimeMillis());
} // DateTime dateTime = new DateTime(date);
// return dateTime.toStringRfc3339();
public void setApiList(ArrayList<T> apiList) { // }
this.apiList = apiList; // public class ArrayTest<T extends BaseActionApi>{
} // public ArrayList<T> getApiList() {
// return apiList;
public T getApi(String id){ // }
T t = apiList.get(0); //
return t; // public void setApiList(ArrayList<T> apiList) {
} // this.apiList = apiList;
// }
private ArrayList<T> apiList = new ArrayList<>(); //
} // public T getApi(String id){
// T t = apiList.get(0);
public class ArrayExtends extends ArrayTest<DataHttpApi> // return t;
{ // }
//
public ArrayExtends() { // private ArrayList<T> apiList = new ArrayList<>();
} // }
} //
// public class ArrayExtends extends ArrayTest<DataHttpApi>
@Test // {
public void testArrayList(){ //
// ArrayList<T> apiList = new ArrayList<>(); // public ArrayExtends() {
// ArrayExtends arr = new ArrayExtends(); // }
// DataHttpApi api = new DataHttpApi("adapter.chicago.transportation"); // }
// arr.getApiList().add(api); //
// api = arr.getApi("adapter.chicago.transportation"); // @Test
// System.out.println(api.toString()); // public void println(){
// System.out.println("Time: "+ currentDate());
} // }
// @Test
} // public void testArrayList(){
//// ArrayList<T> apiList = new ArrayList<>();
//// ArrayExtends arr = new ArrayExtends();
//// DataHttpApi api = new DataHttpApi("adapter.chicago.transportation");
//// arr.getApiList().add(api);
//// api = arr.getApi("adapter.chicago.transportation");
//// System.out.println(api.toString());
//
// }
//
//}
import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.HttpAdapter.HttpAdapter; import logic.adapter.HttpAdapter.HttpAdapter;
import logic.adapter.HttpAdapter.model.DataHttpApi; import logic.adapter.HttpAdapter.model.HttpFlow;
import logic.adapter.model.DataModel; import logic.adapter.loader.FileAdapterLoader;
import logic.adapter.model.AdapterModel;
import logic.adapter.repository.AdaptersRepository; import logic.adapter.repository.AdaptersRepository;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
import org.junit.Test; import org.junit.Test;
import util.Utils;
import java.io.IOException;
/** /**
* Created by eli on 7/7/16. * Created by eli on 7/7/16.
...@@ -15,15 +20,32 @@ public class TestHttpAdapter { ...@@ -15,15 +20,32 @@ public class TestHttpAdapter {
HttpAdapter httpAdapter; HttpAdapter httpAdapter;
try { try {
httpAdapter = new HttpAdapter(logger, "adapter.chicago.transportation"); httpAdapter = new HttpAdapter(logger, "adapter.ge.parking");
DataModel<DataHttpApi> data=httpAdapter.getDataModel(); AdapterModel<HttpFlow> model=httpAdapter.getModel();
System.out.println(data.toString()); System.out.println(model.toString());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
// /opt/mcx/config/ge.parking.json (No such file or directory)
@Test
public void loadAdapterModel(){
AdapterModel<HttpFlow> model;
JsonNode jsonModel =null;
FileAdapterLoader loader = new FileAdapterLoader(logger);
try {
jsonModel = loader.load("adapter.ge.parking");
} catch (IOException e) {
e.printStackTrace();
}
model = (AdapterModel<HttpFlow>) Utils.getNodeAsParametricTypeObject(jsonModel, AdapterModel.class, HttpFlow.class);
System.out.println(model);
}
@Test @Test
public void testAdapterRepository() { public void testAdapterRepository() {
HttpAdapter httpAdapter; HttpAdapter httpAdapter;
......
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.HttpAdapter.model.DataHttpApi; import logic.adapter.HttpAdapter.model.HttpFlow;
import logic.adapter.model.DataModel; import logic.adapter.model.AdapterModel;
import org.junit.Test; import org.junit.Test;
import util.Utils; import util.Utils;
import common.JsonHandler;
import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList;
/** /**
...@@ -16,22 +15,90 @@ import java.util.ArrayList; ...@@ -16,22 +15,90 @@ import java.util.ArrayList;
public class TestJson { public class TestJson {
@Test @Test
public void testSerialize() public void testSerialize(){}
// {
// JsonNode jsonNode = null;
// try {
// jsonNode = Utils.readJsonNodeFromFile("/home/eli/git/ipgallery/java/mde/cfg/testJson.json");
// } catch (IOException e) {
// e.printStackTrace();
// }
//// DataModel dataModel = new DataModel(new ArrayList<DataHttpApi>());
// TypeReference<DataModel<DataHttpApi>> type = new TypeReference<DataModel<DataHttpApi>>() {
// @Override
// public Type getType() {
// return super.getType();
// }
//
// @Override
// public int compareTo(TypeReference<DataModel<DataHttpApi>> o) {
// return super.compareTo(o);
// }
// };
// DataModel<DataHttpApi> dataModel = (DataModel<DataHttpApi>)Utils.getNodeAsObject(jsonNode,type);
// System.out.println(dataModel.toString());
// }
@Test
public void testSerialize2()
{
JsonNode jsonNode = null;
try {
jsonNode = Utils.readJsonNodeFromFile("/home/eli/git/ipgallery/java/mde/cfg/adapter.ge.parking.json");
} catch (IOException e) {
e.printStackTrace();
}
// DataModel dataModel = new DataModel(new ArrayList<DataHttpApi>());
TypeReference<AdapterModel<HttpFlow>> type = new TypeReference<AdapterModel<HttpFlow>>() {
@Override
public Type getType() {
return super.getType();
}
@Override
public int compareTo(TypeReference<AdapterModel<HttpFlow>> o) {
return super.compareTo(o);
}
};
AdapterModel<HttpFlow> dataFlows = null;
try {
dataFlows = (AdapterModel<HttpFlow>) Utils.getNodeAsObject(jsonNode,type);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(dataFlows.toString());
}
@Test
public void testSerializeCommon()
{ {
JsonNode jsonNode = Utils.readJsonNodeFromFile("/home/eli/git/ipgallery/java/mde/cfg/testJson.json"); JsonNode jsonNode = null;
try {
jsonNode = Utils.readJsonNodeFromFile("/home/eli/git/ipgallery/java/mde/cfg/adapter.ge.parking.json");
} catch (IOException e) {
System.out.println("failed to read json fie, exception: " + e);
e.printStackTrace();
}
// DataModel dataModel = new DataModel(new ArrayList<DataHttpApi>()); // DataModel dataModel = new DataModel(new ArrayList<DataHttpApi>());
TypeReference<DataModel<DataHttpApi>> type = new TypeReference<DataModel<DataHttpApi>>() { TypeReference<AdapterModel<HttpFlow>> type = new TypeReference<AdapterModel<HttpFlow>>() {
@Override @Override
public Type getType() { public Type getType() {
return super.getType(); return super.getType();
} }
@Override @Override
public int compareTo(TypeReference<DataModel<DataHttpApi>> o) { public int compareTo(TypeReference<AdapterModel<HttpFlow>> o) {
return super.compareTo(o); return super.compareTo(o);
} }
}; };
DataModel<DataHttpApi> dataModel = (DataModel<DataHttpApi>)Utils.getNodeAsObject(jsonNode,type); AdapterModel<HttpFlow> dataFlows = null;
System.out.println(dataModel.toString()); try {
dataFlows = (AdapterModel<HttpFlow>) Utils.getNodeAsObject(jsonNode,type);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(dataFlows.toString());
} }
} }
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