Пример #1
0
  @Test
  public void testNotTooOldFilter() throws Exception {
    fakeFtpServer.start();
    int port = fakeFtpServer.getServerControlPort();
    context
        .getRouteDefinitions()
        .get(0)
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                replaceFromWith(
                    "ftp://[email protected]:"
                        + port
                        + "?password=password&filter=#notTooOld&passiveMode=true");
                weaveByType(ToDefinition.class).selectFirst().replace().to("mock:end");
              }
            });
    MockEndpoint end = context.getEndpoint("mock:end", MockEndpoint.class);
    end.expectedMessageCount(1);

    end.assertIsSatisfied();

    // Make sure that the received file has the correct file name
    String fileName =
        (String) end.getReceivedExchanges().get(0).getIn().getHeader(Exchange.FILE_NAME_ONLY);
    assertEquals(fileName, "DMI1.nc");

    fakeFtpServer.stop();
  }
Пример #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");
 }
Пример #3
0
 public void start() throws Exception {
   if (context.isSuspended()) {
     context.resume();
   } else {
     context.start();
   }
 }
Пример #4
0
  @Test
  public void testFilePollerB() throws Exception {
    String expected = "xxx";
    final MockEndpoint mockEndpoint = getMockEndpoint("mock:" + routeATo);
    cc.getRouteDefinitions()
        .get(0)
        .adviceWith(
            cc,
            new RouteBuilder() {
              @Override
              public void configure() throws Exception {
                // intercept sending to mock:foo and do something else
                interceptSendToEndpoint(routeATo).to(mockEndpoint);
              }
            });

    mockEndpoint.expectedBodiesReceived(expected);

    Endpoint ep = cc.getEndpoint(routeAFrom);
    Assert.assertNotNull(ep);
    ProducerTemplate pt = cc.createProducerTemplate();
    pt.start();
    pt.sendBody(ep, expected);

    assertMockEndpointsSatisfied();
  }
Пример #5
0
 public String getApplicationContextClassName() {
   if (context.getApplicationContextClassLoader() != null) {
     return context.getApplicationContextClassLoader().toString();
   } else {
     return null;
   }
 }
Пример #6
0
 public void resume() throws Exception {
   if (context.isSuspended()) {
     context.resume();
   } else {
     throw new IllegalStateException("CamelContext is not suspended");
   }
 }
Пример #7
0
  @Before
  public void setUp() throws Exception {

    // We replace the 'from' web service endpoint with a direct endpoint we call in our test
    context
        .getRouteDefinition("CriminalHistoryUpdateReportingServiceHandlerRoute")
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                // The line below allows us to bypass CXF and send a message directly into the route
                replaceFromWith("direct:criminalHistoryUpdatedReportingService");
                mockEndpoints("log:org.ojbc.intermediaries.crimhistoryupdate*");
              }
            });

    // We mock the web service endpoints here
    context
        .getRouteDefinition("callNotificationBrokerRoute")
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {

                // We mock the notification broker endpoint
                mockEndpointsAndSkip("cxf:bean:notificationBrokerService*");
              }
            });

    context.start();
  }
Пример #8
0
 public String getManagementStatisticsLevel() {
   if (context.getManagementStrategy().getManagementAgent() != null) {
     return context.getManagementStrategy().getManagementAgent().getStatisticsLevel().name();
   } else {
     return null;
   }
 }
Пример #9
0
 public void shutdown(long timeout) throws Exception {
   if (!context.getStatus().isStarted()) {
     throw new IllegalArgumentException("CamelContext is not started");
   }
   String routeId = getRouteId();
   context.stopRoute(routeId, timeout, TimeUnit.SECONDS);
   context.removeRoute(routeId);
 }
Пример #10
0
 public Integer getStartedRoutes() {
   int started = 0;
   for (Route route : context.getRoutes()) {
     if (context.getRouteStatus(route.getId()).isStarted()) {
       started++;
     }
   }
   return started;
 }
