Commit 5b97ddfd by Eli Ben Baruch

mde: add support for threadSafe microservice.

parent f43e562a
Showing with 3105 additions and 750 deletions
This diff could not be displayed because it is too large.
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
"valueType": "ARRAY-NODE" "valueType": "ARRAY-NODE"
} }
}, { }, {
"metaDataActionClass": "logic.adapter.action.JsonConvertAction", "metaDataActionClass": "logic.adapter.action.ArrayNodeAction",
"params": { "params": {
"intermediateOperations": [{ "intermediateOperations": [{
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation", "metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
......
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
"valueType": "ARRAY-NODE" "valueType": "ARRAY-NODE"
} }
}, { }, {
"metaDataActionClass": "logic.adapter.action.JsonConvertAction", "metaDataActionClass": "logic.adapter.action.ArrayNodeAction",
"params": { "params": {
"intermediateOperations": [{ "intermediateOperations": [{
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation", "metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
......
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
"valueType": "ARRAY-NODE" "valueType": "ARRAY-NODE"
} }
}, { }, {
"metaDataActionClass": "logic.adapter.action.JsonConvertAction", "metaDataActionClass": "logic.adapter.action.ArrayNodeAction",
"params": { "params": {
"intermediateOperations": [{ "intermediateOperations": [{
"metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation", "metaDataOperationClass": "logic.adapter.HttpAdapter.model.MapStringToJsonOperation",
......
...@@ -6,5 +6,5 @@ log4j.prop.file.path=/logs/conf/log4j.xml ...@@ -6,5 +6,5 @@ log4j.prop.file.path=/logs/conf/log4j.xml
### microservice/rest server ### microservice/rest server
server.port=50040 server.port=50040
server.host=0.0.0.0 server.host=0.0.0.0
server.worker.threads=1 server.worker.threads=6
...@@ -10,5 +10,6 @@ mde: ...@@ -10,5 +10,6 @@ mde:
extra_hosts: extra_hosts:
- "transportation:172.16.1.56" - "transportation:172.16.1.56"
- "parking:172.16.1.56" - "parking:172.16.1.56"
- "public-safety:172.16.1.151"
# volumes: # volumes:
# - "/opt/mcz/user_images:/opt/mcz/user_images" # - "/opt/mcz/user_images:/opt/mcz/user_images"
\ No newline at end of file
...@@ -35,11 +35,6 @@ public class MdeHandler extends BaseHandler { ...@@ -35,11 +35,6 @@ public class MdeHandler extends BaseHandler {
@Override @Override
public void init() { public void init() {
try { try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
this.mdeManager = new MdeManager(logger); this.mdeManager = new MdeManager(logger);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -50,6 +45,7 @@ public class MdeHandler extends BaseHandler { ...@@ -50,6 +45,7 @@ public class MdeHandler extends BaseHandler {
@Override @Override
public void doCreate(RequestContext requestContext) { public void doCreate(RequestContext requestContext) {
JsonNode content = (JsonNode)readObjectFromRequest(requestContext,JsonNode.class); JsonNode content = (JsonNode)readObjectFromRequest(requestContext,JsonNode.class);
BaseRestResponse brr; BaseRestResponse brr;
brr = validityCheck(requestContext); brr = validityCheck(requestContext);
......
...@@ -17,10 +17,14 @@ import microservice.io.iface.ILogger; ...@@ -17,10 +17,14 @@ import microservice.io.iface.ILogger;
import microservice.types.BaseRestResponse; import microservice.types.BaseRestResponse;
import util.Utils; import util.Utils;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static util.Utils.currentDate;
import static util.Utils.paramsToString;
/** /**
* Created by eli on 6/7/16. * Created by eli on 6/7/16.
*/ */
...@@ -35,6 +39,9 @@ public class MdeManager { ...@@ -35,6 +39,9 @@ public class MdeManager {
public MdeManager(ILogger logger) throws Exception { public MdeManager(ILogger logger) throws Exception {
Thread.sleep(10000);
try{ try{
jsonPatchAddLocationUID = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+"jsonPatchAddLocationUid.json"); jsonPatchAddLocationUID = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+"jsonPatchAddLocationUid.json");
jsonPatchAddAppKey = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+"jsonPatchAddAppKey.json"); jsonPatchAddAppKey = Utils.readJsonNodeFromFile(Constants.CONFIG_LOCATION+"jsonPatchAddAppKey.json");
...@@ -59,14 +66,20 @@ public class MdeManager { ...@@ -59,14 +66,20 @@ public class MdeManager {
// example: GET ../mde/api/v1/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;
String[] params = requestContext.params; String serviceId;// = params[0] +"." +params[1];
String serviceId = params[0] +"." +params[1]; boolean isMaintenanceRequest=false;
String[] apiIdAsParams = getApiIdAsParams(requestContext); int offset=0;
String error = null; System.out.print(Thread.currentThread().getName()+ " " + currentDate() +" MdeManager.doRead: ");
SimpleHttpResponse resp=null; if (requestContext.params[0].equals("maintenance")) {
isMaintenanceRequest=true;
brr = executeRequest(serviceId,apiIdAsParams,requestContext,null); //to skip first param("maintenance")
offset=1;
}
serviceId=getServiceId(requestContext, offset);
String[] apiIdAsParams = getApiIdAsParams(requestContext,offset);
brr = executeRequest(serviceId,apiIdAsParams,requestContext,null,isMaintenanceRequest);
return brr; return brr;
} }
...@@ -75,20 +88,30 @@ public class MdeManager { ...@@ -75,20 +88,30 @@ public class MdeManager {
public BaseRestResponse doCreate(RequestContext requestContext, JsonNode content) { public BaseRestResponse doCreate(RequestContext requestContext, JsonNode content) {
BaseRestResponse brr=null; BaseRestResponse brr=null;
String serviceId ; String serviceId ;
int offset=0;
boolean isMaintenanceRequest=false;
int i; System.out.print(Thread.currentThread().getName()+ " " + currentDate() +" MdeManager.doCreate: ["+paramsToString(requestContext.params)+"] ");
serviceId = getServiceId(requestContext); if (requestContext.params[0].equals("maintenance")) {
String[] apiIdAsParams = getApiIdAsParams(requestContext); System.out.print(" MAINTENANCE");
isMaintenanceRequest=true;
//to skip first param("maintenance")
offset=1;
}
System.out.print("\n");
serviceId = getServiceId(requestContext,offset);
String[] apiIdAsParams = getApiIdAsParams(requestContext, offset);
brr = executeRequest(serviceId,apiIdAsParams,requestContext,content); brr = executeRequest(serviceId,apiIdAsParams,requestContext,content, isMaintenanceRequest);
return brr; return brr;
} }
private BaseRestResponse executeRequest(String serviceId, String[] apiIdAsParams, RequestContext requestContext, JsonNode content) { private BaseRestResponse executeRequest(String serviceId, String[] apiIdAsParams, RequestContext requestContext, JsonNode content, boolean isMaintenanceRequest) {
SimpleHttpResponse resp=null; SimpleHttpResponse resp=null;
String error=null; String error=null;
if (apiIdAsParams!=null) { if (apiIdAsParams!=null) {
Api api = servicesRepository.getApi(serviceId, apiIdAsParams); Api api = servicesRepository.getApi(serviceId, apiIdAsParams);
if (api != null) { if (api != null) {
...@@ -98,7 +121,7 @@ public class MdeManager { ...@@ -98,7 +121,7 @@ public class MdeManager {
for (Action action : actions) { for (Action action : actions) {
BaseAdapter adapter = adaptersRepository.getAdapter(action.getAdapterId()); BaseAdapter adapter = adaptersRepository.getAdapter(action.getAdapterId());
if (adapter != null) {// && adapter.getClass().isInstance(HttpAdapter.class)) { if (adapter != null) {// && adapter.getClass().isInstance(HttpAdapter.class)) {
RequestParams requestParams = convertToRequestParams(requestContext, content, api.getMapKeyToParamIndex()); RequestParams requestParams = convertToRequestParams(requestContext, apiIdAsParams, content, api.getMapKeyToParamIndex(),isMaintenanceRequest);
resp = ((HttpAdapter) adapter).executeFlow(action.getApiOut(), requestParams); resp = ((HttpAdapter) adapter).executeFlow(action.getApiOut(), requestParams);
break;//currently only one action break;//currently only one action
} }
...@@ -114,17 +137,17 @@ public class MdeManager { ...@@ -114,17 +137,17 @@ public class MdeManager {
return convertToBaseRestResponse(resp,error); return convertToBaseRestResponse(resp,error);
} }
private String getServiceId(RequestContext requestContext) { private String getServiceId(RequestContext requestContext, int offset) {
return requestContext.params[0]+"."+requestContext.params[1]; return requestContext.params[offset]+"."+requestContext.params[offset+1];
} }
private String[] getApiIdAsParams(RequestContext requestContext) { private String[] getApiIdAsParams(RequestContext requestContext, int offset) {
String[] params = null; String[] params = null;
int size = requestContext.params.length; int size = requestContext.params.length;
if (size>2){ if (size-offset>2){
params = new String[size-2]; params = new String[size-offset-2];
System.arraycopy(requestContext.params, 2, params,0, size-2); System.arraycopy(requestContext.params, 2+offset, params,0, size-offset-2);
} }
return params; return params;
} }
...@@ -181,37 +204,38 @@ public class MdeManager { ...@@ -181,37 +204,38 @@ public class MdeManager {
private RequestParams convertToRequestParams(RequestContext requestContext, JsonNode content, Map<String, Integer> mapVariableToParamIndex, boolean isMaintenanceRequest) { private RequestParams convertToRequestParams(RequestContext requestContext,
RequestParams requestParams = new RequestParams(); String[] apiIdAsParams,
JsonNode content,
if (isMaintenanceRequest){ Map<String, Integer> mapVariableToParamIndex,
String[] params = new String[requestContext.params.length-1]; boolean isMaintenanceRequest) {
for (int i = 1 ; i< requestContext.params.length; i++){ RequestParams requestParams;
params[i-1]=requestContext.params[i]; Map<String,String> keyValueVariables=null;
}
requestParams.setParams(params);
requestParams.setIsMaintenance(true);
}
else
requestParams.setParams(requestContext.params);
requestParams.setQueryParameters(requestContext.queryParameters);
requestParams.setMethod(requestContext.enumCrudMethod);
if (content != null )
requestParams.setContent(content.toString());
//create the variables with its values as derived from the defined keys in the exposed apis (prefixed with '$')
//i.e for $mdeKey, at run time this key will include "mdekey"->"100000025"
if (mapVariableToParamIndex!=null && mapVariableToParamIndex.size()>0) { if (mapVariableToParamIndex!=null && mapVariableToParamIndex.size()>0) {
Map<String,String> keyValueVariables = mapVariableToParamIndex.entrySet().stream() keyValueVariables = mapVariableToParamIndex.entrySet().stream()
.collect(Collectors.toMap( .collect(Collectors.toMap(
e -> e.getKey(), e -> e.getKey(),
e -> requestContext.params[e.getValue()])); //if maintenance request, set offset of 1 to skip "maintenance"
requestParams.setVariablesValues(keyValueVariables); e -> requestContext.params[((isMaintenanceRequest)?(e.getValue()+1):e.getValue())]));
} }
requestParams= new RequestParams(apiIdAsParams,
keyValueVariables,
requestContext.queryParameters,
requestContext.enumCrudMethod,
(content!=null)? content.toString():null,
isMaintenanceRequest);
return requestParams; return requestParams;
} }
private RequestParams convertToRequestParams(RequestContext requestContext, JsonNode content,Map<String, Integer> mapVariableToParamIndex) { private RequestParams convertToRequestParams(RequestContext requestContext,
return convertToRequestParams(requestContext, content, mapVariableToParamIndex, false); String[] apiIdAsParams,
JsonNode content,
Map<String, Integer> mapVariableToParamIndex) {
return convertToRequestParams(requestContext, apiIdAsParams, content, mapVariableToParamIndex, false);
} }
} }
package logic.adapter.HttpAdapter;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;
/**
* Created by eli on 1/23/17.
*/
public class ComputeActionVariablesParams {
public ComputeActionVariablesParams(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
public Map<String, String> getVariablesValues() {
return variablesValues;
}
public void setVariablesValues(Map<String, String> variablesValues) {
this.variablesValues = variablesValues;
}
public JsonNode getJsonNode() {
return jsonNode;
}
private Map<String, String> variablesValues =null;
private JsonNode jsonNode;
}
...@@ -6,8 +6,8 @@ import logic.adapter.HttpAdapter.action.OnHttpResponse; ...@@ -6,8 +6,8 @@ import logic.adapter.HttpAdapter.action.OnHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction; import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.HttpAdapter.action.WebSocketAction; import logic.adapter.HttpAdapter.action.WebSocketAction;
import logic.adapter.HttpAdapter.model.*; import logic.adapter.HttpAdapter.model.*;
import logic.adapter.action.ArrayNodeAction;
import logic.adapter.action.BaseAction; import logic.adapter.action.BaseAction;
import logic.adapter.action.JsonConvertAction;
import logic.adapter.loader.FileAdapterLoader; import logic.adapter.loader.FileAdapterLoader;
import logic.adapter.model.*; import logic.adapter.model.*;
import logic.webSocket.WebSocketManager; import logic.webSocket.WebSocketManager;
...@@ -17,6 +17,8 @@ import http.simpleHttpClient.SimpleHttpResponse; ...@@ -17,6 +17,8 @@ import http.simpleHttpClient.SimpleHttpResponse;
import java.util.*; import java.util.*;
import static util.Utils.myTypeOf;
/** /**
* Created by eli on 13/06/16. * Created by eli on 13/06/16.
...@@ -26,13 +28,13 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -26,13 +28,13 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
private SimpleHttpClient httpClient = null; private SimpleHttpClient httpClient = null;
private WebSocketManager webSocketManager = null; private WebSocketManager webSocketManager = null;
public static String myTypeOf(Object obj){ // public static String myTypeOf(Object obj){
int end_index = obj.toString().indexOf('@'); // int end_index = obj.toString().indexOf('@');
String type=obj.toString().substring(0,end_index); // String type=obj.toString().substring(0,end_index);
int startIndex = type.lastIndexOf("."); // int startIndex = type.lastIndexOf(".");
startIndex++; // startIndex++;
return type.substring(startIndex,end_index); // return type.substring(startIndex,end_index);
} // }
public HttpAdapter(ILogger logger, String id) throws Exception { public HttpAdapter(ILogger logger, String id) throws Exception {
...@@ -78,7 +80,7 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -78,7 +80,7 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
for (HttpFlow httpFlow : for (HttpFlow httpFlow :
getModel().getFlows()) { getModel().getFlows()) {
httpAction = (SimpleHttpAction) httpFlow.getAction(); httpAction = (SimpleHttpAction) httpFlow.getAction();
httpFlow.addHttpAction(httpAction); // httpFlow.addHttpAction(httpAction);
httpAction.setAdapterReferences(config.getConfigHttpRequestParams(), httpAction.setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient, httpClient,
authClient); authClient);
...@@ -90,21 +92,21 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -90,21 +92,21 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
for (BaseAction action : for (BaseAction action :
actions) { actions) {
if (myTypeOf(action).equals("WebSocketAction")) { if (myTypeOf(action).equals("WebSocketAction")) {
httpFlow.addWebSocketAction((WebSocketAction) action); // httpFlow.addWebSocketAction((WebSocketAction) action);
((WebSocketAction) action).setWebSocetManager(webSocketManager); ((WebSocketAction) action).setWebSocketManager(webSocketManager);
} else if (myTypeOf(action).equals("SimpleHttpAction")) { } else if (myTypeOf(action).equals("SimpleHttpAction")) {
action.setAdapterReferences(config.getConfigHttpRequestParams(), action.setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient, httpClient,
authClient); authClient);
httpFlow.addHttpAction((SimpleHttpAction) action); // httpFlow.addHttpAction((SimpleHttpAction) action);
} else if (myTypeOf(action).equals("JsonConvertAction")) { } else if (myTypeOf(action).equals("ArrayNodeAction")) {
List<IntermediateOperation> interOperations = ((JsonConvertAction) action).getParams().getIntermediateOperations(); List<IntermediateOperation> interOperations = ((ArrayNodeAction) action).getParams().getIntermediateOperations();
for (IntermediateOperation operation : for (IntermediateOperation operation :
interOperations) { interOperations) {
if (myTypeOf(operation).contains("Map")) { if (myTypeOf(operation).contains("Map")) {
BaseAction action1 = ((MapOperationParams) operation.getOperationParams()).getAction(); BaseAction action1 = ((MapOperationParams) operation.getOperationParams()).getAction();
if (myTypeOf(action1).equals("SimpleHttpAction")) { if (myTypeOf(action1).equals("SimpleHttpAction")) {
httpFlow.addHttpAction((SimpleHttpAction) action1); // httpFlow.addHttpAction((SimpleHttpAction) action1);
action1.setAdapterReferences(config.getConfigHttpRequestParams(), action1.setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient, httpClient,
authClient); authClient);
...@@ -120,22 +122,22 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -120,22 +122,22 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
actions = actionsListOnError.getActions(); actions = actionsListOnError.getActions();
for (BaseAction act : actions) { for (BaseAction act : actions) {
if (myTypeOf(act).equals("WebSocketAction")) { if (myTypeOf(act).equals("WebSocketAction")) {
httpFlow.addWebSocketAction((WebSocketAction) act); // httpFlow.addWebSocketAction((WebSocketAction) act);
((WebSocketAction) act).setWebSocetManager(webSocketManager); ((WebSocketAction) act).setWebSocketManager(webSocketManager);
} }
if (myTypeOf(act).equals("SimpleHttpAction")) { if (myTypeOf(act).equals("SimpleHttpAction")) {
httpFlow.addHttpAction((SimpleHttpAction) act); // httpFlow.addHttpAction((SimpleHttpAction) act);
act.setAdapterReferences(config.getConfigHttpRequestParams(), act.setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient, httpClient,
authClient); authClient);
} else if (myTypeOf(act).equals("JsonConvertAction")) { } else if (myTypeOf(act).equals("ArrayNodeAction")) {
List<IntermediateOperation> interOperations = ((JsonConvertAction) act).getParams().getIntermediateOperations(); List<IntermediateOperation> interOperations = ((ArrayNodeAction) act).getParams().getIntermediateOperations();
for (IntermediateOperation operation : for (IntermediateOperation operation :
interOperations) { interOperations) {
if (myTypeOf(operation).contains("Map")) { if (myTypeOf(operation).contains("Map")) {
BaseAction action1 = ((MapOperationParams) operation.getOperationParams()).getAction(); BaseAction action1 = ((MapOperationParams) operation.getOperationParams()).getAction();
if (myTypeOf(action1).equals("SimpleHttpAction")) { if (myTypeOf(action1).equals("SimpleHttpAction")) {
httpFlow.addHttpAction((SimpleHttpAction) action1); // httpFlow.addHttpAction((SimpleHttpAction) action1);
action1.setAdapterReferences(config.getConfigHttpRequestParams(), action1.setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient, httpClient,
authClient); authClient);
...@@ -151,31 +153,6 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -151,31 +153,6 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
} }
private void setHttpActionsReferences(List<BaseAction> listBaseActions) {
HttpAdapterConfig config = (HttpAdapterConfig) getModel().getConfig();
if (listBaseActions== null) {getLogger().error("setHttpActionsReferences failed"); return;}
// List<BaseAction> listBaseActions = actionsList.getActions();
for (BaseAction action : listBaseActions) {
if (action.getType().equals(SimpleHttpAction.TYPE)){
((SimpleHttpAction)action).setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient,
authClient);
}
// else if (action.getClass().isInstance(JsonConvertAction.class)){
else if (action.getType().equals(JsonConvertAction.TYPE)){
JsonConvertActionParams params = ((JsonConvertAction)action).getParams();
List<IntermediateOperation> operationList = params.getIntermediateOperations();
for (IntermediateOperation operation : operationList) {
operation.getOperationParams().setAdapterReferences(config.getConfigHttpRequestParams(),
httpClient,
authClient);
}
}
}
}
@Override @Override
...@@ -189,8 +166,6 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp ...@@ -189,8 +166,6 @@ public class HttpAdapter extends BaseAdapter<HttpFlow, RequestParams, SimpleHttp
HttpFlow flow = this.getModel().getFlow(flowId); HttpFlow flow = this.getModel().getFlow(flowId);
if (flow!=null){ if (flow!=null){
//set run time RequestParams to all action of types SimpleHttpAction and WebSocketAction
flow.setRunTimeHttpRequest(input);
try { try {
resp = flow.execute(input); resp = flow.execute(input);
} catch (Exception e) { } catch (Exception e) {
......
package logic.adapter.HttpAdapter; package logic.adapter.HttpAdapter;
import logic.adapter.HttpAdapter.model.NameValueParam; import com.fasterxml.jackson.databind.JsonNode;
import microservice.defs.Enums; import microservice.defs.Enums;
import java.util.ArrayList;
import java.util.Deque; import java.util.Deque;
import java.util.Map; import java.util.Map;
...@@ -10,70 +9,80 @@ import java.util.Map; ...@@ -10,70 +9,80 @@ import java.util.Map;
* Created by eli on 11/29/16. * Created by eli on 11/29/16.
*/ */
public class RequestParams { public class RequestParams {
private String[] params = null; private final String[] params;
private Map<String, String> variablesValues =null; private final Map<String, String> variablesValues;
private Map<String, Deque<String>> queryParameters = null; private final Map<String, Deque<String>> queryParameters;
private Enums.EnumCrudMethod enumCrudMethod; private final Enums.EnumCrudMethod enumCrudMethod;
private final String content;
private final boolean isMaintenance;
private Map<String, String> headersMap = null; private Map<String, String> headersMap = null;
private String content; private ComputeActionVariablesParams computeActionVariablesParams;
private boolean isMaintenance=false;
public RequestParams(String[] params,
Map<String, String> keyValueVariables,
Map<String, Deque<String>> queryParameters,
Enums.EnumCrudMethod enumCrudMethod,
String content,
boolean isMaintenanceRequest) {
this(params, keyValueVariables, queryParameters, enumCrudMethod, content, isMaintenanceRequest, null);
}
public RequestParams(String[] params,
Map<String, String> keyValueVariables,
Map<String, Deque<String>> queryParameters,
Enums.EnumCrudMethod enumCrudMethod,
String content,
boolean isMaintenanceRequest,
Map<String, String> headersMap/*default null*/) {
this.params=params;
this.variablesValues=keyValueVariables;
this.queryParameters=queryParameters;
this.enumCrudMethod=enumCrudMethod;
this.content=content;
this.isMaintenance=isMaintenanceRequest;
this.headersMap=headersMap;
}
public ComputeActionVariablesParams getComputeActionVariablesParams() {
return computeActionVariablesParams;
}
public void setComputeActionVariablesParams(ComputeActionVariablesParams computeActionVariablesParams) {
this.computeActionVariablesParams = computeActionVariablesParams;
}
public boolean isMaintenance() { public boolean isMaintenance() {
return isMaintenance; return isMaintenance;
} }
public String[] getParams() { public String[] getParams() {
return params; return params;
} }
public void setParams(String[] params) {
this.params = params;
}
public Map<String, Deque<String>> getQueryParameters() { public Map<String, Deque<String>> getQueryParameters() {
return queryParameters; return queryParameters;
} }
public void setQueryParameters(Map<String, Deque<String>> queryParameters) { public Enums.EnumCrudMethod getEnumCrudMethod()
this.queryParameters = queryParameters; {
}
public Enums.EnumCrudMethod getEnumCrudMethod() {
return enumCrudMethod; return enumCrudMethod;
} }
public void setMethod(Enums.EnumCrudMethod enumCrudMethod) { public Map<String, String> getHeadersMap()
this.enumCrudMethod = enumCrudMethod; {
}
public Map<String, String> getHeadersMap() {
return headersMap; return headersMap;
} }
public void setHeadersMap(Map<String, String> headersMap) { public void setHeadersMap(Map<String, String> headersMap) {
this.headersMap = headersMap; this.headersMap = headersMap;
} }
public String getContent()
public String getContent() { {
return content; return content;
} }
public Map<String, String> getVariablesValues()
public void setContent(String content) { {
this.content = content; return this.variablesValues;
}
public Map<String, String> getVariablesValues() {
return variablesValues;
}
public void setVariablesValues(Map<String, String> variablesValues) {
this.variablesValues = variablesValues;
} }
public RequestParams() {}
public String getQueryParameter(String paramName) { public String getQueryParameter(String paramName) {
return (((this.queryParameters != null) && (this.queryParameters.containsKey(paramName)))? return (((this.queryParameters != null) && (this.queryParameters.containsKey(paramName)))?
(String)((Deque)this.queryParameters.get(paramName)).getFirst():null); (String)((Deque)this.queryParameters.get(paramName)).getFirst():null);
} }
public void setIsMaintenance(boolean isMaintenance) {
this.isMaintenance = isMaintenance;
}
} }
...@@ -4,15 +4,16 @@ import com.fasterxml.jackson.annotation.JsonCreator; ...@@ -4,15 +4,16 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import http.simpleHttpClient.SimpleHttpResponse; import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.HttpAdapter; import logic.adapter.HttpAdapter.ComputeActionVariablesParams;
import logic.adapter.HttpAdapter.RequestParams; import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.model.ConvertActionRunTimeParams;
import logic.adapter.action.ArrayNodeAction;
import logic.adapter.action.BaseAction; import logic.adapter.action.BaseAction;
import logic.adapter.model.HttpFlowParams;
import util.Utils; import util.Utils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Created by eli on 11/27/16. * Created by eli on 11/27/16.
...@@ -81,7 +82,7 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> { ...@@ -81,7 +82,7 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> {
} }
// @Override // @Override
public boolean isValid() { public boolean isValid() {
if (actionsInput.equals("CONTENT")) { if (actionsInput.equals("CONTENT")) {
if (actions.size() != 0) if (actions.size() != 0)
...@@ -95,24 +96,23 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> { ...@@ -95,24 +96,23 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> {
} }
// public void setRunTimeHttpRequest(RequestParams inRequestParams) { // public SimpleHttpResponse executeActions(SimpleHttpResponse input) throws Exception {
// this.runTimeHttpRequest = inRequestParams; public SimpleHttpResponse executeActions(HttpFlowParams flowParams) throws Exception {
// } // HttpFlowParams flowParams;
// SimpleHttpResponse input = flowParams.getHttpResp();
// private RequestParams runTimeHttpRequest; RequestParams requestParams = flowParams.getRequestParams();
// @Override
public SimpleHttpResponse executeActions(SimpleHttpResponse input) throws Exception {
String content = input.getContent(); String content = input.getContent();
JsonNode node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class); JsonNode node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class);
List<BaseAction> actions=getActions(); List<BaseAction> actions = getActions();
SimpleHttpResponse resp; SimpleHttpResponse resp;
for (BaseAction action : actions) for (BaseAction action : actions)
{ {
if (action.getType().equals(SimpleHttpAction.TYPE)) { //prepare the run time input required to calculate variables inside action
//SimpleHttpResponse resp = (SimpleHttpResponse) action.apply(runTimeHttpRequest); requestParams.setComputeActionVariablesParams(new ComputeActionVariablesParams(node));
((SimpleHttpAction)action).computeVariables(node);
resp = (SimpleHttpResponse) action.apply(null); if (action.getObjectType().equals(SimpleHttpAction.TYPE)) {
resp = (SimpleHttpResponse) action.apply(requestParams);
if (resp.getStatusCode()!= 200) if (resp.getStatusCode()!= 200)
{ {
return new SimpleHttpResponse(500,"failed onSuccess.executeActions.httpAction with error:" +resp.getStatusCode() ); return new SimpleHttpResponse(500,"failed onSuccess.executeActions.httpAction with error:" +resp.getStatusCode() );
...@@ -120,16 +120,20 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> { ...@@ -120,16 +120,20 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> {
content = resp.getContent(); content = resp.getContent();
node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class); node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class);
} }
//assumed that after extractValueAction //assumed that this is the last response action.
else if (HttpAdapter.myTypeOf(action).equals("WebSocketAction")){ else if (action.getObjectType().equals(WebSocketAction.TYPE)){
// Map<String,String > runTimeParams = new HashMap<>(); resp = (SimpleHttpResponse) action.apply(requestParams);
// if (node!=null && node.isTextual()) runTimeParams.put("webSocket", node.asText()); // content = resp.getContent();
// action.setRunTimeVariables(runTimeParams); // node = (JsonNode)Utils.readObjectFromString1(content, JsonNode.class);
// SimpleHttpResponse resp = (SimpleHttpResponse) action.apply(runTimeHttpRequest);
((WebSocketAction)action).computeVariables(node);
resp = (SimpleHttpResponse) action.apply(null);
} }
else if (action.getObjectType().equals("ArrayNodeAction"))
{
ConvertActionRunTimeParams runTimeParams=new ConvertActionRunTimeParams(node,requestParams);
node = (((ArrayNodeAction)action).apply(runTimeParams));
if (node==null)
return new SimpleHttpResponse(500,"failed onSuccess.executeActions.JsonAction " );
}
else //JsonNodeAction.class else //JsonNodeAction.class
{ {
node = (JsonNode)action.apply(node); node = (JsonNode)action.apply(node);
...@@ -139,7 +143,6 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> { ...@@ -139,7 +143,6 @@ public class HttpContentActions {//extends ActionsList<SimpleHttpResponse> {
} }
return new SimpleHttpResponse(200,node.toString()); return new SimpleHttpResponse(200,node.toString());
// return input
} }
} }
...@@ -3,12 +3,8 @@ package logic.adapter.HttpAdapter.action; ...@@ -3,12 +3,8 @@ package logic.adapter.HttpAdapter.action;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import http.simpleHttpClient.SimpleHttpResponse; import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.model.OnResponse; import logic.adapter.model.HttpFlowParams;
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. * Created by eli on 11/27/16.
...@@ -35,17 +31,17 @@ public class OnHttpResponse{ //extends OnResponse<SimpleHttpResponse> { ...@@ -35,17 +31,17 @@ public class OnHttpResponse{ //extends OnResponse<SimpleHttpResponse> {
} }
public SimpleHttpResponse execute(SimpleHttpResponse actionResp) { public SimpleHttpResponse execute(HttpFlowParams flowParams) {
if (actionResp.getStatusCode() == 200) { if (flowParams.getHttpResp().getStatusCode() == 200) {
try { try {
return onSuccess.executeActions(actionResp); return onSuccess.executeActions(flowParams);
} catch (Exception e) { } catch (Exception e) {
return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e); return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e);
} }
} else { } else {
try { try {
return onError.executeActions(actionResp); return onError.executeActions(flowParams);
} catch (Exception e) { } catch (Exception e) {
return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e); return new SimpleHttpResponse(500, "OnHttpResponse.execute failed with error: " + e);
} }
......
...@@ -40,6 +40,7 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques ...@@ -40,6 +40,7 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques
*/ */
@JsonCreator @JsonCreator
public SimpleHttpAction(@JsonProperty("params") HttpRequestActionParams params) { public SimpleHttpAction(@JsonProperty("params") HttpRequestActionParams params) {
super(params); super(params);
} }
...@@ -63,12 +64,14 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques ...@@ -63,12 +64,14 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques
public SimpleHttpResponse apply(RequestParams requestParams) { public SimpleHttpResponse apply(RequestParams requestParams) {
//if not null authentication required //if not null authentication required
SimpleHttpResponse authResp,resp; SimpleHttpResponse authResp,resp;
SimpleHttpRequest httpRequest; SimpleHttpRequest httpRequest=null;
RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput();
// RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput();
RequestParams inRequestParams = requestParams;
//if authentication not needed or token already exist //if authentication not needed or token already exist
httpRequest = buildHttpRequest(inRequestParams);
try { try {
httpRequest = buildHttpRequest(inRequestParams);
resp = httpClient.processRequest(httpRequest); resp = httpClient.processRequest(httpRequest);
if (resp.getStatusCode()==401 || resp.getStatusCode() == 403){ if (resp.getStatusCode()==401 || resp.getStatusCode() == 403){
{ {
...@@ -83,9 +86,11 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques ...@@ -83,9 +86,11 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques
} }
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
resp = new SimpleHttpResponse(500, "failed to proccess http request with error: "+e); resp = new SimpleHttpResponse(500, "failed to process http request with error: "+e);
} catch (ErrorLoginException e) { } catch (ErrorLoginException e) {
resp = new SimpleHttpResponse(500, "authentication failed with error "+e); resp = new SimpleHttpResponse(500, "authentication failed with error "+e);
} catch (Exception e) {
resp = new SimpleHttpResponse(500, "SimpleHttpRequest.apply failed with error: "+e);
} }
return resp; return resp;
} }
...@@ -94,20 +99,17 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques ...@@ -94,20 +99,17 @@ public class SimpleHttpAction extends BaseAction<HttpRequestActionParams ,Reques
protected SimpleHttpRequest buildHttpRequest(RequestParams inRequestParams) { protected SimpleHttpRequest buildHttpRequest(RequestParams inRequestParams) throws Exception {
SimpleHttpRequest request = new HttpRequestResolver().createResolvedRequest(inRequestParams, SimpleHttpRequest request = HttpRequestResolver.createResolvedRequest(inRequestParams,
adapterHttpParams, adapterHttpParams,
getParams(), getParams(),
((oauth2Client != null)?oauth2Client.getToken():null), ((oauth2Client != null)?oauth2Client.getToken():null));
getRunTimeVariables());
return request; return request;
} }
public void computeVariables(JsonNode node) throws Exception {
setRunTimeVariables(getParams().computeVariables(node));
}
} }
...@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; ...@@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.neovisionaries.ws.client.WebSocketException; import com.neovisionaries.ws.client.WebSocketException;
import http.simpleHttpClient.SimpleHttpResponse; import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.ComputeActionVariablesParams;
import logic.adapter.HttpAdapter.ErrorLoginException; import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.RequestParams; import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.action.BaseAction; import logic.adapter.action.BaseAction;
...@@ -61,30 +62,45 @@ public class WebSocketAction extends BaseAction<WebSocketActionParams ,RequestPa ...@@ -61,30 +62,45 @@ public class WebSocketAction extends BaseAction<WebSocketActionParams ,RequestPa
@Override @Override
public SimpleHttpResponse apply(RequestParams requestParams) { public SimpleHttpResponse apply(RequestParams requestParams) {
OnEventDetails details=null; OnEventDetails details=null;
RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput(); // RequestParams inRequestParams = (requestParams!=null)?requestParams:getRunTimeInput();
RequestParams inRequestParams = requestParams;
Map<String,String> dynamicVariables=null;
try {
dynamicVariables = this.computeVariables(inRequestParams.getComputeActionVariablesParams());
} catch (Exception e) {
e.printStackTrace();
return new SimpleHttpResponse(500, "WebSocketAction Failed to compute Dynamic Variables with error: "+e);
}
String mdeKey=null; String mdeKey=null;
String uid=null; String uid=null;
if (!inRequestParams.isMaintenance()){
String httpPayload = inRequestParams.getContent(); String httpPayload = inRequestParams.getContent();
try { try {
details = (OnEventDetails) Utils.readObjectFromString1(httpPayload, OnEventDetails.class); details = (OnEventDetails) Utils.readObjectFromString1(httpPayload, OnEventDetails.class);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return new SimpleHttpResponse(500, "Failed to read Request payload OnEventDetails"); return new SimpleHttpResponse(500, "Failed to read Request payload OnEventDetails with error:" +e);
}
} }
Map<String, String> runTimeParameters = getRunTimeVariables();
String webSocket=null; 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 { try {
mdeKey=getParams().getResolvedMdeKey(inRequestParams.getVariablesValues()); WebSocketActionParams params;
uid=getParams().getResolvedUid(inRequestParams.getVariablesValues()); if (dynamicVariables !=null) {
webSocket=getParams().getResolvedWebSocket(getRunTimeVariables()); params = getParams();
webSocketManager.connect(mdeKey,uid,webSocket,details); mdeKey = params.getResolvedMdeKey(inRequestParams.getVariablesValues(), dynamicVariables);
uid = getParams().getResolvedUid(inRequestParams.getVariablesValues(), dynamicVariables);
webSocket = getParams().getResolvedWebSocket(dynamicVariables, inRequestParams.getVariablesValues());
}
else
{
mdeKey = getParams().getResolvedMdeKey(inRequestParams.getVariablesValues());
uid = getParams().getResolvedUid(inRequestParams.getVariablesValues());
webSocket = getParams().getResolvedWebSocket(inRequestParams.getVariablesValues());
}
webSocketManager.connect(mdeKey,uid,webSocket,details, inRequestParams.isMaintenance());
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
return new SimpleHttpResponse(500, "failed to connect to webSocket with error: "+e); return new SimpleHttpResponse(500, "failed to connect to webSocket with error: "+e);
} catch (ErrorLoginException e) { } catch (ErrorLoginException e) {
...@@ -106,12 +122,12 @@ public class WebSocketAction extends BaseAction<WebSocketActionParams ,RequestPa ...@@ -106,12 +122,12 @@ public class WebSocketAction extends BaseAction<WebSocketActionParams ,RequestPa
} }
public void setWebSocetManager(WebSocketManager webSocetManager) { public void setWebSocketManager(WebSocketManager webSocketManager) {
this.webSocketManager = webSocetManager; this.webSocketManager = webSocketManager;
} }
public void computeVariables(JsonNode node) throws Exception { public Map<String, String> computeVariables(ComputeActionVariablesParams computeActionVariablesParams) throws Exception {
setRunTimeVariables(getParams().computeVariables(node)); return getParams().computeVariables(computeActionVariablesParams.getJsonNode());
} }
} }
......
...@@ -7,6 +7,7 @@ import logic.adapter.model.BaseActionParams; ...@@ -7,6 +7,7 @@ import logic.adapter.model.BaseActionParams;
import logic.adapter.model.DynamicVariablesParams; import logic.adapter.model.DynamicVariablesParams;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -17,17 +18,14 @@ public class WebSocketActionParams extends DynamicVariablesParams{ ...@@ -17,17 +18,14 @@ public class WebSocketActionParams extends DynamicVariablesParams{
@JsonProperty("headers") @JsonProperty("headers")
private List<NameValueParam> headers; final private List<NameValueParam> headers;
@JsonProperty("webSocket") @JsonProperty("webSocket")
private String webSocket; final private String webSocket;
@JsonProperty("mdeKey") @JsonProperty("mdeKey")
private String mdeKey; final private String mdeKey;
@JsonProperty("uid") @JsonProperty("uid")
private String uid; final private String uid;
// "webSocket": "$webSocket"
// "mdeKey": "$mdeKey",
// "uid": "$uid"
public WebSocketActionParams(@JsonProperty("variables") Map<String, ComputeVariable> mapVariableToValueComputation, public WebSocketActionParams(@JsonProperty("variables") Map<String, ComputeVariable> mapVariableToValueComputation,
@JsonProperty("headers") List<NameValueParam> headers, @JsonProperty("headers") List<NameValueParam> headers,
...@@ -52,27 +50,35 @@ public class WebSocketActionParams extends DynamicVariablesParams{ ...@@ -52,27 +50,35 @@ public class WebSocketActionParams extends DynamicVariablesParams{
return true; return true;
} }
public String getResolvedMdeKey(Map<String, String> variablesValues) { public String getResolvedMdeKey(Map<String, String>... listOfMapsOfVariables) {
return resolve(this.mdeKey,variablesValues); return resolve(this.mdeKey,listOfMapsOfVariables);
} }
private String resolve(String key, Map<String, String> variablesValues) { private String resolve(String key, Map<String, String>... listOfMapsOfVariables) {
String resolved=null; String resolved=null;
String realKey=null; String realKey=null;
if (key!=null && key.startsWith("$")){ if (key!=null && key.startsWith("$")) {
realKey = key.substring(1); realKey = key.substring(1);
resolved = variablesValues.get(realKey); for (Map<String, String> variables :
listOfMapsOfVariables) {
if (variables.containsKey(realKey)) {
resolved = variables.get(realKey);
break;
}
}
} }
else if (key!=null) else if (key!=null)
resolved=key; resolved=key;
return resolved; return resolved;
} }
public String getResolvedUid(Map<String, String> variablesValues) { public String getResolvedUid(Map<String, String>... listOfMapsOfVariables) {
return resolve(this.uid,variablesValues); return resolve(this.uid,listOfMapsOfVariables);
} }
public String getResolvedWebSocket(Map<String, String> variablesValues) { public String getResolvedWebSocket(Map<String, String>... listOfMapsOfVariables) {
return resolve(this.webSocket,variablesValues); return resolve(this.webSocket,listOfMapsOfVariables);
} }
} }
package logic.adapter.HttpAdapter.model; package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.HttpAdapter.action.ExtractSubStringAction; import logic.adapter.HttpAdapter.action.ExtractSubStringAction;
import logic.adapter.action.BaseAction;
import logic.adapter.action.ExtractValueAction;
import logic.adapter.action.SubStringAction;
import logic.adapter.model.BaseActionParams;
import java.util.List;
import static util.Utils.myTypeOf;
/** /**
* Created by eli on 12/11/16. * Created by eli on 12/11/16.
...@@ -31,9 +22,6 @@ public class ComputeVariable{ ...@@ -31,9 +22,6 @@ public class ComputeVariable{
this.action = action; this.action = action;
} }
@JsonIgnore
private String actionRunTimeResult;
public String execute(JsonNode node) throws Exception { public String execute(JsonNode node) throws Exception {
return action.apply(node); return action.apply(node);
......
package logic.adapter.HttpAdapter.model;
import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.HttpAdapter.RequestParams;
/**
* Created by eli on 1/25/17.
*/
public class ConvertActionRunTimeParams {
public ConvertActionRunTimeParams(JsonNode jsonNode, RequestParams requestParams) {
this.jsonNode = jsonNode;
this.requestParams = requestParams;
}
public JsonNode getJsonNode() {
return jsonNode;
}
public RequestParams getRequestParams() {
return requestParams;
}
private JsonNode jsonNode;
private RequestParams requestParams;
}
...@@ -9,7 +9,7 @@ import java.util.function.Predicate; ...@@ -9,7 +9,7 @@ import java.util.function.Predicate;
/** /**
* Created by eli on 11/22/16. * Created by eli on 11/22/16.
*/ */
public class FilterJsonOperation extends FilterIntermediateOperation<JsonNode> { public class FilterJsonOperation extends FilterIntermediateOperation<ConvertActionRunTimeParams> {
public final static String TYPE="FilterJsonOperation"; public final static String TYPE="FilterJsonOperation";
@JsonCreator @JsonCreator
public FilterJsonOperation(@JsonProperty("operationParams") FilterOperationParams operationParams) { public FilterJsonOperation(@JsonProperty("operationParams") FilterOperationParams operationParams) {
...@@ -17,7 +17,7 @@ public class FilterJsonOperation extends FilterIntermediateOperation<JsonNode> { ...@@ -17,7 +17,7 @@ public class FilterJsonOperation extends FilterIntermediateOperation<JsonNode> {
} }
@Override @Override
protected Predicate<JsonNode> buildFunc() { protected Predicate<ConvertActionRunTimeParams> buildFunc() {
return null; return null;
} }
......
...@@ -11,6 +11,7 @@ import logic.adapter.HttpAdapter.action.SimpleHttpAction; ...@@ -11,6 +11,7 @@ import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.HttpAdapter.action.WebSocketAction; import logic.adapter.HttpAdapter.action.WebSocketAction;
import logic.adapter.action.BaseAction; import logic.adapter.action.BaseAction;
import logic.adapter.model.BaseFlow; import logic.adapter.model.BaseFlow;
import logic.adapter.model.HttpFlowParams;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -19,30 +20,55 @@ import java.util.List; ...@@ -19,30 +20,55 @@ import java.util.List;
* Created by eli on 11/17/16. * Created by eli on 11/17/16.
*/ */
public class HttpFlow extends BaseFlow{ public class HttpFlow extends BaseFlow{
@JsonIgnore @JsonProperty("action")
private List<SimpleHttpAction> httpActions = new ArrayList<>(); protected SimpleHttpAction action;
@JsonProperty("onResponse")
protected OnHttpResponse onResponse;
@JsonIgnore public void build(){
private List<WebSocketAction> webSocketActions = new ArrayList<>(); action.build();
@JsonIgnore // onResponse.build();
public boolean addHttpAction(SimpleHttpAction action) { return httpActions.add(action);} }
@JsonIgnore
public boolean addWebSocketAction(WebSocketAction action) { return webSocketActions.add(action);}
@JsonCreator public SimpleHttpAction getAction() {
public HttpFlow(@JsonProperty("action") SimpleHttpAction action, return action;
@JsonProperty("onResponse") OnHttpResponse onResponse){ }
super(action, onResponse); public void setAction(SimpleHttpAction action) {
this.action = action;
}
public OnHttpResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(OnHttpResponse onResponse) {
this.onResponse = onResponse;
} }
public void setRunTimeHttpRequest(RequestParams input) { public SimpleHttpResponse execute(RequestParams input) throws Exception {
for (SimpleHttpAction action : httpActions){ HttpFlowParams flowParams;
action.setRunTimeInput(input); SimpleHttpResponse actionResp = action.apply(input);
flowParams = new HttpFlowParams();
flowParams.setRequestParams(input);
flowParams.setHttpResp(actionResp);
try {
return onResponse.execute(flowParams);
} catch (Exception e) {
e.printStackTrace();
return actionResp;
}
} }
for (WebSocketAction action : webSocketActions){ @Override
action.setRunTimeInput(input); public boolean isValid() {
return (action.isValid() && onResponse.isValid());
} }
@JsonCreator
public HttpFlow(@JsonProperty("action") SimpleHttpAction action,
@JsonProperty("onResponse") OnHttpResponse onResponse){
super(action.getParams().getId());
this.action = action;
this.onResponse = onResponse;
} }
} }
...@@ -6,10 +6,8 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -6,10 +6,8 @@ import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler; import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpResponse; import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction; import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.action.BaseAction;
import logic.adapter.action.JsonNodeAction; import logic.adapter.action.JsonNodeAction;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import static util.Utils.myTypeOf; import static util.Utils.myTypeOf;
...@@ -17,7 +15,7 @@ import static util.Utils.myTypeOf; ...@@ -17,7 +15,7 @@ import static util.Utils.myTypeOf;
/** /**
* Created by eli on 11/22/16. * Created by eli on 11/22/16.
*/ */
public class MapJsonToJsonOperation extends MapIntermediateOperation<JsonNode, JsonNode> { public class MapJsonToJsonOperation extends MapIntermediateOperation<ConvertActionRunTimeParams, JsonNode> {
@JsonCreator @JsonCreator
public MapJsonToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams) { public MapJsonToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams) {
...@@ -25,17 +23,18 @@ public class MapJsonToJsonOperation extends MapIntermediateOperation<JsonNode, J ...@@ -25,17 +23,18 @@ public class MapJsonToJsonOperation extends MapIntermediateOperation<JsonNode, J
} }
@Override @Override
protected Function<JsonNode, JsonNode> buildFunc() { protected Function<ConvertActionRunTimeParams, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (node) -> { Function<ConvertActionRunTimeParams,JsonNode> ret = (convertActionRunTimeParams) -> {
SimpleHttpResponse resp; SimpleHttpResponse resp;
String content; String content;
JsonNode node=convertActionRunTimeParams.getJsonNode();
try { try {
String type=myTypeOf(getOperationParams().getAction()); String type=myTypeOf(getOperationParams().getAction());
if (type.equals("SimpleHttpAction")) { if (type.equals("SimpleHttpAction")) {
SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction(); SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction();
//assumed that the action holds its input already, and use it //assumed that the action holds its input already, and use it
httpAction.computeVariables(node); // httpAction.computeVariables(convertActionRunTimeParams.get);
resp = ((SimpleHttpAction)httpAction).apply(null); resp = ((SimpleHttpAction)httpAction).apply(convertActionRunTimeParams.getRequestParams());
if (resp.getStatusCode()!=200) if (resp.getStatusCode()!=200)
throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() ); throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() );
else{ else{
......
...@@ -8,14 +8,13 @@ import http.simpleHttpClient.SimpleHttpResponse; ...@@ -8,14 +8,13 @@ import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.action.SimpleHttpAction; import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import logic.adapter.action.JsonNodeAction; import logic.adapter.action.JsonNodeAction;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
/** /**
* Created by eli on 11/22/16. * Created by eli on 11/22/16.
*/ */
public class MapJsonToStringOperation extends MapIntermediateOperation<JsonNode, JsonNode> { public class MapJsonToStringOperation extends MapIntermediateOperation<ConvertActionRunTimeParams, JsonNode> {
@JsonCreator @JsonCreator
public MapJsonToStringOperation(@JsonProperty("operationParams") MapOperationParams operationParams){ public MapJsonToStringOperation(@JsonProperty("operationParams") MapOperationParams operationParams){
...@@ -23,16 +22,16 @@ public class MapJsonToStringOperation extends MapIntermediateOperation<JsonNode ...@@ -23,16 +22,16 @@ public class MapJsonToStringOperation extends MapIntermediateOperation<JsonNode
} }
@Override @Override
protected Function<JsonNode, JsonNode> buildFunc() { protected Function<ConvertActionRunTimeParams, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (node) -> { Function<ConvertActionRunTimeParams,JsonNode> ret = (convertActionRunTimeParams) -> {
SimpleHttpResponse resp; SimpleHttpResponse resp;
JsonNode retNode; JsonNode retNode;
try { try {
//in this case assumed that the action get and return JsonNode!!!!! no else section //in this case assumed that the action get and return JsonNode!!!!! no else section
if(!getOperationParams().getAction().getClass().isInstance(SimpleHttpAction.class)) { if(!getOperationParams().getAction().getClass().isInstance(SimpleHttpAction.class)) {
JsonNodeAction JsonAction = (JsonNodeAction)getOperationParams().getAction(); JsonNodeAction JsonAction = (JsonNodeAction)getOperationParams().getAction();
retNode = (JsonNode)JsonAction.apply(node); retNode = (JsonNode)JsonAction.apply(convertActionRunTimeParams.getJsonNode());
System.out.println("MapJsonToStringOperation ,params="+ getOperationParams().toString()+"convert from node= [" +node.toString()+"] to convertedNode= ["+ retNode.toString()+"]"); System.out.println("MapJsonToStringOperation ,params="+ getOperationParams().toString()+"convert from node= [" +convertActionRunTimeParams.getJsonNode().toString()+"] to convertedNode= ["+ retNode.toString()+"]");
return retNode; return retNode;
} }
......
...@@ -30,24 +30,6 @@ public class MapOperationParams extends BaseOperationParams{ ...@@ -30,24 +30,6 @@ public class MapOperationParams extends BaseOperationParams{
return str; return str;
} }
// @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 @Override
public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams, public void setAdapterReferences(ConfigHttpRequestParams adapterHttpParams,
......
...@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; ...@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler; import common.JsonHandler;
import http.simpleHttpClient.SimpleHttpResponse; import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.ComputeActionVariablesParams;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.action.SimpleHttpAction; import logic.adapter.HttpAdapter.action.SimpleHttpAction;
import java.util.Map; import java.util.Map;
...@@ -13,7 +15,7 @@ import java.util.function.Function; ...@@ -13,7 +15,7 @@ import java.util.function.Function;
/** /**
* Created by eli on 11/22/16. * Created by eli on 11/22/16.
*/ */
public class MapStringToJsonOperation extends MapIntermediateOperation<JsonNode, JsonNode> { public class MapStringToJsonOperation extends MapIntermediateOperation<ConvertActionRunTimeParams, JsonNode> {
@JsonCreator @JsonCreator
public MapStringToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams){ public MapStringToJsonOperation(@JsonProperty("operationParams") MapOperationParams operationParams){
...@@ -21,24 +23,24 @@ public class MapStringToJsonOperation extends MapIntermediateOperation<JsonNode, ...@@ -21,24 +23,24 @@ public class MapStringToJsonOperation extends MapIntermediateOperation<JsonNode,
} }
@Override @Override
protected Function<JsonNode, JsonNode> buildFunc() { protected Function<ConvertActionRunTimeParams, JsonNode> buildFunc() {
Function<JsonNode,JsonNode> ret = (node) -> { Function<ConvertActionRunTimeParams,JsonNode> ret = (convertActionRunTimeParams) -> {
SimpleHttpResponse resp; SimpleHttpResponse resp;
String content; String content;
try { try {
//currently support only httpAction //currently support only httpAction
if (getOperationParams().getAction().getType().equals(SimpleHttpAction.TYPE)) { if (getOperationParams().getAction().getType().equals(SimpleHttpAction.TYPE)) {
SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction(); SimpleHttpAction httpAction = (SimpleHttpAction)getOperationParams().getAction();
RequestParams requestParams = convertActionRunTimeParams.getRequestParams();
//assumed that the action holds its input already, and use it requestParams.setComputeActionVariablesParams(new ComputeActionVariablesParams(convertActionRunTimeParams.getJsonNode()));
httpAction.computeVariables(node); resp = httpAction.apply(requestParams);
resp = httpAction.apply(null);
if (resp.getStatusCode()!=200) if (resp.getStatusCode()!=200)
throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() ); throw new Exception("MapJsonToJsonOperation: http action failed with status code: "+resp.getStatusCode()+" errorMsg: "+ resp.getContent() );
content=resp.getContent(); content=resp.getContent();
System.out.println("MapStringToJsonOperation params="+ getOperationParams().toString()+" convert node= "+node.toString()+" to convertedNode= "+content.toString()); System.out.println("MapStringToJsonOperation params="+ getOperationParams().toString()+" convert node= "
+convertActionRunTimeParams.getJsonNode().toString()+" to convertedNode= "+content);
return JsonHandler.getJsonNodeFromString(resp.getContent()); return JsonHandler.getJsonNodeFromString(resp.getContent());
} }
......
...@@ -9,6 +9,7 @@ import logic.adapter.model.ModelValidator; ...@@ -9,6 +9,7 @@ import logic.adapter.model.ModelValidator;
/** /**
* Created by eli on 11/17/16. * Created by eli on 11/17/16.
*/ */
@Deprecated
public abstract class OnResponse<TypeInOut > implements ModelValidator{ public abstract class OnResponse<TypeInOut > implements ModelValidator{
@JsonProperty("onSuccess") @JsonProperty("onSuccess")
......
...@@ -24,4 +24,10 @@ public abstract class Operation<T extends BaseOperationParams> { ...@@ -24,4 +24,10 @@ public abstract class Operation<T extends BaseOperationParams> {
private T operationParams; private T operationParams;
@Override
public final String toString(){
return super.toString();
}
} }
...@@ -12,6 +12,7 @@ import java.util.List; ...@@ -12,6 +12,7 @@ import java.util.List;
/** /**
* Created by eli on 11/17/16. * Created by eli on 11/17/16.
*/ */
@Deprecated
public abstract class ActionsList<TypeExecuteInOut> implements ModelValidator{ public abstract class ActionsList<TypeExecuteInOut> implements ModelValidator{
@JsonProperty("actionsInput") @JsonProperty("actionsInput")
private String actionsInput; private String actionsInput;
......
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import logic.adapter.HttpAdapter.RequestParams;
import logic.adapter.HttpAdapter.model.*;
import logic.adapter.model.ArrayNodeActionParams;
import logic.adapter.model.TerminateOperation;
import util.ArrayNodeCollector;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static util.Utils.myTypeOf;
/**
* Created by eli on 1/25/17.
*/
public class ArrayNodeAction extends BaseAction<ArrayNodeActionParams, ConvertActionRunTimeParams, JsonNode>{
@JsonCreator
public ArrayNodeAction(@JsonProperty("params") ArrayNodeActionParams params) {
super(params);
}
@Override
public String getType() {
return null;
}
@Override
public void build() throws Exception {
}
@Override
public JsonNode apply(ConvertActionRunTimeParams convertActionRunTimeParams) throws Exception {
final JsonNode arrayNode = convertActionRunTimeParams.getJsonNode();
final RequestParams requestParams= convertActionRunTimeParams.getRequestParams();
if (arrayNode == null || !arrayNode.isArray())
throw new Exception("ArrayNodeAction failed. expected ARRAY-NODE input ");
else{
Stream<JsonNode> streamOfJsonNodes;
streamOfJsonNodes = StreamSupport.stream(arrayNode.spliterator(),false);
ArrayNodeActionParams params=getParams();
List<IntermediateOperation> operations = params.getIntermediateOperations();
for (IntermediateOperation operation : operations) {
String type=myTypeOf(operation);
switch (type) {
case "MapJsonToJsonOperation":
streamOfJsonNodes = streamOfJsonNodes.map( (node) -> {
ConvertActionRunTimeParams runTimeParams = new ConvertActionRunTimeParams(node, requestParams);
return ((MapJsonToJsonOperation) operation).getFunc().apply(runTimeParams);
});
break;
case "MapJsonToStringOperation":
streamOfJsonNodes = streamOfJsonNodes.map((node -> {
ConvertActionRunTimeParams runTimeParams = new ConvertActionRunTimeParams(node, requestParams);
return ((MapJsonToStringOperation) operation).getFunc().apply(runTimeParams);
}));
break;
case "MapStringToJsonOperation":
streamOfJsonNodes = streamOfJsonNodes.map((node -> {
ConvertActionRunTimeParams runTimeParams = new ConvertActionRunTimeParams(node, requestParams);
return ((MapStringToJsonOperation) operation).getFunc().apply(runTimeParams);
}));
break;
case "FilterJsonOperation":
streamOfJsonNodes = streamOfJsonNodes.filter((node -> {
ConvertActionRunTimeParams runTimeParams = new ConvertActionRunTimeParams(node, requestParams);
return ((FilterJsonOperation) operation).getFunc().test(runTimeParams);
}));
break;
default:
throw new Exception("ArrayNodeAction failed. unsupported intermediate operation");
}
}
TerminateOperation termOperation = params.getTerminateOperation();
//HandleTerminateOperation
ArrayNodeCollector collector = new ArrayNodeCollector();
return streamOfJsonNodes.collect(collector);
}
}
}
...@@ -2,7 +2,6 @@ package logic.adapter.action; ...@@ -2,7 +2,6 @@ package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.JsonNode;
import http.simpleHttpClient.SimpleHttpClient; import http.simpleHttpClient.SimpleHttpClient;
import logic.adapter.HttpAdapter.OAuth2Client; import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams; import logic.adapter.HttpAdapter.model.ConfigHttpRequestParams;
...@@ -11,49 +10,39 @@ import logic.adapter.model.ModelValidator; ...@@ -11,49 +10,39 @@ import logic.adapter.model.ModelValidator;
import java.util.Map; import java.util.Map;
import static util.Utils.myTypeOf;
/** /**
* Created by eli on 11/17/16. * Created by eli on 11/17/16.
*/ */
@JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, include= JsonTypeInfo.As.PROPERTY, property="metaDataActionClass") @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> { public abstract class BaseAction<T extends BaseActionParams, TypeIn, TypeOut> implements ModelValidator, ThrowableFunction<TypeIn,TypeOut> {
private final String objectType;
@JsonProperty @JsonProperty
T params; T params;
public Map<String, String> getRunTimeVariables() {
return runTimeVariables;
}
private Map<String, String> runTimeVariables;
public BaseAction(T params) { public BaseAction(T params) {
this.params = params; this.params = params;
this.objectType =myTypeOf(this);
} }
public T getParams() {return params;}
public TypeIn getRunTimeInput() { public String getObjectType() { return objectType;}
return runTimeInput; public T getParams() {return params;}
}
public void setRunTimeInput(TypeIn runTimeInput) {
this.runTimeInput = runTimeInput;
}
TypeIn runTimeInput;
@Override @Override
public boolean isValid() { public boolean isValid() {
return params.isValid(); return params.isValid();
} }
abstract public String getType(); //must not override this method. used in myTypeOf to determine the type instead of using 'isInstanceOf'
public abstract void build() throws Exception; @Override
public final String toString(){
public void setRunTimeVariables(Map<String, String> convertedParameters) { return super.toString();
this.runTimeVariables = convertedParameters;
} }
abstract public String getType();
public abstract void build() throws Exception;
public ConfigHttpRequestParams getAdapterHttpParams() { public ConfigHttpRequestParams getAdapterHttpParams() {
return adapterHttpParams; return adapterHttpParams;
......
package logic.adapter.action;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
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.Stream;
import java.util.stream.StreamSupport;
import static util.Utils.myTypeOf;
/**
* 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) {
String type=myTypeOf(operation);
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);
}
}
}
...@@ -38,14 +38,6 @@ public class AdapterModel<T extends BaseFlow> implements ModelValidator{ ...@@ -38,14 +38,6 @@ public class AdapterModel<T extends BaseFlow> implements ModelValidator{
return null; return null;
} }
public void buildFlows() {
for (T flow:
flows) {
flow.build();
}
}
@Override @Override
public boolean isValid() { public boolean isValid() {
if ( config == null || !config.isValid() || flows == null ) if ( config == null || !config.isValid() || flows == null )
......
...@@ -11,7 +11,7 @@ import java.util.List; ...@@ -11,7 +11,7 @@ import java.util.List;
/** /**
* Created by eli on 11/21/16. * Created by eli on 11/21/16.
*/ */
public class JsonConvertActionParams extends BaseActionParams { public class ArrayNodeActionParams extends BaseActionParams {
@JsonProperty("intermediateOperations") @JsonProperty("intermediateOperations")
private List<IntermediateOperation> intermediateOperations= new ArrayList<>(); private List<IntermediateOperation> intermediateOperations= new ArrayList<>();
...@@ -29,7 +29,7 @@ public class JsonConvertActionParams extends BaseActionParams { ...@@ -29,7 +29,7 @@ public class JsonConvertActionParams extends BaseActionParams {
@JsonCreator @JsonCreator
public JsonConvertActionParams(@JsonProperty("intermediateOperations") List<IntermediateOperation> intermediateOperations, public ArrayNodeActionParams(@JsonProperty("intermediateOperations") List<IntermediateOperation> intermediateOperations,
@JsonProperty("terminateOperation") TerminateOperation terminateOperation) { @JsonProperty("terminateOperation") TerminateOperation terminateOperation) {
this.intermediateOperations = intermediateOperations; this.intermediateOperations = intermediateOperations;
this.terminateOperation = terminateOperation; this.terminateOperation = terminateOperation;
......
...@@ -12,55 +12,14 @@ import logic.adapter.HttpAdapter.action.SimpleHttpAction; ...@@ -12,55 +12,14 @@ import logic.adapter.HttpAdapter.action.SimpleHttpAction;
//HttpRequestActionParams, RequestParams,SimpleHttpResponse //HttpRequestActionParams, RequestParams,SimpleHttpResponse
public abstract class BaseFlow implements ModelValidator{ public abstract class BaseFlow implements ModelValidator{
@JsonProperty("action") private String flowId;
protected SimpleHttpAction action;
@JsonProperty("onResponse")
protected OnHttpResponse onResponse;
public BaseFlow(SimpleHttpAction action, public BaseFlow(String flowId) {
OnHttpResponse onResponse) this.flowId = flowId;
{
this.action = action;
this.onResponse = onResponse;
} }
public void build(){ public String getFlowId() {
action.build(); return flowId;
// 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 {
// action.getRunTimeVariables();
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());
} }
} }
......
...@@ -11,7 +11,7 @@ import java.util.stream.Collectors; ...@@ -11,7 +11,7 @@ import java.util.stream.Collectors;
* Created by eli on 12/15/16. * Created by eli on 12/15/16.
*/ */
public abstract class DynamicVariablesParams extends BaseActionParams{ public abstract class DynamicVariablesParams extends BaseActionParams{
private Map<String, ComputeVariable> mapVariableToValueComputation; final private Map<String, ComputeVariable> mapVariableToValueComputation;
public DynamicVariablesParams(Map<String, ComputeVariable> mapVariableToValueComputation) { public DynamicVariablesParams(Map<String, ComputeVariable> mapVariableToValueComputation) {
this.mapVariableToValueComputation = mapVariableToValueComputation; this.mapVariableToValueComputation = mapVariableToValueComputation;
......
package logic.adapter.model;
import http.simpleHttpClient.SimpleHttpResponse;
import logic.adapter.HttpAdapter.RequestParams;
/**
* Created by eli on 1/19/17.
*/
public class HttpFlowParams {
public RequestParams getRequestParams() {
return requestParams;
}
public void setRequestParams(RequestParams requestParams) {
this.requestParams = requestParams;
}
public SimpleHttpResponse getHttpResp() {
return httpResp;
}
public void setHttpResp(SimpleHttpResponse httpResp) {
this.httpResp = httpResp;
}
private RequestParams requestParams;
private SimpleHttpResponse httpResp;
}
//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.zjsonpatch.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;
////
//// }
// }
//
//}
...@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
/** /**
* Created by eli on 7/11/16. * Created by eli on 7/11/16.
*/ */
@Deprecated
public class ResponseAction { public class ResponseAction {
public String getType() { public String getType() {
return type; return type;
......
...@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
/** /**
* Created by eli on 7/11/16. * Created by eli on 7/11/16.
*/ */
@Deprecated
public interface INormalizer { public interface INormalizer {
String activate(String strToNormalize, JsonNode format); String activate(String strToNormalize, JsonNode format);
} }
...@@ -11,6 +11,7 @@ import util.zjsonpatch.ZJsonPatch; ...@@ -11,6 +11,7 @@ import util.zjsonpatch.ZJsonPatch;
/** /**
* Created by eli on 7/13/16. * Created by eli on 7/13/16.
*/ */
@Deprecated
public class JsonConverterNormalizer implements INormalizer { public class JsonConverterNormalizer implements INormalizer {
final private static String JSON_PATCH_LOCATION = Constants.CONFIG_LOCATION; final private static String JSON_PATCH_LOCATION = Constants.CONFIG_LOCATION;
@Override @Override
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
///** ///**
// * Created by eli on 7/11/16. // * Created by eli on 7/11/16.
// */ // */
//public class Xml2jsonNormalizer implements INormalizer { //public class Xml2jsonNormalizer implements INormalizer {
// //
// /** // /**
......
...@@ -13,15 +13,31 @@ import java.io.IOException; ...@@ -13,15 +13,31 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.*; import java.util.*;
import static util.Utils.currentDate;
/** /**
* Created by eli on 12/4/16. * Created by eli on 12/4/16.
*/ */
public class WebSocketConnection extends Thread { public class WebSocketConnection extends Thread {
private final String maintenanceBasePath = "mde/api/v1/maintenance/"; private final String maintenanceBasePath = "mde/api/v1/maintenance/";
private final String adapterId; private final String adapterId;
public WebSocketConnection(String adapterId, String connectionId, String uid, String webSocketUrl, OAuth2Client auth2Client, List<NameValueParam> defaultHeaders, OnEventDetails details, WebSocketEventListener eventListener) throws UnsupportedEncodingException, ErrorLoginException { private final String connectionDetails;
private final boolean initiateDisconnection;
static final long TIMEOUT_FOR_DISCONNECT_SEC = 300;
public WebSocketConnection(String adapterId,
String connectionId,
String uid,
String webSocketUrl,
OAuth2Client auth2Client,
List<NameValueParam> defaultHeaders,
OnEventDetails details,
WebSocketEventListener eventListener,
boolean initiateDisconnection) throws UnsupportedEncodingException, ErrorLoginException {
this.initiateDisconnection=initiateDisconnection;
this.adapterId=adapterId; this.adapterId=adapterId;
this.webSocketOpen =true; this.isDisconnected =false;
this.isStopRequested = false;
this.factory = new WebSocketFactory(); this.factory = new WebSocketFactory();
this.connectionId = connectionId; this.connectionId = connectionId;
this.uid = uid; this.uid = uid;
...@@ -40,6 +56,7 @@ public class WebSocketConnection extends Thread { ...@@ -40,6 +56,7 @@ public class WebSocketConnection extends Thread {
this.eventListener = new WebSocketEventListener(this, adapterId,connectionId, this.uid, details,null, eventListener.getMapUidToDetails()); this.eventListener = new WebSocketEventListener(this, adapterId,connectionId, this.uid, details,null, eventListener.getMapUidToDetails());
else else
this.eventListener = new WebSocketEventListener(this, adapterId,connectionId, this.uid, details,null, null); this.eventListener = new WebSocketEventListener(this, adapterId,connectionId, this.uid, details,null, null);
this.connectionDetails =" connection=[adapterId-" + adapterId + " ,connectionId-" + connectionId + "]";
this.initReconnectRequest(); this.initReconnectRequest();
...@@ -78,18 +95,29 @@ public class WebSocketConnection extends Thread { ...@@ -78,18 +95,29 @@ public class WebSocketConnection extends Thread {
} }
private Exception exception; private Exception exception;
private volatile boolean webSocketOpen; private volatile boolean isDisconnected;
private volatile boolean isStopRequested=false;
public boolean isClosedWebSocketWaitingForMaintenance() { public synchronized boolean isStopRequested() {
return closedWebSocketWaitingForMaintenance; return isStopRequested;
} }
private volatile boolean closedWebSocketWaitingForMaintenance; public synchronized boolean isDisconnected() {
return isDisconnected;
}
public synchronized void setDisconnected() {
this.isDisconnected=true;
// this.isStopRequested=true;
this.notify();
}
public synchronized void setStopRequested() {
System.out.println(Thread.currentThread().getName()+ " " + currentDate() +" applying stop request ");
this.isStopRequested =true;
this.notify();
System.out.println(Thread.currentThread().getName()+ " " + currentDate() +" Notify stop request ");
}
private void initReconnectRequest() { private void initReconnectRequest() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
...@@ -122,15 +150,12 @@ public class WebSocketConnection extends Thread { ...@@ -122,15 +150,12 @@ public class WebSocketConnection extends Thread {
webSocket.addHeader(header.getName(), header.getValue()); webSocket.addHeader(header.getName(), header.getValue());
} }
} }
// //for reconnection the listener is already exist
// if(eventListener==null)
// this.eventListener = new WebSocketEventListener(this, adapterId,connectionId, this.uid, details,null);
webSocket.addListener(eventListener); webSocket.addListener(eventListener);
webSocket.setPingInterval(50*1000); webSocket.setPingInterval(50*1000);
webSocket = webSocket.connect(); webSocket = webSocket.connect();
System.out.println("WebSocketConnection.createWebSocket(): status of connection: " + connectionId+ ": " +eventListener.getState().toString()); System.out.println(Thread.currentThread().getName()+ " " + currentDate() +" WebSocketConnection.createWebSocket(): status of connection: " + connectionId+ ": " +eventListener.getState().toString());
} }
public void addEventListener(String uid, OnEventDetails details) { public void addEventListener(String uid, OnEventDetails details) {
...@@ -158,6 +183,7 @@ public class WebSocketConnection extends Thread { ...@@ -158,6 +183,7 @@ public class WebSocketConnection extends Thread {
try { try {
synchronized (this) { synchronized (this) {
System.out.println(Thread.currentThread().getName()+ " " + currentDate() +"webSocketConnection start...."+ connectionDetails);
this.createWebSocket(); this.createWebSocket();
this.notify(); this.notify();
} }
...@@ -165,19 +191,23 @@ public class WebSocketConnection extends Thread { ...@@ -165,19 +191,23 @@ public class WebSocketConnection extends Thread {
// Status line. // Status line.
StatusLine sl = e.getStatusLine(); StatusLine sl = e.getStatusLine();
if ((sl.getStatusCode() == 401 || sl.getStatusCode() == 403) && auth2Client != null) { if ((sl.getStatusCode() == 401 || sl.getStatusCode() == 403) && auth2Client != null) {
System.out.println("webSocketConnection "+Thread.currentThread().getName()+ " " + currentDate() +" authentication failed, re-login trying to get new token trying again..."+ connectionDetails+" error:"+ e);
try { try {
this.auth2Client.login(); this.auth2Client.login();
synchronized (this) { synchronized (this) {
createWebSocket(); createWebSocket();
System.out.println("webSocketConnection "+Thread.currentThread().getName()+ " " + currentDate() +" reLogin Succeeded,"+ connectionDetails);
this.notify(); this.notify();
} }
} catch (ErrorLoginException | UnsupportedEncodingException e1) { } catch (ErrorLoginException | UnsupportedEncodingException e1) {
synchronized (this) { synchronized (this) {
System.out.println("webSocketConnection "+Thread.currentThread().getName()+ " " + currentDate() +" error#1: "+e1+connectionDetails+" error:"+ e1);
this.setException(e1); this.setException(e1);
this.notify(); this.notify();
} }
} catch (WebSocketException e1) { } catch (WebSocketException e1) {
System.out.println("webSocketConnection "+Thread.currentThread().getName()+ " " + currentDate() +" error#2: "+e1+connectionDetails+" error:"+ e1);
synchronized (this) { synchronized (this) {
this.setException(e1); this.setException(e1);
this.notify(); this.notify();
...@@ -187,55 +217,82 @@ public class WebSocketConnection extends Thread { ...@@ -187,55 +217,82 @@ public class WebSocketConnection extends Thread {
} catch (WebSocketException e) { } catch (WebSocketException e) {
synchronized (this) { synchronized (this) {
System.out.println("webSocketConnection "+Thread.currentThread().getName()+ " " + currentDate() +" error#3: "+e+connectionDetails+" error:"+ e);
this.setException(e); this.setException(e);
this.notify(); this.notify();
} }
} }
this.waitForClosedWebSocket();
} /*UNCOMMENT THE FOLLOWING TO TEST RECONNECTION FLOW. IT WILL APPLY
* ONE DISCONNECTION AFTER THE SPECIFIED INTERVAL
* BUT IT HAPPENS ONLY ONCE. RECONNECTED CONNECTIONS WON'T BE DISCONNECTED
private void waitForClosedWebSocket() { if (initiateDisconnection) {
while (webSocketOpen) {
try { try {
Thread.sleep(500); System.out.println("webSocketConnection " + Thread.currentThread().getName() + " " + currentDate() + " waiting "+ TIMEOUT_FOR_DISCONNECT_SEC +" seconds before initiating client disconnection" + connectionDetails);
sleep(TIMEOUT_FOR_DISCONNECT_SEC * 1000);
//disconnection, not in case of already reconnected connection
if (details != null) {
System.out.println("webSocketConnection " + Thread.currentThread().getName() + " " + currentDate() + " start Test: initiated disconnect of:" + connectionDetails);
webSocket.disconnect();
System.out.println("webSocketConnection " + Thread.currentThread().getName() + " " + currentDate() + " disconnected:" + connectionDetails);
}
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
*/
this.waitForDisconnection();
//Let the websocket maintenance a chance to handle the closed websocket
try {
synchronized (this) {
this.closedWebSocketWaitingForMaintenance = true;
this.sendReconnectRequest();
} }
while (this.closedWebSocketWaitingForMaintenance) {
private void waitForDisconnection() {
synchronized (this) {
// try {
//wait that the listener signals that the websocket connection was disconnected
try { try {
Thread.sleep(500); System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "start waitForDisconnection [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
} catch (InterruptedException e) { while (!isDisconnected())
e.printStackTrace(); this.wait();
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "assumed disconnect [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
} catch (InterruptedException e1) {
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "ERROR: " + e1 + " waitForDisconnection [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
e1.printStackTrace();
} }
System.out.println("#1 " + Thread.currentThread().getName() + " "+ currentDate() + "isDisconnected=" + isDisconnected() + "isStopRequested=" + isStopRequested() + " [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
} }
System.out.println("maintenance reconnect msg was completed for: [adapterId-" + adapterId + " ,connectionId-" + connectionId + "], closing websocket connection"); // if (isDisconnected() && isStopRequested()) {
}
catch (UnsupportedEncodingException e) {
System.out.println("reconnect failed with error: "+ e+", [adapterId-"+adapterId+" ,connectionId-" +connectionId+ "] closing websocket connection");
e.printStackTrace();
try { try {
Thread.sleep(500); this.sendReconnectRequest();
synchronized (this) {
//wait that manager signals that the reconnect completed and this connection instance can be exited
try {
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "wait for stop request [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
while (!this.isStopRequested())
this.wait();
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "going to exit this thread[adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + "Error: " + e1 + " waitForDisconnection[adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
e1.printStackTrace(); e1.printStackTrace();
} }
} }
} catch (UnsupportedEncodingException e) {
System.out.println(Thread.currentThread().getName() + " "+ currentDate() + " maintenance reconnect msg was completed for: [adapterId-" + adapterId + " ,connectionId-" + connectionId + "], closing the old websocket connection");
e.printStackTrace();
}
} }
private SimpleHttpResponse sendReconnectRequest() throws UnsupportedEncodingException { private SimpleHttpResponse sendReconnectRequest() throws UnsupportedEncodingException {
SimpleHttpResponse simpleHttpResponse; SimpleHttpResponse simpleHttpResponse;
System.out.println(Thread.currentThread().getName()+ " " + currentDate() +" WebSocketConnection.sendReconnectRequest: [adapterId-" + adapterId + " ,connectionId-" + connectionId + "]");
simpleHttpResponse = httpClient.processRequest(this.reConnectRequest); simpleHttpResponse = httpClient.processRequest(this.reConnectRequest);
System.out.println( Thread.currentThread().getName()+ currentDate() +" ResponseCode="+ simpleHttpResponse.getStatusCode()+", ResponseContent="+ ((simpleHttpResponse.getContent()!=null)?simpleHttpResponse.getContent():"")+"]");
return simpleHttpResponse; return simpleHttpResponse;
} }
...@@ -244,10 +301,6 @@ public class WebSocketConnection extends Thread { ...@@ -244,10 +301,6 @@ public class WebSocketConnection extends Thread {
this.exception = exception; this.exception = exception;
} }
public void webSocketClosed() {
webSocketOpen = false;
}
public String getAdapterId() { public String getAdapterId() {
return adapterId; return adapterId;
} }
...@@ -268,9 +321,6 @@ public class WebSocketConnection extends Thread { ...@@ -268,9 +321,6 @@ public class WebSocketConnection extends Thread {
return eventListener; return eventListener;
} }
public void setIsClosedWebSocketWaitForMaintenance(boolean isClosedWebSocketWaitForMaintenance) {
this.closedWebSocketWaitingForMaintenance = isClosedWebSocketWaitForMaintenance;
}
} }
......
...@@ -22,6 +22,8 @@ import java.util.List; ...@@ -22,6 +22,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import static util.Utils.currentDate;
/** /**
* Created by eli on 12/4/16. * Created by eli on 12/4/16.
*/ */
...@@ -68,6 +70,7 @@ public class WebSocketEventListener implements WebSocketListener { ...@@ -68,6 +70,7 @@ public class WebSocketEventListener implements WebSocketListener {
mapUidToDetails.putIfAbsent(clientId,details); mapUidToDetails.putIfAbsent(clientId,details);
return true; return true;
} }
System.out.println("registerForEvents(key already exist): clientId="+clientId+", Details="+ details.toString());
} }
} }
...@@ -80,11 +83,7 @@ public class WebSocketEventListener implements WebSocketListener { ...@@ -80,11 +83,7 @@ public class WebSocketEventListener implements WebSocketListener {
enum eTraceLevel{ eFATAL, eERROR, eWARNING, eINFO, eDEBUG, eTRACE}; enum eTraceLevel{ eFATAL, eERROR, eWARNING, eINFO, eDEBUG, eTRACE};
private static String currentDate() {
Date date = new Date(System.currentTimeMillis());
DateTime dateTime = new DateTime(date);
return dateTime.toStringRfc3339();
}
public WebSocketEventListener(WebSocketConnection webSocketConnection, String adapterId, String connectionId, String uid, OnEventDetails details, ILogger logFile, Map<String, OnEventDetails> mapUidToDetails) { public WebSocketEventListener(WebSocketConnection webSocketConnection, String adapterId, String connectionId, String uid, OnEventDetails details, ILogger logFile, Map<String, OnEventDetails> mapUidToDetails) {
...@@ -106,7 +105,7 @@ public class WebSocketEventListener implements WebSocketListener { ...@@ -106,7 +105,7 @@ public class WebSocketEventListener implements WebSocketListener {
} }
private void logging(String str, eTraceLevel level, boolean writeToLog ) { private void logging(String str, eTraceLevel level, boolean writeToLog ) {
System.out.println(adapterId+" "+str); System.out.println(Thread.currentThread().getName()+" "+adapterId+" "+str);
if (writeToLog){ if (writeToLog){
switch (level){ switch (level){
case eFATAL: case eFATAL:
...@@ -211,7 +210,7 @@ public class WebSocketEventListener implements WebSocketListener { ...@@ -211,7 +210,7 @@ public class WebSocketEventListener implements WebSocketListener {
@Override @Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception { public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
String str = connectionId +" "+ currentDate()+" "+"onDisconnected: the WebSocket connection was closed by"+ ((closedByServer)?" server": " client"); String str = connectionId +" "+ currentDate()+" "+"onDisconnected: the WebSocket connection was closed by"+ ((closedByServer)?" server": " client");
this.webSocketConnection.webSocketClosed(); this.webSocketConnection.setDisconnected();
setState(websocket.getState()); setState(websocket.getState());
logging(str, eTraceLevel.eDEBUG,false); logging(str, eTraceLevel.eDEBUG,false);
} }
...@@ -395,7 +394,7 @@ public class WebSocketEventListener implements WebSocketListener { ...@@ -395,7 +394,7 @@ public class WebSocketEventListener implements WebSocketListener {
logging(connectionId+ " sendHttpPost failed to send event with error: "+e, eTraceLevel.eERROR, false); logging(connectionId+ " sendHttpPost failed to send event with error: "+e, eTraceLevel.eERROR, false);
return; return;
} }
logging(connectionId+ " sendHttpPost event was send successfuly to"+callBackUrl, eTraceLevel.eDEBUG, false); logging(connectionId+ " sendHttpPost event was send successfully to: "+callBackUrl, eTraceLevel.eDEBUG, false);
} }
/** /**
......
package logic.webSocket; package logic.webSocket;
import com.neovisionaries.ws.client.WebSocketException; import com.neovisionaries.ws.client.WebSocketException;
import io.undertow.websockets.WebSocketConnectionCallback;
import logic.adapter.HttpAdapter.ErrorLoginException; import logic.adapter.HttpAdapter.ErrorLoginException;
import logic.adapter.HttpAdapter.OAuth2Client; import logic.adapter.HttpAdapter.OAuth2Client;
import logic.adapter.HttpAdapter.model.NameValueParam; import logic.adapter.HttpAdapter.model.NameValueParam;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static util.Utils.currentDate;
/** /**
* Created by eli on 12/4/16. * Created by eli on 12/4/16.
*/ */
public class WebSocketManager { public class WebSocketManager {
private String adapterId; private final String adapterId;
private Map<String, WebSocketConnection> webSocketConnections; private final Map<String, WebSocketConnection> webSocketConnections;
private List<NameValueParam> defaultHeaders; private final List<NameValueParam> defaultHeaders;
private OAuth2Client auth2Client; private final OAuth2Client auth2Client;
public WebSocketManager(OAuth2Client oAuth2Client, List<NameValueParam> defaultHeaders, String adapterId) public WebSocketManager(OAuth2Client oAuth2Client, List<NameValueParam> defaultHeaders, String adapterId) {
{ this.adapterId = adapterId;
this.adapterId=adapterId; this.webSocketConnections = new ConcurrentHashMap<>();
this.webSocketConnections = new HashMap<>();
this.defaultHeaders = defaultHeaders; this.defaultHeaders = defaultHeaders;
this.auth2Client = oAuth2Client; this.auth2Client = oAuth2Client;
} }
public boolean isConnected( String connectionId, String uid){ public boolean isConnected(String connectionId, String uid) {
if (webSocketConnections.containsKey(connectionId)){ if (webSocketConnections.containsKey(connectionId)) {
WebSocketConnection connection = webSocketConnections.get(connectionId); WebSocketConnection connection = webSocketConnections.get(connectionId);
if (connection!=null ){ if (connection != null) {
if (connection.isRegisteredListener(uid)) if (connection.isRegisteredListener(uid))
return true; return true;
} }
...@@ -43,32 +41,58 @@ public class WebSocketManager { ...@@ -43,32 +41,58 @@ public class WebSocketManager {
return false; return false;
} }
public void connect(String connectionId, String uid, String webSocketUrl, OnEventDetails details) throws Exception { public void connect(String connectionId,
String uid,
String webSocketUrl,
OnEventDetails details,
boolean isReconnect) throws Exception {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(connectionId).append(":").append(uid); sb.append(connectionId).append(":").append(uid);
String key = sb.toString(); String key = sb.toString();
WebSocketConnection connection,reConnection; WebSocketConnection connection, reConnection;
if (!webSocketConnections.containsKey(connectionId)) { if (!webSocketConnections.containsKey(connectionId)) {
connection = new WebSocketConnection(adapterId,connectionId, uid, webSocketUrl, auth2Client, defaultHeaders, details,null); System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " websocketManager.connect[connectionId = " + connectionId + "uid="+(uid!=null?uid:"")+"]. create new connection");
this.startConnection(connection,details); connection = new WebSocketConnection(adapterId, connectionId, uid, webSocketUrl, auth2Client, defaultHeaders, details, null, true);
synchronized (connection) {
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ "LOCKING connection: "+ connection.toString()+ " websocketManager.connect[connectionId = " + connectionId + "uid="+(uid!=null?uid:"")+"]. create new connection");
this.startConnection(connection, details, false);
webSocketConnections.put(connection.getConnectionId(), connection);
System.out.println(Thread.currentThread().getName()+" "+ currentDate() + "UN-LOCKING connection: "+ connection.toString()+ " "+((isReconnect) ? "RECONNECTED " : "") + "websocket created successfully: "
+ connection.getConnectionId() + " uid=" + connection.getUid() + " " + ((details != null) ? details.toString() : ""));
} }
else{ } else {
connection = webSocketConnections.get(connectionId); connection = webSocketConnections.get(connectionId);
synchronized (connection) { synchronized (connection) {
if (connection.isClosedWebSocketWaitingForMaintenance()) {
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " LOCKING connection: " + connection.toString()+
" websocketManager.connect[connectionId = " + connectionId + " ,uid="+(uid!=null?uid:"")+", adapterId=" + connection.getAdapterId() + "]. isReconnect=" + isReconnect + ", isConnectionWaitingForMaintenance" + connection.isStopRequested());
if (isReconnect && connection.isDisconnected()) {
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+"websocketManager.RECONNECT[connectionId = " + connectionId + ", adapterId=" + connection.getAdapterId() + "]. RECONNECTING starts ");
reConnection = createReconnection(webSocketUrl, connection); reConnection = createReconnection(webSocketUrl, connection);
this.startConnection(reConnection, details); this.startConnection(reConnection, details, true);
connection.setIsClosedWebSocketWaitForMaintenance(false); webSocketConnections.put(connection.getConnectionId(), reConnection);
} else { System.out.println(Thread.currentThread().getName()+" "+ currentDate()+"RECONNECTED websocket created successfully: "
+ connection.getConnectionId() + " " +connection.toString()+" uid=" + connection.getUid());
connection.setStopRequested();
// connection.notify();
} else { //if (!isReconnect){
connection.addEventListener(uid, details); connection.addEventListener(uid, details);
System.out.println("websocket updated successfully: " + connectionId + " " + "uid=" System.out.print(Thread.currentThread().getName()+" "+ currentDate()+"websocket updated successfully: " + connectionId + " " + "uid="
+ uid + " was added to websocket. " + ((details != null) ? details.toString() : "Details=NULL")); + uid + " , " + ((details != null) ? details.toString() : "Details=NULL")+"uidList: [" );
connection.getEventListener().getMapUidToDetails().entrySet().forEach(entry -> System.out.print(entry.getKey()+ " "));
System.out.print("]\n");
} }
} }
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " UN-LOCKING connection: " + connection.toString()+
" websocketManager.connect[connectionId = " + connectionId + " ,uid="+(uid!=null?uid:"")+", adapterId=" + connection.getAdapterId() + "]. isReconnect=" + isReconnect + ", isConnectionWaitingForMaintenance" + connection.isStopRequested());
} }
} }
private WebSocketConnection createReconnection(String reConnectUrl, WebSocketConnection connection) throws ErrorLoginException, IOException, WebSocketException {
private WebSocketConnection createReconnection(String reConnectUrl,
WebSocketConnection connection) throws ErrorLoginException, IOException, WebSocketException {
WebSocketConnection reConnection = new WebSocketConnection((connection.getAdapterId()), WebSocketConnection reConnection = new WebSocketConnection((connection.getAdapterId()),
connection.getConnectionId(), connection.getConnectionId(),
...@@ -77,23 +101,22 @@ public class WebSocketManager { ...@@ -77,23 +101,22 @@ public class WebSocketManager {
connection.getAuth2Client(), connection.getAuth2Client(),
connection.getHttpHeaders(), connection.getHttpHeaders(),
connection.getDetails(), connection.getDetails(),
connection.getEventListener()); connection.getEventListener(),
false);
return reConnection; return reConnection;
} }
private void startConnection(WebSocketConnection connection, OnEventDetails details) throws Exception { private void startConnection(WebSocketConnection connection, OnEventDetails details, boolean isReconnect) throws Exception {
synchronized (connection){ synchronized (connection) {
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " LOCKING connection: "+ connection.toString()+ " waiting for startConnection[connectionId= " + connection.getConnectionId() +"]" );
connection.start(); connection.start();
connection.wait(); connection.wait();
if (connection.getException()!=null) System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " notified startConnection[connectionId= " + connection.getConnectionId() +"] locking connection: " + connection.toString());
if (connection.getException() != null)
throw connection.getException(); throw connection.getException();
else {
webSocketConnections.put(connection.getConnectionId(), connection);
System.out.println(((details==null)?"RECONNECTED ":"")+"websocket created successfully: "
+ connection.getConnectionId()+ " uid="+connection.getUid()+" "+ ((details!=null)?details.toString():""));
}
} }
System.out.println(Thread.currentThread().getName()+" "+ currentDate()+ " UN-LOCKED connection: "+ connection.toString()+ " waiting for startConnection[connectionId= " + connection.getConnectionId() +"]" );
} }
} }
package util; package util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import http.simpleHttpClient.SimpleHttpRequest; import http.simpleHttpClient.SimpleHttpRequest;
import logic.adapter.HttpAdapter.RequestParams; import logic.adapter.HttpAdapter.RequestParams;
...@@ -26,66 +27,30 @@ import static defs.Enums.eKeyWord; ...@@ -26,66 +27,30 @@ import static defs.Enums.eKeyWord;
* Created by eli on 11/29/16. * Created by eli on 11/29/16.
*/ */
public class HttpRequestResolver { 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) public static SimpleHttpRequest createResolvedRequest(RequestParams srcRequest,
// private final static String regexQueryParamValue = "^\\$[a-zA-Z]{1,15}\\.[a-zA-Z]{1,15}$"; ConfigHttpRequestParams commonRequestParams,
// private final static Pattern patternFullMatchValue = Pattern.compile(regexQueryParamValue); HttpRequestActionParams requestActionParams,
// private final static String regexPathParamValue = "^\\$[a-zA-Z]{1,15}\\.[a-zA-Z]{1,15}$"; String tokenAccess) throws Exception {
// 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(); // use it to create JsonNode JsonNodeFactory.instance.arrayNode();
String domain,path; String domain,path;
String name,value; String name,value;
Map<String,String> runTimeVariables=null;
JsonNode node=null;
try {
if (srcRequest.getComputeActionVariablesParams()!=null) {
node = srcRequest.getComputeActionVariablesParams().getJsonNode();
runTimeVariables = requestActionParams.computeVariables(node);
}
} catch (Exception e) {
throw new Exception("createResolvedRequest failed on computeVariables. error:"+e);
}
SimpleHttpRequest request = new SimpleHttpRequest(); SimpleHttpRequest request = new SimpleHttpRequest();
if (tokenAccess!=null)
request.setProtocol("https");
else
request.setProtocol("https");
domain = dstConfigRequestParamsPattern.getBaseUrl()+dstConfigRequestParamsPattern.getBasePath();
domain = commonRequestParams.getBaseUrl()+commonRequestParams.getBasePath();
request.setDomain(domain); request.setDomain(domain);
String method = dstRequestParamsPattern.getHttpMethod(); String method = requestActionParams.getHttpMethod();
SimpleHttpRequest.Method eMethod; SimpleHttpRequest.Method eMethod;
switch (method){ switch (method){
case "GET": case "GET":
...@@ -105,7 +70,7 @@ public class HttpRequestResolver { ...@@ -105,7 +70,7 @@ public class HttpRequestResolver {
break; break;
} }
request.setMethod(eMethod); request.setMethod(eMethod);
List<NameValueParam> headers= dstConfigRequestParamsPattern.getHeaders(); List<NameValueParam> headers= commonRequestParams.getHeaders();
for (NameValueParam header: headers) for (NameValueParam header: headers)
{ {
name = header.getName(); name = header.getName();
...@@ -114,16 +79,23 @@ public class HttpRequestResolver { ...@@ -114,16 +79,23 @@ public class HttpRequestResolver {
} }
if (tokenAccess!=null) { if (tokenAccess!=null) {
request.addHeader("Authorization", "Bearer " + tokenAccess); request.addHeader("Authorization", "Bearer " + tokenAccess);
request.setProtocol("https");
} }
else
request.setProtocol("http");
path = dstRequestParamsPattern.getPath(); /*Handle Dynamic variables assignment, currently support only "path".
implement the same logic if needed for variables on query params, headers etc*/
//start
path = requestActionParams.getPath();
if (srcRequest.getVariablesValues()!=null && srcRequest.getVariablesValues().size()>0) if (srcRequest.getVariablesValues()!=null && srcRequest.getVariablesValues().size()>0)
path = replaceMatchedKeysByItsValues(path, srcRequest.getVariablesValues()); path = replaceMatchedKeysByItsValues(path, srcRequest.getVariablesValues());
if (runTimeVariables!=null && runTimeVariables.size()>0) if (runTimeVariables!=null && runTimeVariables.size()>0)
path = replaceMatchedKeysByItsValues(path, runTimeVariables); path = replaceMatchedKeysByItsValues(path, runTimeVariables);
request.setPath(path); request.setPath(path);
//end
List<NameValueParam> queryParams = dstRequestParamsPattern.getQueryParams(); List<NameValueParam> queryParams = requestActionParams.getQueryParams();
if (queryParams!=null) { if (queryParams!=null) {
request.InitQueryStringBuilder(); request.InitQueryStringBuilder();
for (NameValueParam param : queryParams) { for (NameValueParam param : queryParams) {
......
...@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import common.JsonHandler; import common.JsonHandler;
@Deprecated
public class MDEResult { public class MDEResult {
protected boolean success; protected boolean success;
......
//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 {
}
...@@ -2,8 +2,11 @@ package util; ...@@ -2,8 +2,11 @@ package util;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.*;
import com.google.api.client.util.DateTime;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Date;
/** /**
* Created by eli on 6/23/16. * Created by eli on 6/23/16.
...@@ -11,7 +14,26 @@ import java.io.IOException; ...@@ -11,7 +14,26 @@ import java.io.IOException;
public class Utils { public class Utils {
public static final ObjectMapper SORTED_MAPPER = new ObjectMapper(); public static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
public static String paramsToString(String[] params){
StringBuilder sb = new StringBuilder();
if (params == null || params.length==0 || params[0].equals(""))
return "";
else{
sb.append("[");
for (int i=0; i< params.length; i++){
sb.append(params[i]);
if (i<params.length-1)
sb.append(",");
}
sb.append("]");
return sb.toString();
}
}
public static String currentDate() {
Date date = new Date(System.currentTimeMillis());
DateTime dateTime = new DateTime(date);
return dateTime.toStringRfc3339();
}
public static String myTypeOf(Object obj){ public static String myTypeOf(Object obj){
int end_index = obj.toString().indexOf('@'); int end_index = obj.toString().indexOf('@');
......
import org.junit.Test;
import java.util.stream.Stream;
/**
* Created by eli on 1/24/17.
*/
public class TestStream {
@Test
public void testStream(){
Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> {
System.out.println("map: " + s);
return s.toUpperCase();
})
.anyMatch(s -> {
System.out.println("anyMatch: " + s);
return s.startsWith("A");
});
}
}
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