public void onRouteContextCreate(RouteContext routeContext) {
    if (!initialized) {
      return;
    }

    // Create a map (ProcessorType -> PerformanceCounter)
    // to be passed to InstrumentationInterceptStrategy.
    Map<ProcessorDefinition<?>, PerformanceCounter> registeredCounters =
        new HashMap<ProcessorDefinition<?>, PerformanceCounter>();

    // Each processor in a route will have its own performance counter.
    // These performance counter will be embedded to InstrumentationProcessor
    // and wrap the appropriate processor by InstrumentationInterceptStrategy.
    RouteDefinition route = routeContext.getRoute();

    // register performance counters for all processors and its children
    for (ProcessorDefinition<?> processor : route.getOutputs()) {
      registerPerformanceCounters(routeContext, processor, registeredCounters);
    }

    // set this managed intercept strategy that executes the JMX instrumentation for performance
    // metrics
    // so our registered counters can be used for fine grained performance instrumentation
    routeContext.setManagedInterceptStrategy(
        new InstrumentationInterceptStrategy(registeredCounters, wrappedProcessors));
  }
Пример #2
0
 private void dumpCamelContext(String msg) {
   LOGGER.debug("\n\n***************  START: " + msg + "  *****************");
   List<RouteDefinition> routeDefinitions = camelContext.getRouteDefinitions();
   if (routeDefinitions != null) {
     LOGGER.debug("Number of routes = " + routeDefinitions.size());
     for (RouteDefinition routeDef : routeDefinitions) {
       String routeId = routeDef.getId();
       LOGGER.debug("route ID = " + routeId);
       List<FromDefinition> routeInputs = routeDef.getInputs();
       if (routeInputs.isEmpty()) {
         LOGGER.debug("routeInputs are EMPTY");
       } else {
         for (FromDefinition fromDef : routeInputs) {
           LOGGER.debug("route input's URI = " + fromDef.getUri());
         }
       }
       ServiceStatus routeStatus = camelContext.getRouteStatus(routeId);
       if (routeStatus != null) {
         LOGGER.debug("Route ID " + routeId + " is started = " + routeStatus.isStarted());
       } else {
         LOGGER.debug("routeStatus is NULL for routeId = " + routeId);
       }
     }
   }
   LOGGER.debug("***************  END: " + msg + "  *****************\n\n");
 }
 /**
  * Appends a namespace on the end of all URIs found in the specified route.
  *
  * @param route the specified route
  * @param namespace the specified namespace
  */
 public static final void addNamespaceParameter(RouteDefinition route, String namespace) {
   for (FromDefinition fromDef : route.getInputs()) {
     addNamespaceParameterFrom(fromDef, namespace);
   }
   for (ProcessorDefinition<?> procDef : route.getOutputs()) {
     addNamespaceParameterTo(procDef, namespace);
   }
 }
  /**
   * Add the route in the database if it's not already, or update its state.
   *
   * @param routes being added to the app
   */
  @Override
  public void onRoutesAdd(Collection<Route> routes) {
    for (Route routeCamel : routes) {
      // adding a performance counter on the route
      if (routeCamel instanceof EventDrivenConsumerRoute) {
        EventDrivenConsumerRoute edcr = (EventDrivenConsumerRoute) routeCamel;
        Processor processor = edcr.getProcessor();
        if (processor instanceof InstrumentationProcessor) {
          InstrumentationProcessor ip = (InstrumentationProcessor) processor;
          ConsolePerformanceCounter counter =
              new ConsolePerformanceCounter(routeCamel.getId(), repository);
          ip.setCounter(counter);
          log.debug("Adding a counter" + counter.toString() + " to " + routeCamel.getId());
        }
      }

      // saving route in database
      log.debug("Route added " + routeCamel.getId());
      com.ninja_squad.console.Route route = repository.findRoute(routeCamel.getId());
      if (route == null) {
        route =
            new com.ninja_squad.console.Route(routeCamel.getId())
                .state(State.Started)
                .uri(routeCamel.getEndpoint().getEndpointUri());
        ObjectMapper mapper = new ObjectMapper();
        AnnotationIntrospector introspector =
            new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
        // make serializer use JAXB annotations (only)
        mapper.setAnnotationIntrospector(introspector);
        String definition = null;
        RouteDefinition routeDefinition = routeCamel.getRouteContext().getRoute();
        try {
          definition = mapper.writeValueAsString(routeDefinition);
        } catch (IOException e) {
          log.error("Error while marshalling route definition", e);
        }
        route.setDefinition(definition);
        for (ProcessorDefinition<?> stepDefinition : routeDefinition.getOutputs()) {
          if (stepDefinition.getId() == null) {
            stepDefinition.setId(stepDefinition.getClass().getSimpleName());
          }
          route.getSteps().put(stepDefinition.getId(), stepDefinition.getLabel());
        }
        repository.save(route);
      }

      // saving state in database
      RouteState routeState = repository.lastRouteState(routeCamel.getId());
      if (routeState == null || routeState.getState().equals(State.Stopped)) {
        routeState = new RouteState();
        routeState.setRouteId(routeCamel.getId());
        routeState.setState(State.Started);
        routeState.setTimestamp(DateTime.now().getMillis());
        repository.save(routeState);
      }
    }
  }
Пример #5
0
  private boolean isMyRoute(String routeId) {

    boolean status = false;

    if (this.routeCollection != null) {
      for (RouteDefinition routeDef : this.routeCollection) {
        if (routeDef.getId().equals(routeId)) {
          return true;
        }
      }
    }

    return status;
  }
  /**
   * Removes the wrapped processors for the given routes, as they are no longer in use.
   *
   * <p>This is needed to avoid accumulating memory, if a lot of routes is being added and removed.
   *
   * @param routes the routes
   */
  private void removeWrappedProcessorsForRoutes(Collection<Route> routes) {
    // loop the routes, and remove the route associated wrapped processors, as they are no longer in
    // use
    for (Route route : routes) {
      String id = route.getId();

      Iterator<KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor>> it =
          wrappedProcessors.values().iterator();
      while (it.hasNext()) {
        KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor> holder = it.next();
        RouteDefinition def = ProcessorDefinitionHelper.getRoute(holder.getKey());
        if (def != null && id.equals(def.getId())) {
          it.remove();
        }
      }
    }
  }
 public void testAdviceWithErrorHandler() throws Exception {
   RouteDefinition route = context.getRouteDefinitions().get(0);
   try {
     route.adviceWith(
         context,
         new AdviceWithRouteBuilder() {
           @Override
           public void configure() throws Exception {
             errorHandler(deadLetterChannel("mock:dead"));
           }
         });
     fail("Should have thrown exception");
   } catch (IllegalArgumentException e) {
     assertEquals(
         "You can not advice with error handlers. Remove the error handlers from the route builder.",
         e.getMessage());
   }
 }
  public void testAdviceWithOnCompletion() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(
        context,
        new AdviceWithRouteBuilder() {
          @Override
          public void configure() throws Exception {
            onCompletion().to("mock:done");
          }
        });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:done").expectedBodiesReceived("Hello World");

    template.sendBody("direct:start", "World");

    assertMockEndpointsSatisfied();
  }
  public void testAdviceWithOnException() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(
        context,
        new AdviceWithRouteBuilder() {
          @Override
          public void configure() throws Exception {
            onException(IllegalArgumentException.class).handled(true).to("mock:error");
          }
        });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:error").expectedBodiesReceived("Kaboom");

    template.sendBody("direct:start", "World");
    template.sendBody("direct:start", "Kaboom");

    assertMockEndpointsSatisfied();
  }
 private ToDefinition getDroolsNode(RouteDefinition routeDef) {
   ToDefinition toDrools = null;
   for (ProcessorDefinition<?> child : routeDef.getOutputs()) {
     toDrools = getDroolsNode(child);
     if (toDrools != null) {
       break;
     }
   }
   return toDrools;
 }
Пример #11
0
 public RouteService(
     DefaultCamelContext camelContext,
     RouteDefinition routeDefinition,
     List<RouteContext> routeContexts,
     List<Route> routes) {
   this.camelContext = camelContext;
   this.routeDefinition = routeDefinition;
   this.routeContexts = routeContexts;
   this.routes = routes;
   this.id = routeDefinition.idOrCreate(camelContext.getNodeIdFactory());
 }
  public void testAdviceWithInterceptFrom() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(
        context,
        new AdviceWithRouteBuilder() {
          @Override
          public void configure() throws Exception {
            interceptFrom().to("mock:from");
          }
        });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:from").expectedBodiesReceived("World");
    getMockEndpoint("mock:from")
        .expectedHeaderReceived(Exchange.INTERCEPTED_ENDPOINT, "direct://start");

    template.sendBody("direct:start", "World");

    assertMockEndpointsSatisfied();
  }
  public void testIssue() throws Exception {
    final Predicate fail =
        PredicateBuilder.or(
            header(Exchange.REDELIVERY_COUNTER).isNull(),
            header(Exchange.REDELIVERY_COUNTER).isLessThan(5));

    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(
        context,
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            interceptSendToEndpoint("seda:*")
                .skipSendToOriginalEndpoint()
                .process(
                    new Processor() {
                      public void process(Exchange exchange) throws Exception {
                        invoked.incrementAndGet();

                        if (fail.matches(exchange)) {
                          throw new ConnectException("Forced");
                        }
                      }
                    })
                .to("mock:ok");
          }
        });

    getMockEndpoint("mock:global").expectedMessageCount(0);
    getMockEndpoint("mock:ok").expectedMessageCount(1);
    getMockEndpoint("mock:exhausted").expectedMessageCount(0);

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();

    // 5 retry + 1 ok
    assertEquals(6, invoked.get());
  }