Пример #11
0
 @Override
 public void init(ManagementStrategy strategy) {
   super.init(strategy);
   boolean enabled =
       context.getManagementStrategy().getManagementAgent() != null
           && context.getManagementStrategy().getManagementAgent().getStatisticsLevel()
               != ManagementStatisticsLevel.Off;
   setStatisticsEnabled(enabled);
 }
Пример #12
0
 /**
  * Used for aggregate dot generation, generate a single camel context containing all of the
  * available contexts.
  */
 private CamelContext aggregateCamelContext() throws Exception {
   if (camelContexts.size() == 1) {
     return camelContexts.get(0);
   } else {
     ModelCamelContext answer = new DefaultCamelContext();
     for (CamelContext camelContext : camelContexts) {
       answer.addRouteDefinitions(((ModelCamelContext) camelContext).getRouteDefinitions());
     }
     return answer;
   }
 }
  @Test
  public void shouldDLQOrginalHandler() throws Exception {

    ModelCamelContext context = new DefaultCamelContext();
    context.setTracing(true);
    ProducerTemplate pt = context.createProducerTemplate();
    context.addRoutes(
        new RouteBuilder() {

          @Override
          public void configure() throws Exception {
            // will use original
            ErrorHandlerBuilder a =
                deadLetterChannel("seda:dead")
                    .maximumRedeliveries(1)
                    .redeliveryDelay(300)
                    .logStackTrace(false)
                    .useOriginalMessage()
                    .logHandled(false);

            from("seda:start")
                .errorHandler(a)
                .log(LoggingLevel.INFO, "myCamel", "==== ${body}")
                .bean(SampleErrorBean.class)
                .bean(ChangeBody.class)
                .bean(ErrorBean.class)
                .bean(SampleErrorBean.class)
                .transform(constant("ok"));
            from("seda:dead")
                .bean(FailureBean.class)
                .process(
                    exchange -> {
                      counterA.incrementAndGet();
                      Throwable e =
                          exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
                      log.info("+++  properties :  {}", exchange.getProperties());
                      log.info("+++  body :  {}", exchange.getIn().getBody());
                      log.info("+++  headers  :  {}", exchange.getIn().getHeaders());
                      log.info("+++  exception Processor : {}", e);
                      log.info(
                          "+++ counterA :  {} , header : {}",
                          counterA.get(),
                          exchange.getProperty("CamelExceptionCaught"));
                    })
                .convertBodyTo(String.class)
                .bean(SampleErrorBean.class);
          }
        });
    context.start();
    String result = (String) pt.requestBody("seda:start", "test");
    Assertions.assertThat(result).isEqualTo("test");
    Thread.sleep(3000);
  }
Пример #14
0
 public String componentParameterJsonSchema(String componentName) throws Exception {
   // favor using pre generated schema if component has that
   String json = context.getComponentParameterJsonSchema(componentName);
   if (json == null) {
     // okay this requires having the component on the classpath and being instantiated
     Component component = context.getComponent(componentName);
     if (component != null) {
       ComponentConfiguration configuration = component.createComponentConfiguration();
       json = configuration.createParameterJsonSchema();
     }
   }
   return json;
 }
