@Override
 protected void tearDown() throws Exception {
   if (camel1 != null) {
     camel1.stop();
   }
   if (camel2 != null) {
     camel2.stop();
   }
   super.tearDown();
 }
  @Test
  public void testOgnlExpressionFromFile() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start")
                .choice()
                .when()
                .ognl("resource:classpath:test-ognl-expression.txt")
                .transform(simple("Hello ${body.name}"))
                .otherwise()
                .to("mock:dlq");
          }
        });

    Person person = new Person();
    person.setName("Kermit");

    camelctx.start();
    try {
      ProducerTemplate producer = camelctx.createProducerTemplate();
      String result = producer.requestBody("direct:start", person, String.class);
      Assert.assertEquals("Hello Kermit", result);
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void testSQLEndpoint() throws Exception {
    Assert.assertNotNull("DataSource not null", dataSource);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("sql:select name from information_schema.users?dataSource=java:jboss/datasources/ExampleDS")
                .to("direct:end");
          }
        });

    camelctx.start();
    try {
      PollingConsumer pollingConsumer = camelctx.getEndpoint("direct:end").createPollingConsumer();
      pollingConsumer.start();

      String result = (String) pollingConsumer.receive().getIn().getBody(Map.class).get("NAME");
      Assert.assertEquals("SA", result);
    } finally {
      camelctx.stop();
    }
  }
  public void testMultipleLifecycleStrategies() throws Exception {
    CamelContext context = createCamelContext();
    context.start();

    Component log = new LogComponent();
    context.addComponent("log", log);
    context.addEndpoint("log:/foo", log.createEndpoint("log://foo"));
    context.removeComponent("log");
    context.stop();

    List<String> expectedEvents =
        Arrays.asList(
            "onContextStart",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onServiceAdd",
            "onComponentAdd",
            "onEndpointAdd",
            "onComponentRemove",
            "onContextStop");

    assertEquals(expectedEvents, dummy1.getEvents());
    assertEquals(expectedEvents, dummy2.getEvents());
  }
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    CamelContext context = new DefaultCamelContext();

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm:/localhost");
    context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    context.addRoutes(
        new RouteBuilder() {
          public void configure() {
            from("ftp://127.0.0.1/orders?username=johnny&password=quest")
                .process(
                    new Processor() {
                      public void process(Exchange exchange) throws Exception {
                        System.out.println(
                            "\nWe just downloaded: " + exchange.getIn().getHeader("CamelFileName"));
                        System.out.println("Body:");
                        System.out.println(exchange.getIn().getBody());
                        System.out.println("\n==================\n");
                      }
                    })
                .to("jms:incomingOrders");
          }
        });

    context.start();
    Thread.sleep(60000);
    context.stop();
  }
  @Test
  public void testUnmarshalJackson() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start").unmarshal().json(JsonLibrary.Jackson, Customer.class);
          }
        });

    String input = "{'firstName':'John','lastName':'Doe'}";

    camelctx.start();
    try {
      ProducerTemplate producer = camelctx.createProducerTemplate();
      Customer customer =
          producer.requestBody("direct:start", input.replace('\'', '"'), Customer.class);
      Assert.assertEquals("John", customer.getFirstName());
      Assert.assertEquals("Doe", customer.getLastName());
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void testRoleBasedAccess() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start")
                .policy(new DomainAuthorizationPolicy().roles("Role2"))
                .transform(body().prepend("Hello "));
          }
        });

    camelctx.start();
    try {
      ProducerTemplate producer = camelctx.createProducerTemplate();
      Subject subject =
          getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, AnnotatedSLSB.PASSWORD);
      String result =
          producer.requestBodyAndHeader(
              "direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
      Assert.assertEquals("Hello Kermit", result);
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void testSqlIdempotentConsumer() throws Exception {
    Assert.assertNotNull("DataSource not null", dataSource);

    final JdbcMessageIdRepository jdbcMessageIdRepository =
        new JdbcMessageIdRepository(dataSource, "myProcessorName");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start")
                .idempotentConsumer(simple("${header.messageId}"), jdbcMessageIdRepository)
                .to("mock:result");
          }
        });

    camelctx.start();
    try {
      MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
      mockEndpoint.expectedMessageCount(1);

      // Send 5 messages with the same messageId header. Only 1 should be forwarded to the
      // mock:result endpoint
      ProducerTemplate template = camelctx.createProducerTemplate();
      for (int i = 0; i < 5; i++) {
        template.requestBodyAndHeader("direct:start", null, "messageId", "12345");
      }

      mockEndpoint.assertIsSatisfied();
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void writesResultToSender_ConfiguredViaXML() throws Exception {
    String receiver = "*****@*****.**";
    createMailUser(receiver, "loginIdReceiver", "secretOfReceiver");

    String validSender = "*****@*****.**";
    createMailUser(validSender, "loginIdSender", "secretOfSender");
    String commandName = "nameMe";
    sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText(commandName);

    InputStream is = getClass().getResourceAsStream("/ardulinkmail.xml");
    try {
      CamelContext context = new DefaultCamelContext();
      loadRoutesDefinition(is, context, commandName);
      context.start();

      try {
        assertThat(
            ((String) fetchMail("loginIdSender", "secretOfSender").getContent()),
            is(
                "SwitchDigitalPinCommand [pin=1, value=true]=OK\r\n"
                    + "SwitchAnalogPinCommand [pin=2, value=123]=OK"));
      } finally {
        context.stop();
      }
    } finally {
      is.close();
    }
  }
  @Test
  public void testEndpointClass() throws Exception {

    final CountDownLatch latch = new CountDownLatch(3);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("quartz2://mytimer?trigger.repeatCount=3&trigger.repeatInterval=100")
                .process(
                    new Processor() {
                      @Override
                      public void process(Exchange exchange) throws Exception {
                        latch.countDown();
                      }
                    })
                .to("mock:result");
          }
        });

    camelctx.start();
    try {
      Assert.assertTrue("Countdown reached zero", latch.await(500, TimeUnit.MILLISECONDS));
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void testInvalidCredentials() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start")
                .policy(new DomainAuthorizationPolicy())
                .transform(body().prepend("Hello "));
          }
        });

    camelctx.start();
    try {
      ProducerTemplate producer = camelctx.createProducerTemplate();
      try {
        Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, "bogus");
        producer.requestBodyAndHeader(
            "direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
        Assert.fail("CamelExecutionException expected");
      } catch (CamelExecutionException e) {
        // expected
      }
    } finally {
      camelctx.stop();
    }
  }
  @Test
  public void testNoAuthenticationHeader() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            from("direct:start")
                .policy(new DomainAuthorizationPolicy())
                .transform(body().prepend("Hello "));
          }
        });

    camelctx.start();
    try {
      ProducerTemplate producer = camelctx.createProducerTemplate();
      try {
        producer.requestBody("direct:start", "Kermit", String.class);
        Assert.fail("CamelExecutionException expected");
      } catch (CamelExecutionException e) {
        // expected
      }
    } finally {
      camelctx.stop();
    }
  }
