Search in sources :

Example 11 with ProcessorDefinition

use of org.apache.camel.model.ProcessorDefinition in project camel by apache.

the class AdviceWithTasks method doAfter.

private static AdviceWithTask doAfter(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition<?> after, boolean selectFirst, boolean selectLast, int selectFrom, int selectTo, int maxDeep) {
    return new AdviceWithTask() {

        public void task() throws Exception {
            boolean match = false;
            Iterator<ProcessorDefinition<?>> it = AdviceWithTasks.createMatchByIterator(route, matchBy, selectFirst, selectLast, selectFrom, selectTo, maxDeep);
            while (it.hasNext()) {
                ProcessorDefinition<?> output = it.next();
                if (matchBy.match(output)) {
                    List<ProcessorDefinition<?>> outputs = getOutputs(output);
                    if (outputs != null) {
                        int index = outputs.indexOf(output);
                        if (index != -1) {
                            match = true;
                            Object existing = outputs.get(index);
                            outputs.add(index + 1, after);
                            // must set parent on the node we added in the route
                            after.setParent(output.getParent());
                            LOG.info("AdviceWith (" + matchBy.getId() + ") : [" + existing + "] --> after [" + after + "]");
                        }
                    }
                }
            }
            if (!match) {
                throw new IllegalArgumentException("There are no outputs which matches: " + matchBy.getId() + " in the route: " + route);
            }
        }
    };
}
Also used : ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) Endpoint(org.apache.camel.Endpoint)

Example 12 with ProcessorDefinition

use of org.apache.camel.model.ProcessorDefinition in project camel by apache.

the class RandomLoadBalanceJavaDSLBuilderTest method navigateDefinition.

private void navigateDefinition(ProcessorDefinition<?> def, StringBuilder sb) {
    // must do this ugly cast to avoid compiler error on HP-UX
    ProcessorDefinition<?> defn = (ProcessorDefinition<?>) def;
    if (defn instanceof LoadBalanceDefinition) {
        sb.append(".loadBalance()");
        LoadBalanceDefinition lbd = (LoadBalanceDefinition) defn;
        LoadBalancer balancer = lbd.getLoadBalancerType().getLoadBalancer(null);
        if (balancer instanceof RandomLoadBalancer) {
            sb.append(".random()");
        }
    }
    if (defn instanceof SendDefinition) {
        SendDefinition<?> send = (SendDefinition<?>) defn;
        sb.append(".to(\"" + send.getUri() + "\")");
    }
    List<ProcessorDefinition<?>> children = defn.getOutputs();
    if (children == null || children.isEmpty()) {
        return;
    }
    for (ProcessorDefinition<?> child : children) {
        navigateDefinition(child, sb);
    }
}
Also used : SendDefinition(org.apache.camel.model.SendDefinition) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) LoadBalanceDefinition(org.apache.camel.model.LoadBalanceDefinition) LoadBalancer(org.apache.camel.processor.loadbalancer.LoadBalancer) RandomLoadBalancer(org.apache.camel.processor.loadbalancer.RandomLoadBalancer) RandomLoadBalancer(org.apache.camel.processor.loadbalancer.RandomLoadBalancer)

Example 13 with ProcessorDefinition

use of org.apache.camel.model.ProcessorDefinition in project camel by apache.

the class DefaultCamelContext method explainEipJson.

