How to use retrieveFile method of com.consol.citrus.ftp.client.FtpClient class

Best Citrus code snippet using com.consol.citrus.ftp.client.FtpClient.retrieveFile

Source:FtpClient.java Github

copy

Full Screen

...90 connectAndLogin();91 CommandType ftpCommand = ftpMessage.getPayload(CommandType.class);92 FtpMessage response;93 if (ftpCommand instanceof GetCommand) {94 response = retrieveFile((GetCommand) ftpCommand, context);95 } else if (ftpCommand instanceof PutCommand) {96 response = storeFile((PutCommand) ftpCommand, context);97 } else if (ftpCommand instanceof ListCommand) {98 response = listFiles((ListCommand) ftpCommand, context);99 } else if (ftpCommand instanceof DeleteCommand) {100 response = deleteFile((DeleteCommand) ftpCommand, context);101 } else {102 response = executeCommand(ftpCommand, context);103 }104 if (getEndpointConfiguration().getErrorHandlingStrategy().equals(ErrorHandlingStrategy.THROWS_EXCEPTION)) {105 if (!isPositive(response.getReplyCode())) {106 throw new CitrusRuntimeException(String.format("Failed to send FTP command - reply is: %s:%s", response.getReplyCode(), response.getReplyString()));107 }108 }109 log.info(String.format("FTP message was sent to: '%s:%s'", getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort()));110 correlationManager.store(correlationKey, response);111 } catch (IOException e) {112 throw new CitrusRuntimeException("Failed to execute ftp command", e);113 }114 }115 protected FtpMessage executeCommand(CommandType ftpCommand, TestContext context) {116 try {117 int reply = ftpClient.sendCommand(ftpCommand.getSignal(), ftpCommand.getArguments());118 return FtpMessage.result(reply, ftpClient.getReplyString(), isPositive(reply));119 } catch (IOException e) {120 throw new CitrusRuntimeException("Failed to execute ftp command", e);121 }122 }123 private boolean isPositive(int reply) {124 return FTPReply.isPositiveCompletion(reply) || FTPReply.isPositivePreliminary(reply);125 }126 /**127 * Perform list files operation and provide file information as response.128 * @param list129 * @param context130 * @return131 */132 protected FtpMessage listFiles(ListCommand list, TestContext context) {133 String remoteFilePath = Optional.ofNullable(list.getTarget())134 .map(ListCommand.Target::getPath)135 .map(context::replaceDynamicContentInString)136 .orElse("");137 try {138 List<String> fileNames = new ArrayList<>();139 FTPFile[] ftpFiles;140 if (StringUtils.hasText(remoteFilePath)) {141 ftpFiles = ftpClient.listFiles(remoteFilePath);142 } else {143 ftpFiles = ftpClient.listFiles(remoteFilePath);144 }145 for (FTPFile ftpFile : ftpFiles) {146 fileNames.add(ftpFile.getName());147 }148 return FtpMessage.result(ftpClient.getReplyCode(), ftpClient.getReplyString(), fileNames);149 } catch (IOException e) {150 throw new CitrusRuntimeException(String.format("Failed to list files in path '%s'", remoteFilePath), e);151 }152 }153 /**154 * Performs delete file operation.155 * @param delete156 * @param context157 */158 protected FtpMessage deleteFile(DeleteCommand delete, TestContext context) {159 String remoteFilePath = context.replaceDynamicContentInString(delete.getTarget().getPath());160 try {161 if (!StringUtils.hasText(remoteFilePath)) {162 return null;163 }164 boolean success = true;165 if (isDirectory(remoteFilePath)) {166 if (!ftpClient.changeWorkingDirectory(remoteFilePath)) {167 throw new CitrusRuntimeException("Failed to change working directory to " + remoteFilePath + ". FTP reply code: " + ftpClient.getReplyString());168 }169 if (delete.isRecursive()) {170 FTPFile[] ftpFiles = ftpClient.listFiles();171 for (FTPFile ftpFile : ftpFiles) {172 DeleteCommand recursiveDelete = new DeleteCommand();173 DeleteCommand.Target target = new DeleteCommand.Target();174 target.setPath(remoteFilePath + "/" + ftpFile.getName());175 recursiveDelete.setTarget(target);176 recursiveDelete.setIncludeCurrent(true);177 deleteFile(recursiveDelete, context);178 }179 }180 if (delete.isIncludeCurrent()) {181 // we cannot delete the current working directory, so go to root directory and delete from there182 ftpClient.changeWorkingDirectory("/");183 success = ftpClient.removeDirectory(remoteFilePath);184 }185 } else {186 success = ftpClient.deleteFile(remoteFilePath);187 }188 if (!success) {189 throw new CitrusRuntimeException("Failed to delete path " + remoteFilePath + ". FTP reply code: " + ftpClient.getReplyString());190 }191 } catch (IOException e) {192 throw new CitrusRuntimeException("Failed to delete file from FTP server", e);193 }194 // If there was no file to delete, the ftpClient has the reply code from the previously executed195 // operation. Since we want to have a deterministic behaviour, we need to set the reply code and196 // reply string on our own!197 if (ftpClient.getReplyCode() != FILE_ACTION_OK) {198 return FtpMessage.deleteResult(FILE_ACTION_OK, String.format("%s No files to delete.", FILE_ACTION_OK), true);199 }200 return FtpMessage.deleteResult(ftpClient.getReplyCode(), ftpClient.getReplyString(), isPositive(ftpClient.getReplyCode()));201 }202 /**203 * Check file path type directory or file.204 * @param remoteFilePath205 * @return206 * @throws IOException207 */208 protected boolean isDirectory(String remoteFilePath) throws IOException {209 if (!ftpClient.changeWorkingDirectory(remoteFilePath)) { // not a directory or not accessible210 switch (ftpClient.listFiles(remoteFilePath).length) {211 case 0:212 throw new CitrusRuntimeException("Remote file path does not exist or is not accessible: " + remoteFilePath);213 case 1:214 return false;215 default:216 throw new CitrusRuntimeException("Unexpected file type result for file path: " + remoteFilePath);217 }218 } else {219 return true;220 }221 }222 /**223 * Performs store file operation.224 * @param command225 * @param context226 */227 protected FtpMessage storeFile(PutCommand command, TestContext context) {228 try {229 String localFilePath = context.replaceDynamicContentInString(command.getFile().getPath());230 String remoteFilePath = addFileNameToTargetPath(localFilePath, context.replaceDynamicContentInString(command.getTarget().getPath()));231 String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElse(DataType.BINARY.name()));232 try (InputStream localFileInputStream = getLocalFileInputStream(command.getFile().getPath(), dataType, context)) {233 ftpClient.setFileType(getFileType(dataType));234 if (!ftpClient.storeFile(remoteFilePath, localFileInputStream)) {235 throw new IOException("Failed to put file to FTP server. Remote path: " + remoteFilePath236 + ". Local file path: " + localFilePath + ". FTP reply: " + ftpClient.getReplyString());237 }238 }239 } catch (IOException e) {240 throw new CitrusRuntimeException("Failed to put file to FTP server", e);241 }242 return FtpMessage.putResult(ftpClient.getReplyCode(), ftpClient.getReplyString(), isPositive(ftpClient.getReplyCode()));243 }244 /**245 * Constructs local file input stream. When using ASCII data type the test variable replacement is activated otherwise246 * plain byte stream is used.247 *248 * @param path249 * @param dataType250 * @param context251 * @return252 * @throws IOException253 */254 protected InputStream getLocalFileInputStream(String path, String dataType, TestContext context) throws IOException {255 if (dataType.equals(DataType.ASCII.name())) {256 String content = context.replaceDynamicContentInString(FileUtils.readToString(FileUtils.getFileResource(path)));257 return new ByteArrayInputStream(content.getBytes(FileUtils.getDefaultCharset()));258 } else {259 return FileUtils.getFileResource(path).getInputStream();260 }261 }262 /**263 * Performs retrieve file operation.264 * @param command265 */266 protected FtpMessage retrieveFile(GetCommand command, TestContext context) {267 try {268 String remoteFilePath = context.replaceDynamicContentInString(command.getFile().getPath());269 String localFilePath = addFileNameToTargetPath(remoteFilePath, context.replaceDynamicContentInString(command.getTarget().getPath()));270 if (Paths.get(localFilePath).getParent() != null) {271 Files.createDirectories(Paths.get(localFilePath).getParent());272 }273 String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElse(DataType.BINARY.name()));274 try (FileOutputStream localFileOutputStream = new FileOutputStream(localFilePath)) {275 ftpClient.setFileType(getFileType(dataType));276 if (!ftpClient.retrieveFile(remoteFilePath, localFileOutputStream)) {277 throw new CitrusRuntimeException("Failed to get file from FTP server. Remote path: " + remoteFilePath278 + ". Local file path: " + localFilePath + ". FTP reply: " + ftpClient.getReplyString());279 }280 }281 if (getEndpointConfiguration().isAutoReadFiles()) {282 String fileContent;283 if (command.getFile().getType().equals(DataType.BINARY.name())) {284 fileContent = Base64.encodeBase64String(FileCopyUtils.copyToByteArray(FileUtils.getFileResource(localFilePath).getInputStream()));285 } else {286 fileContent = FileUtils.readToString(FileUtils.getFileResource(localFilePath));287 }288 return FtpMessage.result(ftpClient.getReplyCode(), ftpClient.getReplyString(), localFilePath, fileContent);289 } else {290 return FtpMessage.result(ftpClient.getReplyCode(), ftpClient.getReplyString(), localFilePath, null);...

Full Screen

Full Screen

Source:FtpClientTest.java Github

copy

Full Screen

...110 @Test111 public void testRetrieveFile() {112 assertTrue(fakeFtpServer.getFileSystem().exists(DOWNLOAD_FILE));113 String localFilePath = Paths.get(targetPath, "download_file").toString();114 ftpClient.retrieveFile(getCommand(DOWNLOAD_FILE, localFilePath), context);115 assertTrue(fakeFtpServer.getFileSystem().exists(DOWNLOAD_FILE));116 assertTrue(new File(localFilePath).exists());117 }118 @Test119 public void testRetrieveFileImplicitFilename() {120 assertTrue(fakeFtpServer.getFileSystem().exists(DOWNLOAD_FILE));121 ftpClient.retrieveFile(getCommand(DOWNLOAD_FILE, targetPath + "/"), context);122 assertTrue(fakeFtpServer.getFileSystem().exists(DOWNLOAD_FILE));123 assertTrue(new File(targetPath + DOWNLOAD_FILE).exists());124 }125 @Test126 public void testStoreFile() throws Exception {127 assertFalse(fakeFtpServer.getFileSystem().exists("/" + UPLOAD_FILE));128 Path uploadFile = Paths.get(targetPath, UPLOAD_FILE);129 Files.write(uploadFile, "Upload content\n".getBytes());130 FtpMessage ftpMessage = ftpClient.storeFile(putCommand(Paths.get(targetPath, UPLOAD_FILE).toString(), "/" + UPLOAD_FILE), context);131 verifyMessage(ftpMessage, PutCommandResult.class, CLOSING_DATA_CONNECTION, "226 Created file /upload_file.");132 assertTrue(fakeFtpServer.getFileSystem().exists("/" + UPLOAD_FILE));133 fakeFtpServer.getFileSystem().delete("/" + UPLOAD_FILE);134 }135 @Test...

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.samples.ftp;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;4import org.springframework.beans.factory.annotation.Autowired;5import org.springframework.core.io.ClassPathResource;6import org.testng.annotations.Test;7public class FtpClientJavaIT extends TestNGCitrusTestRunner {8 private FtpClient ftpClient;9 public void ftpClientJavaIT() {10 variable("localPath", "target");11 variable("remotePath", "test");12 variable("fileName", "3.txt");13 variable("fileContent", "Hello from Citrus!");14 echo("Create local file");15 create().file(new ClassPathResource("com/consol/citrus/samples/ftp/3.txt"));16 echo("Upload file to FTP server");17 ftpClient.upload()18 .localPath("${localPath}")19 .remotePath("${remotePath}")20 .fileName("${fileName}");21 echo("Download file from FTP server");22 ftpClient.download()23 .localPath("${localPath}")24 .remotePath("${remotePath}")25 .fileName("${fileName}");26 echo("Verify file content");27 validate().file("${localPath}/${fileName}", "${fileContent}");28 }29}30package com.consol.citrus.samples.ftp;31import com.consol.citrus.dsl.builder.FtpClientBuilder;32import com.consol.citrus.dsl.builder.FtpServerBuilder;33import com.consol.citrus.dsl.builder.HttpServerBuilder;34import com.consol.citrus.dsl.builder.JmsServerBuilder;35import com.consol.citrus.dsl.builder.SoapClientBuilder;36import com.consol.citrus.dsl.builder.SoapServerBuilder;37import com.consol.citrus.dsl.builder.TcpClientBuilder;38import com.consol.citrus.dsl.builder.TcpServerBuilder;39import com.consol.citrus.dsl.builder.WebServiceClientBuilder;40import com.consol.citrus.dsl.builder.WebServiceServerBuilder;41import com.consol.citrus.dsl.builder.XpathMessageValidationBuilder;42import com.consol.citrus.dsl.builder.XsdSchemaValidationBuilder;43import com.consol.citrus.dsl.builder.XsltMessageProcessorBuilder;44import com.consol.citrus.dsl.builder.XmlMessageValidationBuilder;45import com.consol.citrus.dsl.builder

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.samples.ftp;2import org.springframework.context.annotation.Bean;3import org.springframework.context.annotation.Configuration;4import org.springframework.context.annotation.Import;5import com.consol.citrus.dsl.builder.BuilderSupport;6import com.consol.citrus.dsl.endpoint.FtpEndpointConfigurator;7import com.consol.citrus.dsl.endpoint.FtpEndpointConfigurator.FtpServerConfig;8import com.consol.citrus.dsl.runner.TestRunner;9import com.consol.citrus.dsl.runner.TestRunnerSupport;10import com.consol.citrus.dsl.testng.TestNGCitrusTest;11import com.consol.citrus.ftp.client.FtpClient;12import com.consol.citrus.ftp.message.FtpMessage;13import com.consol.citrus.ftp.server.FtpServer;14import com.consol.citrus.ftp.server.FtpServerConfiguration;15import com.consol.citrus.ftp.server.FtpServerConfigurationBuilder;16import com.consol.citrus.ftp.server.FtpServerConfigurationBuilder.FtpServerConfigBuilder;17import com.consol.citrus.ftp.server.FtpServerConfigurationBuilder.FtpServerConfigBuilder.FtpServerUserConfigBuilder;

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.samples.ftp;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;4import com.consol.citrus.ftp.client.FtpClient;5import org.springframework.beans.factory.annotation.Autowired;6import org.testng.annotations.Test;7public class FtpClientRetrieveFileJavaIT extends TestNGCitrusTestRunner {8 private FtpClient ftpClient;9 public void ftpClientRetrieveFile() {10 ftpClient.retrieveFile("citrus:file:target/ftp/retrieve");11 }12}13package com.consol.citrus.samples.ftp;14import com.consol.citrus.annotations.CitrusTest;15import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;16import com.consol.citrus.ftp.client.FtpClient;17import org.springframework.beans.factory.annotation.Autowired;18import org.testng.annotations.Test;19public class FtpClientRetrieveFileJavaIT extends TestNGCitrusTestRunner {20 private FtpClient ftpClient;21 public void ftpClientRetrieveFile() {22 ftpClient.retrieveFile("citrus:file:target/ftp/retrieve", "test.txt");23 }24}25package com.consol.citrus.samples.ftp;26import com.consol.citrus.annotations.CitrusTest;27import com.consol.citrus.dsl.testng

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ftp;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;4import org.testng.annotations.Test;5public class RetrieveFileTest extends TestNGCitrusTestRunner {6 public void retrieveFile() {7 variable("localPath", "target/ftp/retrieveFileTest");8 variable("remotePath", "remotePath");9 variable("remoteFile", "remoteFile");10 variable("localFile", "localFile");11 parallel().actions(12 ftp().client("ftpClient")13 .send()14 .retrieveFile("${localPath}/${localFile}", "${remotePath}/${remoteFile}"),15 http().client("httpServer")16 .send()17 .post("/ftp/retrieveFileTest")18 .contentType("application/json")19 .payload("{\"localPath\":\"${localPath}\",\"remotePath\":\"${remotePath}\",\"remoteFile\":\"${remoteFile}\",\"localFile\":\"${localFile}\"}"),20 http().client("httpServer")21 .receive()22 .response(HttpStatus.OK)23 );24 }25}26package com.consol.citrus.ftp;27import com.consol.citrus.annotations.CitrusTest;28import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;29import org.testng.annotations.Test;30public class StoreFileTest extends TestNGCitrusTestRunner {31 public void storeFile() {32 variable("localPath", "target/ftp/storeFileTest");33 variable("remotePath", "remotePath");34 variable("remoteFile", "remoteFile");35 variable("localFile", "localFile");36 parallel().actions(37 ftp().client("ftpClient")38 .send()39 .storeFile("${localPath}/${localFile}", "${remotePath}/${remoteFile}"),40 http().client("httpServer")41 .send()42 .post("/ftp/storeFileTest")43 .contentType("application/json")44 .payload("{\"localPath\":\"${localPath}\",\"remotePath\":\"${remotePath}\",\"

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1ftpClient.retrieveFile("test.txt", "target/test.txt");2ftpClient.putFile("test.txt", "target/test.txt");3ftpClient.deleteFile("test.txt");4ftpClient.disconnect();5ftpClient.connect();6ftpClient.send(command);7ftpClient.send(command, replyCode);8ftpClient.send(command, replyCode, replyText);9ftpClient.receive(command);10ftpClient.receive(command, replyCode);11ftpClient.receive(command, replyCode, replyText);12ftpClient.sendAndReceive(command);13ftpClient.sendAndReceive(command, replyCode);14ftpClient.sendAndReceive(command, replyCode, replyText);

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1public class 3 {2 private FtpClient ftpClient;3 public void setup() {4 ftpClient = new FtpClient();5 ftpClient.setEndpointConfiguration(new FtpEndpointConfiguration());6 ftpClient.getEndpointConfiguration().setHost("localhost");7 ftpClient.getEndpointConfiguration().setPort(21);8 ftpClient.getEndpointConfiguration().setUsername("user");9 ftpClient.getEndpointConfiguration().setPassword("password");10 ftpClient.getEndpointConfiguration().setAutoCreateLocalDirectory(true);11 ftpClient.getEndpointConfiguration().setAutoCreateRemoteDirectory(true);12 }13 public void test() {14 ftpClient.connect();15 ftpClient.retrieveFile("remote.txt", "local.txt");16 ftpClient.disconnect();17 }18}19public class 4 {20 private FtpClient ftpClient;21 public void setup() {22 ftpClient = new FtpClient();23 ftpClient.setEndpointConfiguration(new FtpEndpointConfiguration());24 ftpClient.getEndpointConfiguration().setHost("localhost");25 ftpClient.getEndpointConfiguration().setPort(21);26 ftpClient.getEndpointConfiguration().setUsername("user");27 ftpClient.getEndpointConfiguration().setPassword("password");28 ftpClient.getEndpointConfiguration().setAutoCreateLocalDirectory(true);29 ftpClient.getEndpointConfiguration().setAutoCreateRemoteDirectory(true);30 }31 public void test() {32 ftpClient.connect();33 ftpClient.retrieveFile("remote.txt", "local.txt", "UTF-8");34 ftpClient.disconnect();35 }36}37public class 5 {38 private FtpClient ftpClient;39 public void setup() {40 ftpClient = new FtpClient();41 ftpClient.setEndpointConfiguration(new FtpEndpointConfiguration());42 ftpClient.getEndpointConfiguration().setHost("localhost");43 ftpClient.getEndpointConfiguration().setPort(21);44 ftpClient.getEndpointConfiguration().setUsername("user");45 ftpClient.getEndpointConfiguration().setPassword("password");46 ftpClient.getEndpointConfiguration().setAutoCreateLocalDirectory(true);47 ftpClient.getEndpointConfiguration().setAutoCreateRemoteDirectory(true

Full Screen

Full Screen

retrieveFile

Using AI Code Generation

copy

Full Screen

1public class FtpClientRetrieveFileTest extends AbstractTestNGCitrusTest {2 public void ftpClientRetrieveFileTest() {3 variable("localPath", "target/ftp");4 variable("remotePath", "test.txt");5 variable("localFile", "test.txt");6 variable("remoteFile", "test.txt");7 parallel().actions(8 ftp()9 .client("ftpClient")10 .send()11 .retrieveFile("${localPath}", "${remotePath}"),12 http()13 .client("httpClient")14 .send()15 .put("/ftp/${remoteFile}")16 .contentType("text/plain")17 .payload("<test>Test FTP file upload</test>")18 );19 ftp()20 .client("ftpClient")21 .receive()22 .reply(HttpStatus.OK)23 .messageType(MessageType.BINARY)24 .payload(new ClassPathResource("test.txt"));25 }26}27public class FtpClientStoreFileTest extends AbstractTestNGCitrusTest {28 public void ftpClientStoreFileTest() {29 variable("localPath", "target/ftp");30 variable("remotePath", "test.txt");31 variable("localFile", "test.txt");32 variable("remoteFile", "test.txt");33 parallel().actions(34 ftp()35 .client("ftpClient")36 .send()37 .storeFile("${localPath}", "${remotePath}"),38 http()39 .client("httpClient")40 .send()41 .put("/ftp/${remoteFile}")42 .contentType("text/plain")43 .payload("<test>Test FTP file upload</test>")44 );45 ftp()46 .client("ftpClient")47 .receive()48 .reply(HttpStatus.OK)49 .messageType(MessageType.BINARY)50 .payload(new ClassPathResource("test.txt"));51 }52}53public class FtpClientRemoveFileTest extends AbstractTestNGCitrusTest {54 public void ftpClientRemoveFileTest() {55 variable("localPath", "target/ftp");56 variable("remotePath", "test.txt");57 variable("

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful