Пример #1
0
  @Test
  public void testRoute() throws Exception {

    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("Hello World 2");

    template.sendBodyAndHeader("direct:start", "Hello World 1", "isfailed", true);
    template.sendBodyAndHeader("direct:start", "Hello World 2", "isfailed", false);

    mock.assertIsSatisfied();
  }
Пример #2
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());
  }
  @Test
  public void testTransactionWithRollback() throws InterruptedException {
    // Assertions
    deletedEndpoint.expectedMessageCount(2);
    deletedEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 204);

    transactedEndpoint.expectedMessageCount(0);

    verifiedEndpoint.expectedMessageCount(0);

    midtransactionEndpoint.expectedMessageCount(2);
    midtransactionEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 201);

    notfoundEndpoint.expectedMessageCount(3);
    notfoundEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 404);

    // Start the transaction
    final Map<String, Object> headers = new HashMap<>();
    headers.put(Exchange.HTTP_METHOD, "POST");
    headers.put(Exchange.CONTENT_TYPE, "text/turtle");

    // Create the object
    final String fullPath =
        template.requestBodyAndHeaders(
            "direct:create", FcrepoTestUtils.getTurtleDocument(), headers, String.class);

    assertNotNull(fullPath);

    final String identifier = fullPath.replaceAll(FcrepoTestUtils.getFcrepoBaseUrl(), "");

    // Test the creation of several objects
    template.sendBodyAndHeader("direct:transactWithError", null, "TestIdentifierBase", identifier);

    // Test the object
    template.sendBodyAndHeader(
        "direct:verifyMissing", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one");
    template.sendBodyAndHeader(
        "direct:verifyMissing", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two");

    // Teardown
    template.sendBodyAndHeader(
        "direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier);

    // Confirm assertions
    verifiedEndpoint.assertIsSatisfied();
    deletedEndpoint.assertIsSatisfied();
    transactedEndpoint.assertIsSatisfied();
    notfoundEndpoint.assertIsSatisfied();
    midtransactionEndpoint.assertIsSatisfied();
  }
Пример #4
0
 private void sendBodyAndHeader(
     final String channelUri,
     final Object payload,
     final String header,
     final String headerValue) {
   final ProducerTemplate<Exchange> producer = getContext().createProducerTemplate();
   producer.sendBodyAndHeader(channelUri, payload, header, headerValue);
 }
Пример #5
0
  @DirtiesContext
  public void testSendNotMatchingMessage() throws Exception {
    resultEndpoint.expectedMessageCount(0);

    template.sendBodyAndHeader("<notMatched/>", "foo", "notMatchedHeaderValue");

    resultEndpoint.assertIsSatisfied();
  }
 @Test
 public void testDefault() throws Exception {
   mock.expectedBodiesReceived("test1");
   mock.expectedHeaderReceived("test", "test2");
   producerTemplate.sendBodyAndHeader("direct:input", "test1", "test", "test2");
   mock.assertIsSatisfied();
   Message received = mock.getExchanges().get(0).getIn();
   assertEquals("default", received.getHeader(GTaskBinding.GTASK_QUEUE_NAME));
   assertEquals(0, received.getHeader(GTaskBinding.GTASK_RETRY_COUNT));
 }
Пример #7
0
  @DirtiesContext
  public void testSendMatchingMessage() throws Exception {
    String expectedBody = "<matched/>";

    resultEndpoint.expectedBodiesReceived(expectedBody);

    template.sendBodyAndHeader(expectedBody, "foo", "bar");

    resultEndpoint.assertIsSatisfied();
  }
Пример #8
0
 @Test
 public void testEndpointWithoutHttps() {
   mockEndpoint.reset();
   try {
     template.sendBodyAndHeader(
         "http://localhost:" + port + "/test", expectedBody, "Content-Type", "application/xml");
     fail("expect exception on access to https endpoint via http");
   } catch (RuntimeCamelException expected) {
   }
   assertTrue("mock endpoint was not called", mockEndpoint.getExchanges().isEmpty());
 }
  @Test
  public void testDNSWithEmptyNameHeader() throws Exception {
    resultEndpoint.expectedMessageCount(0);
    try {
      template.sendBodyAndHeader("hello", "dns.name", "");
    } catch (Throwable t) {

      assertTrue(t.toString(), t.getCause() instanceof IllegalArgumentException);
    }
    resultEndpoint.assertIsSatisfied();
  }
Пример #10
0
 /**
  * Test using two following different theme from different folder without Resource URI header
  * defined
  */
 @Test
 public void testChunkSubfolder() throws Exception {
   // Prepare
   endSimpleMock.expectedMessageCount(1);
   endSimpleMock.expectedBodiesReceived(
       "This the result of last call to chunk Earth to Andrew. Come in, Andrew.\n\n");
   // Act
   startSimpleProducerTemplate.sendBodyAndHeader("The Body", "name", "Andrew");
   // Verify
   assertMockEndpointsSatisfied();
 }
Пример #11
0
  @Test
  public void testQuartz2Scheduler() throws Exception {
    // start bundle
    getInstalledBundle(NAME).start();

    // must use the camel context from osgi
    CamelContext ctx =
        getOsgiService(CamelContext.class, "(camel.context.symbolicname=" + NAME + ")", 10000);

    MockEndpoint mock = ctx.getEndpoint("mock:result", MockEndpoint.class);
    mock.expectedMessageCount(2);

    ProducerTemplate myTemplate = ctx.createProducerTemplate();
    myTemplate.start();

    myTemplate.sendBodyAndHeader("file:target/foo", "Hello World", Exchange.FILE_NAME, "hello.txt");
    myTemplate.sendBodyAndHeader("file:target/foo", "Bye World", Exchange.FILE_NAME, "bye.txt");

    mock.assertIsSatisfied();

    myTemplate.stop();
  }
Пример #12
0
  @Test
  public void testMoveFile() throws Exception {
    context.setTracing(true);

    // create a new file in the inbox folder with the name hello.txt and containing Hello World as
    // body
    inbox.sendBodyAndHeader("Hello World", Exchange.FILE_NAME, "hello.txt");

    // wait a while to let the file be moved
    Thread.sleep(2000);

    // test the file was moved
    File target = new File(outboxDir + "/hello.txt");
    assertTrue("File should have been moved", target.exists());

    // test that its content is correct as well
    String content = context.getTypeConverter().convertTo(String.class, target);
    assertEquals("Hello World", content);
  }
  @Test
  public void testProducerAndConsumer() throws Exception {
    getInstalledBundle("CamelBlueprintJcloudsTestBundle").start();
    CamelContext ctx =
        getOsgiService(
            CamelContext.class,
            "(camel.context.symbolicname=CamelBlueprintJcloudsTestBundle)",
            20000);

    MockEndpoint mock = ctx.getEndpoint("mock:results", MockEndpoint.class);
    ProducerTemplate template = ctx.createProducerTemplate();
    mock.expectedMessageCount(2);

    template.sendBodyAndHeader("direct:start", "Test 1", JcloudsConstants.BLOB_NAME, "blob1");
    template.sendBodyAndHeader("direct:start", "Test 2", JcloudsConstants.BLOB_NAME, "blob2");

    assertMockEndpointsSatisfied();

    template.stop();
  }
Пример #14
0
  @Test
  public void testPostStatusUpdateRequestResponse() throws Exception {
    Date now = new Date();
    String tweet = "UserProducerInOnlyTest: This is a tweet posted on " + now.toString();
    LOG.info("Tweet: " + tweet);
    ProducerTemplate producerTemplate = context.createProducerTemplate();
    // send tweet to the twitter endpoint
    producerTemplate.sendBodyAndHeader("direct:tweets", tweet, "customHeader", 12312);

    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(String.class);
    // Message headers should be preserved
    resultEndpoint.expectedHeaderReceived("customHeader", 12312);
    resultEndpoint.assertIsSatisfied();

    List<Exchange> tweets = resultEndpoint.getExchanges();
    assertNotNull(tweets);
    assertThat(tweets.size(), is(1));
    String receivedTweet = tweets.get(0).getIn().getBody(String.class);
    assertThat(receivedTweet, is(tweet));
  }
Пример #15
0
  @Test
  public void testTraversal() throws Exception {

    getMockEndpoint("mock:direct:recipients").expectedMessageCount(1);
    getMockEndpoint("mock:" + reindexingStream).expectedMessageCount(7);
    getMockEndpoint("mock:" + reindexingStream)
        .expectedHeaderValuesReceivedInAnyOrder(
            FCREPO_IDENTIFIER,
            "/foo/a",
            "/foo/b",
            "/foo/c",
            "/foo/d",
            "/foo/e",
            "/foo/f",
            "/foo/g");

    context
        .getRouteDefinition("FcrepoReindexingTraverse")
        .adviceWith(
            context,
            new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                replaceFromWith("direct:traverse");
                mockEndpointsAndSkip("fcrepo:*");
                mockEndpointsAndSkip(reindexingStream + "*");
                mockEndpointsAndSkip("direct:recipients");
              }
            });
    context.start();

    template.sendBodyAndHeader(
        "direct:traverse",
        ObjectHelper.loadResourceAsStream("indexable.rdf"),
        FCREPO_BASE_URL,
        "http://localhost:8080/fcrepo4/rest");

    assertMockEndpointsSatisfied();
  }
