Java & Apache- Camel : From direct-endpoint to file-endpoint

标签 java apache-camel

我试图建立一个路径来将文件从一个目录复制到另一个目录。但不是使用: 从(文件://源目录)到(文件://目标目录) 我想做这样的事情:

from(direct:start)
  .to(direct:doStuff)
  .to(direct:readDirectory)
  .to(file://destination-folder)

我做了以下事情:

路线

@Component
public class Route extends AbstractRouteBuilder {
  @Override
  public void configure() throws Exception {
      from("direct:start")
        .bean(lookup(ReadDirectory.class))
        .split(body())
          .setHeader("FILENAME", method(lookup(CreateFilename.class)))
          .to("file:///path/to/my/output/directory/?fileName=${header.FILENAME}");
  }

处理器

@Component
public class ReadDirectory implements CamelProcessorBean {
  @Handler
  public ImmutableList<File> apply(@Header("SOURCE_DIR") final String sourceDir) {
    final File directory = new File(sourceDir);
    final File[] files = directory.listFiles();
    if (files == null) {
      return ImmutableList.copyOf(Lists.<File>newArrayList());
    }
    return ImmutableList.copyOf(files);
  }
}

我可以使用以下伪测试开始我的路线(关键是我可以通过 producer.sendBodyAndHeader(..) 手动开始我的路线)

public class RouteIT extends StandardIT {
  @Produce
  private ProducerTemplate producer;

  @Test
  public void testRoute() throws Exception {
    final String uri = "direct:start";
    producer.sendBodyAndHeaders(uri, InOut, null, header());
  }

  private Map<String, Object> header() {
    final Map<String, Object> header = Maps.newHashMap();
    header.put("SOURCE_DIR", "/path/to/my/input/directory/");
    return header;
  }
}
  • AbstractRouteBuilder扩展 SpringRouteBuilder
  • CamelProcessorBean 只是一个标记接口(interface)
  • StandardIT 加载 SpringContext 和东西

问题是,我必须设置文件名。我读过一些关于 Camel 设置 header CamelFileNameProduced 的内容(在文件端点期间)。它是一个带有时间戳的通用字符串,如果我不设置文件名 - 写入的文件将使用这个通用字符串作为文件名。

我的问题是:是否有更漂亮的解决方案来复制文件(但从直接端点开始并读取路径中间的目录)并保留目标文件名? (当我使用 from("file:source").to("file:destination") 时,我不必设置文件名,为什么我现在必须这样做?)

最佳答案

您可以在使用生产者模板发送时设置文件名,只要在路由之间的路由期间传播 header 就可以了,这是 Camel 默认情况下所做的。

例如

  @Test
  public void testRoute() throws Exception {
    final String uri = "direct:start";
    Map headers = ...
    headers.put(Exchange.FILE_NAME, "myfile.txt");
    producer.sendBodyAndHeaders(uri, InOut, null, headers);
  }

文件组件更多的是讲如何控制文件名

关于Java & Apache- Camel : From direct-endpoint to file-endpoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818765/

相关文章:

java - 在 Camel 上使用 Springboot 的 Rest DSL 在重新启动 EAP 后创建路由抛出异常

java - 如何将 R 脚本加载到 JRI 并从 Java 执行?

asynchronous - 何时使用 Camel Wiretap 或 SEDA?

java - "seda + concurrentConsumers"和 "direct + threads"有什么区别

java - com.github.dandelion.datatables.core.configuration.Configuration.applyConfiguration 处的 NullpointerException 仅在 Tomcat 8 上(在 Tomcat 7 上工作正常)

java - 在更改 Camel 版本时,War 未部署在 weblogic 中

redis - 使用 Redis 的 Camel 保证交付

java - 两个代码片段的数组赋值输出表现不同

java - 循环访问 3 个不同的 JDBC 结果集

java - Ant 构建成功甚至语法错误