Пример #15
0
  @Test
  public void testIdempotent() throws Exception {
    String uri = "file:target/test-classes/idempotent?idempotent=true&delay=10";
    context
        .getRouteDefinitions()
        .get(1)
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                replaceFromWith(uri);
                weaveByType(ToDefinition.class).selectFirst().replace().to("mock:endpoint");
              }
            });
    MockEndpoint end = context.getEndpoint("mock:endpoint", MockEndpoint.class);
    end.expectedMessageCount(1);

    producer.sendBodyAndHeader(
        "file://target/test-classes/idempotent", Exchange.FILE_NAME, "FCOO1.nc");

    end.assertIsSatisfied();

    String fileName =
        (String) end.getReceivedExchanges().get(0).getIn().getHeader(Exchange.FILE_NAME_ONLY);
    assertEquals(fileName, "FCOO1.nc");

    // reset the mock
    end.reset();
    end.expectedMessageCount(0);

    // move file back
    File file = new File("target/test-classes/idempotent/.camel/FCOO1.nc");
    File renamed = new File("target/test-classes/idempotent/FCOO1.nc");
    file.renameTo(renamed);

    producer.sendBodyAndHeader(
        "file://target/test-classes/idempotent", Exchange.FILE_NAME, "FCOO1.nc");

    // let some time pass to let the consumer try to consume even though it cannot
    Thread.sleep(100);
    end.assertIsSatisfied();

    FileEndpoint fe = context.getEndpoint(uri, FileEndpoint.class);
    assertNotNull(fe);

    // Make sure that there are no incoming messages
    MemoryIdempotentRepository repo = (MemoryIdempotentRepository) fe.getInProgressRepository();
    assertEquals("Should be no in-progress files", 0, repo.getCacheSize());
  }
Пример #16
0
  public TabularData listEips() throws Exception {
    try {
      // find all EIPs
      Map<String, Properties> eips = context.findEips();

      TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listEipsTabularType());

      // gather EIP detail for each eip
      for (Map.Entry<String, Properties> entry : eips.entrySet()) {
        String name = entry.getKey();
        String title = (String) entry.getValue().get("title");
        String description = (String) entry.getValue().get("description");
        String label = (String) entry.getValue().get("label");
        String type = (String) entry.getValue().get("class");
        String status = CamelContextHelper.isEipInUse(context, name) ? "in use" : "on classpath";
        CompositeType ct = CamelOpenMBeanTypes.listEipsCompositeType();
        CompositeData data =
            new CompositeDataSupport(
                ct,
                new String[] {"name", "title", "description", "label", "status", "type"},
                new Object[] {name, title, description, label, status, type});
        answer.put(data);
      }
      return answer;
    } catch (Exception e) {
      throw ObjectHelper.wrapRuntimeCamelException(e);
    }
  }
Пример #17
0
 public void sendBody(String endpointUri, Object body) throws Exception {
   ProducerTemplate template = context.createProducerTemplate();
   try {
     template.sendBody(endpointUri, body);
   } finally {
     template.stop();
   }
 }
Пример #18
0
 public ManagedRoute(ModelCamelContext context, Route route) {
   this.route = route;
   this.context = context;
   this.description = route.toString();
   boolean enabled =
       context.getManagementStrategy().getStatisticsLevel() != ManagementStatisticsLevel.Off;
   setStatisticsEnabled(enabled);
 }
Пример #19
0
 public String dumpRouteAsXml() throws Exception {
   String id = route.getId();
   RouteDefinition def = context.getRouteDefinition(id);
   if (def != null) {
     return ModelHelper.dumpModelAsXml(def);
   }
   return null;
 }
Пример #20
0
 private void startRoutes() {
   LOGGER.trace("ENTERING: startRoutes");
   List<RouteDefinition> routeDefinitions = camelContext.getRouteDefinitions();
   for (RouteDefinition routeDef : routeDefinitions) {
     startRoute(routeDef);
   }
   LOGGER.trace("EXITING: startRoutes");
 }
Пример #21
0
 public void sendBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers)
     throws Exception {
   ProducerTemplate template = context.createProducerTemplate();
   try {
     template.sendBodyAndHeaders(endpointUri, body, headers);
   } finally {
     template.stop();
   }
 }
Пример #22
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);
   }
 }
Пример #23
0
 public String getState() {
   // must use String type to be sure remote JMX can read the attribute without requiring Camel
   // classes.
   ServiceStatus status = context.getRouteStatus(route.getId());
   // if no status exists then its stopped
   if (status == null) {
     status = ServiceStatus.Stopped;
   }
   return status.name();
 }
