private void doActionTransformTask()

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


    private void doActionTransformTask(JsonObject root) throws Exception {
        StopWatch watch = new StopWatch();
        long timestamp = System.currentTimeMillis();
        String source = root.getString("source");
        String language = root.getString("language");
        String component = root.getString("component");
        String dataformat = root.getString("dataformat");
        String template = Jsoner.unescape(root.getStringOrDefault("template", ""));
        if (component == null && template.startsWith("file:")) {
            template = "resource:" + template;
        }
        String body = Jsoner.unescape(root.getString("body"));
        InputStream is = null;
        Object b = body;
        if (body.startsWith("file:")) {
            File file = new File(body.substring(5));
            is = new FileInputStream(file);
            b = IOHelper.loadText(is);
        }
        final Object inputBody = b;
        Map<String, Object> map = null;
        Collection<JsonObject> headers = root.getCollection("headers");
        if (headers != null) {
            map = new LinkedHashMap<>();
            for (JsonObject jo : headers) {
                map.put(jo.getString("key"), jo.getString("value"));
            }
        }
        final Map<String, Object> inputHeaders = map;
        Map<String, Object> map2 = null;
        Collection<JsonObject> options = root.getCollection("options");
        if (options != null) {
            map2 = new LinkedHashMap<>();
            for (JsonObject jo : options) {
                map2.put(jo.getString("key"), jo.getString("value"));
            }
        }
        final Map<String, Object> inputOptions = map2;
        Exchange out = camelContext.getCamelContextExtension().getExchangeFactory().create(false);
        try {
            if (source != null) {
                Integer sourceLine = LoggerHelper.extractSourceLocationLineNumber(source);
                String sourceId = LoggerHelper.extractSourceLocationId(source);
                source = LoggerHelper.stripSourceLocationLineNumber(source);
                LOG.debug("Source: {} line: {} id: {}", source, sourceLine, sourceId);

                boolean update = true;
                File f = new File(source);
                if (f.isFile() && f.exists()) {
                    byte[] data = Files.readAllBytes(f.toPath());
                    if (Arrays.equals(lastSource, data)) {
                        LOG.debug("Source file: {} is not updated since last", source);
                        update = false;
                    }
                    lastSource = data;
                }
                if (update) {
                    if (sourceLine != null) {
                        LOG.info("Transforming from source: {}:{}", source, sourceLine);
                    } else if (sourceId != null) {
                        LOG.info("Transforming from source: {}:{}", source, sourceId);
                    } else {
                        LOG.info("Transforming from source: {}", source);
                    }

                    // load route definition
                    if (!source.startsWith("file:")) {
                        source = "file:" + source;
                    }
                    // load the source via routes loader, and find the builders, which we can use to get to the model
                    Resource res = camelContext.getCamelContextExtension().getContextPlugin(ResourceLoader.class)
                            .resolveResource(source);
                    RoutesLoader loader = camelContext.getCamelContextExtension().getContextPlugin(RoutesLoader.class);
                    Collection<RoutesBuilder> builders = loader.findRoutesBuilders(res);
                    for (RoutesBuilder builder : builders) {
                        // use the model as we just want to find the EIP with the inlined expression
                        ModelRoutesBuilder mrb = (ModelRoutesBuilder) builder;
                        // must prepare model before we can access them
                        mrb.prepareModel(camelContext);
                        // find the EIP with the inlined expression to use
                        ExpressionDefinition found = null;
                        for (RouteDefinition rd : mrb.getRoutes().getRoutes()) {
                            Collection<ProcessorDefinition> defs
                                    = ProcessorDefinitionHelper.filterTypeInOutputs(rd.getOutputs(),
                                            ProcessorDefinition.class);
                            for (ProcessorDefinition p : defs) {
                                if (p instanceof HasExpressionType et) {
                                    ExpressionDefinition def = et.getExpressionType();
                                    if (def != null) {
                                        if (sourceLine != null) {
                                            if (p.getLineNumber() == -1 || p.getLineNumber() <= sourceLine) {
                                                found = def;
                                            }
                                        } else if (sourceId != null) {
                                            if (sourceId.equals(p.getId()) || sourceId.equals(def.getId())) {
                                                found = def;
                                            }
                                        } else {
                                            found = def;
                                        }
                                    }
                                }
                            }
                            if (found != null) {
                                lastSourceExpression = found;
                            }
                        }
                    }
                }
                if (lastSourceExpression != null) {
                    // create dummy exchange with
                    out.setPattern(ExchangePattern.InOut);
                    out.getMessage().setBody(inputBody);
                    if (inputHeaders != null) {
                        out.getMessage().setHeaders(inputHeaders);
                    }
                    String result = lastSourceExpression.evaluate(out, String.class);
                    out.getMessage().setBody(result);
                }
            } else if (component != null) {
                // transform via component
                out.setPattern(ExchangePattern.InOut);
                out.getMessage().setBody(inputBody);
                if (inputHeaders != null) {
                    out.getMessage().setHeaders(inputHeaders);
                }
                String uri = component + ":" + template;
                // must disable any kind of content cache on the component, so template is always reloaded
                EndpointUriFactory euf = camelContext.getCamelContextExtension().getEndpointUriFactory(component);
                if (euf.propertyNames().contains("contentCache")) {
                    uri = uri + "?contentCache=false";
                }
                if (inputOptions != null) {
                    uri = URISupport.appendParametersToURI(uri, inputOptions);
                }
                out = producer.send(uri, out);
            } else if (dataformat != null) {
                // transform via dataformat
                out.setPattern(ExchangePattern.InOut);
                out.getMessage().setBody(inputBody);
                if (inputHeaders != null) {
                    out.getMessage().setHeaders(inputHeaders);
                }
                String uri = "dataformat:" + dataformat + ":unmarshal";
                if (inputOptions != null) {
                    uri = URISupport.appendParametersToURI(uri, inputOptions);
                }
                out = producer.send(uri, out);
            } else {
                // transform via language
                Language lan = camelContext.resolveLanguage(language);
                Expression exp = lan.createExpression(template);
                // configure expression if options provided
                if (inputOptions != null) {
                    PropertyBindingSupport.build()
                            .withCamelContext(camelContext).withTarget(exp).withProperties(inputOptions).bind();
                }
                exp.init(camelContext);
                // create dummy exchange with
                out.setPattern(ExchangePattern.InOut);
                out.getMessage().setBody(inputBody);
                if (inputHeaders != null) {
                    out.getMessage().setHeaders(inputHeaders);
                }
                String result = exp.evaluate(out, String.class);
                out.getMessage().setBody(result);
            }
            IOHelper.close(is);
        } catch (Exception e) {
            out.setException(e);
        }
        LOG.trace("Updating output file: {}", outputFile);
        if (out.getException() != null) {
            JsonObject jo = new JsonObject();
            if (language != null) {
                jo.put("language", language);
            }
            if (source != null) {
                jo.put("source", source);
            }
            jo.put("exchangeId", out.getExchangeId());
            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 {
            JsonObject jo = new JsonObject();
            if (language != null) {
                jo.put("language", language);
            }
            if (source != null) {
                jo.put("source", source);
            }
            jo.put("exchangeId", out.getExchangeId());
            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, true,
                    BODY_MAX_CHARS).getMap("message"));
            IOHelper.writeText(jo.toJson(), outputFile);
        }
        camelContext.getCamelContextExtension().getExchangeFactory().release(out);
    }