예제 #13
0
  @After
  public void tearDown() throws Exception {
    template.stop();
    camelContext.stop();

    stopTestServer();
  }
예제 #14
0
 @Override
 public void run() {
   try {
     context.stop();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Test
  public void canProcessMultipleLinksWhenCommandNotKnownOnLink2() throws Exception {
    final String receiver = "*****@*****.**";
    createMailUser(receiver, "loginIdReceiver", "secretOfReceiver");

    String validSender = "*****@*****.**";
    sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText("usedScenario");

    Link link1 = Links.getLink(new URI(mockURI + "?num=1&foo=bar"));
    Link link2 = Links.getLink(new URI(mockURI + "?num=2&foo=bar"));

    final String to1 =
        makeURI(
            mockURI,
            newMapBuilder()
                .put("linkparams", encode("num=1&foo=bar"))
                .put("validfroms", validSender)
                .put("scenario.usedScenario", "D11=true;A12=11")
                .build());
    final String to2 =
        makeURI(
            mockURI,
            newMapBuilder()
                .put("linkparams", encode("num=2&foo=bar"))
                .put("validfroms", validSender)
                .build());

    try {
      CamelContext context = new DefaultCamelContext();
      context.addRoutes(
          new RouteBuilder() {
            @Override
            public void configure() {
              from(localImap(receiver))
                  .multicast()
                  .setAggregationStrategy(new UseOriginalAggregationStrategy())
                  .to(to1, to2);
            }
          });
      context.start();

      waitUntilMailWasFetched();
      context.stop();

      Link mock1 = getMock(link1);
      verify(mock1).switchDigitalPin(digitalPin(11), true);
      verify(mock1).switchAnalogPin(analogPin(12), 11);
      verify(mock1).close();
      verifyNoMoreInteractions(mock1);

      Link mock2 = getMock(link2);
      verify(mock2).close();
      verifyNoMoreInteractions(mock2);
    } finally {
      link1.close();
      link2.close();
    }
  }
 protected void stopCamelContext() throws Exception {
   if (camelContextService != null) {
     camelContextService.stop();
   } else {
     if (context != null) {
       context.stop();
     }
   }
 }
  public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/camel.xml");
    CamelContext camelContext = (CamelContext) context.getBean("camelContext");
    camelContext.start();

    Thread.sleep(3000);
    camelContext.stop();
    context.close();
  }
  @Test
  public void writesResultToSender() throws Exception {
    final String receiver = "*****@*****.**";
    createMailUser(receiver, "loginIdReceiver", "secretOfReceiver");

    String validSender = "*****@*****.**";
    createMailUser(validSender, "loginIdSender", "secretOfSender");
    sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText("usedScenario");

    final String ardulink =
        makeURI(
            mockURI,
            newMapBuilder()
                .put("validfroms", validSender)
                .put("scenario.usedScenario", "D1=true;A2=123")
                .build());

    SmtpServer smtpd = mailMock.getSmtp();
    final String smtp =
        "smtp://"
            + smtpd.getBindTo()
            + ":"
            + smtpd.getPort()
            + "?username="******"loginIdReceiver"
            + "&password="******"secretOfReceiver"
            + "&debugMode=true";

    CamelContext context = new DefaultCamelContext();
    context.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() {
            from(localImap(receiver))
                .to(ardulink)
                .setHeader("to", simple("${in.header.from}"))
                .setHeader("from", simple("${in.header.to}"))
                .to(smtp);
          }
        });
    context.start();

    try {
      assertThat(
          ((String) fetchMail("loginIdSender", "secretOfSender").getContent()),
          is(
              "SwitchDigitalPinCommand [pin=1, value=true]=OK\r\n"
                  + "SwitchAnalogPinCommand [pin=2, value=123]=OK"));
    } finally {
      context.stop();
    }
  }
  public void testLoadFileNotFound() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    try {
      ResourceHelper.resolveMandatoryResourceAsInputStream(
          context, "file:src/test/resources/notfound.txt");
      fail("Should not find file");
    } catch (FileNotFoundException e) {
      assertTrue(e.getMessage().contains("notfound.txt"));
    }

    context.stop();
  }
  public void testLoadClasspathDefault() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    InputStream is =
        ResourceHelper.resolveMandatoryResourceAsInputStream(context, "log4j2.properties");
    assertNotNull(is);

    String text = context.getTypeConverter().convertTo(String.class, is);
    assertNotNull(text);
    assertTrue(text.contains("log4j"));
    is.close();

    context.stop();
  }
  public void testLoadClasspathNotFound() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    try {
      ResourceHelper.resolveMandatoryResourceAsInputStream(context, "classpath:notfound.txt");
      fail("Should not find file");
    } catch (FileNotFoundException e) {
      assertEquals(
          "Cannot find resource: classpath:notfound.txt in classpath for URI: classpath:notfound.txt",
          e.getMessage());
    }

    context.stop();
  }
  public void testLoadClasspathAsUrl() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    URL url =
        ResourceHelper.resolveMandatoryResourceAsUrl(
            context.getClassResolver(), "classpath:log4j2.properties");
    assertNotNull(url);

    String text = context.getTypeConverter().convertTo(String.class, url);
    assertNotNull(text);
    assertTrue(text.contains("log4j"));

    context.stop();
  }
