protected void actionTask()

in dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java [202:467]


    protected void actionTask() {
        try {
            JsonObject root = loadAction();
            if (root == null || root.isEmpty()) {
                return;
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Action: {}", root);
            }

            String action = root.getString("action");
            if ("route".equals(action)) {
                // id is a pattern
                String[] patterns = root.getString("id").split(",");
                // find matching IDs
                List<String> ids = camelContext.getRoutes()
                        .stream().map(Route::getRouteId)
                        .filter(routeId -> {
                            for (String p : patterns) {
                                if (PatternHelper.matchPattern(routeId, p)) {
                                    return true;
                                }
                            }
                            return false;
                        })
                        .collect(Collectors.toList());
                for (String id : ids) {
                    try {
                        String command = root.getString("command");
                        if ("start".equals(command)) {
                            if ("*".equals(id)) {
                                camelContext.getRouteController().startAllRoutes();
                            } else {
                                camelContext.getRouteController().startRoute(id);
                            }
                        } else if ("stop".equals(command)) {
                            if ("*".equals(id)) {
                                camelContext.getRouteController().stopAllRoutes();
                            } else {
                                camelContext.getRouteController().stopRoute(id);
                            }
                        } else if ("suspend".equals(command)) {
                            camelContext.getRouteController().suspendRoute(id);
                        } else if ("resume".equals(command)) {
                            camelContext.getRouteController().resumeRoute(id);
                        }
                    } catch (Exception e) {
                        // ignore
                    }
                }
            } else if ("logger".equals(action)) {
                try {
                    String command = root.getString("command");
                    if ("set-logging-level".equals(command)) {
                        String logger = root.getString("logger-name");
                        String level = root.getString("logging-level");
                        LoggerHelper.changeLoggingLevel(logger, level);
                    }
                } catch (Exception e) {
                    // ignore
                }
            } else if ("gc".equals(action)) {
                System.gc();
            } else if ("reload".equals(action)) {
                ContextReloadStrategy cr = camelContext.hasService(ContextReloadStrategy.class);
                if (cr != null) {
                    cr.onReload("Camel CLI");
                } else {
                    ResourceReloadStrategy rr = camelContext.hasService(ResourceReloadStrategy.class);
                    if (rr != null) {
                        rr.onReload("Camel CLI");
                    }
                }
            } else if ("reset-stats".equals(action)) {
                ManagedCamelContext mcc = camelContext.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class);
                if (mcc != null) {
                    mcc.getManagedCamelContext().reset(true);
                }
            } else if ("thread-dump".equals(action)) {
                DevConsole dc = camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class)
                        .resolveById("thread");
                if (dc != null) {
                    JsonObject json = (JsonObject) dc.call(DevConsole.MediaType.JSON, Map.of("stackTrace", "true"));
                    LOG.trace("Updating output file: {}", outputFile);
                    IOHelper.writeText(json.toJson(), outputFile);
                }
            } else if ("top-processors".equals(action)) {
                DevConsole dc
                        = camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class).resolveById("top");
                if (dc != null) {
                    JsonObject json = (JsonObject) dc.call(DevConsole.MediaType.JSON, Map.of(Exchange.HTTP_PATH, "/*"));
                    LOG.trace("Updating output file: {}", outputFile);
                    IOHelper.writeText(json.toJson(), outputFile);
                }
            } else if ("source".equals(action)) {
                DevConsole dc = camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class)
                        .resolveById("source");
                if (dc != null) {
                    String filter = root.getString("filter");
                    JsonObject json = (JsonObject) dc.call(DevConsole.MediaType.JSON, Map.of("filter", filter));
                    LOG.trace("Updating output file: {}", outputFile);
                    IOHelper.writeText(json.toJson(), outputFile);
                }
            } else if ("route-dump".equals(action)) {
                DevConsole dc = camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class)
                        .resolveById("route-dump");
                if (dc != null) {
                    String filter = root.getString("filter");
                    String format = root.getString("format");
                    String uriAsParameters = root.getString("uriAsParameters");
                    JsonObject json
                            = (JsonObject) dc.call(DevConsole.MediaType.JSON,
                                    Map.of("filter", filter, "format", format, "uriAsParameters", uriAsParameters));
                    LOG.trace("Updating output file: {}", outputFile);
                    IOHelper.writeText(json.toJson(), outputFile);
                }
            } else if ("route-controller".equals(action)) {
                DevConsole dc = camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class)
                        .resolveById("route-controller");
                if (dc != null) {
                    String stacktrace = root.getString("stacktrace");
                    JsonObject json = (JsonObject) dc.call(DevConsole.MediaType.JSON, Map.of("stacktrace", stacktrace));
                    LOG.trace("Updating output file: {}", outputFile);
                    IOHelper.writeText(json.toJson(), outputFile);
                }
            } else if ("send".equals(action)) {
                StopWatch watch = new StopWatch();
                long timestamp = System.currentTimeMillis();
                String endpoint = root.getString("endpoint");
                String body = root.getString("body");
                String exchangePattern = root.getString("exchangePattern");
                Collection<JsonObject> headers = root.getCollection("headers");
                if (body != null) {
                    InputStream is = null;
                    Object b = body;
                    Map<String, Object> map = null;
                    if (body.startsWith("file:")) {
                        File file = new File(body.substring(5));
                        is = new FileInputStream(file);
                        b = is;
                    }
                    if (headers != null) {
                        map = new HashMap<>();
                        for (JsonObject jo : headers) {
                            map.put(jo.getString("key"), jo.getString("value"));
                        }
                    }
                    final Object inputBody = b;
                    final Map<String, Object> inputHeaders = map;
                    Exchange out;
                    Endpoint target = null;
                    if (endpoint == null) {
                        List<Route> routes = camelContext.getRoutes();
                        if (!routes.isEmpty()) {
                            // grab endpoint from 1st route
                            target = routes.get(0).getEndpoint();
                        }
                    } else {
                        // is the endpoint a pattern or route id
                        boolean scheme = endpoint.contains(":");
                        boolean pattern = endpoint.endsWith("*");
                        if (!scheme || pattern) {
                            if (!scheme) {
                                endpoint = endpoint + "*";
                            }
                            for (Route route : camelContext.getRoutes()) {
                                Endpoint e = route.getEndpoint();
                                if (EndpointHelper.matchEndpoint(camelContext, e.getEndpointUri(), endpoint)) {
                                    target = e;
                                    break;
                                }
                            }
                            if (target == null) {
                                // okay it may refer to a route id
                                for (Route route : camelContext.getRoutes()) {
                                    String id = route.getRouteId();
                                    Endpoint e = route.getEndpoint();
                                    if (EndpointHelper.matchEndpoint(camelContext, id, endpoint)) {
                                        target = e;
                                        break;
                                    }
                                }
                            }
                        } else {
                            target = camelContext.getEndpoint(endpoint);
                        }
                    }

                    if (target != null) {
                        out = producer.send(target, new Processor() {
                            @Override
                            public void process(Exchange exchange) throws Exception {
                                exchange.getMessage().setBody(inputBody);
                                if (inputHeaders != null) {
                                    exchange.getMessage().setHeaders(inputHeaders);
                                }
                                exchange.setPattern(
                                        "InOut".equals(exchangePattern) ? ExchangePattern.InOut : ExchangePattern.InOnly);
                            }
                        });
                        IOHelper.close(is);
                        LOG.trace("Updating output file: {}", outputFile);
                        if (out.getException() != null) {
                            JsonObject jo = new JsonObject();
                            jo.put("endpoint", target.getEndpointUri());
                            jo.put("exchangeId", out.getExchangeId());
                            jo.put("exchangePattern", exchangePattern);
                            jo.put("timestamp", timestamp);
                            jo.put("elapsed", watch.taken());
                            jo.put("status", "failed");
                            // avoid double wrap
                            jo.put("exception",
                                    MessageHelper.dumpExceptionAsJSonObject(out.getException()).getMap("exception"));
                            IOHelper.writeText(jo.toJson(), outputFile);
                        } else if ("InOut".equals(exchangePattern)) {
                            JsonObject jo = new JsonObject();
                            jo.put("endpoint", target.getEndpointUri());
                            jo.put("exchangeId", out.getExchangeId());
                            jo.put("exchangePattern", exchangePattern);
                            jo.put("timestamp", timestamp);
                            jo.put("elapsed", watch.taken());
                            jo.put("status", "success");
                            // avoid double wrap
                            jo.put("message", MessageHelper.dumpAsJSonObject(out.getMessage(), true, true, true, true, true,
                                    BODY_MAX_CHARS).getMap("message"));
                            IOHelper.writeText(jo.toJson(), outputFile);
                        } else {
                            JsonObject jo = new JsonObject();
                            jo.put("endpoint", target.getEndpointUri());
                            jo.put("exchangeId", out.getExchangeId());
                            jo.put("exchangePattern", exchangePattern);
                            jo.put("timestamp", timestamp);
                            jo.put("elapsed", watch.taken());
                            jo.put("status", "success");
                            IOHelper.writeText(jo.toJson(), outputFile);
                        }
                    } else {
                        // there is no valid endpoint
                        JsonObject jo = new JsonObject();
                        jo.put("endpoint", root.getString("endpoint"));
                        jo.put("exchangeId", "");
                        jo.put("exchangePattern", exchangePattern);
                        jo.put("timestamp", timestamp);
                        jo.put("elapsed", watch.taken());
                        jo.put("status", "failed");
                        // avoid double wrap
                        jo.put("exception",
                                MessageHelper.dumpExceptionAsJSonObject(new NoSuchEndpointException(root.getString("endpoint")))
                                        .getMap("exception"));
                        IOHelper.writeText(jo.toJson(), outputFile);
                    }
                }
            }

            // action done so delete file
            FileUtil.deleteFile(actionFile);

        } catch (Throwable e) {
            // ignore
            LOG.debug(
                    "Error executing action file: " + actionFile + " due to: " + e.getMessage()
                      + ". This exception is ignored.",
                    e);
        }
    }