public String explainEipJson(String nameOrId, boolean includeAllOptions) {
    try {
        // try to find the id within all known routes and their eips
        String eipName = nameOrId;
        NamedNode target = null;
        for (RouteDefinition route : getRouteDefinitions()) {
            if (route.getId().equals(nameOrId)) {
                target = route;
                break;
            }
            for (FromDefinition from : route.getInputs()) {
                if (nameOrId.equals(from.getId())) {
                    target = route;
                    break;
                }
            }
            Iterator<ProcessorDefinition> it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class);
            while (it.hasNext()) {
                ProcessorDefinition def = it.next();
                if (nameOrId.equals(def.getId())) {
                    target = def;
                    break;
                }
            }
            if (target != null) {
                break;
            }
        }
        if (target != null) {
            eipName = target.getShortName();
        }
        String json = getEipParameterJsonSchema(eipName);
        if (json == null) {
            return null;
        }
        // overlay with runtime parameters that id uses at runtime
        if (target != null) {
            List<Map<String, String>> rows = JsonSchemaHelper.parseJsonSchema("properties", json, true);
            // selected rows to use for answer
            Map<String, String[]> selected = new LinkedHashMap<String, String[]>();
            // extract options from the node
            Map<String, Object> options = new LinkedHashMap<String, Object>();
            IntrospectionSupport.getProperties(target, options, "", false);
            // remove outputs which we do not want to include
            options.remove("outputs");
            // include other rows
            for (Map<String, String> row : rows) {
                String name = row.get("name");
                String kind = row.get("kind");
                String label = row.get("label");
                String required = row.get("required");
                String value = row.get("value");
                String defaultValue = row.get("defaultValue");
                String type = row.get("type");
                String javaType = row.get("javaType");
                String deprecated = row.get("deprecated");
                String description = row.get("description");
                // find the configured option
                Object o = options.get(name);
                if (o != null) {
                    value = o.toString();
                }
                value = URISupport.sanitizePath(value);
                if (includeAllOptions || o != null) {
                    // add as selected row
                    if (!selected.containsKey(name)) {
                        selected.put(name, new String[] { name, kind, label, required, type, javaType, deprecated, value, defaultValue, description });
                    }
                }
            }
            json = ObjectHelper.before(json, "  \"properties\": {");
            StringBuilder buffer = new StringBuilder("  \"properties\": {");
            boolean first = true;
            for (String[] row : selected.values()) {
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append("\n    ");
                String name = row[0];
                String kind = row[1];
                String label = row[2];
                String required = row[3];
                String type = row[4];
                String javaType = row[5];
                String deprecated = row[6];
                String value = row[7];
                String defaultValue = row[8];
                String description = row[9];
                // add json of the option
                buffer.append(StringQuoteHelper.doubleQuote(name)).append(": { ");
                CollectionStringBuffer csb = new CollectionStringBuffer();
                if (kind != null) {
                    csb.append("\"kind\": \"" + kind + "\"");
                }
                if (label != null) {
                    csb.append("\"label\": \"" + label + "\"");
                }
                if (required != null) {
                    csb.append("\"required\": \"" + required + "\"");
                }
                if (type != null) {
                    csb.append("\"type\": \"" + type + "\"");
                }
                if (javaType != null) {
                    csb.append("\"javaType\": \"" + javaType + "\"");
                }
                if (deprecated != null) {
                    csb.append("\"deprecated\": \"" + deprecated + "\"");
                }
                if (value != null) {
                    csb.append("\"value\": \"" + value + "\"");
                }
                if (defaultValue != null) {
                    csb.append("\"defaultValue\": \"" + defaultValue + "\"");
                }
                if (description != null) {
                    csb.append("\"description\": \"" + description + "\"");
                }
                if (!csb.isEmpty()) {
                    buffer.append(csb.toString());
                }
                buffer.append(" }");
            }
            buffer.append("\n  }\n}\n");
            // insert the original first part of the json into the start of the buffer
            buffer.insert(0, json);
            return buffer.toString();
        }
        return json;
    } catch (Exception e) {
        // ignore and return empty response
        return null;
    }
}
Also used : FromDefinition(org.apache.camel.model.FromDefinition) CollectionStringBuffer(org.apache.camel.util.CollectionStringBuffer) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) NamedNode(org.apache.camel.NamedNode) RuntimeCamelException(org.apache.camel.RuntimeCamelException) MalformedObjectNameException(javax.management.MalformedObjectNameException) VetoCamelContextStartException(org.apache.camel.VetoCamelContextStartException) IOException(java.io.IOException) LoadPropertiesException(org.apache.camel.util.LoadPropertiesException) NoSuchEndpointException(org.apache.camel.NoSuchEndpointException) ResolveEndpointFailedException(org.apache.camel.ResolveEndpointFailedException) NoFactoryAvailableException(org.apache.camel.NoFactoryAvailableException) FailedToStartRouteException(org.apache.camel.FailedToStartRouteException) LinkedHashMap(java.util.LinkedHashMap) RouteDefinition(org.apache.camel.model.RouteDefinition) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 14 with ProcessorDefinition

use of org.apache.camel.model.ProcessorDefinition in project camel by apache.

the class DefaultDebugger method addSingleStepBreakpoint.

