List of usage examples for org.springframework.messaging Message getPayload
T getPayload();
From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java
@Test public void testFileNameHeader() throws Exception { Message<?> message = MessageBuilder.withPayload(SAMPLE_CONTENT) .setHeader(FileHeaders.FILENAME, "dir1" + File.separator + "dir2/test").build(); QueueChannel output = new QueueChannel(); handler.setCharset(DEFAULT_ENCODING); handler.setOutputChannel(output);//from w w w . java 2 s .c o m handler.handleMessage(message); Message<?> result = output.receive(0); assertFileContentIsMatching(result); File destFile = (File) result.getPayload(); assertThat(destFile.getAbsolutePath(), containsString(TestUtils.applySystemFileSeparator("/dir1/dir2/test"))); }
From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java
@Test public void existingWritingFileIgnored() throws Exception { Message<?> message = MessageBuilder.withPayload(SAMPLE_CONTENT).build(); QueueChannel output = new QueueChannel(); File outFile = temp.newFile("/outputDirectory/" + message.getHeaders().getId().toString() + ".msg.writing"); FileCopyUtils.copy("foo".getBytes(), new FileOutputStream(outFile)); handler.setCharset(DEFAULT_ENCODING); handler.setOutputChannel(output);//from w w w . j a v a2 s . c om handler.setFileExistsMode(FileExistsMode.IGNORE); handler.handleMessage(message); Message<?> result = output.receive(0); File destFile = (File) result.getPayload(); assertNotSame(destFile, sourceFile); assertThat(destFile.exists(), is(false)); assertThat(outFile.exists(), is(true)); }
From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java
@Test public void existingWritingFileNotIgnoredIfEmptySuffix() throws Exception { Message<?> message = MessageBuilder.withPayload(SAMPLE_CONTENT).build(); QueueChannel output = new QueueChannel(); File outFile = temp.newFile("/outputDirectory/" + message.getHeaders().getId().toString() + ".msg.writing"); FileCopyUtils.copy("foo".getBytes(), new FileOutputStream(outFile)); handler.setCharset(DEFAULT_ENCODING); handler.setOutputChannel(output);//from w w w.ja v a 2 s . c o m handler.setFileExistsMode(FileExistsMode.IGNORE); handler.setTemporaryFileSuffix(""); handler.handleMessage(message); Message<?> result = output.receive(0); File destFile = (File) result.getPayload(); assertNotSame(destFile, sourceFile); assertFileContentIsMatching(result); assertThat(outFile.exists(), is(true)); assertFileContentIs(outFile, "foo"); }
From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java
protected File messageToFile(Message<?> result) { assertThat(result, is(notNullValue())); assertThat(result.getPayload(), is(instanceOf(File.class))); File destFile = (File) result.getPayload(); return destFile; }
From source file:org.springframework.integration.file.remote.RemoteFileTemplate.java
private String send(final Message<?> message, final String subDirectory, final FileExistsMode mode) { Assert.notNull(this.directoryExpressionProcessor, "'remoteDirectoryExpression' is required"); Assert.isTrue(!FileExistsMode.APPEND.equals(mode) || !this.useTemporaryFileName, "Cannot append when using a temporary file name"); Assert.isTrue(!FileExistsMode.REPLACE_IF_MODIFIED.equals(mode), "FilExistsMode.REPLACE_IF_MODIFIED can only be used for local files"); final StreamHolder inputStreamHolder = this.payloadToInputStream(message); if (inputStreamHolder != null) { try {// w w w .j a v a2s . co m return this.execute(session -> { String fileName = inputStreamHolder.getName(); try { String remoteDirectory = RemoteFileTemplate.this.directoryExpressionProcessor .processMessage(message); remoteDirectory = RemoteFileTemplate.this.normalizeDirectoryPath(remoteDirectory); if (StringUtils.hasText(subDirectory)) { if (subDirectory.startsWith(RemoteFileTemplate.this.remoteFileSeparator)) { remoteDirectory += subDirectory.substring(1); } else { remoteDirectory += RemoteFileTemplate.this.normalizeDirectoryPath(subDirectory); } } String temporaryRemoteDirectory = remoteDirectory; if (RemoteFileTemplate.this.temporaryDirectoryExpressionProcessor != null) { temporaryRemoteDirectory = RemoteFileTemplate.this.temporaryDirectoryExpressionProcessor .processMessage(message); } fileName = RemoteFileTemplate.this.fileNameGenerator.generateFileName(message); RemoteFileTemplate.this.sendFileToRemoteDirectory(inputStreamHolder.getStream(), temporaryRemoteDirectory, remoteDirectory, fileName, session, mode); return remoteDirectory + fileName; } catch (FileNotFoundException e) { throw new MessageDeliveryException(message, "File [" + inputStreamHolder.getName() + "] not found in local working directory; it was moved or deleted unexpectedly.", e); } catch (IOException e) { throw new MessageDeliveryException(message, "Failed to transfer file [" + inputStreamHolder.getName() + " -> " + fileName + "] from local directory to remote directory.", e); } catch (Exception e) { throw new MessageDeliveryException(message, "Error handling message for file [" + inputStreamHolder.getName() + " -> " + fileName + "]", e); } }); } finally { try { inputStreamHolder.getStream().close(); } catch (IOException e) { } } } else { // A null holder means a File payload that does not exist. if (this.logger.isWarnEnabled()) { this.logger.warn("File " + message.getPayload() + " does not exist"); } return null; } }
From source file:org.springframework.integration.file.remote.RemoteFileTemplate.java
private StreamHolder payloadToInputStream(Message<?> message) throws MessageDeliveryException { try {//from w ww . j av a2 s . c om Object payload = message.getPayload(); InputStream dataInputStream = null; String name = null; if (payload instanceof InputStream) { dataInputStream = (InputStream) payload; } else if (payload instanceof File) { File inputFile = (File) payload; if (inputFile.exists()) { dataInputStream = new BufferedInputStream(new FileInputStream(inputFile)); name = inputFile.getAbsolutePath(); } } else if (payload instanceof byte[] || payload instanceof String) { byte[] bytes = null; if (payload instanceof String) { bytes = ((String) payload).getBytes(this.charset); name = "String payload"; } else { bytes = (byte[]) payload; name = "byte[] payload"; } dataInputStream = new ByteArrayInputStream(bytes); } else { throw new IllegalArgumentException("Unsupported payload type. The only supported payloads are " + "java.io.File, java.lang.String, byte[] and InputStream"); } if (dataInputStream == null) { return null; } else { return new StreamHolder(dataInputStream, name); } } catch (Exception e) { throw new MessageDeliveryException(message, "Failed to create sendable file.", e); } }
From source file:org.springframework.integration.ftp.dsl.FtpTests.java
@Test public void testFtpInboundFlow() { QueueChannel out = new QueueChannel(); IntegrationFlow flow = IntegrationFlows.from( Ftp.inboundAdapter(sessionFactory()).preserveTimestamp(true).remoteDirectory("ftpSource") .regexFilter(".*\\.txt$").localFilename(f -> f.toUpperCase() + ".a") .localDirectory(getTargetLocalDirectory()), e -> e.id("ftpInboundAdapter").poller(Pollers.fixedDelay(100))).channel(out).get(); IntegrationFlowRegistration registration = this.flowContext.registration(flow).register(); Message<?> message = out.receive(10_000); assertNotNull(message);//from www. ja v a 2 s.c o m Object payload = message.getPayload(); assertThat(payload, instanceOf(File.class)); File file = (File) payload; assertThat(file.getName(), isOneOf(" FTPSOURCE1.TXT.a", "FTPSOURCE2.TXT.a")); assertThat(file.getAbsolutePath(), containsString("localTarget")); message = out.receive(10_000); assertNotNull(message); file = (File) message.getPayload(); assertThat(file.getName(), isOneOf(" FTPSOURCE1.TXT.a", "FTPSOURCE2.TXT.a")); assertThat(file.getAbsolutePath(), containsString("localTarget")); assertNull(out.receive(10)); File remoteFile = new File(this.sourceRemoteDirectory, " " + prefix() + "Source1.txt"); remoteFile.setLastModified(System.currentTimeMillis() - 1000 * 60 * 60 * 24); message = out.receive(10_000); assertNotNull(message); payload = message.getPayload(); assertThat(payload, instanceOf(File.class)); file = (File) payload; assertEquals(" FTPSOURCE1.TXT.a", file.getName()); registration.destroy(); }
From source file:org.springframework.integration.ftp.dsl.FtpTests.java
@Test public void testFtpInboundStreamFlow() throws Exception { QueueChannel out = new QueueChannel(); StandardIntegrationFlow flow = IntegrationFlows.from( Ftp.inboundStreamingAdapter(new FtpRemoteFileTemplate(sessionFactory())) .remoteDirectory("ftpSource").regexFilter(".*\\.txt$"), e -> e.id("ftpInboundAdapter").poller(Pollers.fixedDelay(100))).channel(out).get(); IntegrationFlowRegistration registration = this.flowContext.registration(flow).register(); Message<?> message = out.receive(10_000); assertNotNull(message);//from w w w . j av a2 s . c o m assertThat(message.getPayload(), instanceOf(InputStream.class)); assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE), isOneOf(" ftpSource1.txt", "ftpSource2.txt")); new IntegrationMessageHeaderAccessor(message).getCloseableResource().close(); message = out.receive(10_000); assertNotNull(message); assertThat(message.getPayload(), instanceOf(InputStream.class)); assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE), isOneOf(" ftpSource1.txt", "ftpSource2.txt")); new IntegrationMessageHeaderAccessor(message).getCloseableResource().close(); registration.destroy(); }
From source file:org.springframework.integration.ftp.dsl.FtpTests.java
@Test @SuppressWarnings("unchecked") public void testFtpMgetFlow() { QueueChannel out = new QueueChannel(); IntegrationFlow flow = f -> f//from ww w . ja v a 2s .c o m .handle(Ftp .outboundGateway(sessionFactory(), AbstractRemoteFileOutboundGateway.Command.MGET, "payload") .options(AbstractRemoteFileOutboundGateway.Option.RECURSIVE) .filterExpression("name matches 'subFtpSource|.*1.txt'") .localDirectoryExpression("'" + getTargetLocalDirectoryName() + "' + #remoteDirectory") .localFilenameExpression("#remoteFileName.replaceFirst('ftpSource', 'localTarget')")) .channel(out); IntegrationFlowRegistration registration = this.flowContext.registration(flow).register(); String dir = "ftpSource/"; registration.getInputChannel().send(new GenericMessage<>(dir + "*")); Message<?> result = out.receive(10_000); assertNotNull(result); List<File> localFiles = (List<File>) result.getPayload(); // should have filtered ftpSource2.txt assertEquals(2, localFiles.size()); for (File file : localFiles) { assertThat(file.getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"), Matchers.containsString(dir)); } assertThat(localFiles.get(1).getPath().replaceAll(Matcher.quoteReplacement(File.separator), "/"), Matchers.containsString(dir + "subFtpSource")); registration.destroy(); }
From source file:org.springframework.integration.ftp.inbound.FtpStreamingMessageSourceTests.java
@SuppressWarnings("unchecked") @Test/*from w w w . j a va 2 s .co m*/ public void testAllContents() { Message<byte[]> received = (Message<byte[]>) this.data.receive(10000); assertNotNull(received); assertThat(new String(received.getPayload()), equalTo("source1")); String fileInfo = (String) received.getHeaders().get(FileHeaders.REMOTE_FILE_INFO); assertThat(fileInfo, containsString("remoteDirectory\":\"ftpSource")); assertThat(fileInfo, containsString("permissions\":\"-rw-------")); assertThat(fileInfo, containsString("size\":7")); assertThat(fileInfo, containsString("directory\":false")); assertThat(fileInfo, containsString("filename\":\" ftpSource1.txt")); assertThat(fileInfo, containsString("modified\":")); assertThat(fileInfo, containsString("link\":false")); received = (Message<byte[]>) this.data.receive(10000); assertNotNull(received); assertThat(new String(received.getPayload()), equalTo("source2")); fileInfo = (String) received.getHeaders().get(FileHeaders.REMOTE_FILE_INFO); assertThat(fileInfo, containsString("remoteDirectory\":\"ftpSource")); assertThat(fileInfo, containsString("permissions\":\"-rw-------")); assertThat(fileInfo, containsString("size\":7")); assertThat(fileInfo, containsString("directory\":false")); assertThat(fileInfo, containsString("filename\":\"ftpSource2.txt")); assertThat(fileInfo, containsString("modified\":")); assertThat(fileInfo, containsString("link\":false")); this.adapter.stop(); this.source.setFileInfoJson(false); this.data.purge(null); this.adapter.start(); received = (Message<byte[]>) this.data.receive(10000); assertNotNull(received); assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE_INFO), instanceOf(FtpFileInfo.class)); this.adapter.stop(); }