Best Citrus code snippet using com.consol.citrus.ftp.client.FtpClient.isPositive
Source:FtpClient.java
...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);291 }292 } catch (IOException e) {293 throw new CitrusRuntimeException("Failed to get file from FTP server", e);294 }295 }296 /**297 * Get file type from info string.298 * @param typeInfo299 * @return300 */301 private int getFileType(String typeInfo) {302 switch (typeInfo) {303 case "ASCII":304 return FTP.ASCII_FILE_TYPE;305 case "BINARY":306 return FTP.BINARY_FILE_TYPE;307 case "EBCDIC":308 return FTP.EBCDIC_FILE_TYPE;309 case "LOCAL":310 return FTP.LOCAL_FILE_TYPE;311 default:312 return FTP.BINARY_FILE_TYPE;313 }314 }315 /**316 * If the target path is a directory (ends with "/"), add the file name from the source path to the target path.317 * Otherwise, don't do anything318 *319 * Example:320 * <p>321 * sourcePath="/some/dir/file.pdf"<br>322 * targetPath="/other/dir/"<br>323 * returns: "/other/dir/file.pdf"324 * </p>325 *326 */327 protected static String addFileNameToTargetPath(String sourcePath, String targetPath) {328 if (targetPath.endsWith("/")) {329 String filename = Paths.get(sourcePath).getFileName().toString();330 return targetPath + filename;331 }332 return targetPath;333 }334 /**335 * Opens a new connection and performs login with user name and password if set.336 * @throws IOException337 */338 protected void connectAndLogin() throws IOException {339 if (!ftpClient.isConnected()) {340 ftpClient.connect(getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort());341 if (log.isDebugEnabled()) {342 log.debug("Connected to FTP server: " + ftpClient.getReplyString());343 }344 int reply = ftpClient.getReplyCode();345 if (!FTPReply.isPositiveCompletion(reply)) {346 throw new CitrusRuntimeException("FTP server refused connection.");347 }348 log.info("Opened connection to FTP server");349 if (getEndpointConfiguration().getUser() != null) {350 if (log.isDebugEnabled()) {351 log.debug(String.format("Login as user: '%s'", getEndpointConfiguration().getUser()));352 }353 boolean login = ftpClient.login(getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword());354 if (!login) {355 throw new CitrusRuntimeException(String.format("Failed to login to FTP server using credentials: %s:%s", getEndpointConfiguration().getUser(), getEndpointConfiguration().getPassword()));356 }357 }358 if (getEndpointConfiguration().isLocalPassiveMode()) {359 ftpClient.enterLocalPassiveMode();...
isPositive
Using AI Code Generation
1import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;2import com.consol.citrus.testng.CitrusParameters;3import org.testng.annotations.Test;4public class MyFtpTest extends TestNGCitrusTestDesigner {5 @CitrusParameters("ftpServerPort")6 public void myFtpTest(@CitrusResource TestContext context, @CitrusResource TestNGCitrusSupport runner, @CitrusParameter("ftpServerPort") int ftpServerPort) {7 variable("ftpServerPort", ftpServerPort);8 variable("ftpServerHost", "localhost");9 echo("FTP Server Port: ${ftpServerPort}");10 createVariable("ftpUserName", "citrus");11 createVariable("ftpPassword", "citrus");12 createVariable("ftpLocalFilePath", "src/test/resources/ftp/remote.txt");13 createVariable("ftpRemoteFilePath", "/remote.txt");14 ftp(ftpClient -> ftpClient.server("localhost")15 .port("${ftpServerPort}")16 .autoReadFiles(true)17 .autoDetectFileEvents(true)18 .user("${ftpUserName}")19 .password("${ftpPassword}")20 .autoConnect(true)21 .autoLogin(true)22 .autoPut(true)23 .localFilePath("${ftpLocalFilePath}")24 .remoteFilePath("${ftpRemoteFilePath}")25 .autoDelete(true)26 .autoDisconnect(true)27 );28 ftp(ftpClient -> ftpClient.server("localhost")29 .port("${ftpServerPort}")30 .user("${ftpUserName}")31 .password("${ftpPassword}")32 .autoConnect(true)33 .autoLogin(true)34 .autoGet(true)35 .localFilePath("${ftpLocalFilePath}")36 .remoteFilePath("${ftpRemoteFilePath}")37 .autoDelete(true)38 .autoDisconnect(true)39 );40 ftp(ftpClient -> ftpClient.server("localhost")41 .port("${ftpServerPort}")42 .user("${ftpUserName}")43 .password("${ftpPassword}")44 .autoConnect(true)45 .autoLogin(true)46 .autoDelete(true)47 .autoDisconnect(true)48 .autoGet(true)49 .localFilePath("${ftpLocalFilePath}")50 .remoteFilePath("${ftpRemoteFilePath}")51 );52 ftp(ftpClient -> ftpClient.server("localhost")53 .port("${ftpServerPort}")54 .user("${ftpUserName}")55 .password("${ftpPassword}")
isPositive
Using AI Code Generation
1public class FtpClientIT extends TestCase {2 private FtpClient ftpClient;3 public void testFtpClient() {4 ftpClient.isPositive("ls -la");5 }6}
isPositive
Using AI Code Generation
1import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;2import org.testng.annotations.Test;3public class FtpTest extends TestNGCitrusTestDesigner {4 public void ftpTest() {5 variable("fileName", "test.txt");6 variable("fileContent", "Hello Citrus!");7 echo("Creating file on FTP server");8 create()9 .file("${fileName}")10 .content("${fileContent}");11 echo("Check if file exists on FTP server");12 send(ftp())13 .command("STAT ${fileName}");14 receive(ftp())15 .response(isPositive());16 echo("Check if file does not exist on FTP server");17 send(ftp())18 .command("STAT unknown.txt");19 receive(ftp())20 .response(isNegative());21 echo("Delete file on FTP server");22 send(ftp())23 .command("DELE ${fileName}");24 receive(ftp())25 .response(isPositive());26 }27}
isPositive
Using AI Code Generation
1public class MyFtpTest {2 public void ftpTest() {3 variable("file", "test.txt");4 variable("localDir", "target/ftp");5 createDirectory(localDir);6 echo("FTP PUT test.txt to server");7 ftp()8 .client(ftpClient)9 .put(localDir + "/" + file);10 echo("FTP GET test.txt from server");11 ftp()12 .client(ftpClient)13 .get(localDir + "/" + file);14 echo("FTP DELETE test.txt from server");15 ftp()16 .client(ftpClient)17 .delete(file);18 echo("FTP LIST files from server");19 ftp()20 .client(ftpClient)21 .list(localDir);22 echo("FTP CHECK file exists on server");23 ftp()24 .client(ftpClient)25 .isPositive(isPositive -> isPositive26 .file(file));27 }28}29public class MyFtpTest {30 public void ftpTest() {31 variable("file", "test.txt");32 variable("localDir", "target/ftp");33 createDirectory(localDir);34 echo("FTP PUT test.txt to server");35 ftp()36 .client(ftpClient)37 .put(localDir + "/" + file);38 echo("FTP GET test.txt from server");39 ftp()40 .client(ftpClient)41 .get(localDir + "/" + file);42 echo("FTP DELETE test.txt from server");43 ftp()44 .client(ftpClient)45 .delete(file);46 echo("FTP LIST files from server");47 ftp()48 .client(ftpClient)49 .list(localDir);50 echo("FTP CHECK file exists on server");51 ftp()52 .client(ftpClient)53 .isPositive(isPositive -> isPositive54 .file(file));55 }56}
isPositive
Using AI Code Generation
1public void testFtpClient() {2 given(ftp().client(ftpClient)3 .send("file:test.txt")4 .content("Hello Citrus!"));5 when(ftp().client(ftpClient)6 .receive("file:test.txt"));7 then(ftp().client(ftpClient)8 .assertThat().isPositive());9}10public void testFtpClient() {11 given(ftp().client(ftpClient)12 .send("file:test.txt")13 .content("Hello Citrus!"));14 when(ftp().client(ftpClient)15 .receive("file:test.txt"));16 then(ftp().client(ftpClient)17 .assertThat().isNegative());18}19public void testFtpClient() {20 given(ftp().client(ftpClient)21 .send("file:test.txt")22 .content("Hello Citrus!"));23 when(ftp().client(ftpClient)24 .receive("file:test.txt"));25 then(ftp().client(ftpClient)26 .assertThat().isPositive());27}28public void testFtpClient() {29 given(ftp().client(ftpClient)30 .send("file:test.txt")31 .content("Hello Citrus!"));32 when(ftp().client(ftpClient)33 .receive("file:test.txt"));34 then(ftp().client(ftpClient)35 .assertThat().isNegative());36}
isPositive
Using AI Code Generation
1ftp:send-command("isPositive", "FILE", "com.consol.citrus.ftp.client.FtpClient")2ftp:send-command("isPositive", "FILE", "com.consol.citrus.ftp.client.FtpClient", "fileExists")3ftp:send-command("isNegative", "FILE", "com.consol.citrus.ftp.client.FtpClient")4ftp:send-command("isNegative", "FILE", "com.consol.citrus.ftp.client.FtpClient", "fileDoesNotExist")5ftp:send-command("isPositive", "DIRECTORY", "com.consol.citrus.ftp.client.FtpClient")6ftp:send-command("isPositive", "DIRECTORY", "com.consol.citrus.ftp.client.FtpClient", "directoryExists")7ftp:send-command("isNegative", "DIRECTORY", "com.consol.citrus.ftp.client.FtpClient")8ftp:send-command("isNegative", "DIRECTORY", "com.consol.citrus.ftp.client.FtpClient", "directoryDoesNotExist")9ftp:send-command("isPositive", "", "com.consol.citrus.ftp.client.FtpClient")10ftp:send-command("isPositive", "", "com.consol.citrus.ftp.client.FtpClient", "serverRunning")11ftp:send-command("isNegative", "", "com.consol.citrus.ftp.client.FtpClient")
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!