use of com.networknt.status.Status in project light-rest-4j by networknt.
the class ValidatorHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
OpenApiOperation openApiOperation = null;
Map<String, Object> auditInfo = exchange.getAttachment(AuditHandler.AUDIT_INFO);
if (auditInfo != null) {
openApiOperation = (OpenApiOperation) auditInfo.get(Constants.OPENAPI_OPERATION_STRING);
}
if (openApiOperation == null) {
Status status = new Status(STATUS_MISSING_OPENAPI_OPERATION);
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
Status status = requestValidator.validateRequest(requestPath, exchange, openApiOperation);
if (status != null) {
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
next.handleRequest(exchange);
}
use of com.networknt.status.Status in project light-rest-4j by networknt.
the class SchemaValidator method doValidate.
private Status doValidate(final String value, final Object schema) {
requireNonNull(schema, "A schema is required");
Status status = null;
Set<ValidationMessage> processingReport = null;
try {
final JsonNode schemaObject = Json.mapper().readTree(Json.pretty(schema));
if (api != null) {
if (this.definitions == null) {
this.definitions = Json.mapper().readTree(Json.pretty(api.getDefinitions()));
}
((ObjectNode) schemaObject).set(DEFINITIONS_FIELD, this.definitions);
}
JsonSchema jsonSchema = JsonSchemaFactory.getInstance().getSchema(schemaObject);
String normalisedValue = value;
if (schema instanceof StringProperty) {
normalisedValue = Util.quote(value);
}
final JsonNode content = Json.mapper().readTree(normalisedValue);
processingReport = jsonSchema.validate(content);
} catch (JsonParseException e) {
return new Status(VALIDATOR_SCHEMA_INVALID_JSON, e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
if (processingReport != null && processingReport.size() > 0) {
ValidationMessage vm = processingReport.iterator().next();
status = new Status(VALIDATOR_SCHEMA, vm.getMessage());
}
return status;
}
use of com.networknt.status.Status in project light-rest-4j by networknt.
the class ValidatorHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
SwaggerOperation swaggerOperation = null;
Map<String, Object> auditInfo = exchange.getAttachment(AuditHandler.AUDIT_INFO);
if (auditInfo != null) {
swaggerOperation = (SwaggerOperation) auditInfo.get(Constants.SWAGGER_OPERATION_STRING);
}
if (swaggerOperation == null) {
Status status = new Status(STATUS_MISSING_SWAGGER_OPERATION);
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
Status status = requestValidator.validateRequest(requestPath, exchange, swaggerOperation);
if (status != null) {
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
return;
}
next.handleRequest(exchange);
}
use of com.networknt.status.Status in project light-4j by networknt.
the class FailbackRegistry method unregister.
@Override
public void unregister(URL url) {
failedRegistered.remove(url);
failedUnregistered.remove(url);
try {
super.unregister(url);
} catch (Exception e) {
if (isCheckingUrls(getUrl(), url)) {
throw new FrameworkException(new Status(UNREGISTER_ERROR, registryClassName, url, getUrl()), e);
}
failedUnregistered.add(url);
}
}
use of com.networknt.status.Status in project light-4j by networknt.
the class CommandServiceManager method buildWeightsMap.
/*
@Override
public void notifyCommand(URL serviceUrl, String commandString) {
if(logger.isInfoEnabled()) logger.info("CommandServiceManager notify command. service:" + serviceUrl.toSimpleString() + ", command:" + commandString);
if (!SwitcherUtil.isOpen(LIGHT_COMMAND_SWITCHER) || commandString == null) {
if(logger.isInfoEnabled()) logger.info("command reset empty since swither is close.");
commandString = "";
}
List<URL> finalResult = new ArrayList<URL>();
URL urlCopy = serviceUrl.createCopy();
if (!StringUtils.equals(commandString, commandStringCache)) {
commandStringCache = commandString;
commandCache = RpcCommandUtil.stringToCommand(commandStringCache);
Map<String, Integer> weights = new HashMap<String, Integer>();
if (commandCache != null) {
commandCache.sort();
finalResult = discoverServiceWithCommand(refUrl, weights, commandCache);
} else {
// If command is abnormal, handle it just like there is no command to prevent wrong command
if (StringUtils.isNotBlank(commandString)) {
logger.warn("command parse fail, ignored! command:" + commandString);
commandString = "";
}
// If there is no command, return manager group
finalResult.addAll(discoverOneGroup(refUrl));
}
// when command is changed, delete cache and unsubscribe group
Set<String> groupKeys = groupServiceCache.keySet();
for (String gk : groupKeys) {
if (!weights.containsKey(gk)) {
groupServiceCache.remove(gk);
URL urlTemp = urlCopy.createCopy();
urlTemp.addParameter(URLParamType.group.getName(), gk);
registry.unsubscribeService(urlTemp, this);
}
}
} else {
if(logger.isInfoEnabled()) logger.info("command is not changed. url:" + serviceUrl.toSimpleString());
// command not changed do nothing
return;
}
for (NotifyListener notifyListener : notifySet) {
notifyListener.notify(registry.getUrl(), finalResult);
}
// when command is empty, trigger resub service
if ("".equals(commandString)) {
if(logger.isInfoEnabled()) logger.info("reSub service" + refUrl.toSimpleString());
registry.subscribeService(refUrl, this);
}
}
public List<URL> discoverServiceWithCommand(URL serviceUrl, Map<String, Integer> weights, RpcCommand rpcCommand) {
String localIP = NetUtils.getLocalAddress().getHostAddress();
return this.discoverServiceWithCommand(serviceUrl, weights, rpcCommand, localIP);
}
public List<URL> discoverServiceWithCommand(URL serviceUrl, Map<String, Integer> weights, RpcCommand rpcCommand, String localIP) {
if (rpcCommand == null || CollectionUtil.isEmpty(rpcCommand.getClientCommandList())) {
return discoverOneGroup(serviceUrl);
}
List<URL> mergedResult = new LinkedList<URL>();
String path = serviceUrl.getPath();
List<RpcCommand.ClientCommand> clientCommandList = rpcCommand.getClientCommandList();
boolean hit = false;
for (RpcCommand.ClientCommand command : clientCommandList) {
mergedResult = new LinkedList<URL>();
// check if current url matches
boolean match = RpcCommandUtil.match(command.getPattern(), path);
if (match) {
hit = true;
if (!CollectionUtil.isEmpty(command.getMergeGroups())) {
// calculate weight
try {
buildWeightsMap(weights, command);
} catch (FrameworkException e) {
logger.error("build weights map fail!" + e.getMessage());
continue;
}
// According to the result, discover each group's services and combine them together
mergedResult.addAll(mergeResult(serviceUrl, weights));
} else {
mergedResult.addAll(discoverOneGroup(serviceUrl));
}
if(logger.isInfoEnabled()) logger.info("mergedResult: size-" + mergedResult.size() + " --- " + mergedResult.toString());
if (!CollectionUtil.isEmpty(command.getRouteRules())) {
if(logger.isInfoEnabled()) logger.info("router: " + command.getRouteRules().toString());
for (String routeRule : command.getRouteRules()) {
String[] fromTo = routeRule.replaceAll("\\s+", "").split("to");
if (fromTo.length != 2) {
logger.warn("Invalid route rule configuration");
continue;
}
String from = fromTo[0];
String to = fromTo[1];
if (from.length() < 1 || to.length() < 1 || !IP_PATTERN.matcher(from).find() || !IP_PATTERN.matcher(to).find()) {
logger.warn("Invalid route rule configuration");
continue;
}
boolean oppositeFrom = from.startsWith("!");
boolean oppositeTo = to.startsWith("!");
if (oppositeFrom) {
from = from.substring(1);
}
if (oppositeTo) {
to = to.substring(1);
}
int idx = from.indexOf('*');
boolean matchFrom;
if (idx != -1) {
matchFrom = localIP.startsWith(from.substring(0, idx));
} else {
matchFrom = localIP.equals(from);
}
// prefixed with !,reverse
if (oppositeFrom) {
matchFrom = !matchFrom;
}
if(logger.isInfoEnabled()) logger.info("matchFrom: " + matchFrom + ", localip:" + localIP + ", from:" + from);
if (matchFrom) {
boolean matchTo;
Iterator<URL> iterator = mergedResult.iterator();
while (iterator.hasNext()) {
URL url = iterator.next();
if (url.getProtocol().equalsIgnoreCase("rule")) {
continue;
}
idx = to.indexOf('*');
if (idx != -1) {
matchTo = url.getHost().startsWith(to.substring(0, idx));
} else {
matchTo = url.getHost().equals(to);
}
if (oppositeTo) {
matchTo = !matchTo;
}
if (!matchTo) {
iterator.remove();
if(logger.isInfoEnabled()) logger.info("router To not match. url remove : " + url.toSimpleString());
}
}
}
}
}
// use the first one matched TODO Consider if this meet most user cases
break;
}
}
List<URL> finalResult = new ArrayList<URL>();
if (!hit) {
finalResult = discoverOneGroup(serviceUrl);
} else {
finalResult.addAll(mergedResult);
}
return finalResult;
}
*/
private void buildWeightsMap(Map<String, Integer> weights, RpcCommand.ClientCommand command) {
for (String rule : command.getMergeGroups()) {
String[] gw = rule.split(":");
int weight = 1;
if (gw.length > 1) {
try {
weight = Integer.parseInt(gw[1]);
} catch (NumberFormatException e) {
throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight));
}
if (weight < 0 || weight > 100) {
throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight));
}
}
weights.put(gw[0], weight);
}
}
Aggregations