Пример #16
0
  @Test
  public void testEndpoint() throws Exception {
    mockEndpoint.reset();
    mockEndpoint.expectedBodiesReceived(expectedBody);

    template.sendBodyAndHeader(
        "https://localhost:" + port + "/test", expectedBody, "Content-Type", "application/xml");

    mockEndpoint.assertIsSatisfied();
    List<Exchange> list = mockEndpoint.getReceivedExchanges();
    Exchange exchange = list.get(0);
    TestSupport.assertNotNull("exchange", exchange);

    Message in = exchange.getIn();
    assertNotNull("in", in);

    Map<String, Object> headers = in.getHeaders();

    log.info("Headers: " + headers);

    assertTrue("Should be more than one header but was: " + headers, headers.size() > 0);
  }
  protected Status processCommunicateAction(
      final Exchange exchange, final CommunicateAction communicateAction) throws IOException {
    final EmotionKind emotionKind =
        Optional.ofNullable(communicateAction.getEmotionKind()).orElse(EmotionKind.NEUTRAL);
    final Locale lang = Optional.ofNullable(communicateAction.getInLanguage()).orElse(Locale.US);
    log.info("Got speech lang-legacy={}: {}", lang.getLanguage(), communicateAction);
    final String avatarId = Optional.ofNullable(communicateAction.getAvatarId()).orElse("nao1");

    // final File wavFile = File.createTempFile("lumen-speech-synthesis_", ".wav");
    //                        final File oggFile = File.createTempFile("lumen-speech-synthesis_",
    // ".ogg");
    try {
      byte[] wavBytes = null;
      if (INDONESIAN.getLanguage().equals(lang.getLanguage())) {
        // Expressive speech (for now, Indonesian only)
        try {
          PhonemeDoc phonemeDoc;
          if (EmotionKind.NEUTRAL == emotionKind) {
            phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
          } else {
            try {
              final EmotionProsody emotionProsody =
                  emotionProsodies
                      .getEmotion(emotionKind)
                      .orElseThrow(
                          () ->
                              new SpeechSynthesisException(
                                  "Emotion " + emotionKind + " not supported"));
              phonemeDoc = speechProsody.perform(communicateAction.getObject(), emotionProsody);
            } catch (Exception e) {
              log.error(
                  "Cannot speak with emotion "
                      + emotionKind
                      + ", falling back to NEUTRAL: "
                      + communicateAction.getObject(),
                  e);
              phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
            }
          }

          try (final ByteArrayInputStream objectIn =
                  new ByteArrayInputStream(phonemeDoc.toString().getBytes(StandardCharsets.UTF_8));
              final ByteArrayOutputStream wavStream = new ByteArrayOutputStream();
              final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
            final CommandLine cmdLine = new CommandLine("mbrola");
            cmdLine.addArgument("-v");
            cmdLine.addArgument(String.valueOf(INDONESIAN_AMPLITUDE / 100f));
            cmdLine.addArgument(new File(mbrolaShareFolder, "id1/id1").toString());
            cmdLine.addArgument("-");
            cmdLine.addArgument("-.wav");
            executor.setStreamHandler(new PumpStreamHandler(wavStream, err, objectIn));
            final int executed;
            try {
              executed = executor.execute(cmdLine);
              wavBytes = wavStream.toByteArray();
            } finally {
              log.info("{}: {}", cmdLine, err.toString());
            }
          }
        } catch (Exception e) {
          log.error(
              "Cannot speak Indonesian using prosody engine, falling back to direct espeak: "
                  + communicateAction.getObject(),
              e);
        }
      }
      if (wavBytes == null) {
        // Neutral speech using direct espeak
        try {
          wavBytes = performEspeak(communicateAction, lang);
        } catch (Exception e) {
          if (!Locale.US.getLanguage().equals(lang.getLanguage())) {
            // Indonesian sometimes fails especially "k-k", e.g. "baik koq".
            // retry using English as last resort, as long as it says something!
            log.error(
                "Cannot speak using "
                    + lang.toLanguageTag()
                    + ", falling back to English (US): "
                    + communicateAction.getObject(),
                e);
            wavBytes = performEspeak(communicateAction, Locale.US);
          } else {
            throw e;
          }
        }
      }

      log.info("espeak/mbrola generated {} bytes WAV", wavBytes.length);
      try (final ByteArrayInputStream wavIn = new ByteArrayInputStream(wavBytes);
          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
        // flac.exe doesn't support mp3, and that's a problem for now (note: mp3 patent is expiring)
        final CommandLine cmdLine = new CommandLine(ffmpegExecutable);
        cmdLine.addArgument("-i");
        cmdLine.addArgument("-"); // cmdLine.addArgument(wavFile.toString());
        cmdLine.addArgument("-ar");
        cmdLine.addArgument(String.valueOf(SAMPLE_RATE));
        cmdLine.addArgument("-ac");
        cmdLine.addArgument("1");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("ogg");
        // without this you'll get FLAC instead, which browsers do not support
        cmdLine.addArgument("-acodec");
        cmdLine.addArgument("libvorbis");
        //                                cmdLine.addArgument("-y"); // happens, weird!
        //                                cmdLine.addArgument(oggFile.toString());
        cmdLine.addArgument("-");
        executor.setStreamHandler(new PumpStreamHandler(bos, err, wavIn));
        final int executed;
        try {
          executed = executor.execute(cmdLine);
        } finally {
          log.info("{}: {}", cmdLine, err.toString());
        }
        //                                Preconditions.checkState(oggFile.exists(), "Cannot convert
        // %s bytes WAV to OGG",
        //                                        wavBytes.length);

        // Send
        //                                final byte[] audioContent =
        // FileUtils.readFileToByteArray(oggFile);
        final byte[] audioContent = bos.toByteArray();
        final String audioContentType = "audio/ogg";

        final AudioObject audioObject = new AudioObject();
        audioObject.setTranscript(communicateAction.getObject());
        audioObject.setInLanguage(lang);
        audioObject.setMediaLayer(MediaLayer.SPEECH);
        audioObject.setContentType(audioContentType + "; rate=" + SAMPLE_RATE);
        audioObject.setContentUrl(
            "data:" + audioContentType + ";base64," + Base64.encodeBase64String(audioContent));
        audioObject.setContentSize((long) audioContent.length);
        //
        // audioObject.setName(FilenameUtils.getName(oggFile.getName()));
        audioObject.setName("lumen-speech-" + new DateTime() + ".ogg");
        audioObject.setDateCreated(new DateTime());
        audioObject.setDatePublished(audioObject.getDateCreated());
        audioObject.setDateModified(audioObject.getDateCreated());
        audioObject.setUploadDate(audioObject.getDateCreated());
        final String audioOutUri =
            "rabbitmq://dummy/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&skipQueueDeclare=true&routingKey="
                + AvatarChannel.AUDIO_OUT.key(avatarId);
        log.info("Sending {} to {} ...", audioObject, audioOutUri);
        producer.sendBodyAndHeader(
            audioOutUri,
            toJson.getMapper().writeValueAsBytes(audioObject),
            RabbitMQConstants.EXPIRATION,
            String.valueOf(MESSAGE_EXPIRATION.getMillis()));
      }
    } finally {
      //                            oggFile.delete();
      // wavFile.delete();
    }

    // reply
    log.trace("Exchange {} is {}", exchange.getIn().getMessageId(), exchange.getPattern());
    final Status status = new Status();
    exchange.getOut().setBody(status);
    return status;
    //                        final String replyTo = exchange.getIn().getHeader("rabbitmq.REPLY_TO",
    // String.class);
    //                        if (replyTo != null) {
    //                            log.debug("Sending reply to {} ...", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.ROUTING_KEY", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.EXCHANGE_NAME", "");
    //                            exchange.getOut().setHeader("recipients",
    //
    // "rabbitmq://dummy/dummy?connectionFactory=#amqpConnFactory&autoDelete=false,log:OUT." +
    // LumenChannel.SPEECH_SYNTHESIS);
    //                        } else {
    //                            exchange.getOut().setHeader("recipients");
    //                        }
  }