Пример #24
0
 public Object requestBody(String endpointUri, Object body) throws Exception {
   ProducerTemplate template = context.createProducerTemplate();
   Object answer = null;
   try {
     answer = template.requestBody(endpointUri, body);
   } finally {
     template.stop();
   }
   return answer;
 }
Пример #25
0
  public String dumpRoutesAsXml() throws Exception {
    List<RouteDefinition> routes = context.getRouteDefinitions();
    if (routes.isEmpty()) {
      return null;
    }

    // use a routes definition to dump the routes
    RoutesDefinition def = new RoutesDefinition();
    def.setRoutes(routes);
    return ModelHelper.dumpModelAsXml(context, def);
  }
Пример #26
0
  public boolean createEndpoint(String uri) throws Exception {
    if (context.hasEndpoint(uri) != null) {
      // endpoint already exists
      return false;
    }

    Endpoint endpoint = context.getEndpoint(uri);
    if (endpoint != null) {
      // ensure endpoint is registered, as the management strategy could have been configured to not
      // always
      // register new endpoints in JMX, so we need to check if its registered, and if not register
      // it manually
      ObjectName on =
          context
              .getManagementStrategy()
              .getManagementNamingStrategy()
              .getObjectNameForEndpoint(endpoint);
      if (on != null && !context.getManagementStrategy().getManagementAgent().isRegistered(on)) {
        // register endpoint as mbean
        Object me =
            context
                .getManagementStrategy()
                .getManagementObjectStrategy()
                .getManagedObjectForEndpoint(context, endpoint);
        context.getManagementStrategy().getManagementAgent().register(me, on);
      }
      return true;
    } else {
      return false;
    }
  }
Пример #27
0
  public boolean canSendToEndpoint(String endpointUri) {
    try {
      Endpoint endpoint = context.getEndpoint(endpointUri);
      if (endpoint != null) {
        Producer producer = endpoint.createProducer();
        return producer != null;
      }
    } catch (Exception e) {
      // ignore
    }

    return false;
  }
Пример #28
0
 public Map<String, Properties> findComponents() throws Exception {
   Map<String, Properties> answer = context.findComponents();
   for (Map.Entry<String, Properties> entry : answer.entrySet()) {
     if (entry.getValue() != null) {
       // remove component as its not serializable over JMX
       entry.getValue().remove("component");
       // .. and components which just list all the components in the JAR/bundle and that is
       // verbose and not needed
       entry.getValue().remove("components");
     }
   }
   return answer;
 }
Пример #29
0
  @Before
  public void setUpMocking() throws Exception {
    ModelCamelContext modelCamelContext = (ModelCamelContext) camelContext;

    modelCamelContext
        .getRouteDefinition("mainRoute")
        .adviceWith(
            modelCamelContext,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                mockEndpoints();
              }
            });

    modelCamelContext
        .getRouteDefinition("standardXMLRoute")
        .adviceWith(
            modelCamelContext,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                mockEndpoints();
              }
            });

    modelCamelContext
        .getRouteDefinition("t5XMLRoute")
        .adviceWith(
            modelCamelContext,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                mockEndpoints();
              }
            });
    camelContext.start();
  }
Пример #30
0
  public void addOrUpdateRoutesFromXml(String xml, boolean urlDecode) throws Exception {
    // decode String as it may have been encoded, from its xml source
    if (urlDecode) {
      xml = URLDecoder.decode(xml, "UTF-8");
    }

    InputStream is = context.getTypeConverter().mandatoryConvertTo(InputStream.class, xml);
    RoutesDefinition def = context.loadRoutesDefinition(is);
    if (def == null) {
      return;
    }

    try {
      // add will remove existing route first
      context.addRouteDefinitions(def.getRoutes());
    } catch (Exception e) {
      // log the error as warn as the management api may be invoked remotely over JMX which does not
      // propagate such exception
      String msg = "Error updating routes from xml: " + xml + " due: " + e.getMessage();
      LOG.warn(msg, e);
      throw e;
    }
  }