Пример #14
0
  public void updateRouteFromXml(String xml) throws Exception {
    // convert to model from xml
    RouteDefinition def = ModelHelper.createModelFromXml(xml, RouteDefinition.class);
    if (def == null) {
      return;
    }

    // if the xml does not contain the route-id then we fix this by adding the actual route id
    // this may be needed if the route-id was auto-generated, as the intend is to update this route
    // and not add a new route, adding a new route, use the MBean operation on ManagedCamelContext
    // instead.
    if (ObjectHelper.isEmpty(def.getId())) {
      def.setId(getRouteId());
    } else if (!def.getId().equals(getRouteId())) {
      throw new IllegalArgumentException(
          "Cannot update route from XML as routeIds does not match. routeId: "
              + getRouteId()
              + ", routeId from XML: "
              + def.getId());
    }

    // add will remove existing route first
    context.addRouteDefinition(def);
  }
Пример #15
0
 private void startRoute(RouteDefinition routeDef) {
   String routeId = routeDef.getId();
   try {
     if (isMyRoute(routeId)) {
       ServiceStatus routeStatus = camelContext.getRouteStatus(routeId);
       // Only start the route if it is not already started
       if (routeStatus == null || !routeStatus.isStarted()) {
         LOGGER.trace("Starting route with ID = " + routeId);
         camelContext.startRoute(routeDef); // DEPRECATED
         // this method does not reliably start a route that was created, then
         // app shutdown, and restarted
         //                camelContext.startRoute(routeId);
       }
     }
   } catch (Exception e) {
     LOGGER.warn("Unable to start Camel route with route ID = " + routeId, e);
   }
 }
Пример #16
0
 /** Gather the route scoped error handler from the given route */
 private void doGetRouteScopedErrorHandler(Set<Service> services, Route route) {
   // only include error handlers if they are route scoped
   boolean includeErrorHandler =
       !routeDefinition.isContextScopedErrorHandler(route.getRouteContext().getCamelContext());
   List<Service> extra = new ArrayList<Service>();
   if (includeErrorHandler) {
     for (Service service : services) {
       if (service instanceof Channel) {
         Processor eh = ((Channel) service).getErrorHandler();
         if (eh != null && eh instanceof Service) {
           extra.add((Service) eh);
         }
       }
     }
   }
   if (!extra.isEmpty()) {
     services.addAll(extra);
   }
 }
Пример #17
0
  private void removeRoutes() {
    LOGGER.trace("ENTERING: stopRoutes");
    List<RouteDefinition> routeDefinitions = camelContext.getRouteDefinitions();
    for (RouteDefinition routeDef : routeDefinitions) {
      try {
        // Only remove routes that this Content Directory Monitor created
        // (since same camelContext shared across all ContentDirectoryMonitors
        // this is necessary)
        if (isMyRoute(routeDef.getId())) {
          LOGGER.trace("Stopping route with ID = " + routeDef.getId());
          camelContext.stopRoute(routeDef); // DEPRECATED
          //                    camelContext.stopRoute(routeDef.getId());
          boolean status = camelContext.removeRoute(routeDef.getId());
          LOGGER.trace("Status of removing route " + routeDef.getId() + " is " + status);
          camelContext.removeRouteDefinition(routeDef);
        }
      } catch (Exception e) {
        LOGGER.warn("Unable to stop Camel route with route ID = " + routeDef.getId(), e);
      }
    }

    LOGGER.trace("EXITING: stopRoutes");
  }