예제 #23
0
  public void testDumpAsXmlPlainBody() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("Hello World");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message);
    assertTrue(
        "Should contain body", out.contains("<body type=\"java.lang.String\">Hello World</body>"));

    context.stop();
  }
  public void testLoadRegistry() throws Exception {
    SimpleRegistry registry = new SimpleRegistry();
    registry.put("myBean", "This is a log4j logging configuation file");

    CamelContext context = new DefaultCamelContext(registry);
    context.start();

    InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, "ref:myBean");
    assertNotNull(is);

    String text = context.getTypeConverter().convertTo(String.class, is);
    assertNotNull(text);
    assertTrue(text.contains("log4j"));
    is.close();

    context.stop();
  }
예제 #25
0
  public static void main(String args[]) throws Exception {
    // START SNIPPET: e1
    CamelContext context = new DefaultCamelContext();
    // END SNIPPET: e1
    // Set up the ActiveMQ JMS Components
    // START SNIPPET: e2
    ConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    // Note we can explicit name the component
    context.addComponent("test-jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
    // END SNIPPET: e2
    // Add some configuration by hand ...
    // START SNIPPET: e3
    context.addRoutes(
        new RouteBuilder() {
          public void configure() {
            //    from("test-jms:queue:test.queue").to("file://tmp/camel");
            from("test-jms:queue:test.queue").to("file:/tmp/camel");
          }
        });
    // END SNIPPET: e3
    // Camel template - a handy class for kicking off exchanges
    // START SNIPPET: e4
    ProducerTemplate template = context.createProducerTemplate();
    // END SNIPPET: e4
    // Now everything is set up - lets start the context
    context.start();
    // Now send some test text to a component - for this case a JMS Queue
    // The text get converted to JMS messages - and sent to the Queue
    // test.queue
    // The file component is listening for messages from the Queue
    // test.queue, consumes
    // them and stores them to disk. The content of each file will be the
    // test we sent here.
    // The listener on the file component gets notified when new files are
    // found ... that's it!
    // START SNIPPET: e5
    for (int i = 0; i < 10; i++) {
      template.sendBody("test-jms:queue:test.queue", "Test Message: " + i);
    }
    // END SNIPPET: e5

    // wait a bit and then stop
    Thread.sleep(1000);
    context.stop();
  }
  public static void main(String[] args) throws Exception {

    logger.info("start");

    CamelContext camelContext = SpringCamelContext.springCamelContext("camel-context.xml");

    for (int index = 0; index < 3; index++) {
      logger.info("get " + index);
      get(camelContext);

      logger.info("put " + index);
      put(camelContext);
    }

    camelContext.stop();

    logger.info("end");
  }
예제 #27
0
  public void testDumpAsXmlBody() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("<?xml version=\"1.0\"?><hi>Hello World</hi>");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message);
    assertTrue(
        "Should contain body",
        out.contains(
            "<body type=\"java.lang.String\">&lt;?xml version=&quot;1.0&quot;?&gt;&lt;hi&gt;Hello World&lt;/hi&gt;</body>"));
    assertTrue("Should contain exchangeId", out.contains(message.getExchange().getExchangeId()));

    context.stop();
  }
