Commit 4002ac06 by amir

first working service - server only

parent 7fd64090
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
# new services design # new services design
- counters and metrics in the reactor - counters and metrics in the reactor
- validateRequest in RestService , the jwt issues - validateRequest in RestService , the jwt issues
- Add monitoring apis
- All the validation ,pre/post handling that was were done by the handler will be done by the base service - All the validation ,pre/post handling that was were done by the handler will be done by the base service
- add Runtime Test: - add Runtime Test:
addTest(const char *testName, nsMicroservice_Iface::TestFunction testFunction); addTest(const char *testName, nsMicroservice_Iface::TestFunction testFunction);
......
...@@ -24,6 +24,7 @@ import java.util.*; ...@@ -24,6 +24,7 @@ import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream;
import static io.undertow.Handlers.resource; import static io.undertow.Handlers.resource;
...@@ -102,6 +103,12 @@ public class MicroserviceApp ...@@ -102,6 +103,12 @@ public class MicroserviceApp
return appName; return appName;
} }
public String getId() {
return id;
}
public boolean isEnableDefaultServiceAuthorization() { return enableDefaultServiceAuthorization; }
/************************* /*************************
* WITH SECTION * WITH SECTION
*************************/ *************************/
...@@ -517,17 +524,17 @@ public class MicroserviceApp ...@@ -517,17 +524,17 @@ public class MicroserviceApp
/*************************************************************************/ /*************************************************************************/
// //
/// the services array /// the services array
private final List<Map<String,CommonServices.IService>> servicesArray = new ArrayList<>(Enums.EnumServiceType.values().length); //private final List<Map<String,CommonServices.IService>> servicesArray = new ArrayList<>(Enums.EnumServiceType.values().length);
private final Map<String,CommonServices.IService>[] servicesArray = new Map[Enums.EnumServiceType.values().length];
public MicroserviceApp addService(Enums.EnumServiceType serviceType, public MicroserviceApp addService(Enums.EnumServiceType serviceType,
CommonServices.IService iService, CommonServices.IService iService,
String serviceKey) String serviceKey)
{ {
Map<String, CommonServices.IService> serviceMap = servicesArray.get(serviceType.ordinal()); Map<String, CommonServices.IService> serviceMap = servicesArray[serviceType.ordinal()];
if (serviceMap == null){ if (serviceMap == null){
serviceMap = new HashMap<>(); serviceMap = new HashMap<>();
servicesArray.set(serviceType.ordinal(),serviceMap); servicesArray[serviceType.ordinal()] = serviceMap;
} }
serviceMap.put(serviceKey,iService); serviceMap.put(serviceKey,iService);
iService.setReactor(reactor); iService.setReactor(reactor);
...@@ -535,14 +542,14 @@ public class MicroserviceApp ...@@ -535,14 +542,14 @@ public class MicroserviceApp
} }
CommonServices.IService getService(Enums.EnumServiceType serviceType, String serviceKey){ CommonServices.IService getService(Enums.EnumServiceType serviceType, String serviceKey){
Map<String, CommonServices.IService> serviceMap = servicesArray.get(serviceType.ordinal()); Map<String, CommonServices.IService> serviceMap = servicesArray[serviceType.ordinal()];
if (serviceMap != null) if (serviceMap != null)
return serviceMap.get(serviceKey); return serviceMap.get(serviceKey);
return null; return null;
} }
CommonServices.IService getService(String serviceKey){ CommonServices.IService getService(String serviceKey){
Optional<CommonServices.IService> iServiceOptional = servicesArray.stream() Optional<CommonServices.IService> iServiceOptional = Arrays.stream(servicesArray)
.filter(serviceMap -> serviceMap != null && serviceMap.containsKey(serviceKey)) .filter(serviceMap -> serviceMap != null && serviceMap.containsKey(serviceKey))
.map(serviceMap -> serviceMap.get(serviceKey)) .map(serviceMap -> serviceMap.get(serviceKey))
.findFirst(); .findFirst();
...@@ -593,38 +600,45 @@ public class MicroserviceApp ...@@ -593,38 +600,45 @@ public class MicroserviceApp
/** /**
* init services * init services
* iterating only over non empty elements
*/ */
servicesArray.stream().forEach(servicesMap -> { Arrays.stream(servicesArray)
servicesMap.forEach( (serviceKey,service) -> { .filter(p -> p != null)
service.init(); .forEach(servicesMap ->
}); servicesMap.forEach((serviceKey, service) -> {
}); service.init();
service.register(serviceDiscovery, id);
})
);
return this; return this;
} }
public void _run() { public void _run() {
if (!servicesArray.isEmpty()) /**
* מי מתחכם זה מיקו!!!
*/
if (Arrays.stream(servicesArray)
.filter(p -> p != null)
.count() > 0)
{ {
if (this.enableMetrics) { if (this.enableMetrics) {
IMetricsFactoryImpl.getInstance().startReporting(appName); IMetricsFactoryImpl.getInstance().startReporting(appName);
} }
servicesArray.stream().forEach(servicesMap -> { Arrays.stream(servicesArray)
servicesMap.forEach( (serviceKey,service) -> { .filter(p -> p != null)
service.run(); .forEach(servicesMap ->
}); servicesMap.forEach( (serviceKey,service) -> service.run() ) );
});
Runtime.getRuntime().addShutdownHook(new Thread(() -> { Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try { try {
servicesArray.stream().forEach(servicesMap -> { Arrays.stream(servicesArray)
servicesMap.forEach( (serviceKey,service) -> { .filter(p -> p != null)
service.shutdown(); .forEach(servicesMap ->
}); servicesMap.forEach( (serviceKey,service) -> service.shutdown() ) );
});
// notify main // notify main
notifyAll(); notifyAll();
} catch (Exception e) { } catch (Exception e) {
...@@ -645,7 +659,7 @@ public class MicroserviceApp ...@@ -645,7 +659,7 @@ public class MicroserviceApp
} }
else else
{ {
System.out.println("no server/s...exit!"); System.out.println("no service/s...exit!");
} }
} }
......
...@@ -6,17 +6,19 @@ import java.util.Map; ...@@ -6,17 +6,19 @@ import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import microservice.defs.Enums; import microservice.defs.Enums;
import microservice.io.iface.CommonServices;
import microservice.io.iface.IContainer; import microservice.io.iface.IContainer;
import microservice.io.iface.IRequest; import microservice.io.iface.IRequest;
import microservice.io.iface.IResponse; import microservice.io.iface.IResponse;
import microservice.types.UserProfile; import microservice.types.UserProfile;
public class RequestContext public class RestContext implements CommonServices.IMsgContext
{ {
public String[] params = null; public String[] params = null;
public Map<String, Deque<String>> queryParameters = null; public Map<String, Deque<String>> queryParameters = null;
public Map<String, String> pathParameters = null;
// request-interface // request-interface
// response interface // response interface
public IContainer container; public IContainer container;
...@@ -25,7 +27,7 @@ public class RequestContext ...@@ -25,7 +27,7 @@ public class RequestContext
public ObjectMapper objMapper; public ObjectMapper objMapper;
public String rcid; // request correlation id public String rcid; // request correlation id
public UserProfile userProfile; public UserProfile userProfile;
public Enums.EnumCrudMethod enumCrudMethod; public CommonServices.EnumRestCommands enumRestCommands;
public String getParameter(String paramName) { public String getParameter(String paramName) {
...@@ -34,4 +36,16 @@ public class RequestContext ...@@ -34,4 +36,16 @@ public class RequestContext
else else
return null; return null;
} }
public String getPathParameter(String paramName) {
if (pathParameters != null )
return pathParameters.get(paramName);
else
return null;
}
@Override
public void setParameters(Map<String, String> parameters) {
pathParameters = parameters;
}
} }
...@@ -80,5 +80,10 @@ public class Enums ...@@ -80,5 +80,10 @@ public class Enums
E_PUBSUB E_PUBSUB
} }
public enum EnumAuthenticationType {
DEFAULT,
NONE,
JWT,
FORM
}
} }
...@@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import microservice.MicroserviceApp; import microservice.MicroserviceApp;
import microservice.RequestContext; import microservice.RestContext;
import microservice.io.iface.IConfiguration; import microservice.io.iface.IConfiguration;
import microservice.io.iface.IContainer; import microservice.io.iface.IContainer;
import microservice.io.iface.ILogger; import microservice.io.iface.ILogger;
...@@ -29,7 +29,6 @@ public abstract class BaseHandler ...@@ -29,7 +29,6 @@ public abstract class BaseHandler
protected EnumAuthenticationType authType = EnumAuthenticationType.DEFAULT; protected EnumAuthenticationType authType = EnumAuthenticationType.DEFAULT;
/* /*
* SOME HELPERS * SOME HELPERS
*/ */
...@@ -74,27 +73,27 @@ public abstract class BaseHandler ...@@ -74,27 +73,27 @@ public abstract class BaseHandler
} }
public void sendErrorResp(RequestContext reqCtx, String error) public void sendErrorResp(RestContext reqCtx, String error)
{ {
reqCtx.container.sendErrorResp(reqCtx.response, error); reqCtx.container.sendErrorResp(reqCtx.response, error);
} }
public void writeObjectToResponse(RequestContext reqCtx, Object value) public void writeObjectToResponse(RestContext reqCtx, Object value)
{ {
reqCtx.container.writeObjectToResponse(reqCtx.response, value); reqCtx.container.writeObjectToResponse(reqCtx.response, value);
} }
public Object readObjectFromRequest(RequestContext reqCtx,Class<?> ObjClass) public Object readObjectFromRequest(RestContext reqCtx, Class<?> ObjClass)
{ {
return reqCtx.container.readObjectFromRequest(reqCtx.request, ObjClass); return reqCtx.container.readObjectFromRequest(reqCtx.request, ObjClass);
} }
public void subscribe(RequestContext reqCtx,String topic, INotifyCallback notifyHandler) public void subscribe(RestContext reqCtx, String topic, INotifyCallback notifyHandler)
{ {
reqCtx.container.subscribe(topic,notifyHandler); reqCtx.container.subscribe(topic,notifyHandler);
} }
public void unsubscribe(RequestContext reqCtx,String topic) public void unsubscribe(RestContext reqCtx, String topic)
{ {
reqCtx.container.unsubscribe(topic); reqCtx.container.unsubscribe(topic);
} }
...@@ -113,7 +112,7 @@ public abstract class BaseHandler ...@@ -113,7 +112,7 @@ public abstract class BaseHandler
optContainer.ifPresent(container -> container.unsubscribe(topic)); optContainer.ifPresent(container -> container.unsubscribe(topic));
} }
public void publish(RequestContext reqCtx,String topic, JsonNode messageNode) public void publish(RestContext reqCtx, String topic, JsonNode messageNode)
{ {
reqCtx.container.publish(topic,messageNode); reqCtx.container.publish(topic,messageNode);
} }
...@@ -157,32 +156,32 @@ public abstract class BaseHandler ...@@ -157,32 +156,32 @@ public abstract class BaseHandler
* the create/post of CRUD * the create/post of CRUD
* @param reqCtx * @param reqCtx
*/ */
public abstract void doCreate(RequestContext reqCtx); public abstract void doCreate(RestContext reqCtx);
/** /**
* the read/get of CRUD * the read/get of CRUD
* @param reqCtx * @param reqCtx
*/ */
public abstract void doRead(RequestContext reqCtx); public abstract void doRead(RestContext reqCtx);
/** /**
* the update/put of CRUD * the update/put of CRUD
* @param reqCtx * @param reqCtx
*/ */
public abstract void doUpdate(RequestContext reqCtx); public abstract void doUpdate(RestContext reqCtx);
/** /**
* the delete of CRUD * the delete of CRUD
* @param reqCtx * @param reqCtx
*/ */
public abstract void doDelete(RequestContext reqCtx); public abstract void doDelete(RestContext reqCtx);
/** /**
* represents simple send message - not a rest command * represents simple send message - not a rest command
* @param reqCtx * @param reqCtx
*/ */
public void doMessage(RequestContext reqCtx) {}; public void doMessage(RestContext reqCtx) {};
/** /**
* reloading configuration or other data * reloading configuration or other data
......
...@@ -5,7 +5,7 @@ import java.util.Deque; ...@@ -5,7 +5,7 @@ import java.util.Deque;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import microservice.RequestContext; import microservice.RestContext;
import microservice.defs.Constants; import microservice.defs.Constants;
import microservice.defs.Enums.EnumHttpMethod; import microservice.defs.Enums.EnumHttpMethod;
import microservice.io.iface.*; import microservice.io.iface.*;
...@@ -40,7 +40,7 @@ public class MBIHandler extends RMQHandler implements IContainer ...@@ -40,7 +40,7 @@ public class MBIHandler extends RMQHandler implements IContainer
@Override @Override
public void handleRequest(RMQMessage request) throws Exception public void handleRequest(RMQMessage request) throws Exception
{ {
RequestContext reqContext = getRequestContext(request); RestContext reqContext = getRequestContext(request);
if (reqContext != null) if (reqContext != null)
{ {
String sMethod = request.getParameterByName(RMQRestRequest.METHOD); String sMethod = request.getParameterByName(RMQRestRequest.METHOD);
...@@ -88,9 +88,9 @@ public class MBIHandler extends RMQHandler implements IContainer ...@@ -88,9 +88,9 @@ public class MBIHandler extends RMQHandler implements IContainer
* @param exchange * @param exchange
* @return * @return
*/ */
private RequestContext getRequestContext(RMQMessage request) private RestContext getRequestContext(RMQMessage request)
{ {
RequestContext reqCtx = new RequestContext(); RestContext reqCtx = new RestContext();
reqCtx.container = this; reqCtx.container = this;
reqCtx.request = new IRequestMBIImpl(request); reqCtx.request = new IRequestMBIImpl(request);
reqCtx.response = new IResponseMBIImpl(request, listenerRmqId, logger); reqCtx.response = new IResponseMBIImpl(request, listenerRmqId, logger);
...@@ -131,28 +131,28 @@ public class MBIHandler extends RMQHandler implements IContainer ...@@ -131,28 +131,28 @@ public class MBIHandler extends RMQHandler implements IContainer
return paramsMap; return paramsMap;
} }
public void doGet(RequestContext reqCtx) public void doGet(RestContext reqCtx)
{ {
msHandler.doRead(reqCtx); msHandler.doRead(reqCtx);
} }
public void doPost(RequestContext reqCtx) public void doPost(RestContext reqCtx)
{ {
msHandler.doCreate(reqCtx); msHandler.doCreate(reqCtx);
} }
public void doPut(RequestContext reqCtx) public void doPut(RestContext reqCtx)
{ {
msHandler.doUpdate(reqCtx); msHandler.doUpdate(reqCtx);
} }
public void doDelete(RequestContext reqCtx) public void doDelete(RestContext reqCtx)
{ {
msHandler.doDelete(reqCtx); msHandler.doDelete(reqCtx);
} }
public void doMessage(RequestContext reqCtx) public void doMessage(RestContext reqCtx)
{ {
msHandler.doMessage(reqCtx); msHandler.doMessage(reqCtx);
} }
......
...@@ -6,9 +6,7 @@ import java.util.List; ...@@ -6,9 +6,7 @@ import java.util.List;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import microservice.io.impl.IMetricsFactoryImpl; import microservice.io.impl.IMetricsFactoryImpl;
import microservice.types.BaseRestResponse; import microservice.types.BaseRestResponse;
import microservice.MicroserviceApp; import microservice.RestContext;
import microservice.RequestContext;
import microservice.io.iface.IContainer;
/** /**
* this class is for monitoring the microservice * this class is for monitoring the microservice
...@@ -35,7 +33,7 @@ public class MonitorHandler extends BaseHandler ...@@ -35,7 +33,7 @@ public class MonitorHandler extends BaseHandler
} }
@Override @Override
public void doCreate(RequestContext reqCtx) public void doCreate(RestContext reqCtx)
{ {
switch(reqCtx.params[0]) switch(reqCtx.params[0])
{ {
...@@ -49,7 +47,7 @@ public class MonitorHandler extends BaseHandler ...@@ -49,7 +47,7 @@ public class MonitorHandler extends BaseHandler
} }
private void printStats(RequestContext reqCtx) { private void printStats(RestContext reqCtx) {
BaseRestResponse brr = new BaseRestResponse(true, null); BaseRestResponse brr = new BaseRestResponse(true, null);
IMetricsFactoryImpl factoryImpl = (IMetricsFactoryImpl) IMetricsFactoryImpl.getInstance(); IMetricsFactoryImpl factoryImpl = (IMetricsFactoryImpl) IMetricsFactoryImpl.getInstance();
ObjectNode objectNode = this.objMapper.createObjectNode(); ObjectNode objectNode = this.objMapper.createObjectNode();
...@@ -64,7 +62,7 @@ public class MonitorHandler extends BaseHandler ...@@ -64,7 +62,7 @@ public class MonitorHandler extends BaseHandler
writeObjectToResponse(reqCtx, brr); writeObjectToResponse(reqCtx, brr);
} }
private void reloadServiceApp(RequestContext reqCtx) { private void reloadServiceApp(RestContext reqCtx) {
this.optConfiguration.ifPresent(cfg -> cfg.reload()); this.optConfiguration.ifPresent(cfg -> cfg.reload());
containers.forEach(handler -> handler.doReload()); containers.forEach(handler -> handler.doReload());
...@@ -72,7 +70,7 @@ public class MonitorHandler extends BaseHandler ...@@ -72,7 +70,7 @@ public class MonitorHandler extends BaseHandler
} }
@Override @Override
public void doRead(RequestContext reqCtx) public void doRead(RestContext reqCtx)
{ {
switch(reqCtx.params[0]) switch(reqCtx.params[0])
{ {
...@@ -84,14 +82,14 @@ public class MonitorHandler extends BaseHandler ...@@ -84,14 +82,14 @@ public class MonitorHandler extends BaseHandler
} }
@Override @Override
public void doUpdate(RequestContext reqCtx) public void doUpdate(RestContext reqCtx)
{ {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void doDelete(RequestContext reqCtx) public void doDelete(RestContext reqCtx)
{ {
// TODO Auto-generated method stub // TODO Auto-generated method stub
......
...@@ -84,6 +84,14 @@ public class Reactor implements CommonServices.IServiceReactor { ...@@ -84,6 +84,14 @@ public class Reactor implements CommonServices.IServiceReactor {
methodParams.getResourceUri(); methodParams.getResourceUri();
} }
public static String buildServiceKey(Enums.EnumServiceType enumServiceType,
CommonServices.IServiceCommands serviceCommands,
String resourceUri) {
return new StringBuilder(32).append(enumServiceType.name()).append(Constants.TYPE_PREFIX_SEPERATOR)
.append(serviceCommands.toString()).append(Constants.TYPE_PREFIX_SEPERATOR)
.append(resourceUri).toString();
}
/** /**
* delegating the msg/request from the service to the method if any * delegating the msg/request from the service to the method if any
* @param orgService * @param orgService
...@@ -98,12 +106,15 @@ public class Reactor implements CommonServices.IServiceReactor { ...@@ -98,12 +106,15 @@ public class Reactor implements CommonServices.IServiceReactor {
final PathTemplateMatcher.PathMatchResult<MethodMatch> match = methodsMap.match(key); final PathTemplateMatcher.PathMatchResult<MethodMatch> match = methodsMap.match(key);
try { try {
if (match != null && match.getValue().getMethodCallback() != null) { if (match != null && match.getValue().getMethodCallback() != null) {
msgContext.setParameters(match.getParameters());
final BiConsumer<CommonServices.IMsgContext, CommonServices.IService> methodCallback = match.getValue().getMethodCallback(); final BiConsumer<CommonServices.IMsgContext, CommonServices.IService> methodCallback = match.getValue().getMethodCallback();
/** /**
* pre-handling * pre-handling
*/ */
if (metricsFactory != null) { if (metricsFactory != null) {
methodMetrics = methodMetricsMap.get(key); methodMetrics = methodMetricsMap.get(match.getMatchedTemplate());
if (methodMetrics != null)
methodMetrics.preHandle();
} }
methodCallback.accept(msgContext, orgService); methodCallback.accept(msgContext, orgService);
} else { } else {
...@@ -140,8 +151,8 @@ public class Reactor implements CommonServices.IServiceReactor { ...@@ -140,8 +151,8 @@ public class Reactor implements CommonServices.IServiceReactor {
* create counters for every method * create counters for every method
*/ */
for (String key : methodKeyList){ for (String key : methodKeyList){
IMetricsFactory.IMeter meter = metricsFactory.createMeter(key); IMetricsFactory.IMeter meter = metricsFactory.createMeter("Meter:" + key);
IMetricsFactory.ITimer timer = metricsFactory.createTimer(key); IMetricsFactory.ITimer timer = metricsFactory.createTimer("Timer:" + key);
methodMetricsMap.put(key,new MethodMetrics(meter,timer)); methodMetricsMap.put(key,new MethodMetrics(meter,timer));
} }
} }
......
...@@ -11,7 +11,7 @@ import io.undertow.util.HeaderMap; ...@@ -11,7 +11,7 @@ import io.undertow.util.HeaderMap;
import io.undertow.util.Headers; import io.undertow.util.Headers;
import io.undertow.util.HttpString; import io.undertow.util.HttpString;
import microservice.MicroserviceApp; import microservice.MicroserviceApp;
import microservice.RequestContext; import microservice.RestContext;
import microservice.common.EncryptionUtils; import microservice.common.EncryptionUtils;
import microservice.defs.Constants; import microservice.defs.Constants;
import microservice.defs.Enums; import microservice.defs.Enums;
...@@ -86,11 +86,11 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -86,11 +86,11 @@ public class RestHandler implements HttpHandler , IContainer
/* /*
* async part * async part
*/ */
RequestContext reqContext = getRequestContext(exchange); RestContext reqContext = getRequestContext(exchange);
if (reqContext != null) { if (reqContext != null) {
HttpString requestMethod = exchange.getRequestMethod(); HttpString requestMethod = exchange.getRequestMethod();
EnumHttpMethod eMethod = EnumHttpMethod.resolveMethod(requestMethod.toString()); EnumHttpMethod eMethod = EnumHttpMethod.resolveMethod(requestMethod.toString());
reqContext.enumCrudMethod = Enums.EnumCrudMethod.resolveMethodFromHttp(eMethod); reqContext.enumRestCommands = CommonServices.EnumRestCommands.resolveMethodFromHttp(eMethod);
//exchange. request.setCharacterEncoding(Constants.C_ENCODING_UTF8); //exchange. request.setCharacterEncoding(Constants.C_ENCODING_UTF8);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, Constants.CONTENT_TYPE_JSON); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, Constants.CONTENT_TYPE_JSON);
...@@ -143,15 +143,15 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -143,15 +143,15 @@ public class RestHandler implements HttpHandler , IContainer
/** /**
* validate the request: service authorization etc. * validate the request: service authorization etc.
* @param requestContext * @param restContext
* @return * @return
*/ */
private boolean validateRequest(RequestContext requestContext) private boolean validateRequest(RestContext restContext)
{ {
boolean valid = true; boolean valid = true;
if (msHandler.getAuthType().equals(BaseHandler.EnumAuthenticationType.JWT)){ if (msHandler.getAuthType().equals(BaseHandler.EnumAuthenticationType.JWT)){
// get token // get token
String token = getJwtToken(requestContext); String token = getJwtToken(restContext);
if (token != null) if (token != null)
{ {
try { try {
...@@ -160,41 +160,41 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -160,41 +160,41 @@ public class RestHandler implements HttpHandler , IContainer
// resolve service authorization // resolve service authorization
UserProfile up = new UserProfile(claims); UserProfile up = new UserProfile(claims);
// resolve authorization // resolve authorization
valid = up.isServiceAuthorized(appName, requestContext.enumCrudMethod); valid = up.isServiceAuthorized(appName, restContext.enumRestCommands);
if (valid) { if (valid) {
// set user profile // set user profile
requestContext.userProfile = up; restContext.userProfile = up;
} else { } else {
sendErrorResp(requestContext.response, METHOD_NOT_AUTHORIZED); sendErrorResp(restContext.response, METHOD_NOT_AUTHORIZED);
} }
} }
else { else {
sendErrorResp(requestContext.response,Constants.INVALID_REQUEST_TOKEN); sendErrorResp(restContext.response,Constants.INVALID_REQUEST_TOKEN);
} }
} catch (ExpiredJwtException exception){ } catch (ExpiredJwtException exception){
sendErrorResp(requestContext.response,TOKEN_EXPIRED); sendErrorResp(restContext.response,TOKEN_EXPIRED);
valid = false; valid = false;
} }
} }
else else
{ {
MicroserviceApp.getsInstance().getLogger().error(NO_TOKEN_FOR_REQUEST); MicroserviceApp.getsInstance().getLogger().error(NO_TOKEN_FOR_REQUEST);
sendErrorResp(requestContext.response,NO_TOKEN_FOR_REQUEST); sendErrorResp(restContext.response,NO_TOKEN_FOR_REQUEST);
valid = false; valid = false;
} }
} }
return valid; return valid;
} }
private String getJwtToken(RequestContext requestContext) { private String getJwtToken(RestContext restContext) {
String jwt = null; String jwt = null;
/* /*
* jwt token * jwt token
*/ */
if (jwtTokenInAuthorization) if (jwtTokenInAuthorization)
{ {
String authValue = requestContext.request.getFirstHeader(Constants.AUTHORIZATION_HEADER); String authValue = restContext.request.getFirstHeader(Constants.AUTHORIZATION_HEADER);
if(authValue != null) if(authValue != null)
{ {
// "Bearer <token>" // "Bearer <token>"
...@@ -206,7 +206,7 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -206,7 +206,7 @@ public class RestHandler implements HttpHandler , IContainer
else else
{ {
// url - param // url - param
jwt =requestContext.getParameter(JWT_TOKEN); jwt = restContext.getParameter(JWT_TOKEN);
} }
return jwt; return jwt;
} }
...@@ -260,9 +260,9 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -260,9 +260,9 @@ public class RestHandler implements HttpHandler , IContainer
* @param exchange * @param exchange
* @return * @return
*/ */
private RequestContext getRequestContext(HttpServerExchange exchange) private RestContext getRequestContext(HttpServerExchange exchange)
{ {
RequestContext reqCtx = new RequestContext(); RestContext reqCtx = new RestContext();
reqCtx.container = this; reqCtx.container = this;
reqCtx.request = new IRequestRestImpl(exchange); reqCtx.request = new IRequestRestImpl(exchange);
reqCtx.response = new IResponseRestImpl(exchange); reqCtx.response = new IResponseRestImpl(exchange);
...@@ -290,26 +290,26 @@ public class RestHandler implements HttpHandler , IContainer ...@@ -290,26 +290,26 @@ public class RestHandler implements HttpHandler , IContainer
} }
public void doGet(RequestContext reqCtx) public void doGet(RestContext reqCtx)
{ {
msHandler.doRead(reqCtx); msHandler.doRead(reqCtx);
} }
public void doPost(RequestContext reqCtx) public void doPost(RestContext reqCtx)
{ {
msHandler.doCreate(reqCtx); msHandler.doCreate(reqCtx);
} }
public void doPut(RequestContext reqCtx) public void doPut(RestContext reqCtx)
{ {
msHandler.doUpdate(reqCtx); msHandler.doUpdate(reqCtx);
} }
public void doDelete(RequestContext reqCtx) public void doDelete(RestContext reqCtx)
{ {
msHandler.doDelete(reqCtx); msHandler.doDelete(reqCtx);
......
...@@ -5,6 +5,7 @@ import microservice.params.CommandParams; ...@@ -5,6 +5,7 @@ import microservice.params.CommandParams;
import microservice.types.BaseRestResponse; import microservice.types.BaseRestResponse;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
...@@ -18,6 +19,7 @@ public class CommonServices { ...@@ -18,6 +19,7 @@ public class CommonServices {
} }
public interface IMsgContext { public interface IMsgContext {
void setParameters(Map<String, String> parameters);
} }
public interface IServiceReactor { public interface IServiceReactor {
...@@ -31,6 +33,8 @@ public class CommonServices { ...@@ -31,6 +33,8 @@ public class CommonServices {
public abstract void run(); public abstract void run();
public abstract void shutdown(); public abstract void shutdown();
public abstract void handleNotImplmented(IMsgContext msgContext); public abstract void handleNotImplmented(IMsgContext msgContext);
/// when relevant
public abstract void register(IServiceDiscovery serviceDiscovery, String id);
public void setReactor(IServiceReactor reactor) { public void setReactor(IServiceReactor reactor) {
this.reactor = reactor; this.reactor = reactor;
...@@ -84,6 +88,26 @@ public class CommonServices { ...@@ -84,6 +88,26 @@ public class CommonServices {
E_READ, E_READ,
E_UPDATE, E_UPDATE,
E_DELETE; E_DELETE;
public static EnumRestCommands resolveMethodFromHttp(Enums.EnumHttpMethod enumHttpMethod){
EnumRestCommands enumRestCommands= null;
switch (enumHttpMethod){
case E_GET:
enumRestCommands = EnumRestCommands.E_READ;
break;
case E_POST:
enumRestCommands = EnumRestCommands.E_CREATE;
break;
case E_PUT:
enumRestCommands = EnumRestCommands.E_UPDATE;
break;
case E_DELETE:
enumRestCommands = EnumRestCommands.E_DELETE;
break;
}
return enumRestCommands;
}
} }
public static abstract class IRestService extends IService { public static abstract class IRestService extends IService {
...@@ -111,6 +135,11 @@ public class CommonServices { ...@@ -111,6 +135,11 @@ public class CommonServices {
this.topic = topic; this.topic = topic;
this.msg = msg; this.msg = msg;
} }
@Override
public void setParameters(Map<String, String> parameters) {
}
} }
public abstract void subscribe(String topic, Consumer<String> notifyFunc); public abstract void subscribe(String topic, Consumer<String> notifyFunc);
......
...@@ -3,6 +3,7 @@ package microservice.io.impl.service; ...@@ -3,6 +3,7 @@ package microservice.io.impl.service;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import common.JsonHandler; import common.JsonHandler;
import microservice.io.iface.CommonServices; import microservice.io.iface.CommonServices;
import microservice.io.iface.IServiceDiscovery;
import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.*;
import java.util.HashMap; import java.util.HashMap;
...@@ -137,4 +138,9 @@ public class IPubSubServiceMqttImpl extends CommonServices.IPubSubService { ...@@ -137,4 +138,9 @@ public class IPubSubServiceMqttImpl extends CommonServices.IPubSubService {
public void handleNotImplmented(CommonServices.IMsgContext msgContext) { public void handleNotImplmented(CommonServices.IMsgContext msgContext) {
} }
@Override
public void register(IServiceDiscovery serviceDiscovery, String id) {
}
} }
...@@ -3,6 +3,7 @@ package microservice.types; ...@@ -3,6 +3,7 @@ package microservice.types;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims; import io.jsonwebtoken.impl.DefaultClaims;
import microservice.defs.Enums; import microservice.defs.Enums;
import microservice.io.iface.CommonServices;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -62,14 +63,14 @@ public class UserProfile extends DefaultClaims { ...@@ -62,14 +63,14 @@ public class UserProfile extends DefaultClaims {
return serviceAuthorizations; return serviceAuthorizations;
} }
public boolean isServiceAuthorized(String serviceName, Enums.EnumCrudMethod enumCrudMethod){ public boolean isServiceAuthorized(String serviceName, CommonServices.EnumRestCommands enumRestCommands){
boolean authorized = false; boolean authorized = false;
String serviceAuth = serviceAuthorizations.get(serviceName); String serviceAuth = serviceAuthorizations.get(serviceName);
if (serviceAuth == null) // check for all services authorizations if (serviceAuth == null) // check for all services authorizations
serviceAuth = serviceAuthorizations.get(ALL_SERVICES); serviceAuth = serviceAuthorizations.get(ALL_SERVICES);
if(serviceAuth != null) if(serviceAuth != null)
authorized = serviceAuth.getBytes()[enumCrudMethod.ordinal()] == 'Y'; authorized = serviceAuth.getBytes()[enumRestCommands.ordinal()] == 'Y';
return authorized; return authorized;
} }
......
package microservice; package microservice;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import microservice.defs.Enums; import microservice.defs.Enums;
import microservice.io.iface.CommonServices; import microservice.io.iface.CommonServices;
import microservice.io.iface.ICommandClient; import microservice.io.iface.ICommandClient;
...@@ -78,22 +80,26 @@ public class TestMicroserviceApp { ...@@ -78,22 +80,26 @@ public class TestMicroserviceApp {
.withMonitoring() .withMonitoring()
//.withDefaultServiceAuthorization() //.withDefaultServiceAuthorization()
.addService(Enums.EnumServiceType.E_REST,new IRestServiceHttpImpl(new RestServerParams(32000, "localhost", 2)),"undertowRestService") .addService(Enums.EnumServiceType.E_REST,new IRestServiceHttpImpl(new RestServerParams(32000, "localhost", 2)),"undertowRestService")
.addMethod(Enums.EnumServiceType.E_REST, CommonServices.EnumRestCommands.E_READ,"/resource/r1",(msgCtx,orgService) -> { .addMethod(Enums.EnumServiceType.E_REST, CommonServices.EnumRestCommands.E_READ,"/resource/{rid}",(msgCtx,orgService) -> {
BaseRestResponse brr; BaseRestResponse brr = new BaseRestResponse(true,null);
RestContext restContext = (RestContext)msgCtx;
msApp.getLogger(); msApp.getLogger();
CommonServices.IRestService restService = (CommonServices.IRestService)orgService; String rid = restContext.getParameter("rid");
//brr.setObject({ "a":"b" }) ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
//restService.writeResponse(brr); if (restContext.pathParameters != null)
restContext.pathParameters.forEach((key,value) -> objectNode.put(key,value));
brr.objectNode = objectNode;
restContext.container.writeObjectToResponse(restContext.response,brr);
}) })
.addMethod(Enums.EnumServiceType.E_REST,CommonServices.EnumRestCommands.E_READ,"/resource/r1",(msgCtx,orgService) -> { .addMethod(Enums.EnumServiceType.E_REST,CommonServices.EnumRestCommands.E_READ,"/resource/r2",(msgCtx,orgService) -> {
CommonServices.IRestService outRestService = (CommonServices.IRestService)MicroserviceApp.getsInstance().getService(Enums.EnumServiceType.E_REST,"undertowRestService"); CommonServices.IRestService outRestService = (CommonServices.IRestService)MicroserviceApp.getsInstance().getService(Enums.EnumServiceType.E_REST,"undertowRestService");
CommonServices.IRestService restService = (CommonServices.IRestService)orgService; CommonServices.IRestService restService = (CommonServices.IRestService)orgService;
CommandParams cmdParams = new CommandParams(); CommandParams cmdParams = new CommandParams();
BaseRestResponse brr = restService.read(cmdParams); BaseRestResponse brr = restService.read(cmdParams);
//restService.writeResponse(brr); //restService.writeResponse(brr);
}) })
.build() ._build()
.run(); ._run();
} }
} }
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