Пример #18
0
  public void commit() {
    // now lets turn all of the event driven consumer processors into a single route
    if (!eventDrivenProcessors.isEmpty()) {
      Processor target = Pipeline.newInstance(getCamelContext(), eventDrivenProcessors);

      String routeId = route.idOrCreate(getCamelContext().getNodeIdFactory());

      // and wrap it in a unit of work so the UoW is on the top, so the entire route will be in the
      // same UoW
      CamelInternalProcessor internal = new CamelInternalProcessor(target);
      internal.addAdvice(new CamelInternalProcessor.UnitOfWorkProcessorAdvice(routeId));

      // and then in route context so we can keep track which route this is at runtime
      internal.addAdvice(new CamelInternalProcessor.RouteContextAdvice(this));

      // and then optionally add route policy processor if a custom policy is set
      List<RoutePolicy> routePolicyList = getRoutePolicyList();
      if (routePolicyList != null && !routePolicyList.isEmpty()) {
        for (RoutePolicy policy : routePolicyList) {
          // add policy as service if we have not already done that (eg possible if two routes have
          // the same service)
          // this ensures Camel can control the lifecycle of the policy
          if (!camelContext.hasService(policy)) {
            try {
              camelContext.addService(policy);
            } catch (Exception e) {
              throw ObjectHelper.wrapRuntimeCamelException(e);
            }
          }
        }

        internal.addAdvice(new CamelInternalProcessor.RoutePolicyAdvice(routePolicyList));
      }

      // wrap in route inflight processor to track number of inflight exchanges for the route
      internal.addAdvice(
          new CamelInternalProcessor.RouteInflightRepositoryAdvice(
              camelContext.getInflightRepository(), routeId));

      // wrap in JMX instrumentation processor that is used for performance stats
      internal.addAdvice(new CamelInternalProcessor.InstrumentationAdvice("route"));

      // wrap in route lifecycle
      internal.addAdvice(new CamelInternalProcessor.RouteLifecycleAdvice());

      // and create the route that wraps the UoW
      Route edcr = new EventDrivenConsumerRoute(this, getEndpoint(), internal);
      edcr.getProperties().put(Route.ID_PROPERTY, routeId);
      edcr.getProperties().put(Route.PARENT_PROPERTY, Integer.toHexString(route.hashCode()));
      edcr.getProperties().put(Route.DESCRIPTION_PROPERTY, route.getDescriptionText());
      if (route.getGroup() != null) {
        edcr.getProperties().put(Route.GROUP_PROPERTY, route.getGroup());
      }
      String rest = "false";
      if (route.isRest() != null && route.isRest()) {
        rest = "true";
      }
      edcr.getProperties().put(Route.REST_PROPERTY, rest);

      // after the route is created then set the route on the policy processor so we get hold of it
      CamelInternalProcessor.RoutePolicyAdvice task =
          internal.getAdvice(CamelInternalProcessor.RoutePolicyAdvice.class);
      if (task != null) {
        task.setRoute(edcr);
      }
      CamelInternalProcessor.RouteLifecycleAdvice task2 =
          internal.getAdvice(CamelInternalProcessor.RouteLifecycleAdvice.class);
      if (task2 != null) {
        task2.setRoute(edcr);
      }

      // invoke init on route policy
      if (routePolicyList != null && !routePolicyList.isEmpty()) {
        for (RoutePolicy policy : routePolicyList) {
          policy.onInit(edcr);
        }
      }

      routes.add(edcr);
    }
  }
Пример #19
0
 public Endpoint resolveEndpoint(String uri) {
   return route.resolveEndpoint(getCamelContext(), uri);
 }
 public ProcessorDefinition<?> apply(RouteDefinition rd) {
   return rd.onException(Exception.class)
       .handled(true)
       .transform(Builder.exceptionMessage())
       .end();
 }