@Override
public void addSingleStepBreakpoint(final Breakpoint breakpoint, Condition... conditions) {
    // wrap the breakpoint into single step breakpoint so we can automatic enable/disable the single step mode
    Breakpoint singlestep = new Breakpoint() {

        @Override
        public State getState() {
            return breakpoint.getState();
        }

        @Override
        public void suspend() {
            breakpoint.suspend();
        }

        @Override
        public void activate() {
            breakpoint.activate();
        }

        @Override
        public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition) {
            breakpoint.beforeProcess(exchange, processor, definition);
        }

        @Override
        public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition, long timeTaken) {
            breakpoint.afterProcess(exchange, processor, definition, timeTaken);
        }

        @Override
        public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition<?> definition) {
            if (event instanceof ExchangeCreatedEvent) {
                exchange.getContext().getDebugger().startSingleStepExchange(exchange.getExchangeId(), this);
            } else if (event instanceof ExchangeCompletedEvent) {
                exchange.getContext().getDebugger().stopSingleStepExchange(exchange.getExchangeId());
            }
            breakpoint.onEvent(exchange, event, definition);
        }

        @Override
        public String toString() {
            return breakpoint.toString();
        }
    };
    addBreakpoint(singlestep, conditions);
}
Also used : Exchange(org.apache.camel.Exchange) Breakpoint(org.apache.camel.spi.Breakpoint) ExchangeCreatedEvent(org.apache.camel.management.event.ExchangeCreatedEvent) Processor(org.apache.camel.Processor) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) ExchangeCompletedEvent(org.apache.camel.management.event.ExchangeCompletedEvent) EventObject(java.util.EventObject)

Example 15 with ProcessorDefinition

use of org.apache.camel.model.ProcessorDefinition in project camel by apache.

the class RestDefinition method addRouteDefinition.

