Search in sources :

Example 36 with 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());
    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);
}
Also used : Status(com.networknt.status.Status)

Example 37 with Status

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;
}
Also used : Status(com.networknt.status.Status) ValidationMessage(com.networknt.schema.ValidationMessage) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonSchema(com.networknt.schema.JsonSchema) StringProperty(io.swagger.models.properties.StringProperty) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) JsonParseException(com.fasterxml.jackson.core.JsonParseException)

Example 38 with 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);
}
Also used : Status(com.networknt.status.Status)

Example 39 with Status

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);
    }
}
Also used : Status(com.networknt.status.Status) FrameworkException(com.networknt.exception.FrameworkException) FrameworkException(com.networknt.exception.FrameworkException)

Example 40 with Status

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);
    }
}
Also used : Status(com.networknt.status.Status) FrameworkException(com.networknt.exception.FrameworkException)

Aggregations

Status (com.networknt.status.Status)71 Test (org.junit.Test)45 Http2Client (com.networknt.client.Http2Client)19 ClientException (com.networknt.exception.ClientException)19 URI (java.net.URI)19 CountDownLatch (java.util.concurrent.CountDownLatch)19 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 ClientConnection (io.undertow.client.ClientConnection)17 ClientRequest (io.undertow.client.ClientRequest)17 ClientResponse (io.undertow.client.ClientResponse)17 IOException (java.io.IOException)12 FrameworkException (com.networknt.exception.FrameworkException)9 HttpString (io.undertow.util.HttpString)7 IntegerProperty (io.swagger.models.properties.IntegerProperty)4 BigDecimal (java.math.BigDecimal)4 HashMap (java.util.HashMap)4 JsonParseException (com.fasterxml.jackson.core.JsonParseException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 JsonSchema (com.networknt.schema.JsonSchema)3 ValidationMessage (com.networknt.schema.ValidationMessage)3