Пример #21
0
    public void process(ComponentDefinitionRegistry componentDefinitionRegistry) {
      CamelContextFactoryBean ccfb =
          (CamelContextFactoryBean)
              blueprintContainer.getComponentInstance(
                  ".camelBlueprint.factory." + camelContextName);
      CamelContext camelContext = ccfb.getContext();

      Set<String> components = new HashSet<String>();
      Set<String> languages = new HashSet<String>();
      Set<String> dataformats = new HashSet<String>();
      Set<String> dependsOn = new HashSet<String>();
      for (RouteDefinition rd : camelContext.getRouteDefinitions()) {
        findInputComponents(rd.getInputs(), components, languages, dataformats);
        findOutputComponents(rd.getOutputs(), components, languages, dataformats);
      }
      try {
        for (String component : components) {
          ComponentMetadata cm =
              componentDefinitionRegistry.getComponentDefinition(
                  ".camelBlueprint.componentResolver." + component);
          if (cm == null) {
            MutableReferenceMetadata svc = createMetadata(MutableReferenceMetadata.class);
            svc.setId(".camelBlueprint.componentResolver." + component);
            svc.setFilter("(component=" + component + ")");
            svc.setAvailability(
                componentDefinitionRegistry.containsComponentDefinition(component)
                    ? AVAILABILITY_OPTIONAL
                    : AVAILABILITY_MANDATORY);
            try {
              // Try to set the runtime interface (only with aries blueprint > 0.1
              svc.getClass()
                  .getMethod("setRuntimeInterface", Class.class)
                  .invoke(svc, ComponentResolver.class);
            } catch (Throwable t) {
              // Check if the bundle can see the class
              try {
                PassThroughMetadata ptm =
                    (PassThroughMetadata)
                        componentDefinitionRegistry.getComponentDefinition("blueprintBundle");
                Bundle b = (Bundle) ptm.getObject();
                if (b.loadClass(ComponentResolver.class.getName()) != ComponentResolver.class) {
                  throw new UnsupportedOperationException();
                }
                svc.setInterface(ComponentResolver.class.getName());
              } catch (Throwable t2) {
                throw new UnsupportedOperationException();
              }
            }
            componentDefinitionRegistry.registerComponentDefinition(svc);
            dependsOn.add(svc.getId());
          }
        }
        for (String language : languages) {
          ComponentMetadata cm =
              componentDefinitionRegistry.getComponentDefinition(
                  ".camelBlueprint.languageResolver." + language);
          if (cm == null) {
            MutableReferenceMetadata svc = createMetadata(MutableReferenceMetadata.class);
            svc.setId(".camelBlueprint.languageResolver." + language);
            svc.setFilter("(language=" + language + ")");
            svc.setAvailability(
                componentDefinitionRegistry.containsComponentDefinition(language)
                    ? AVAILABILITY_OPTIONAL
                    : AVAILABILITY_MANDATORY);
            try {
              // Try to set the runtime interface (only with aries blueprint > 0.1
              svc.getClass()
                  .getMethod("setRuntimeInterface", Class.class)
                  .invoke(svc, LanguageResolver.class);
            } catch (Throwable t) {
              // Check if the bundle can see the class
              try {
                PassThroughMetadata ptm =
                    (PassThroughMetadata)
                        componentDefinitionRegistry.getComponentDefinition("blueprintBundle");
                Bundle b = (Bundle) ptm.getObject();
                if (b.loadClass(LanguageResolver.class.getName()) != LanguageResolver.class) {
                  throw new UnsupportedOperationException();
                }
                svc.setInterface(LanguageResolver.class.getName());
              } catch (Throwable t2) {
                throw new UnsupportedOperationException();
              }
            }
            componentDefinitionRegistry.registerComponentDefinition(svc);
            dependsOn.add(svc.getId());
          }
        }
        for (String dataformat : dataformats) {
          ComponentMetadata cm =
              componentDefinitionRegistry.getComponentDefinition(
                  ".camelBlueprint.dataformatResolver." + dataformat);
          if (cm == null) {
            MutableReferenceMetadata svc = createMetadata(MutableReferenceMetadata.class);
            svc.setId(".camelBlueprint.dataformatResolver." + dataformat);
            svc.setFilter("(dataformat=" + dataformat + ")");
            svc.setAvailability(
                componentDefinitionRegistry.containsComponentDefinition(dataformat)
                    ? AVAILABILITY_OPTIONAL
                    : AVAILABILITY_MANDATORY);
            try {
              // Try to set the runtime interface (only with aries blueprint > 0.1
              svc.getClass()
                  .getMethod("setRuntimeInterface", Class.class)
                  .invoke(svc, DataFormatResolver.class);
            } catch (Throwable t) {
              // Check if the bundle can see the class
              try {
                PassThroughMetadata ptm =
                    (PassThroughMetadata)
                        componentDefinitionRegistry.getComponentDefinition("blueprintBundle");
                Bundle b = (Bundle) ptm.getObject();
                if (b.loadClass(DataFormatResolver.class.getName()) != DataFormatResolver.class) {
                  throw new UnsupportedOperationException();
                }
                svc.setInterface(DataFormatResolver.class.getName());
              } catch (Throwable t2) {
                throw new UnsupportedOperationException();
              }
            }
            componentDefinitionRegistry.registerComponentDefinition(svc);
            dependsOn.add(svc.getId());
          }
        }
      } catch (UnsupportedOperationException e) {
        LOG.warn(
            "Unable to add dependencies on to camel components OSGi services.  "
                + "The Apache Aries blueprint implementation used it too old and the blueprint bundle can not see the org.apache.camel.spi package.");
        components.clear();
        languages.clear();
        dataformats.clear();
      }
    }