private void addRouteDefinition(CamelContext camelContext, List<RouteDefinition> answer, String component) {
    for (VerbDefinition verb : getVerbs()) {
        // either the verb has a singular to or a embedded route
        RouteDefinition route = verb.getRoute();
        if (route == null) {
            // it was a singular to, so add a new route and add the singular
            // to as output to this route
            route = new RouteDefinition();
            ProcessorDefinition def = verb.getTo() != null ? verb.getTo() : verb.getToD();
            route.getOutputs().add(def);
        }
        // add the binding
        RestBindingDefinition binding = new RestBindingDefinition();
        binding.setComponent(component);
        binding.setType(verb.getType());
        binding.setOutType(verb.getOutType());
        // verb takes precedence over configuration on rest
        if (verb.getConsumes() != null) {
            binding.setConsumes(verb.getConsumes());
        } else {
            binding.setConsumes(getConsumes());
        }
        if (verb.getProduces() != null) {
            binding.setProduces(verb.getProduces());
        } else {
            binding.setProduces(getProduces());
        }
        if (verb.getBindingMode() != null) {
            binding.setBindingMode(verb.getBindingMode());
        } else {
            binding.setBindingMode(getBindingMode());
        }
        if (verb.getSkipBindingOnErrorCode() != null) {
            binding.setSkipBindingOnErrorCode(verb.getSkipBindingOnErrorCode());
        } else {
            binding.setSkipBindingOnErrorCode(getSkipBindingOnErrorCode());
        }
        if (verb.getEnableCORS() != null) {
            binding.setEnableCORS(verb.getEnableCORS());
        } else {
            binding.setEnableCORS(getEnableCORS());
        }
        // register all the default values for the query parameters
        for (RestOperationParamDefinition param : verb.getParams()) {
            if (RestParamType.query == param.getType() && ObjectHelper.isNotEmpty(param.getDefaultValue())) {
                binding.addDefaultValue(param.getName(), param.getDefaultValue());
            }
        }
        route.setRestBindingDefinition(binding);
        // create the from endpoint uri which is using the rest component
        String from = "rest:" + verb.asVerb() + ":" + buildUri(verb);
        // append options
        Map<String, Object> options = new HashMap<String, Object>();
        // verb takes precedence over configuration on rest
        if (verb.getConsumes() != null) {
            options.put("consumes", verb.getConsumes());
        } else if (getConsumes() != null) {
            options.put("consumes", getConsumes());
        }
        if (verb.getProduces() != null) {
            options.put("produces", verb.getProduces());
        } else if (getProduces() != null) {
            options.put("produces", getProduces());
        }
        // append optional type binding information
        String inType = binding.getType();
        if (inType != null) {
            options.put("inType", inType);
        }
        String outType = binding.getOutType();
        if (outType != null) {
            options.put("outType", outType);
        }
        // if no route id has been set, then use the verb id as route id
        if (!route.hasCustomIdAssigned()) {
            // use id of verb as route id
            String id = verb.getId();
            if (id != null) {
                route.setId(id);
            }
        }
        String routeId = verb.idOrCreate(camelContext.getNodeIdFactory());
        if (!verb.getUsedForGeneratingNodeId()) {
            routeId = route.idOrCreate(camelContext.getNodeIdFactory());
        }
        verb.setRouteId(routeId);
        options.put("routeId", routeId);
        if (component != null && !component.isEmpty()) {
            options.put("componentName", component);
        }
        // include optional description, which we favor from 1) to/route description 2) verb description 3) rest description
        // this allows end users to define general descriptions and override then per to/route or verb
        String description = verb.getTo() != null ? verb.getTo().getDescriptionText() : route.getDescriptionText();
        if (description == null) {
            description = verb.getDescriptionText();
        }
        if (description == null) {
            description = getDescriptionText();
        }
        if (description != null) {
            options.put("description", description);
        }
        if (!options.isEmpty()) {
            String query;
            try {
                query = URISupport.createQueryString(options);
            } catch (URISyntaxException e) {
                throw ObjectHelper.wrapRuntimeCamelException(e);
            }
            from = from + "?" + query;
        }
        String path = getPath();
        String s1 = FileUtil.stripTrailingSeparator(path);
        String s2 = FileUtil.stripLeadingSeparator(verb.getUri());
        String allPath;
        if (s1 != null && s2 != null) {
            allPath = s1 + "/" + s2;
        } else if (path != null) {
            allPath = path;
        } else {
            allPath = verb.getUri();
        }
        // each {} is a parameter (url templating)
        String[] arr = allPath.split("\\/");
        for (String a : arr) {
            // need to resolve property placeholders first
            try {
                a = camelContext.resolvePropertyPlaceholders(a);
            } catch (Exception e) {
                throw ObjectHelper.wrapRuntimeCamelException(e);
            }
            if (a.startsWith("{") && a.endsWith("}")) {
                String key = a.substring(1, a.length() - 1);
                //  merge if exists
                boolean found = false;
                for (RestOperationParamDefinition param : verb.getParams()) {
                    // name is mandatory
                    String name = param.getName();
                    ObjectHelper.notEmpty(name, "parameter name");
                    // need to resolve property placeholders first
                    try {
                        name = camelContext.resolvePropertyPlaceholders(name);
                    } catch (Exception e) {
                        throw ObjectHelper.wrapRuntimeCamelException(e);
                    }
                    if (name.equalsIgnoreCase(key)) {
                        param.type(RestParamType.path);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    param(verb).name(key).type(RestParamType.path).endParam();
                }
            }
        }
        if (verb.getType() != null) {
            String bodyType = verb.getType();
            if (bodyType.endsWith("[]")) {
                bodyType = "List[" + bodyType.substring(0, bodyType.length() - 2) + "]";
            }
            RestOperationParamDefinition param = findParam(verb, RestParamType.body.name());
            if (param == null) {
                // must be body type and set the model class as data type
                param(verb).name(RestParamType.body.name()).type(RestParamType.body).dataType(bodyType).endParam();
            } else {
                // must be body type and set the model class as data type
                param.type(RestParamType.body).dataType(bodyType);
            }
        }
        // the route should be from this rest endpoint
        route.fromRest(from);
        route.id(routeId);
        route.setRestDefinition(this);
        answer.add(route);
    }
}
Also used : HashMap(java.util.HashMap) ProcessorDefinition(org.apache.camel.model.ProcessorDefinition) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) RouteDefinition(org.apache.camel.model.RouteDefinition)

Aggregations

ProcessorDefinition (org.apache.camel.model.ProcessorDefinition)17 RouteDefinition (org.apache.camel.model.RouteDefinition)5 Endpoint (org.apache.camel.Endpoint)4 HashMap (java.util.HashMap)3 Processor (org.apache.camel.Processor)3 MalformedObjectNameException (javax.management.MalformedObjectNameException)2 NamedNode (org.apache.camel.NamedNode)2 PerformanceCounter (org.apache.camel.api.management.PerformanceCounter)2 FromDefinition (org.apache.camel.model.FromDefinition)2 SendDefinition (org.apache.camel.model.SendDefinition)2 KeyValueHolder (org.apache.camel.util.KeyValueHolder)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 URISyntaxException (java.net.URISyntaxException)1 EventObject (java.util.EventObject)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)1