예제 #28
0
  public static void main(String[] a) throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    camelContext.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {

            from("file:src/data/inbox/dini?noop=true")
                .choice()
                .when(simple("${body} contains 'Dinesh'"))
                .to("file:src/data/outbox")
                .otherwise()
                .to("file:src/data/others");
          }
        });
    camelContext.start();
    Thread.sleep(10000);
    camelContext.stop();
  }
예제 #29
0
  // START SNIPPET: server
  public static void main(String... args) throws Exception {
    CamelContext context = new DefaultCamelContext();
    CreditAgencyServer creditAgencyServer = new CreditAgencyServer();
    // Start the credit server
    creditAgencyServer.start();

    // Start the bank server
    BankServer bankServer = new BankServer();
    bankServer.start();

    // Start the camel context
    context.addRoutes(new LoanBroker());
    context.start();

    // Start the loan broker
    Thread.sleep(5 * 60 * 1000);
    context.stop();
    Thread.sleep(1000);
    bankServer.stop();
    creditAgencyServer.stop();
  }
  public void testLoadFileWithSpace() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    createDirectory("target/my space");
    FileUtil.copyFile(
        new File("src/test/resources/log4j2.properties"),
        new File("target/my space/log4j2.properties"));

    InputStream is =
        ResourceHelper.resolveMandatoryResourceAsInputStream(
            context, "file:target/my%20space/log4j2.properties");
    assertNotNull(is);

    String text = context.getTypeConverter().convertTo(String.class, is);
    assertNotNull(text);
    assertTrue(text.contains("log4j"));
    is.close();

    context.stop();
  }