Как прочитать InputStream из 'in' и записать OutputStream в 'out' в обмене по маршруту Camel? - PullRequest
0 голосов
/ 16 ноября 2018

Обычно это делается с:

try (InputStream is = ...;
     OutputStream os = ...) {
  int b;
  while ((b = is.read()) != -1) {
    // do something with the byte
    os.write(b);
  }
}

В RouteBuilder * configure() у меня есть следующее:

from("file:...")
  ...
  to("direct:second")

from("direct:second")
  ...
  .process(exchange -> {
    try (InputStream is1 = 
           new BufferedInputStream(new FileInputStream(exchange.getIn().getBody(File.class));
         InputStream is2 = exchange.getIn().getBody(BufferedInputStream.class);
         // OutputStream os = ???
    ){
      int b;
      while ((b = [is1|is2].read()) != -1) {
        System.out.print(b); // works

        // now how to obtain the OutputStream, connect it to 'out' and write to it?

      }
    }
  })
  .to("direct:third")

from("direct:third")
  ...

Я читаю документы, блоги, учебники, SOответы о getIn(), getOut(), Переводчик сообщений , transform(), stream: безрезультатно.

Обновление: Я также посмотрел src / test / java / org / apache / верблюд / процессор , особенно StreamCachingInOutTest.Processor там просто читает InputStream.

Следующий вопрос:

Это:

exchange.getIn().getBody(BufferedInputStream.class)

так же, как:

new BufferedInputStream(new FileInputStream(exchange.getIn().getBody(File.class))

если оригинал from(...) равен "file:..."?

ОБНОВЛЕНИЕ

Я попытался сделать следующее:

try (...;
     final OutputStream os = new ByteArrayOutputStream()
){
  while (b = is.read() ...) {
    ...
    os.write(b);
  }
  exchange.getOut().setBody(os, ByteArrayOutputStream.class);
}

Результат:

Caused by: org.apache.camel.InvalidPayloadException:
  No body available of type: java.io.InputStream but has value:
    of type: org.apache.commons.io.output.ByteArrayOutputStream on: Message[].
   Caused by: No type converter available to convert from type:
     org.apache.commons.io.output.ByteArrayOutputStream to the required type:
       java.io.InputStream with value . Exchange[ID-R05377-1542620554174-0-4].
     Caused by: [org.apache.camel.NoTypeConversionAvailableException -
       No type converter available to convert from type:
         org.apache.commons.io.output.ByteArrayOutputStream to the
           required type: java.io.InputStream with value ]
at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:117)
at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:333)
... 17 more
Caused by: org.apache.camel.NoTypeConversionAvailableException:
  No type converter available to convert from type:
    org.apache.commons.io.output.ByteArrayOutputStream to the required type:
      java.io.InputStream with value 
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.mandatoryConvertTo(BaseTypeConverterRegistry.java:206)
at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:115)
... 18 more
1849 [Camel (camel-1) thread #2 - Multicast] ERROR org.apache.camel.processor.DefaultErrorHandler  -
  Failed delivery for (MessageId: ID-R05377-1542620554174-0-7 on
    ExchangeId: ID-R05377-1542620554174-0-4). Exhausted after delivery attempt:
      1 caught: org.apache.camel.component.file.GenericFileOperationFailedException:
        Cannot store file: <... to(...) file path of direct:third here ...>

ОБНОВЛЕНИЕ ОБНОВЛЕНИЯ

Исключение было вызвано, потому что я использовал org.apache.commons.io.output.ByteArrayOutputStream вместо java.io.ByteArrayOutputStream.Это работает с последним, и это также, кажется, ответ на вопрос.

Ответы [ 2 ]

0 голосов
/ 19 ноября 2018
import java.io.ByteArrayOutputStream;

// DO NOT USE THIS IN CONJUNCTION WITH CAMEL!
//import org.apache.commons.io.output.ByteArrayOutputStream;

...    

    from(...)
      ... 
      .streamCaching()
      .process(exchange -> {
        ...
        try (final InputStream is = exchange.getIn().getBody(InputStream.class);
             final OutputStream os = new ByteArrayOutputStream(OUTSTREAM_BUFFER)) {
          while (b = is.read() ...) {

            // do something with the byte

            os.write(b);
          }
          exchange.getOut().setBody(os, OutputStream.class);
        }
      })
      ...
0 голосов
/ 16 ноября 2018

Посмотрите на компонент потока (http://camel.apache.org/stream.html) Пример:

// Route messages to the standard output. 
from("direct:in")
.to("stream:out"); 
...